]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
2014-01-24 Bill Schmidt <wschmidt@linux.vnet.ibm.com>
[thirdparty/gcc.git] / gcc / go / gofrontend / expressions.cc
CommitLineData
e440a328 1// expressions.cc -- Go frontend expression handling.
2
3// Copyright 2009 The Go Authors. All rights reserved.
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
7#include "go-system.h"
8
ffe743ca 9#include <algorithm>
10
e440a328 11#include "toplev.h"
12#include "intl.h"
13#include "tree.h"
9ed99284 14#include "stringpool.h"
15#include "stor-layout.h"
764505e6 16#include "gimple-expr.h"
e440a328 17#include "tree-iterator.h"
18#include "convert.h"
19#include "real.h"
20#include "realmpfr.h"
e440a328 21
e440a328 22#include "go-c.h"
23#include "gogo.h"
24#include "types.h"
25#include "export.h"
26#include "import.h"
27#include "statements.h"
28#include "lex.h"
a9182619 29#include "runtime.h"
6e193e6f 30#include "backend.h"
e440a328 31#include "expressions.h"
d751bb78 32#include "ast-dump.h"
e440a328 33
34// Class Expression.
35
36Expression::Expression(Expression_classification classification,
b13c66cd 37 Location location)
e440a328 38 : classification_(classification), location_(location)
39{
40}
41
42Expression::~Expression()
43{
44}
45
e440a328 46// Traverse the expressions.
47
48int
49Expression::traverse(Expression** pexpr, Traverse* traverse)
50{
51 Expression* expr = *pexpr;
52 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
53 {
54 int t = traverse->expression(pexpr);
55 if (t == TRAVERSE_EXIT)
56 return TRAVERSE_EXIT;
57 else if (t == TRAVERSE_SKIP_COMPONENTS)
58 return TRAVERSE_CONTINUE;
59 }
60 return expr->do_traverse(traverse);
61}
62
63// Traverse subexpressions of this expression.
64
65int
66Expression::traverse_subexpressions(Traverse* traverse)
67{
68 return this->do_traverse(traverse);
69}
70
71// Default implementation for do_traverse for child classes.
72
73int
74Expression::do_traverse(Traverse*)
75{
76 return TRAVERSE_CONTINUE;
77}
78
79// This virtual function is called by the parser if the value of this
a7549a6a 80// expression is being discarded. By default, we give an error.
81// Expressions with side effects override.
e440a328 82
4f2138d7 83bool
e440a328 84Expression::do_discarding_value()
85{
a7549a6a 86 this->unused_value_error();
4f2138d7 87 return false;
e440a328 88}
89
90// This virtual function is called to export expressions. This will
91// only be used by expressions which may be constant.
92
93void
94Expression::do_export(Export*) const
95{
c3e6f413 96 go_unreachable();
e440a328 97}
98
a7549a6a 99// Give an error saying that the value of the expression is not used.
e440a328 100
101void
a7549a6a 102Expression::unused_value_error()
e440a328 103{
4f2138d7 104 this->report_error(_("value computed is not used"));
e440a328 105}
106
107// Note that this expression is an error. This is called by children
108// when they discover an error.
109
110void
111Expression::set_is_error()
112{
113 this->classification_ = EXPRESSION_ERROR;
114}
115
116// For children to call to report an error conveniently.
117
118void
119Expression::report_error(const char* msg)
120{
121 error_at(this->location_, "%s", msg);
122 this->set_is_error();
123}
124
125// Set types of variables and constants. This is implemented by the
126// child class.
127
128void
129Expression::determine_type(const Type_context* context)
130{
131 this->do_determine_type(context);
132}
133
134// Set types when there is no context.
135
136void
137Expression::determine_type_no_context()
138{
139 Type_context context;
140 this->do_determine_type(&context);
141}
142
143// Return a tree handling any conversions which must be done during
144// assignment.
145
146tree
147Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
148 Type* rhs_type, tree rhs_tree,
b13c66cd 149 Location location)
e440a328 150{
5c13bd80 151 if (lhs_type->is_error() || rhs_type->is_error())
e440a328 152 return error_mark_node;
153
e440a328 154 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
155 return error_mark_node;
156
157 Gogo* gogo = context->gogo();
158
9f0e0513 159 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
e440a328 160 if (lhs_type_tree == error_mark_node)
161 return error_mark_node;
162
54211955 163 if (lhs_type->forwarded() != rhs_type->forwarded()
164 && lhs_type->interface_type() != NULL)
e440a328 165 {
166 if (rhs_type->interface_type() == NULL)
167 return Expression::convert_type_to_interface(context, lhs_type,
168 rhs_type, rhs_tree,
169 location);
170 else
171 return Expression::convert_interface_to_interface(context, lhs_type,
172 rhs_type, rhs_tree,
173 false, location);
174 }
54211955 175 else if (lhs_type->forwarded() != rhs_type->forwarded()
176 && rhs_type->interface_type() != NULL)
e440a328 177 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
178 rhs_tree, location);
411eb89e 179 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
e440a328 180 {
181 // Assigning nil to an open array.
c484d925 182 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
e440a328 183
95f84544 184 vec<constructor_elt, va_gc> *init;
185 vec_alloc(init, 3);
e440a328 186
e82e4eb5 187 constructor_elt empty = {NULL, NULL};
95f84544 188 constructor_elt* elt = init->quick_push(empty);
e440a328 189 tree field = TYPE_FIELDS(lhs_type_tree);
c484d925 190 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
e440a328 191 "__values") == 0);
192 elt->index = field;
193 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
194
95f84544 195 elt = init->quick_push(empty);
e440a328 196 field = DECL_CHAIN(field);
c484d925 197 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
e440a328 198 "__count") == 0);
199 elt->index = field;
200 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
201
95f84544 202 elt = init->quick_push(empty);
e440a328 203 field = DECL_CHAIN(field);
c484d925 204 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
e440a328 205 "__capacity") == 0);
206 elt->index = field;
207 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
208
209 tree val = build_constructor(lhs_type_tree, init);
210 TREE_CONSTANT(val) = 1;
211
212 return val;
213 }
214 else if (rhs_type->is_nil_type())
215 {
216 // The left hand side should be a pointer type at the tree
217 // level.
c484d925 218 go_assert(POINTER_TYPE_P(lhs_type_tree));
e440a328 219 return fold_convert(lhs_type_tree, null_pointer_node);
220 }
221 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
222 {
223 // No conversion is needed.
224 return rhs_tree;
225 }
226 else if (POINTER_TYPE_P(lhs_type_tree)
227 || INTEGRAL_TYPE_P(lhs_type_tree)
228 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
229 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
b13c66cd 230 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
3e785901 231 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
232 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
233 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
234 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
e440a328 235 {
bb92f513 236 // Avoid confusion from zero sized variables which may be
237 // represented as non-zero-sized.
238 if (int_size_in_bytes(lhs_type_tree) == 0
239 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
240 return rhs_tree;
241
e440a328 242 // This conversion must be permitted by Go, or we wouldn't have
243 // gotten here.
c484d925 244 go_assert(int_size_in_bytes(lhs_type_tree)
bb92f513 245 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
b13c66cd 246 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
247 lhs_type_tree, rhs_tree);
e440a328 248 }
249 else
250 {
c484d925 251 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
e440a328 252 return rhs_tree;
253 }
254}
255
256// Return a tree for a conversion from a non-interface type to an
257// interface type.
258
259tree
260Expression::convert_type_to_interface(Translate_context* context,
261 Type* lhs_type, Type* rhs_type,
b13c66cd 262 tree rhs_tree, Location location)
e440a328 263{
264 Gogo* gogo = context->gogo();
265 Interface_type* lhs_interface_type = lhs_type->interface_type();
266 bool lhs_is_empty = lhs_interface_type->is_empty();
267
268 // Since RHS_TYPE is a static type, we can create the interface
269 // method table at compile time.
270
271 // When setting an interface to nil, we just set both fields to
272 // NULL.
273 if (rhs_type->is_nil_type())
63697958 274 {
275 Btype* lhs_btype = lhs_type->get_backend(gogo);
276 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
277 }
e440a328 278
279 // This should have been checked already.
c484d925 280 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
e440a328 281
9f0e0513 282 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
e440a328 283 if (lhs_type_tree == error_mark_node)
284 return error_mark_node;
285
286 // An interface is a tuple. If LHS_TYPE is an empty interface type,
287 // then the first field is the type descriptor for RHS_TYPE.
288 // Otherwise it is the interface method table for RHS_TYPE.
289 tree first_field_value;
290 if (lhs_is_empty)
175a4612 291 {
292 Bexpression* rhs_bexpr =
293 rhs_type->type_descriptor_pointer(gogo, location);
294 first_field_value = expr_to_tree(rhs_bexpr);
295 }
e440a328 296 else
297 {
298 // Build the interface method table for this interface and this
299 // object type: a list of function pointers for each interface
300 // method.
301 Named_type* rhs_named_type = rhs_type->named_type();
c0cab2ec 302 Struct_type* rhs_struct_type = rhs_type->struct_type();
e440a328 303 bool is_pointer = false;
c0cab2ec 304 if (rhs_named_type == NULL && rhs_struct_type == NULL)
e440a328 305 {
306 rhs_named_type = rhs_type->deref()->named_type();
c0cab2ec 307 rhs_struct_type = rhs_type->deref()->struct_type();
e440a328 308 is_pointer = true;
309 }
310 tree method_table;
c0cab2ec 311 if (rhs_named_type != NULL)
e440a328 312 method_table =
313 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
314 is_pointer);
c0cab2ec 315 else if (rhs_struct_type != NULL)
316 method_table =
317 rhs_struct_type->interface_method_table(gogo, lhs_interface_type,
318 is_pointer);
319 else
320 method_table = null_pointer_node;
b13c66cd 321 first_field_value = fold_convert_loc(location.gcc_location(),
322 const_ptr_type_node, method_table);
e440a328 323 }
84b7d3c6 324 if (first_field_value == error_mark_node)
325 return error_mark_node;
e440a328 326
327 // Start building a constructor for the value we will return.
328
95f84544 329 vec<constructor_elt, va_gc> *init;
330 vec_alloc(init, 2);
e440a328 331
e82e4eb5 332 constructor_elt empty = {NULL, NULL};
95f84544 333 constructor_elt* elt = init->quick_push(empty);
e440a328 334 tree field = TYPE_FIELDS(lhs_type_tree);
c484d925 335 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
e440a328 336 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
337 elt->index = field;
b13c66cd 338 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
339 first_field_value);
e440a328 340
95f84544 341 elt = init->quick_push(empty);
e440a328 342 field = DECL_CHAIN(field);
c484d925 343 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
e440a328 344 elt->index = field;
345
346 if (rhs_type->points_to() != NULL)
347 {
348 // We are assigning a pointer to the interface; the interface
349 // holds the pointer itself.
350 elt->value = rhs_tree;
351 return build_constructor(lhs_type_tree, init);
352 }
353
354 // We are assigning a non-pointer value to the interface; the
355 // interface gets a copy of the value in the heap.
356
357 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
358
359 tree space = gogo->allocate_memory(rhs_type, object_size, location);
b13c66cd 360 space = fold_convert_loc(location.gcc_location(),
361 build_pointer_type(TREE_TYPE(rhs_tree)), space);
e440a328 362 space = save_expr(space);
363
b13c66cd 364 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
e440a328 365 TREE_THIS_NOTRAP(ref) = 1;
b13c66cd 366 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
367 void_type_node, ref, rhs_tree);
e440a328 368
b13c66cd 369 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
370 space);
e440a328 371
372 return build2(COMPOUND_EXPR, lhs_type_tree, set,
373 build_constructor(lhs_type_tree, init));
374}
375
376// Return a tree for the type descriptor of RHS_TREE, which has
377// interface type RHS_TYPE. If RHS_TREE is nil the result will be
378// NULL.
379
380tree
381Expression::get_interface_type_descriptor(Translate_context*,
382 Type* rhs_type, tree rhs_tree,
b13c66cd 383 Location location)
e440a328 384{
385 tree rhs_type_tree = TREE_TYPE(rhs_tree);
c484d925 386 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
e440a328 387 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
388 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
389 NULL_TREE);
390 if (rhs_type->interface_type()->is_empty())
391 {
c484d925 392 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
e440a328 393 "__type_descriptor") == 0);
394 return v;
395 }
396
c484d925 397 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
e440a328 398 == 0);
c484d925 399 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
e440a328 400 v = save_expr(v);
b13c66cd 401 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
c484d925 402 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
e440a328 403 tree f = TYPE_FIELDS(TREE_TYPE(v1));
c484d925 404 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
e440a328 405 == 0);
406 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
407
b13c66cd 408 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
409 v, fold_convert_loc(location.gcc_location(),
410 TREE_TYPE(v),
411 null_pointer_node));
412 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
413 null_pointer_node);
414 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
e440a328 415 eq, n, v1);
416}
417
418// Return a tree for the conversion of an interface type to an
419// interface type.
420
421tree
422Expression::convert_interface_to_interface(Translate_context* context,
423 Type *lhs_type, Type *rhs_type,
424 tree rhs_tree, bool for_type_guard,
b13c66cd 425 Location location)
e440a328 426{
427 Gogo* gogo = context->gogo();
428 Interface_type* lhs_interface_type = lhs_type->interface_type();
429 bool lhs_is_empty = lhs_interface_type->is_empty();
430
9f0e0513 431 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
e440a328 432 if (lhs_type_tree == error_mark_node)
433 return error_mark_node;
434
435 // In the general case this requires runtime examination of the type
436 // method table to match it up with the interface methods.
437
438 // FIXME: If all of the methods in the right hand side interface
439 // also appear in the left hand side interface, then we don't need
440 // to do a runtime check, although we still need to build a new
441 // method table.
442
443 // Get the type descriptor for the right hand side. This will be
444 // NULL for a nil interface.
445
446 if (!DECL_P(rhs_tree))
447 rhs_tree = save_expr(rhs_tree);
448
449 tree rhs_type_descriptor =
450 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
451 location);
452
453 // The result is going to be a two element constructor.
454
95f84544 455 vec<constructor_elt, va_gc> *init;
456 vec_alloc (init, 2);
e440a328 457
e82e4eb5 458 constructor_elt empty = {NULL, NULL};
95f84544 459 constructor_elt* elt = init->quick_push(empty);
e440a328 460 tree field = TYPE_FIELDS(lhs_type_tree);
461 elt->index = field;
462
463 if (for_type_guard)
464 {
465 // A type assertion fails when converting a nil interface.
175a4612 466 Bexpression* lhs_type_expr = lhs_type->type_descriptor_pointer(gogo,
467 location);
468 tree lhs_type_descriptor = expr_to_tree(lhs_type_expr);
e440a328 469 static tree assert_interface_decl;
470 tree call = Gogo::call_builtin(&assert_interface_decl,
471 location,
472 "__go_assert_interface",
473 2,
474 ptr_type_node,
475 TREE_TYPE(lhs_type_descriptor),
476 lhs_type_descriptor,
477 TREE_TYPE(rhs_type_descriptor),
478 rhs_type_descriptor);
5fb82b5e 479 if (call == error_mark_node)
480 return error_mark_node;
e440a328 481 // This will panic if the interface conversion fails.
482 TREE_NOTHROW(assert_interface_decl) = 0;
b13c66cd 483 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
484 call);
e440a328 485 }
486 else if (lhs_is_empty)
487 {
488 // A convertion to an empty interface always succeeds, and the
489 // first field is just the type descriptor of the object.
c484d925 490 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
e440a328 491 "__type_descriptor") == 0);
7172c949 492 elt->value = fold_convert_loc(location.gcc_location(),
493 TREE_TYPE(field), rhs_type_descriptor);
e440a328 494 }
495 else
496 {
497 // A conversion to a non-empty interface may fail, but unlike a
498 // type assertion converting nil will always succeed.
c484d925 499 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
e440a328 500 == 0);
175a4612 501 Bexpression* lhs_type_expr = lhs_type->type_descriptor_pointer(gogo,
502 location);
503 tree lhs_type_descriptor = expr_to_tree(lhs_type_expr);
504
e440a328 505 static tree convert_interface_decl;
506 tree call = Gogo::call_builtin(&convert_interface_decl,
507 location,
508 "__go_convert_interface",
509 2,
510 ptr_type_node,
511 TREE_TYPE(lhs_type_descriptor),
512 lhs_type_descriptor,
513 TREE_TYPE(rhs_type_descriptor),
514 rhs_type_descriptor);
5fb82b5e 515 if (call == error_mark_node)
516 return error_mark_node;
e440a328 517 // This will panic if the interface conversion fails.
518 TREE_NOTHROW(convert_interface_decl) = 0;
b13c66cd 519 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
520 call);
e440a328 521 }
522
523 // The second field is simply the object pointer.
524
95f84544 525 elt = init->quick_push(empty);
e440a328 526 field = DECL_CHAIN(field);
c484d925 527 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
e440a328 528 elt->index = field;
529
530 tree rhs_type_tree = TREE_TYPE(rhs_tree);
c484d925 531 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
e440a328 532 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
c484d925 533 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
e440a328 534 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
535 NULL_TREE);
536
537 return build_constructor(lhs_type_tree, init);
538}
539
540// Return a tree for the conversion of an interface type to a
541// non-interface type.
542
543tree
544Expression::convert_interface_to_type(Translate_context* context,
545 Type *lhs_type, Type* rhs_type,
b13c66cd 546 tree rhs_tree, Location location)
e440a328 547{
548 Gogo* gogo = context->gogo();
549 tree rhs_type_tree = TREE_TYPE(rhs_tree);
550
9f0e0513 551 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
e440a328 552 if (lhs_type_tree == error_mark_node)
553 return error_mark_node;
554
555 // Call a function to check that the type is valid. The function
556 // will panic with an appropriate runtime type error if the type is
557 // not valid.
175a4612 558 Bexpression* lhs_type_expr = lhs_type->type_descriptor_pointer(gogo,
559 location);
560 tree lhs_type_descriptor = expr_to_tree(lhs_type_expr);
e440a328 561
562 if (!DECL_P(rhs_tree))
563 rhs_tree = save_expr(rhs_tree);
564
565 tree rhs_type_descriptor =
566 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
567 location);
568
175a4612 569 Bexpression* rhs_inter_expr = rhs_type->type_descriptor_pointer(gogo,
570 location);
571 tree rhs_inter_descriptor = expr_to_tree(rhs_inter_expr);
e440a328 572
573 static tree check_interface_type_decl;
574 tree call = Gogo::call_builtin(&check_interface_type_decl,
575 location,
576 "__go_check_interface_type",
577 3,
578 void_type_node,
579 TREE_TYPE(lhs_type_descriptor),
580 lhs_type_descriptor,
581 TREE_TYPE(rhs_type_descriptor),
582 rhs_type_descriptor,
583 TREE_TYPE(rhs_inter_descriptor),
584 rhs_inter_descriptor);
5fb82b5e 585 if (call == error_mark_node)
586 return error_mark_node;
e440a328 587 // This call will panic if the conversion is invalid.
588 TREE_NOTHROW(check_interface_type_decl) = 0;
589
590 // If the call succeeds, pull out the value.
c484d925 591 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
e440a328 592 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
c484d925 593 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
e440a328 594 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
595 NULL_TREE);
596
597 // If the value is a pointer, then it is the value we want.
598 // Otherwise it points to the value.
599 if (lhs_type->points_to() == NULL)
600 {
b13c66cd 601 val = fold_convert_loc(location.gcc_location(),
602 build_pointer_type(lhs_type_tree), val);
603 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
e440a328 604 }
605
606 return build2(COMPOUND_EXPR, lhs_type_tree, call,
b13c66cd 607 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
e440a328 608}
609
610// Convert an expression to a tree. This is implemented by the child
611// class. Not that it is not in general safe to call this multiple
612// times for a single expression, but that we don't catch such errors.
613
614tree
615Expression::get_tree(Translate_context* context)
616{
617 // The child may have marked this expression as having an error.
618 if (this->classification_ == EXPRESSION_ERROR)
619 return error_mark_node;
620
621 return this->do_get_tree(context);
622}
623
48c2a53a 624// Return a backend expression for VAL.
625Bexpression*
626Expression::backend_numeric_constant_expression(Translate_context* context,
627 Numeric_constant* val)
e440a328 628{
48c2a53a 629 Gogo* gogo = context->gogo();
630 Type* type = val->type();
631 if (type == NULL)
632 return gogo->backend()->error_expression();
e440a328 633
48c2a53a 634 Btype* btype = type->get_backend(gogo);
635 Bexpression* ret;
636 if (type->integer_type() != NULL)
e440a328 637 {
638 mpz_t ival;
48c2a53a 639 if (!val->to_int(&ival))
640 {
641 go_assert(saw_errors());
642 return gogo->backend()->error_expression();
643 }
644 ret = gogo->backend()->integer_constant_expression(btype, ival);
e440a328 645 mpz_clear(ival);
e440a328 646 }
48c2a53a 647 else if (type->float_type() != NULL)
e440a328 648 {
48c2a53a 649 mpfr_t fval;
650 if (!val->to_float(&fval))
651 {
652 go_assert(saw_errors());
653 return gogo->backend()->error_expression();
654 }
655 ret = gogo->backend()->float_constant_expression(btype, fval);
656 mpfr_clear(fval);
e440a328 657 }
48c2a53a 658 else if (type->complex_type() != NULL)
e440a328 659 {
48c2a53a 660 mpfr_t real;
661 mpfr_t imag;
662 if (!val->to_complex(&real, &imag))
663 {
664 go_assert(saw_errors());
665 return gogo->backend()->error_expression();
666 }
667 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
668 mpfr_clear(real);
669 mpfr_clear(imag);
e440a328 670 }
671 else
c3e6f413 672 go_unreachable();
e440a328 673
48c2a53a 674 return ret;
e440a328 675}
676
677// Return a tree which evaluates to true if VAL, of arbitrary integer
678// type, is negative or is more than the maximum value of BOUND_TYPE.
679// If SOFAR is not NULL, it is or'red into the result. The return
680// value may be NULL if SOFAR is NULL.
681
682tree
683Expression::check_bounds(tree val, tree bound_type, tree sofar,
b13c66cd 684 Location loc)
e440a328 685{
686 tree val_type = TREE_TYPE(val);
687 tree ret = NULL_TREE;
688
689 if (!TYPE_UNSIGNED(val_type))
690 {
b13c66cd 691 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
e440a328 692 build_int_cst(val_type, 0));
693 if (ret == boolean_false_node)
694 ret = NULL_TREE;
695 }
696
c3068ac0 697 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
698 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
699 go_assert(val_type_size != -1 && bound_type_size != -1);
700 if (val_type_size > bound_type_size
701 || (val_type_size == bound_type_size
702 && TYPE_UNSIGNED(val_type)
703 && !TYPE_UNSIGNED(bound_type)))
e440a328 704 {
705 tree max = TYPE_MAX_VALUE(bound_type);
b13c66cd 706 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
707 val, fold_convert_loc(loc.gcc_location(),
708 val_type, max));
e440a328 709 if (big == boolean_false_node)
710 ;
711 else if (ret == NULL_TREE)
712 ret = big;
713 else
b13c66cd 714 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
715 boolean_type_node, ret, big);
e440a328 716 }
717
718 if (ret == NULL_TREE)
719 return sofar;
720 else if (sofar == NULL_TREE)
721 return ret;
722 else
b13c66cd 723 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
e440a328 724 sofar, ret);
725}
726
d751bb78 727void
728Expression::dump_expression(Ast_dump_context* ast_dump_context) const
729{
730 this->do_dump_expression(ast_dump_context);
731}
732
e440a328 733// Error expressions. This are used to avoid cascading errors.
734
735class Error_expression : public Expression
736{
737 public:
b13c66cd 738 Error_expression(Location location)
e440a328 739 : Expression(EXPRESSION_ERROR, location)
740 { }
741
742 protected:
743 bool
744 do_is_constant() const
745 { return true; }
746
747 bool
0c77715b 748 do_numeric_constant_value(Numeric_constant* nc) const
e440a328 749 {
0c77715b 750 nc->set_unsigned_long(NULL, 0);
e440a328 751 return true;
752 }
753
4f2138d7 754 bool
e440a328 755 do_discarding_value()
4f2138d7 756 { return true; }
e440a328 757
758 Type*
759 do_type()
760 { return Type::make_error_type(); }
761
762 void
763 do_determine_type(const Type_context*)
764 { }
765
766 Expression*
767 do_copy()
768 { return this; }
769
770 bool
771 do_is_addressable() const
772 { return true; }
773
774 tree
775 do_get_tree(Translate_context*)
776 { return error_mark_node; }
d751bb78 777
778 void
779 do_dump_expression(Ast_dump_context*) const;
e440a328 780};
781
d751bb78 782// Dump the ast representation for an error expression to a dump context.
783
784void
785Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
786{
787 ast_dump_context->ostream() << "_Error_" ;
788}
789
e440a328 790Expression*
b13c66cd 791Expression::make_error(Location location)
e440a328 792{
793 return new Error_expression(location);
794}
795
796// An expression which is really a type. This is used during parsing.
797// It is an error if these survive after lowering.
798
799class
800Type_expression : public Expression
801{
802 public:
b13c66cd 803 Type_expression(Type* type, Location location)
e440a328 804 : Expression(EXPRESSION_TYPE, location),
805 type_(type)
806 { }
807
808 protected:
809 int
810 do_traverse(Traverse* traverse)
811 { return Type::traverse(this->type_, traverse); }
812
813 Type*
814 do_type()
815 { return this->type_; }
816
817 void
818 do_determine_type(const Type_context*)
819 { }
820
821 void
822 do_check_types(Gogo*)
823 { this->report_error(_("invalid use of type")); }
824
825 Expression*
826 do_copy()
827 { return this; }
828
829 tree
830 do_get_tree(Translate_context*)
c3e6f413 831 { go_unreachable(); }
e440a328 832
d751bb78 833 void do_dump_expression(Ast_dump_context*) const;
834
e440a328 835 private:
836 // The type which we are representing as an expression.
837 Type* type_;
838};
839
d751bb78 840void
841Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
842{
843 ast_dump_context->dump_type(this->type_);
844}
845
e440a328 846Expression*
b13c66cd 847Expression::make_type(Type* type, Location location)
e440a328 848{
849 return new Type_expression(type, location);
850}
851
e03bdf36 852// Class Parser_expression.
853
854Type*
855Parser_expression::do_type()
856{
857 // We should never really ask for the type of a Parser_expression.
858 // However, it can happen, at least when we have an invalid const
859 // whose initializer refers to the const itself. In that case we
860 // may ask for the type when lowering the const itself.
c484d925 861 go_assert(saw_errors());
e03bdf36 862 return Type::make_error_type();
863}
864
e440a328 865// Class Var_expression.
866
867// Lower a variable expression. Here we just make sure that the
868// initialization expression of the variable has been lowered. This
869// ensures that we will be able to determine the type of the variable
870// if necessary.
871
872Expression*
ceeb4318 873Var_expression::do_lower(Gogo* gogo, Named_object* function,
874 Statement_inserter* inserter, int)
e440a328 875{
876 if (this->variable_->is_variable())
877 {
878 Variable* var = this->variable_->var_value();
879 // This is either a local variable or a global variable. A
880 // reference to a variable which is local to an enclosing
881 // function will be a reference to a field in a closure.
882 if (var->is_global())
ceeb4318 883 {
884 function = NULL;
885 inserter = NULL;
886 }
887 var->lower_init_expression(gogo, function, inserter);
e440a328 888 }
889 return this;
890}
891
e440a328 892// Return the type of a reference to a variable.
893
894Type*
895Var_expression::do_type()
896{
897 if (this->variable_->is_variable())
898 return this->variable_->var_value()->type();
899 else if (this->variable_->is_result_variable())
900 return this->variable_->result_var_value()->type();
901 else
c3e6f413 902 go_unreachable();
e440a328 903}
904
0ab09e06 905// Determine the type of a reference to a variable.
906
907void
908Var_expression::do_determine_type(const Type_context*)
909{
910 if (this->variable_->is_variable())
911 this->variable_->var_value()->determine_type();
912}
913
e440a328 914// Something takes the address of this variable. This means that we
915// may want to move the variable onto the heap.
916
917void
918Var_expression::do_address_taken(bool escapes)
919{
920 if (!escapes)
f325319b 921 {
922 if (this->variable_->is_variable())
923 this->variable_->var_value()->set_non_escaping_address_taken();
924 else if (this->variable_->is_result_variable())
925 this->variable_->result_var_value()->set_non_escaping_address_taken();
926 else
927 go_unreachable();
928 }
e440a328 929 else
f325319b 930 {
931 if (this->variable_->is_variable())
932 this->variable_->var_value()->set_address_taken();
933 else if (this->variable_->is_result_variable())
934 this->variable_->result_var_value()->set_address_taken();
935 else
936 go_unreachable();
937 }
e440a328 938}
939
940// Get the tree for a reference to a variable.
941
942tree
943Var_expression::do_get_tree(Translate_context* context)
944{
fe2f84cf 945 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
946 context->function());
fe2f84cf 947 bool is_in_heap;
c6777780 948 Location loc = this->location();
fe2f84cf 949 if (this->variable_->is_variable())
950 is_in_heap = this->variable_->var_value()->is_in_heap();
951 else if (this->variable_->is_result_variable())
952 is_in_heap = this->variable_->result_var_value()->is_in_heap();
953 else
c3e6f413 954 go_unreachable();
c6777780 955
956 Bexpression* ret = context->backend()->var_expression(bvar, loc);
fe2f84cf 957 if (is_in_heap)
c6777780 958 ret = context->backend()->indirect_expression(ret, true, loc);
959 return expr_to_tree(ret);
e440a328 960}
961
d751bb78 962// Ast dump for variable expression.
963
964void
965Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
966{
967 ast_dump_context->ostream() << this->variable_->name() ;
968}
969
e440a328 970// Make a reference to a variable in an expression.
971
972Expression*
b13c66cd 973Expression::make_var_reference(Named_object* var, Location location)
e440a328 974{
975 if (var->is_sink())
976 return Expression::make_sink(location);
977
978 // FIXME: Creating a new object for each reference to a variable is
979 // wasteful.
980 return new Var_expression(var, location);
981}
982
983// Class Temporary_reference_expression.
984
985// The type.
986
987Type*
988Temporary_reference_expression::do_type()
989{
990 return this->statement_->type();
991}
992
993// Called if something takes the address of this temporary variable.
994// We never have to move temporary variables to the heap, but we do
995// need to know that they must live in the stack rather than in a
996// register.
997
998void
999Temporary_reference_expression::do_address_taken(bool)
1000{
1001 this->statement_->set_is_address_taken();
1002}
1003
1004// Get a tree referring to the variable.
1005
1006tree
eefc1ed3 1007Temporary_reference_expression::do_get_tree(Translate_context* context)
e440a328 1008{
cd440cff 1009 Gogo* gogo = context->gogo();
eefc1ed3 1010 Bvariable* bvar = this->statement_->get_backend_variable(context);
cd440cff 1011 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
eefc1ed3 1012
cd440cff 1013 // The backend can't always represent the same set of recursive types
eefc1ed3 1014 // that the Go frontend can. In some cases this means that a
1015 // temporary variable won't have the right backend type. Correct
1016 // that here by adding a type cast. We need to use base() to push
1017 // the circularity down one level.
cd440cff 1018 Type* stype = this->statement_->type();
ceeb4318 1019 if (!this->is_lvalue_
cd440cff 1020 && stype->has_pointer()
1021 && stype->deref()->is_void_type())
eefc1ed3 1022 {
cd440cff 1023 Btype* btype = this->type()->base()->get_backend(gogo);
1024 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 1025 }
cd440cff 1026 return expr_to_tree(ret);
e440a328 1027}
1028
d751bb78 1029// Ast dump for temporary reference.
1030
1031void
1032Temporary_reference_expression::do_dump_expression(
1033 Ast_dump_context* ast_dump_context) const
1034{
1035 ast_dump_context->dump_temp_variable_name(this->statement_);
1036}
1037
e440a328 1038// Make a reference to a temporary variable.
1039
ceeb4318 1040Temporary_reference_expression*
e440a328 1041Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 1042 Location location)
e440a328 1043{
1044 return new Temporary_reference_expression(statement, location);
1045}
1046
e9d3367e 1047// Class Set_and_use_temporary_expression.
1048
1049// Return the type.
1050
1051Type*
1052Set_and_use_temporary_expression::do_type()
1053{
1054 return this->statement_->type();
1055}
1056
0afbb937 1057// Determine the type of the expression.
1058
1059void
1060Set_and_use_temporary_expression::do_determine_type(
1061 const Type_context* context)
1062{
1063 this->expr_->determine_type(context);
1064}
1065
e9d3367e 1066// Take the address.
1067
1068void
1069Set_and_use_temporary_expression::do_address_taken(bool)
1070{
1071 this->statement_->set_is_address_taken();
1072}
1073
1074// Return the backend representation.
1075
1076tree
1077Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1078{
1079 Bvariable* bvar = this->statement_->get_backend_variable(context);
1080 tree var_tree = var_to_tree(bvar);
1081 tree expr_tree = this->expr_->get_tree(context);
1082 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1083 return error_mark_node;
1084 Location loc = this->location();
1085 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1086 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1087 var_tree, expr_tree),
1088 var_tree);
1089}
1090
1091// Dump.
1092
1093void
1094Set_and_use_temporary_expression::do_dump_expression(
1095 Ast_dump_context* ast_dump_context) const
1096{
1097 ast_dump_context->ostream() << '(';
1098 ast_dump_context->dump_temp_variable_name(this->statement_);
1099 ast_dump_context->ostream() << " = ";
1100 this->expr_->dump_expression(ast_dump_context);
1101 ast_dump_context->ostream() << ')';
1102}
1103
1104// Make a set-and-use temporary.
1105
1106Set_and_use_temporary_expression*
1107Expression::make_set_and_use_temporary(Temporary_statement* statement,
1108 Expression* expr, Location location)
1109{
1110 return new Set_and_use_temporary_expression(statement, expr, location);
1111}
1112
e440a328 1113// A sink expression--a use of the blank identifier _.
1114
1115class Sink_expression : public Expression
1116{
1117 public:
b13c66cd 1118 Sink_expression(Location location)
e440a328 1119 : Expression(EXPRESSION_SINK, location),
1120 type_(NULL), var_(NULL_TREE)
1121 { }
1122
1123 protected:
4f2138d7 1124 bool
e440a328 1125 do_discarding_value()
4f2138d7 1126 { return true; }
e440a328 1127
1128 Type*
1129 do_type();
1130
1131 void
1132 do_determine_type(const Type_context*);
1133
1134 Expression*
1135 do_copy()
1136 { return new Sink_expression(this->location()); }
1137
1138 tree
1139 do_get_tree(Translate_context*);
1140
d751bb78 1141 void
1142 do_dump_expression(Ast_dump_context*) const;
1143
e440a328 1144 private:
1145 // The type of this sink variable.
1146 Type* type_;
1147 // The temporary variable we generate.
1148 tree var_;
1149};
1150
1151// Return the type of a sink expression.
1152
1153Type*
1154Sink_expression::do_type()
1155{
1156 if (this->type_ == NULL)
1157 return Type::make_sink_type();
1158 return this->type_;
1159}
1160
1161// Determine the type of a sink expression.
1162
1163void
1164Sink_expression::do_determine_type(const Type_context* context)
1165{
1166 if (context->type != NULL)
1167 this->type_ = context->type;
1168}
1169
1170// Return a temporary variable for a sink expression. This will
1171// presumably be a write-only variable which the middle-end will drop.
1172
1173tree
1174Sink_expression::do_get_tree(Translate_context* context)
1175{
1176 if (this->var_ == NULL_TREE)
1177 {
c484d925 1178 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
9f0e0513 1179 Btype* bt = this->type_->get_backend(context->gogo());
1180 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
e440a328 1181 }
1182 return this->var_;
1183}
1184
d751bb78 1185// Ast dump for sink expression.
1186
1187void
1188Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1189{
1190 ast_dump_context->ostream() << "_" ;
1191}
1192
e440a328 1193// Make a sink expression.
1194
1195Expression*
b13c66cd 1196Expression::make_sink(Location location)
e440a328 1197{
1198 return new Sink_expression(location);
1199}
1200
1201// Class Func_expression.
1202
1203// FIXME: Can a function expression appear in a constant expression?
1204// The value is unchanging. Initializing a constant to the address of
1205// a function seems like it could work, though there might be little
1206// point to it.
1207
e440a328 1208// Traversal.
1209
1210int
1211Func_expression::do_traverse(Traverse* traverse)
1212{
1213 return (this->closure_ == NULL
1214 ? TRAVERSE_CONTINUE
1215 : Expression::traverse(&this->closure_, traverse));
1216}
1217
1218// Return the type of a function expression.
1219
1220Type*
1221Func_expression::do_type()
1222{
1223 if (this->function_->is_function())
1224 return this->function_->func_value()->type();
1225 else if (this->function_->is_function_declaration())
1226 return this->function_->func_declaration_value()->type();
1227 else
c3e6f413 1228 go_unreachable();
e440a328 1229}
1230
8381eda7 1231// Get the tree for the code of a function expression.
e440a328 1232
97267c39 1233Bexpression*
8381eda7 1234Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1235{
1236 Function_type* fntype;
8381eda7 1237 if (no->is_function())
1238 fntype = no->func_value()->type();
1239 else if (no->is_function_declaration())
1240 fntype = no->func_declaration_value()->type();
e440a328 1241 else
c3e6f413 1242 go_unreachable();
e440a328 1243
1244 // Builtin functions are handled specially by Call_expression. We
1245 // can't take their address.
1246 if (fntype->is_builtin())
1247 {
8381eda7 1248 error_at(loc,
cb0e02f3 1249 "invalid use of special builtin function %qs; must be called",
8381eda7 1250 no->message_name().c_str());
97267c39 1251 return gogo->backend()->error_expression();
e440a328 1252 }
1253
97267c39 1254 Bfunction* fndecl;
e440a328 1255 if (no->is_function())
cf3cae55 1256 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1257 else if (no->is_function_declaration())
cf3cae55 1258 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1259 else
c3e6f413 1260 go_unreachable();
e440a328 1261
97267c39 1262 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1263}
1264
1265// Get the tree for a function expression. This is used when we take
8381eda7 1266// the address of a function rather than simply calling it. A func
1267// value is represented as a pointer to a block of memory. The first
1268// word of that memory is a pointer to the function code. The
1269// remaining parts of that memory are the addresses of variables that
1270// the function closes over.
e440a328 1271
1272tree
1273Func_expression::do_get_tree(Translate_context* context)
1274{
8381eda7 1275 // If there is no closure, just use the function descriptor.
2010c17a 1276 if (this->closure_ == NULL)
8381eda7 1277 {
1278 Gogo* gogo = context->gogo();
1279 Named_object* no = this->function_;
1280 Expression* descriptor;
1281 if (no->is_function())
1282 descriptor = no->func_value()->descriptor(gogo, no);
1283 else if (no->is_function_declaration())
1284 {
1285 if (no->func_declaration_value()->type()->is_builtin())
1286 {
1287 error_at(this->location(),
1288 ("invalid use of special builtin function %qs; "
1289 "must be called"),
1290 no->message_name().c_str());
1291 return error_mark_node;
1292 }
1293 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1294 }
1295 else
1296 go_unreachable();
2010c17a 1297
8381eda7 1298 tree dtree = descriptor->get_tree(context);
1299 if (dtree == error_mark_node)
1300 return error_mark_node;
1301 return build_fold_addr_expr_loc(this->location().gcc_location(), dtree);
1302 }
e440a328 1303
8381eda7 1304 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1305
8381eda7 1306 // If there is a closure, then the closure is itself the function
1307 // expression. It is a pointer to a struct whose first field points
1308 // to the function code and whose remaining fields are the addresses
1309 // of the closed-over variables.
1310 return this->closure_->get_tree(context);
e440a328 1311}
1312
d751bb78 1313// Ast dump for function.
1314
1315void
1316Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1317{
8b1c301d 1318 ast_dump_context->ostream() << this->function_->name();
1319 if (this->closure_ != NULL)
1320 {
1321 ast_dump_context->ostream() << " {closure = ";
1322 this->closure_->dump_expression(ast_dump_context);
1323 ast_dump_context->ostream() << "}";
1324 }
d751bb78 1325}
1326
e440a328 1327// Make a reference to a function in an expression.
1328
1329Expression*
1330Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1331 Location location)
e440a328 1332{
1333 return new Func_expression(function, closure, location);
1334}
1335
c6837989 1336// Class Func_descriptor_expression.
8381eda7 1337
c6837989 1338// Constructor.
8381eda7 1339
c6837989 1340Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1341 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1342 fn_(fn), dvar_(NULL)
c6837989 1343{
1344 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1345}
8381eda7 1346
c6837989 1347// Traversal.
8381eda7 1348
c6837989 1349int
1350Func_descriptor_expression::do_traverse(Traverse*)
1351{
1352 return TRAVERSE_CONTINUE;
1353}
8381eda7 1354
1355// All function descriptors have the same type.
1356
1357Type* Func_descriptor_expression::descriptor_type;
1358
1359void
1360Func_descriptor_expression::make_func_descriptor_type()
1361{
1362 if (Func_descriptor_expression::descriptor_type != NULL)
1363 return;
1364 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1365 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1366 Func_descriptor_expression::descriptor_type =
1367 Type::make_builtin_named_type("functionDescriptor", struct_type);
1368}
1369
1370Type*
1371Func_descriptor_expression::do_type()
1372{
1373 Func_descriptor_expression::make_func_descriptor_type();
1374 return Func_descriptor_expression::descriptor_type;
1375}
1376
1377// The tree for a function descriptor.
1378
1379tree
1380Func_descriptor_expression::do_get_tree(Translate_context* context)
1381{
1382 if (this->dvar_ != NULL)
1383 return var_to_tree(this->dvar_);
1384
1385 Gogo* gogo = context->gogo();
1386 Named_object* no = this->fn_;
1387 Location loc = no->location();
1388
1389 std::string var_name;
1390 if (no->package() == NULL)
1391 var_name = gogo->pkgpath_symbol();
1392 else
1393 var_name = no->package()->pkgpath_symbol();
1394 var_name.push_back('.');
1395 var_name.append(Gogo::unpack_hidden_name(no->name()));
1396 var_name.append("$descriptor");
1397
1398 Btype* btype = this->type()->get_backend(gogo);
1399
1400 Bvariable* bvar;
1401 if (no->package() != NULL
1402 || Linemap::is_predeclared_location(no->location()))
f8bdf81a 1403 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1404 loc);
8381eda7 1405 else
1406 {
1407 Location bloc = Linemap::predeclared_location();
1408 bool is_hidden = ((no->is_function()
1409 && no->func_value()->enclosing() != NULL)
1410 || Gogo::is_thunk(no));
1411 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1412 btype, bloc);
1413 Expression_list* vals = new Expression_list();
f8bdf81a 1414 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1415 Expression* init =
1416 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1417 Translate_context bcontext(gogo, NULL, NULL, NULL);
1418 bcontext.set_is_const();
1419 Bexpression* binit = tree_to_expr(init->get_tree(&bcontext));
1420 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1421 false, btype, bloc, binit);
1422 }
1423
1424 this->dvar_ = bvar;
1425 return var_to_tree(bvar);
1426}
1427
c6837989 1428// Print a function descriptor expression.
1429
1430void
1431Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1432{
1433 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1434}
1435
8381eda7 1436// Make a function descriptor expression.
1437
c6837989 1438Func_descriptor_expression*
1439Expression::make_func_descriptor(Named_object* fn)
8381eda7 1440{
c6837989 1441 return new Func_descriptor_expression(fn);
8381eda7 1442}
1443
1444// Make the function descriptor type, so that it can be converted.
1445
1446void
1447Expression::make_func_descriptor_type()
1448{
1449 Func_descriptor_expression::make_func_descriptor_type();
1450}
1451
1452// A reference to just the code of a function.
1453
1454class Func_code_reference_expression : public Expression
1455{
1456 public:
1457 Func_code_reference_expression(Named_object* function, Location location)
1458 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1459 function_(function)
1460 { }
1461
1462 protected:
1463 int
1464 do_traverse(Traverse*)
1465 { return TRAVERSE_CONTINUE; }
1466
1467 Type*
1468 do_type()
1469 { return Type::make_pointer_type(Type::make_void_type()); }
1470
1471 void
1472 do_determine_type(const Type_context*)
1473 { }
1474
1475 Expression*
1476 do_copy()
1477 {
1478 return Expression::make_func_code_reference(this->function_,
1479 this->location());
1480 }
1481
1482 tree
1483 do_get_tree(Translate_context*);
1484
1485 void
1486 do_dump_expression(Ast_dump_context* context) const
1487 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1488
1489 private:
1490 // The function.
1491 Named_object* function_;
1492};
1493
1494// Get the tree for a reference to function code.
1495
1496tree
1497Func_code_reference_expression::do_get_tree(Translate_context* context)
1498{
97267c39 1499 Bexpression* ret =
1500 Func_expression::get_code_pointer(context->gogo(), this->function_,
1501 this->location());
1502 return expr_to_tree(ret);
8381eda7 1503}
1504
1505// Make a reference to the code of a function.
1506
1507Expression*
1508Expression::make_func_code_reference(Named_object* function, Location location)
1509{
1510 return new Func_code_reference_expression(function, location);
1511}
1512
e440a328 1513// Class Unknown_expression.
1514
1515// Return the name of an unknown expression.
1516
1517const std::string&
1518Unknown_expression::name() const
1519{
1520 return this->named_object_->name();
1521}
1522
1523// Lower a reference to an unknown name.
1524
1525Expression*
ceeb4318 1526Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1527{
b13c66cd 1528 Location location = this->location();
e440a328 1529 Named_object* no = this->named_object_;
deded542 1530 Named_object* real;
1531 if (!no->is_unknown())
1532 real = no;
1533 else
e440a328 1534 {
deded542 1535 real = no->unknown_value()->real_named_object();
1536 if (real == NULL)
1537 {
1538 if (this->is_composite_literal_key_)
1539 return this;
acf8e158 1540 if (!this->no_error_message_)
1541 error_at(location, "reference to undefined name %qs",
1542 this->named_object_->message_name().c_str());
deded542 1543 return Expression::make_error(location);
1544 }
e440a328 1545 }
1546 switch (real->classification())
1547 {
1548 case Named_object::NAMED_OBJECT_CONST:
1549 return Expression::make_const_reference(real, location);
1550 case Named_object::NAMED_OBJECT_TYPE:
1551 return Expression::make_type(real->type_value(), location);
1552 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1553 if (this->is_composite_literal_key_)
1554 return this;
acf8e158 1555 if (!this->no_error_message_)
1556 error_at(location, "reference to undefined type %qs",
1557 real->message_name().c_str());
e440a328 1558 return Expression::make_error(location);
1559 case Named_object::NAMED_OBJECT_VAR:
7d834090 1560 real->var_value()->set_is_used();
e440a328 1561 return Expression::make_var_reference(real, location);
1562 case Named_object::NAMED_OBJECT_FUNC:
1563 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1564 return Expression::make_func_reference(real, NULL, location);
1565 case Named_object::NAMED_OBJECT_PACKAGE:
1566 if (this->is_composite_literal_key_)
1567 return this;
acf8e158 1568 if (!this->no_error_message_)
1569 error_at(location, "unexpected reference to package");
e440a328 1570 return Expression::make_error(location);
1571 default:
c3e6f413 1572 go_unreachable();
e440a328 1573 }
1574}
1575
d751bb78 1576// Dump the ast representation for an unknown expression to a dump context.
1577
1578void
1579Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1580{
1581 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1582 << ")";
d751bb78 1583}
1584
e440a328 1585// Make a reference to an unknown name.
1586
acf8e158 1587Unknown_expression*
b13c66cd 1588Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1589{
e440a328 1590 return new Unknown_expression(no, location);
1591}
1592
1593// A boolean expression.
1594
1595class Boolean_expression : public Expression
1596{
1597 public:
b13c66cd 1598 Boolean_expression(bool val, Location location)
e440a328 1599 : Expression(EXPRESSION_BOOLEAN, location),
1600 val_(val), type_(NULL)
1601 { }
1602
1603 static Expression*
1604 do_import(Import*);
1605
1606 protected:
1607 bool
1608 do_is_constant() const
1609 { return true; }
1610
1611 Type*
1612 do_type();
1613
1614 void
1615 do_determine_type(const Type_context*);
1616
1617 Expression*
1618 do_copy()
1619 { return this; }
1620
1621 tree
1622 do_get_tree(Translate_context*)
1623 { return this->val_ ? boolean_true_node : boolean_false_node; }
1624
1625 void
1626 do_export(Export* exp) const
1627 { exp->write_c_string(this->val_ ? "true" : "false"); }
1628
d751bb78 1629 void
1630 do_dump_expression(Ast_dump_context* ast_dump_context) const
1631 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1632
e440a328 1633 private:
1634 // The constant.
1635 bool val_;
1636 // The type as determined by context.
1637 Type* type_;
1638};
1639
1640// Get the type.
1641
1642Type*
1643Boolean_expression::do_type()
1644{
1645 if (this->type_ == NULL)
1646 this->type_ = Type::make_boolean_type();
1647 return this->type_;
1648}
1649
1650// Set the type from the context.
1651
1652void
1653Boolean_expression::do_determine_type(const Type_context* context)
1654{
1655 if (this->type_ != NULL && !this->type_->is_abstract())
1656 ;
1657 else if (context->type != NULL && context->type->is_boolean_type())
1658 this->type_ = context->type;
1659 else if (!context->may_be_abstract)
1660 this->type_ = Type::lookup_bool_type();
1661}
1662
1663// Import a boolean constant.
1664
1665Expression*
1666Boolean_expression::do_import(Import* imp)
1667{
1668 if (imp->peek_char() == 't')
1669 {
1670 imp->require_c_string("true");
1671 return Expression::make_boolean(true, imp->location());
1672 }
1673 else
1674 {
1675 imp->require_c_string("false");
1676 return Expression::make_boolean(false, imp->location());
1677 }
1678}
1679
1680// Make a boolean expression.
1681
1682Expression*
b13c66cd 1683Expression::make_boolean(bool val, Location location)
e440a328 1684{
1685 return new Boolean_expression(val, location);
1686}
1687
1688// Class String_expression.
1689
1690// Get the type.
1691
1692Type*
1693String_expression::do_type()
1694{
1695 if (this->type_ == NULL)
1696 this->type_ = Type::make_string_type();
1697 return this->type_;
1698}
1699
1700// Set the type from the context.
1701
1702void
1703String_expression::do_determine_type(const Type_context* context)
1704{
1705 if (this->type_ != NULL && !this->type_->is_abstract())
1706 ;
1707 else if (context->type != NULL && context->type->is_string_type())
1708 this->type_ = context->type;
1709 else if (!context->may_be_abstract)
1710 this->type_ = Type::lookup_string_type();
1711}
1712
1713// Build a string constant.
1714
1715tree
1716String_expression::do_get_tree(Translate_context* context)
1717{
1718 return context->gogo()->go_string_constant_tree(this->val_);
1719}
1720
8b1c301d 1721 // Write string literal to string dump.
e440a328 1722
1723void
8b1c301d 1724String_expression::export_string(String_dump* exp,
1725 const String_expression* str)
e440a328 1726{
1727 std::string s;
8b1c301d 1728 s.reserve(str->val_.length() * 4 + 2);
e440a328 1729 s += '"';
8b1c301d 1730 for (std::string::const_iterator p = str->val_.begin();
1731 p != str->val_.end();
e440a328 1732 ++p)
1733 {
1734 if (*p == '\\' || *p == '"')
1735 {
1736 s += '\\';
1737 s += *p;
1738 }
1739 else if (*p >= 0x20 && *p < 0x7f)
1740 s += *p;
1741 else if (*p == '\n')
1742 s += "\\n";
1743 else if (*p == '\t')
1744 s += "\\t";
1745 else
1746 {
1747 s += "\\x";
1748 unsigned char c = *p;
1749 unsigned int dig = c >> 4;
1750 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1751 dig = c & 0xf;
1752 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1753 }
1754 }
1755 s += '"';
1756 exp->write_string(s);
1757}
1758
8b1c301d 1759// Export a string expression.
1760
1761void
1762String_expression::do_export(Export* exp) const
1763{
1764 String_expression::export_string(exp, this);
1765}
1766
e440a328 1767// Import a string expression.
1768
1769Expression*
1770String_expression::do_import(Import* imp)
1771{
1772 imp->require_c_string("\"");
1773 std::string val;
1774 while (true)
1775 {
1776 int c = imp->get_char();
1777 if (c == '"' || c == -1)
1778 break;
1779 if (c != '\\')
1780 val += static_cast<char>(c);
1781 else
1782 {
1783 c = imp->get_char();
1784 if (c == '\\' || c == '"')
1785 val += static_cast<char>(c);
1786 else if (c == 'n')
1787 val += '\n';
1788 else if (c == 't')
1789 val += '\t';
1790 else if (c == 'x')
1791 {
1792 c = imp->get_char();
1793 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1794 c = imp->get_char();
1795 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1796 char v = (vh << 4) | vl;
1797 val += v;
1798 }
1799 else
1800 {
1801 error_at(imp->location(), "bad string constant");
1802 return Expression::make_error(imp->location());
1803 }
1804 }
1805 }
1806 return Expression::make_string(val, imp->location());
1807}
1808
d751bb78 1809// Ast dump for string expression.
1810
1811void
1812String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1813{
8b1c301d 1814 String_expression::export_string(ast_dump_context, this);
d751bb78 1815}
1816
e440a328 1817// Make a string expression.
1818
1819Expression*
b13c66cd 1820Expression::make_string(const std::string& val, Location location)
e440a328 1821{
1822 return new String_expression(val, location);
1823}
1824
1825// Make an integer expression.
1826
1827class Integer_expression : public Expression
1828{
1829 public:
5d4b8566 1830 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1831 Location location)
e440a328 1832 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1833 type_(type), is_character_constant_(is_character_constant)
e440a328 1834 { mpz_init_set(this->val_, *val); }
1835
1836 static Expression*
1837 do_import(Import*);
1838
8b1c301d 1839 // Write VAL to string dump.
e440a328 1840 static void
8b1c301d 1841 export_integer(String_dump* exp, const mpz_t val);
e440a328 1842
d751bb78 1843 // Write VAL to dump context.
1844 static void
1845 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1846
e440a328 1847 protected:
1848 bool
1849 do_is_constant() const
1850 { return true; }
1851
1852 bool
0c77715b 1853 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1854
1855 Type*
1856 do_type();
1857
1858 void
1859 do_determine_type(const Type_context* context);
1860
1861 void
1862 do_check_types(Gogo*);
1863
1864 tree
1865 do_get_tree(Translate_context*);
1866
1867 Expression*
1868 do_copy()
5d4b8566 1869 {
1870 if (this->is_character_constant_)
1871 return Expression::make_character(&this->val_, this->type_,
1872 this->location());
1873 else
1874 return Expression::make_integer(&this->val_, this->type_,
1875 this->location());
1876 }
e440a328 1877
1878 void
1879 do_export(Export*) const;
1880
d751bb78 1881 void
1882 do_dump_expression(Ast_dump_context*) const;
1883
e440a328 1884 private:
1885 // The integer value.
1886 mpz_t val_;
1887 // The type so far.
1888 Type* type_;
5d4b8566 1889 // Whether this is a character constant.
1890 bool is_character_constant_;
e440a328 1891};
1892
0c77715b 1893// Return a numeric constant for this expression. We have to mark
1894// this as a character when appropriate.
e440a328 1895
1896bool
0c77715b 1897Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1898{
0c77715b 1899 if (this->is_character_constant_)
1900 nc->set_rune(this->type_, this->val_);
1901 else
1902 nc->set_int(this->type_, this->val_);
e440a328 1903 return true;
1904}
1905
1906// Return the current type. If we haven't set the type yet, we return
1907// an abstract integer type.
1908
1909Type*
1910Integer_expression::do_type()
1911{
1912 if (this->type_ == NULL)
5d4b8566 1913 {
1914 if (this->is_character_constant_)
1915 this->type_ = Type::make_abstract_character_type();
1916 else
1917 this->type_ = Type::make_abstract_integer_type();
1918 }
e440a328 1919 return this->type_;
1920}
1921
1922// Set the type of the integer value. Here we may switch from an
1923// abstract type to a real type.
1924
1925void
1926Integer_expression::do_determine_type(const Type_context* context)
1927{
1928 if (this->type_ != NULL && !this->type_->is_abstract())
1929 ;
0c77715b 1930 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1931 this->type_ = context->type;
1932 else if (!context->may_be_abstract)
5d4b8566 1933 {
1934 if (this->is_character_constant_)
1935 this->type_ = Type::lookup_integer_type("int32");
1936 else
1937 this->type_ = Type::lookup_integer_type("int");
1938 }
e440a328 1939}
1940
e440a328 1941// Check the type of an integer constant.
1942
1943void
1944Integer_expression::do_check_types(Gogo*)
1945{
0c77715b 1946 Type* type = this->type_;
1947 if (type == NULL)
e440a328 1948 return;
0c77715b 1949 Numeric_constant nc;
1950 if (this->is_character_constant_)
1951 nc.set_rune(NULL, this->val_);
1952 else
1953 nc.set_int(NULL, this->val_);
1954 if (!nc.set_type(type, true, this->location()))
e440a328 1955 this->set_is_error();
1956}
1957
1958// Get a tree for an integer constant.
1959
1960tree
1961Integer_expression::do_get_tree(Translate_context* context)
1962{
48c2a53a 1963 Type* resolved_type = NULL;
e440a328 1964 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 1965 resolved_type = this->type_;
e440a328 1966 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1967 {
1968 // We are converting to an abstract floating point type.
48c2a53a 1969 resolved_type = Type::lookup_float_type("float64");
e440a328 1970 }
1971 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1972 {
1973 // We are converting to an abstract complex type.
48c2a53a 1974 resolved_type = Type::lookup_complex_type("complex128");
e440a328 1975 }
1976 else
1977 {
1978 // If we still have an abstract type here, then this is being
1979 // used in a constant expression which didn't get reduced for
1980 // some reason. Use a type which will fit the value. We use <,
1981 // not <=, because we need an extra bit for the sign bit.
1982 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 1983 Type* int_type = Type::lookup_integer_type("int");
1984 if (bits < int_type->integer_type()->bits())
48c2a53a 1985 resolved_type = int_type;
e440a328 1986 else if (bits < 64)
48c2a53a 1987 resolved_type = Type::lookup_integer_type("int64");
e440a328 1988 else
48c2a53a 1989 {
1990 if (!saw_errors())
1991 error_at(this->location(),
1992 "unknown type for large integer constant");
1993 Bexpression* ret = context->gogo()->backend()->error_expression();
1994 return expr_to_tree(ret);
1995 }
e440a328 1996 }
48c2a53a 1997 Numeric_constant nc;
1998 nc.set_int(resolved_type, this->val_);
1999 Bexpression* ret =
2000 Expression::backend_numeric_constant_expression(context, &nc);
2001 return expr_to_tree(ret);
e440a328 2002}
2003
2004// Write VAL to export data.
2005
2006void
8b1c301d 2007Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 2008{
2009 char* s = mpz_get_str(NULL, 10, val);
2010 exp->write_c_string(s);
2011 free(s);
2012}
2013
2014// Export an integer in a constant expression.
2015
2016void
2017Integer_expression::do_export(Export* exp) const
2018{
2019 Integer_expression::export_integer(exp, this->val_);
5d4b8566 2020 if (this->is_character_constant_)
2021 exp->write_c_string("'");
e440a328 2022 // A trailing space lets us reliably identify the end of the number.
2023 exp->write_c_string(" ");
2024}
2025
2026// Import an integer, floating point, or complex value. This handles
2027// all these types because they all start with digits.
2028
2029Expression*
2030Integer_expression::do_import(Import* imp)
2031{
2032 std::string num = imp->read_identifier();
2033 imp->require_c_string(" ");
2034 if (!num.empty() && num[num.length() - 1] == 'i')
2035 {
2036 mpfr_t real;
2037 size_t plus_pos = num.find('+', 1);
2038 size_t minus_pos = num.find('-', 1);
2039 size_t pos;
2040 if (plus_pos == std::string::npos)
2041 pos = minus_pos;
2042 else if (minus_pos == std::string::npos)
2043 pos = plus_pos;
2044 else
2045 {
2046 error_at(imp->location(), "bad number in import data: %qs",
2047 num.c_str());
2048 return Expression::make_error(imp->location());
2049 }
2050 if (pos == std::string::npos)
2051 mpfr_set_ui(real, 0, GMP_RNDN);
2052 else
2053 {
2054 std::string real_str = num.substr(0, pos);
2055 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2056 {
2057 error_at(imp->location(), "bad number in import data: %qs",
2058 real_str.c_str());
2059 return Expression::make_error(imp->location());
2060 }
2061 }
2062
2063 std::string imag_str;
2064 if (pos == std::string::npos)
2065 imag_str = num;
2066 else
2067 imag_str = num.substr(pos);
2068 imag_str = imag_str.substr(0, imag_str.size() - 1);
2069 mpfr_t imag;
2070 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2071 {
2072 error_at(imp->location(), "bad number in import data: %qs",
2073 imag_str.c_str());
2074 return Expression::make_error(imp->location());
2075 }
2076 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2077 imp->location());
2078 mpfr_clear(real);
2079 mpfr_clear(imag);
2080 return ret;
2081 }
2082 else if (num.find('.') == std::string::npos
2083 && num.find('E') == std::string::npos)
2084 {
5d4b8566 2085 bool is_character_constant = (!num.empty()
2086 && num[num.length() - 1] == '\'');
2087 if (is_character_constant)
2088 num = num.substr(0, num.length() - 1);
e440a328 2089 mpz_t val;
2090 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2091 {
2092 error_at(imp->location(), "bad number in import data: %qs",
2093 num.c_str());
2094 return Expression::make_error(imp->location());
2095 }
5d4b8566 2096 Expression* ret;
2097 if (is_character_constant)
2098 ret = Expression::make_character(&val, NULL, imp->location());
2099 else
2100 ret = Expression::make_integer(&val, NULL, imp->location());
e440a328 2101 mpz_clear(val);
2102 return ret;
2103 }
2104 else
2105 {
2106 mpfr_t val;
2107 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2108 {
2109 error_at(imp->location(), "bad number in import data: %qs",
2110 num.c_str());
2111 return Expression::make_error(imp->location());
2112 }
2113 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2114 mpfr_clear(val);
2115 return ret;
2116 }
2117}
d751bb78 2118// Ast dump for integer expression.
2119
2120void
2121Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2122{
5d4b8566 2123 if (this->is_character_constant_)
2124 ast_dump_context->ostream() << '\'';
8b1c301d 2125 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2126 if (this->is_character_constant_)
2127 ast_dump_context->ostream() << '\'';
d751bb78 2128}
2129
e440a328 2130// Build a new integer value.
2131
2132Expression*
5d4b8566 2133Expression::make_integer(const mpz_t* val, Type* type, Location location)
2134{
2135 return new Integer_expression(val, type, false, location);
2136}
2137
2138// Build a new character constant value.
2139
2140Expression*
2141Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2142{
5d4b8566 2143 return new Integer_expression(val, type, true, location);
e440a328 2144}
2145
2146// Floats.
2147
2148class Float_expression : public Expression
2149{
2150 public:
b13c66cd 2151 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2152 : Expression(EXPRESSION_FLOAT, location),
2153 type_(type)
2154 {
2155 mpfr_init_set(this->val_, *val, GMP_RNDN);
2156 }
2157
e440a328 2158 // Write VAL to export data.
2159 static void
8b1c301d 2160 export_float(String_dump* exp, const mpfr_t val);
2161
d751bb78 2162 // Write VAL to dump file.
2163 static void
2164 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2165
2166 protected:
2167 bool
2168 do_is_constant() const
2169 { return true; }
2170
2171 bool
0c77715b 2172 do_numeric_constant_value(Numeric_constant* nc) const
2173 {
2174 nc->set_float(this->type_, this->val_);
2175 return true;
2176 }
e440a328 2177
2178 Type*
2179 do_type();
2180
2181 void
2182 do_determine_type(const Type_context*);
2183
2184 void
2185 do_check_types(Gogo*);
2186
2187 Expression*
2188 do_copy()
2189 { return Expression::make_float(&this->val_, this->type_,
2190 this->location()); }
2191
2192 tree
2193 do_get_tree(Translate_context*);
2194
2195 void
2196 do_export(Export*) const;
2197
d751bb78 2198 void
2199 do_dump_expression(Ast_dump_context*) const;
2200
e440a328 2201 private:
2202 // The floating point value.
2203 mpfr_t val_;
2204 // The type so far.
2205 Type* type_;
2206};
2207
e440a328 2208// Return the current type. If we haven't set the type yet, we return
2209// an abstract float type.
2210
2211Type*
2212Float_expression::do_type()
2213{
2214 if (this->type_ == NULL)
2215 this->type_ = Type::make_abstract_float_type();
2216 return this->type_;
2217}
2218
2219// Set the type of the float value. Here we may switch from an
2220// abstract type to a real type.
2221
2222void
2223Float_expression::do_determine_type(const Type_context* context)
2224{
2225 if (this->type_ != NULL && !this->type_->is_abstract())
2226 ;
2227 else if (context->type != NULL
2228 && (context->type->integer_type() != NULL
2229 || context->type->float_type() != NULL
2230 || context->type->complex_type() != NULL))
2231 this->type_ = context->type;
2232 else if (!context->may_be_abstract)
48080209 2233 this->type_ = Type::lookup_float_type("float64");
e440a328 2234}
2235
e440a328 2236// Check the type of a float value.
2237
2238void
2239Float_expression::do_check_types(Gogo*)
2240{
0c77715b 2241 Type* type = this->type_;
2242 if (type == NULL)
e440a328 2243 return;
0c77715b 2244 Numeric_constant nc;
2245 nc.set_float(NULL, this->val_);
2246 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2247 this->set_is_error();
e440a328 2248}
2249
2250// Get a tree for a float constant.
2251
2252tree
2253Float_expression::do_get_tree(Translate_context* context)
2254{
48c2a53a 2255 Type* resolved_type;
e440a328 2256 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2257 resolved_type = this->type_;
e440a328 2258 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2259 {
2260 // We have an abstract integer type. We just hope for the best.
48c2a53a 2261 resolved_type = Type::lookup_integer_type("int");
2262 }
2263 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2264 {
2265 // We are converting to an abstract complex type.
2266 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2267 }
2268 else
2269 {
2270 // If we still have an abstract type here, then this is being
2271 // used in a constant expression which didn't get reduced. We
2272 // just use float64 and hope for the best.
48c2a53a 2273 resolved_type = Type::lookup_float_type("float64");
e440a328 2274 }
48c2a53a 2275
2276 Numeric_constant nc;
2277 nc.set_float(resolved_type, this->val_);
2278 Bexpression* ret =
2279 Expression::backend_numeric_constant_expression(context, &nc);
2280 return expr_to_tree(ret);
e440a328 2281}
2282
8b1c301d 2283// Write a floating point number to a string dump.
e440a328 2284
2285void
8b1c301d 2286Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2287{
2288 mp_exp_t exponent;
2289 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2290 if (*s == '-')
2291 exp->write_c_string("-");
2292 exp->write_c_string("0.");
2293 exp->write_c_string(*s == '-' ? s + 1 : s);
2294 mpfr_free_str(s);
2295 char buf[30];
2296 snprintf(buf, sizeof buf, "E%ld", exponent);
2297 exp->write_c_string(buf);
2298}
2299
2300// Export a floating point number in a constant expression.
2301
2302void
2303Float_expression::do_export(Export* exp) const
2304{
2305 Float_expression::export_float(exp, this->val_);
2306 // A trailing space lets us reliably identify the end of the number.
2307 exp->write_c_string(" ");
2308}
2309
d751bb78 2310// Dump a floating point number to the dump file.
2311
2312void
2313Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2314{
8b1c301d 2315 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2316}
2317
e440a328 2318// Make a float expression.
2319
2320Expression*
b13c66cd 2321Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2322{
2323 return new Float_expression(val, type, location);
2324}
2325
2326// Complex numbers.
2327
2328class Complex_expression : public Expression
2329{
2330 public:
2331 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
b13c66cd 2332 Location location)
e440a328 2333 : Expression(EXPRESSION_COMPLEX, location),
2334 type_(type)
2335 {
2336 mpfr_init_set(this->real_, *real, GMP_RNDN);
2337 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2338 }
2339
8b1c301d 2340 // Write REAL/IMAG to string dump.
e440a328 2341 static void
8b1c301d 2342 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
e440a328 2343
d751bb78 2344 // Write REAL/IMAG to dump context.
2345 static void
2346 dump_complex(Ast_dump_context* ast_dump_context,
2347 const mpfr_t real, const mpfr_t val);
2348
e440a328 2349 protected:
2350 bool
2351 do_is_constant() const
2352 { return true; }
2353
2354 bool
0c77715b 2355 do_numeric_constant_value(Numeric_constant* nc) const
2356 {
2357 nc->set_complex(this->type_, this->real_, this->imag_);
2358 return true;
2359 }
e440a328 2360
2361 Type*
2362 do_type();
2363
2364 void
2365 do_determine_type(const Type_context*);
2366
2367 void
2368 do_check_types(Gogo*);
2369
2370 Expression*
2371 do_copy()
2372 {
2373 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2374 this->location());
2375 }
2376
2377 tree
2378 do_get_tree(Translate_context*);
2379
2380 void
2381 do_export(Export*) const;
2382
d751bb78 2383 void
2384 do_dump_expression(Ast_dump_context*) const;
2385
e440a328 2386 private:
2387 // The real part.
2388 mpfr_t real_;
2389 // The imaginary part;
2390 mpfr_t imag_;
2391 // The type if known.
2392 Type* type_;
2393};
2394
e440a328 2395// Return the current type. If we haven't set the type yet, we return
2396// an abstract complex type.
2397
2398Type*
2399Complex_expression::do_type()
2400{
2401 if (this->type_ == NULL)
2402 this->type_ = Type::make_abstract_complex_type();
2403 return this->type_;
2404}
2405
2406// Set the type of the complex value. Here we may switch from an
2407// abstract type to a real type.
2408
2409void
2410Complex_expression::do_determine_type(const Type_context* context)
2411{
2412 if (this->type_ != NULL && !this->type_->is_abstract())
2413 ;
2414 else if (context->type != NULL
2415 && context->type->complex_type() != NULL)
2416 this->type_ = context->type;
2417 else if (!context->may_be_abstract)
48080209 2418 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2419}
2420
e440a328 2421// Check the type of a complex value.
2422
2423void
2424Complex_expression::do_check_types(Gogo*)
2425{
0c77715b 2426 Type* type = this->type_;
2427 if (type == NULL)
e440a328 2428 return;
0c77715b 2429 Numeric_constant nc;
2430 nc.set_complex(NULL, this->real_, this->imag_);
2431 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2432 this->set_is_error();
2433}
2434
2435// Get a tree for a complex constant.
2436
2437tree
2438Complex_expression::do_get_tree(Translate_context* context)
2439{
48c2a53a 2440 Type* resolved_type;
e440a328 2441 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2442 resolved_type = this->type_;
2443 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2444 {
2445 // We are converting to an abstract integer type.
2446 resolved_type = Type::lookup_integer_type("int");
2447 }
2448 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2449 {
2450 // We are converting to an abstract float type.
2451 resolved_type = Type::lookup_float_type("float64");
2452 }
e440a328 2453 else
2454 {
2455 // If we still have an abstract type here, this this is being
2456 // used in a constant expression which didn't get reduced. We
2457 // just use complex128 and hope for the best.
48c2a53a 2458 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2459 }
48c2a53a 2460
2461 Numeric_constant nc;
2462 nc.set_complex(resolved_type, this->real_, this->imag_);
2463 Bexpression* ret =
2464 Expression::backend_numeric_constant_expression(context, &nc);
2465 return expr_to_tree(ret);
e440a328 2466}
2467
2468// Write REAL/IMAG to export data.
2469
2470void
8b1c301d 2471Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
e440a328 2472 const mpfr_t imag)
2473{
2474 if (!mpfr_zero_p(real))
2475 {
2476 Float_expression::export_float(exp, real);
2477 if (mpfr_sgn(imag) > 0)
2478 exp->write_c_string("+");
2479 }
2480 Float_expression::export_float(exp, imag);
2481 exp->write_c_string("i");
2482}
2483
2484// Export a complex number in a constant expression.
2485
2486void
2487Complex_expression::do_export(Export* exp) const
2488{
2489 Complex_expression::export_complex(exp, this->real_, this->imag_);
2490 // A trailing space lets us reliably identify the end of the number.
2491 exp->write_c_string(" ");
2492}
2493
d751bb78 2494// Dump a complex expression to the dump file.
2495
2496void
2497Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2498{
8b1c301d 2499 Complex_expression::export_complex(ast_dump_context,
d751bb78 2500 this->real_,
2501 this->imag_);
2502}
2503
e440a328 2504// Make a complex expression.
2505
2506Expression*
2507Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
b13c66cd 2508 Location location)
e440a328 2509{
2510 return new Complex_expression(real, imag, type, location);
2511}
2512
d5b605df 2513// Find a named object in an expression.
2514
2515class Find_named_object : public Traverse
2516{
2517 public:
2518 Find_named_object(Named_object* no)
2519 : Traverse(traverse_expressions),
2520 no_(no), found_(false)
2521 { }
2522
2523 // Whether we found the object.
2524 bool
2525 found() const
2526 { return this->found_; }
2527
2528 protected:
2529 int
2530 expression(Expression**);
2531
2532 private:
2533 // The object we are looking for.
2534 Named_object* no_;
2535 // Whether we found it.
2536 bool found_;
2537};
2538
e440a328 2539// A reference to a const in an expression.
2540
2541class Const_expression : public Expression
2542{
2543 public:
b13c66cd 2544 Const_expression(Named_object* constant, Location location)
e440a328 2545 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2546 constant_(constant), type_(NULL), seen_(false)
e440a328 2547 { }
2548
d5b605df 2549 Named_object*
2550 named_object()
2551 { return this->constant_; }
2552
a7f064d5 2553 // Check that the initializer does not refer to the constant itself.
2554 void
2555 check_for_init_loop();
2556
e440a328 2557 protected:
ba4aedd4 2558 int
2559 do_traverse(Traverse*);
2560
e440a328 2561 Expression*
ceeb4318 2562 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2563
2564 bool
2565 do_is_constant() const
2566 { return true; }
2567
2568 bool
0c77715b 2569 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2570
2571 bool
af6b489a 2572 do_string_constant_value(std::string* val) const;
e440a328 2573
2574 Type*
2575 do_type();
2576
2577 // The type of a const is set by the declaration, not the use.
2578 void
2579 do_determine_type(const Type_context*);
2580
2581 void
2582 do_check_types(Gogo*);
2583
2584 Expression*
2585 do_copy()
2586 { return this; }
2587
2588 tree
2589 do_get_tree(Translate_context* context);
2590
2591 // When exporting a reference to a const as part of a const
2592 // expression, we export the value. We ignore the fact that it has
2593 // a name.
2594 void
2595 do_export(Export* exp) const
2596 { this->constant_->const_value()->expr()->export_expression(exp); }
2597
d751bb78 2598 void
2599 do_dump_expression(Ast_dump_context*) const;
2600
e440a328 2601 private:
2602 // The constant.
2603 Named_object* constant_;
2604 // The type of this reference. This is used if the constant has an
2605 // abstract type.
2606 Type* type_;
13e818f5 2607 // Used to prevent infinite recursion when a constant incorrectly
2608 // refers to itself.
2609 mutable bool seen_;
e440a328 2610};
2611
ba4aedd4 2612// Traversal.
2613
2614int
2615Const_expression::do_traverse(Traverse* traverse)
2616{
2617 if (this->type_ != NULL)
2618 return Type::traverse(this->type_, traverse);
2619 return TRAVERSE_CONTINUE;
2620}
2621
e440a328 2622// Lower a constant expression. This is where we convert the
2623// predeclared constant iota into an integer value.
2624
2625Expression*
ceeb4318 2626Const_expression::do_lower(Gogo* gogo, Named_object*,
2627 Statement_inserter*, int iota_value)
e440a328 2628{
2629 if (this->constant_->const_value()->expr()->classification()
2630 == EXPRESSION_IOTA)
2631 {
2632 if (iota_value == -1)
2633 {
2634 error_at(this->location(),
2635 "iota is only defined in const declarations");
2636 iota_value = 0;
2637 }
2638 mpz_t val;
2639 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2640 Expression* ret = Expression::make_integer(&val, NULL,
2641 this->location());
2642 mpz_clear(val);
2643 return ret;
2644 }
2645
2646 // Make sure that the constant itself has been lowered.
2647 gogo->lower_constant(this->constant_);
2648
2649 return this;
2650}
2651
0c77715b 2652// Return a numeric constant value.
e440a328 2653
2654bool
0c77715b 2655Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2656{
13e818f5 2657 if (this->seen_)
2658 return false;
2659
e440a328 2660 Expression* e = this->constant_->const_value()->expr();
0c77715b 2661
13e818f5 2662 this->seen_ = true;
2663
0c77715b 2664 bool r = e->numeric_constant_value(nc);
e440a328 2665
13e818f5 2666 this->seen_ = false;
2667
e440a328 2668 Type* ctype;
2669 if (this->type_ != NULL)
2670 ctype = this->type_;
2671 else
2672 ctype = this->constant_->const_value()->type();
e440a328 2673 if (r && ctype != NULL)
2674 {
0c77715b 2675 if (!nc->set_type(ctype, false, this->location()))
e440a328 2676 return false;
e440a328 2677 }
e440a328 2678
e440a328 2679 return r;
2680}
2681
af6b489a 2682bool
2683Const_expression::do_string_constant_value(std::string* val) const
2684{
2685 if (this->seen_)
2686 return false;
2687
2688 Expression* e = this->constant_->const_value()->expr();
2689
2690 this->seen_ = true;
2691 bool ok = e->string_constant_value(val);
2692 this->seen_ = false;
2693
2694 return ok;
2695}
2696
e440a328 2697// Return the type of the const reference.
2698
2699Type*
2700Const_expression::do_type()
2701{
2702 if (this->type_ != NULL)
2703 return this->type_;
13e818f5 2704
2f78f012 2705 Named_constant* nc = this->constant_->const_value();
2706
2707 if (this->seen_ || nc->lowering())
13e818f5 2708 {
2709 this->report_error(_("constant refers to itself"));
2710 this->type_ = Type::make_error_type();
2711 return this->type_;
2712 }
2713
2714 this->seen_ = true;
2715
e440a328 2716 Type* ret = nc->type();
13e818f5 2717
e440a328 2718 if (ret != NULL)
13e818f5 2719 {
2720 this->seen_ = false;
2721 return ret;
2722 }
2723
e440a328 2724 // During parsing, a named constant may have a NULL type, but we
2725 // must not return a NULL type here.
13e818f5 2726 ret = nc->expr()->type();
2727
2728 this->seen_ = false;
2729
2730 return ret;
e440a328 2731}
2732
2733// Set the type of the const reference.
2734
2735void
2736Const_expression::do_determine_type(const Type_context* context)
2737{
2738 Type* ctype = this->constant_->const_value()->type();
2739 Type* cetype = (ctype != NULL
2740 ? ctype
2741 : this->constant_->const_value()->expr()->type());
2742 if (ctype != NULL && !ctype->is_abstract())
2743 ;
2744 else if (context->type != NULL
0c77715b 2745 && context->type->is_numeric_type()
2746 && cetype->is_numeric_type())
e440a328 2747 this->type_ = context->type;
2748 else if (context->type != NULL
2749 && context->type->is_string_type()
2750 && cetype->is_string_type())
2751 this->type_ = context->type;
2752 else if (context->type != NULL
2753 && context->type->is_boolean_type()
2754 && cetype->is_boolean_type())
2755 this->type_ = context->type;
2756 else if (!context->may_be_abstract)
2757 {
2758 if (cetype->is_abstract())
2759 cetype = cetype->make_non_abstract_type();
2760 this->type_ = cetype;
2761 }
2762}
2763
a7f064d5 2764// Check for a loop in which the initializer of a constant refers to
2765// the constant itself.
e440a328 2766
2767void
a7f064d5 2768Const_expression::check_for_init_loop()
e440a328 2769{
5c13bd80 2770 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2771 return;
2772
a7f064d5 2773 if (this->seen_)
2774 {
2775 this->report_error(_("constant refers to itself"));
2776 this->type_ = Type::make_error_type();
2777 return;
2778 }
2779
d5b605df 2780 Expression* init = this->constant_->const_value()->expr();
2781 Find_named_object find_named_object(this->constant_);
a7f064d5 2782
2783 this->seen_ = true;
d5b605df 2784 Expression::traverse(&init, &find_named_object);
a7f064d5 2785 this->seen_ = false;
2786
d5b605df 2787 if (find_named_object.found())
2788 {
5c13bd80 2789 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2790 {
2791 this->report_error(_("constant refers to itself"));
2792 this->type_ = Type::make_error_type();
2793 }
d5b605df 2794 return;
2795 }
a7f064d5 2796}
2797
2798// Check types of a const reference.
2799
2800void
2801Const_expression::do_check_types(Gogo*)
2802{
5c13bd80 2803 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2804 return;
2805
2806 this->check_for_init_loop();
d5b605df 2807
0c77715b 2808 // Check that numeric constant fits in type.
2809 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2810 {
0c77715b 2811 Numeric_constant nc;
2812 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2813 {
0c77715b 2814 if (!nc.set_type(this->type_, true, this->location()))
2815 this->set_is_error();
e440a328 2816 }
e440a328 2817 }
2818}
2819
2820// Return a tree for the const reference.
2821
2822tree
2823Const_expression::do_get_tree(Translate_context* context)
2824{
2825 Gogo* gogo = context->gogo();
2826 tree type_tree;
2827 if (this->type_ == NULL)
2828 type_tree = NULL_TREE;
2829 else
2830 {
9f0e0513 2831 type_tree = type_to_tree(this->type_->get_backend(gogo));
e440a328 2832 if (type_tree == error_mark_node)
2833 return error_mark_node;
2834 }
2835
2836 // If the type has been set for this expression, but the underlying
2837 // object is an abstract int or float, we try to get the abstract
2838 // value. Otherwise we may lose something in the conversion.
2839 if (this->type_ != NULL
0c77715b 2840 && this->type_->is_numeric_type()
a68492b4 2841 && (this->constant_->const_value()->type() == NULL
2842 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2843 {
2844 Expression* expr = this->constant_->const_value()->expr();
0c77715b 2845 Numeric_constant nc;
2846 if (expr->numeric_constant_value(&nc)
2847 && nc.set_type(this->type_, false, this->location()))
e440a328 2848 {
0c77715b 2849 Expression* e = nc.expression(this->location());
2850 return e->get_tree(context);
e440a328 2851 }
e440a328 2852 }
2853
2854 tree const_tree = this->constant_->get_tree(gogo, context->function());
2855 if (this->type_ == NULL
2856 || const_tree == error_mark_node
2857 || TREE_TYPE(const_tree) == error_mark_node)
2858 return const_tree;
2859
2860 tree ret;
2861 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2862 ret = fold_convert(type_tree, const_tree);
2863 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2864 ret = fold(convert_to_integer(type_tree, const_tree));
2865 else if (TREE_CODE(type_tree) == REAL_TYPE)
2866 ret = fold(convert_to_real(type_tree, const_tree));
2867 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2868 ret = fold(convert_to_complex(type_tree, const_tree));
2869 else
c3e6f413 2870 go_unreachable();
e440a328 2871 return ret;
2872}
2873
d751bb78 2874// Dump ast representation for constant expression.
2875
2876void
2877Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2878{
2879 ast_dump_context->ostream() << this->constant_->name();
2880}
2881
e440a328 2882// Make a reference to a constant in an expression.
2883
2884Expression*
2885Expression::make_const_reference(Named_object* constant,
b13c66cd 2886 Location location)
e440a328 2887{
2888 return new Const_expression(constant, location);
2889}
2890
d5b605df 2891// Find a named object in an expression.
2892
2893int
2894Find_named_object::expression(Expression** pexpr)
2895{
2896 switch ((*pexpr)->classification())
2897 {
2898 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 2899 {
2900 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2901 if (ce->named_object() == this->no_)
2902 break;
2903
2904 // We need to check a constant initializer explicitly, as
2905 // loops here will not be caught by the loop checking for
2906 // variable initializers.
2907 ce->check_for_init_loop();
2908
2909 return TRAVERSE_CONTINUE;
2910 }
2911
d5b605df 2912 case Expression::EXPRESSION_VAR_REFERENCE:
2913 if ((*pexpr)->var_expression()->named_object() == this->no_)
2914 break;
2915 return TRAVERSE_CONTINUE;
2916 case Expression::EXPRESSION_FUNC_REFERENCE:
2917 if ((*pexpr)->func_expression()->named_object() == this->no_)
2918 break;
2919 return TRAVERSE_CONTINUE;
2920 default:
2921 return TRAVERSE_CONTINUE;
2922 }
2923 this->found_ = true;
2924 return TRAVERSE_EXIT;
2925}
2926
e440a328 2927// The nil value.
2928
2929class Nil_expression : public Expression
2930{
2931 public:
b13c66cd 2932 Nil_expression(Location location)
e440a328 2933 : Expression(EXPRESSION_NIL, location)
2934 { }
2935
2936 static Expression*
2937 do_import(Import*);
2938
2939 protected:
2940 bool
2941 do_is_constant() const
2942 { return true; }
2943
2944 Type*
2945 do_type()
2946 { return Type::make_nil_type(); }
2947
2948 void
2949 do_determine_type(const Type_context*)
2950 { }
2951
2952 Expression*
2953 do_copy()
2954 { return this; }
2955
2956 tree
2957 do_get_tree(Translate_context*)
2958 { return null_pointer_node; }
2959
2960 void
2961 do_export(Export* exp) const
2962 { exp->write_c_string("nil"); }
d751bb78 2963
2964 void
2965 do_dump_expression(Ast_dump_context* ast_dump_context) const
2966 { ast_dump_context->ostream() << "nil"; }
e440a328 2967};
2968
2969// Import a nil expression.
2970
2971Expression*
2972Nil_expression::do_import(Import* imp)
2973{
2974 imp->require_c_string("nil");
2975 return Expression::make_nil(imp->location());
2976}
2977
2978// Make a nil expression.
2979
2980Expression*
b13c66cd 2981Expression::make_nil(Location location)
e440a328 2982{
2983 return new Nil_expression(location);
2984}
2985
2986// The value of the predeclared constant iota. This is little more
2987// than a marker. This will be lowered to an integer in
2988// Const_expression::do_lower, which is where we know the value that
2989// it should have.
2990
2991class Iota_expression : public Parser_expression
2992{
2993 public:
b13c66cd 2994 Iota_expression(Location location)
e440a328 2995 : Parser_expression(EXPRESSION_IOTA, location)
2996 { }
2997
2998 protected:
2999 Expression*
ceeb4318 3000 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 3001 { go_unreachable(); }
e440a328 3002
3003 // There should only ever be one of these.
3004 Expression*
3005 do_copy()
c3e6f413 3006 { go_unreachable(); }
d751bb78 3007
3008 void
3009 do_dump_expression(Ast_dump_context* ast_dump_context) const
3010 { ast_dump_context->ostream() << "iota"; }
e440a328 3011};
3012
3013// Make an iota expression. This is only called for one case: the
3014// value of the predeclared constant iota.
3015
3016Expression*
3017Expression::make_iota()
3018{
b13c66cd 3019 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 3020 return &iota_expression;
3021}
3022
3023// A type conversion expression.
3024
3025class Type_conversion_expression : public Expression
3026{
3027 public:
3028 Type_conversion_expression(Type* type, Expression* expr,
b13c66cd 3029 Location location)
e440a328 3030 : Expression(EXPRESSION_CONVERSION, location),
3031 type_(type), expr_(expr), may_convert_function_types_(false)
3032 { }
3033
3034 // Return the type to which we are converting.
3035 Type*
3036 type() const
3037 { return this->type_; }
3038
3039 // Return the expression which we are converting.
3040 Expression*
3041 expr() const
3042 { return this->expr_; }
3043
3044 // Permit converting from one function type to another. This is
3045 // used internally for method expressions.
3046 void
3047 set_may_convert_function_types()
3048 {
3049 this->may_convert_function_types_ = true;
3050 }
3051
3052 // Import a type conversion expression.
3053 static Expression*
3054 do_import(Import*);
3055
3056 protected:
3057 int
3058 do_traverse(Traverse* traverse);
3059
3060 Expression*
ceeb4318 3061 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 3062
35a54f17 3063 Expression*
3064 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3065
e440a328 3066 bool
1ca01a59 3067 do_is_constant() const;
e440a328 3068
3069 bool
0c77715b 3070 do_numeric_constant_value(Numeric_constant*) const;
e440a328 3071
3072 bool
3073 do_string_constant_value(std::string*) const;
3074
3075 Type*
3076 do_type()
3077 { return this->type_; }
3078
3079 void
3080 do_determine_type(const Type_context*)
3081 {
3082 Type_context subcontext(this->type_, false);
3083 this->expr_->determine_type(&subcontext);
3084 }
3085
3086 void
3087 do_check_types(Gogo*);
3088
3089 Expression*
3090 do_copy()
3091 {
3092 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3093 this->location());
3094 }
3095
3096 tree
3097 do_get_tree(Translate_context* context);
3098
3099 void
3100 do_export(Export*) const;
3101
d751bb78 3102 void
3103 do_dump_expression(Ast_dump_context*) const;
3104
e440a328 3105 private:
3106 // The type to convert to.
3107 Type* type_;
3108 // The expression to convert.
3109 Expression* expr_;
3110 // True if this is permitted to convert function types. This is
3111 // used internally for method expressions.
3112 bool may_convert_function_types_;
3113};
3114
3115// Traversal.
3116
3117int
3118Type_conversion_expression::do_traverse(Traverse* traverse)
3119{
3120 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3121 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3122 return TRAVERSE_EXIT;
3123 return TRAVERSE_CONTINUE;
3124}
3125
3126// Convert to a constant at lowering time.
3127
3128Expression*
ceeb4318 3129Type_conversion_expression::do_lower(Gogo*, Named_object*,
3130 Statement_inserter*, int)
e440a328 3131{
3132 Type* type = this->type_;
3133 Expression* val = this->expr_;
b13c66cd 3134 Location location = this->location();
e440a328 3135
0c77715b 3136 if (type->is_numeric_type())
e440a328 3137 {
0c77715b 3138 Numeric_constant nc;
3139 if (val->numeric_constant_value(&nc))
e440a328 3140 {
0c77715b 3141 if (!nc.set_type(type, true, location))
3142 return Expression::make_error(location);
3143 return nc.expression(location);
e440a328 3144 }
e440a328 3145 }
3146
55072f2b 3147 if (type->is_slice_type())
e440a328 3148 {
3149 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3150 bool is_byte = (element_type->integer_type() != NULL
3151 && element_type->integer_type()->is_byte());
3152 bool is_rune = (element_type->integer_type() != NULL
3153 && element_type->integer_type()->is_rune());
3154 if (is_byte || is_rune)
e440a328 3155 {
3156 std::string s;
3157 if (val->string_constant_value(&s))
3158 {
3159 Expression_list* vals = new Expression_list();
3160 if (is_byte)
3161 {
3162 for (std::string::const_iterator p = s.begin();
3163 p != s.end();
3164 p++)
3165 {
3166 mpz_t val;
3167 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3168 Expression* v = Expression::make_integer(&val,
3169 element_type,
3170 location);
3171 vals->push_back(v);
3172 mpz_clear(val);
3173 }
3174 }
3175 else
3176 {
3177 const char *p = s.data();
3178 const char *pend = s.data() + s.length();
3179 while (p < pend)
3180 {
3181 unsigned int c;
3182 int adv = Lex::fetch_char(p, &c);
3183 if (adv == 0)
3184 {
3185 warning_at(this->location(), 0,
3186 "invalid UTF-8 encoding");
3187 adv = 1;
3188 }
3189 p += adv;
3190 mpz_t val;
3191 mpz_init_set_ui(val, c);
3192 Expression* v = Expression::make_integer(&val,
3193 element_type,
3194 location);
3195 vals->push_back(v);
3196 mpz_clear(val);
3197 }
3198 }
3199
3200 return Expression::make_slice_composite_literal(type, vals,
3201 location);
3202 }
3203 }
3204 }
3205
3206 return this;
3207}
3208
35a54f17 3209// Flatten a type conversion by using a temporary variable for the slice
3210// in slice to string conversions.
3211
3212Expression*
3213Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3214 Statement_inserter* inserter)
3215{
3216 if (this->type()->is_string_type()
3217 && this->expr_->type()->is_slice_type()
3218 && !this->expr_->is_variable())
3219 {
3220 Temporary_statement* temp =
3221 Statement::make_temporary(NULL, this->expr_, this->location());
3222 inserter->insert(temp);
3223 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3224 }
3225 return this;
3226}
3227
1ca01a59 3228// Return whether a type conversion is a constant.
3229
3230bool
3231Type_conversion_expression::do_is_constant() const
3232{
3233 if (!this->expr_->is_constant())
3234 return false;
3235
3236 // A conversion to a type that may not be used as a constant is not
3237 // a constant. For example, []byte(nil).
3238 Type* type = this->type_;
3239 if (type->integer_type() == NULL
3240 && type->float_type() == NULL
3241 && type->complex_type() == NULL
3242 && !type->is_boolean_type()
3243 && !type->is_string_type())
3244 return false;
3245
3246 return true;
3247}
3248
0c77715b 3249// Return the constant numeric value if there is one.
e440a328 3250
3251bool
0c77715b 3252Type_conversion_expression::do_numeric_constant_value(
3253 Numeric_constant* nc) const
e440a328 3254{
0c77715b 3255 if (!this->type_->is_numeric_type())
e440a328 3256 return false;
0c77715b 3257 if (!this->expr_->numeric_constant_value(nc))
e440a328 3258 return false;
0c77715b 3259 return nc->set_type(this->type_, false, this->location());
e440a328 3260}
3261
3262// Return the constant string value if there is one.
3263
3264bool
3265Type_conversion_expression::do_string_constant_value(std::string* val) const
3266{
3267 if (this->type_->is_string_type()
3268 && this->expr_->type()->integer_type() != NULL)
3269 {
0c77715b 3270 Numeric_constant nc;
3271 if (this->expr_->numeric_constant_value(&nc))
e440a328 3272 {
0c77715b 3273 unsigned long ival;
3274 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3275 {
0c77715b 3276 val->clear();
3277 Lex::append_char(ival, true, val, this->location());
e440a328 3278 return true;
3279 }
3280 }
e440a328 3281 }
3282
3283 // FIXME: Could handle conversion from const []int here.
3284
3285 return false;
3286}
3287
3288// Check that types are convertible.
3289
3290void
3291Type_conversion_expression::do_check_types(Gogo*)
3292{
3293 Type* type = this->type_;
3294 Type* expr_type = this->expr_->type();
3295 std::string reason;
3296
5c13bd80 3297 if (type->is_error() || expr_type->is_error())
842f6425 3298 {
842f6425 3299 this->set_is_error();
3300 return;
3301 }
3302
e440a328 3303 if (this->may_convert_function_types_
3304 && type->function_type() != NULL
3305 && expr_type->function_type() != NULL)
3306 return;
3307
3308 if (Type::are_convertible(type, expr_type, &reason))
3309 return;
3310
3311 error_at(this->location(), "%s", reason.c_str());
3312 this->set_is_error();
3313}
3314
3315// Get a tree for a type conversion.
3316
3317tree
3318Type_conversion_expression::do_get_tree(Translate_context* context)
3319{
3320 Gogo* gogo = context->gogo();
9f0e0513 3321 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
e440a328 3322 tree expr_tree = this->expr_->get_tree(context);
3323
3324 if (type_tree == error_mark_node
3325 || expr_tree == error_mark_node
3326 || TREE_TYPE(expr_tree) == error_mark_node)
3327 return error_mark_node;
3328
3329 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3330 return fold_convert(type_tree, expr_tree);
3331
3332 Type* type = this->type_;
3333 Type* expr_type = this->expr_->type();
3334 tree ret;
3335 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3336 ret = Expression::convert_for_assignment(context, type, expr_type,
3337 expr_tree, this->location());
3338 else if (type->integer_type() != NULL)
3339 {
3340 if (expr_type->integer_type() != NULL
3341 || expr_type->float_type() != NULL
3342 || expr_type->is_unsafe_pointer_type())
3343 ret = fold(convert_to_integer(type_tree, expr_tree));
3344 else
c3e6f413 3345 go_unreachable();
e440a328 3346 }
3347 else if (type->float_type() != NULL)
3348 {
3349 if (expr_type->integer_type() != NULL
3350 || expr_type->float_type() != NULL)
3351 ret = fold(convert_to_real(type_tree, expr_tree));
3352 else
c3e6f413 3353 go_unreachable();
e440a328 3354 }
3355 else if (type->complex_type() != NULL)
3356 {
3357 if (expr_type->complex_type() != NULL)
3358 ret = fold(convert_to_complex(type_tree, expr_tree));
3359 else
c3e6f413 3360 go_unreachable();
e440a328 3361 }
3362 else if (type->is_string_type()
3363 && expr_type->integer_type() != NULL)
3364 {
1b1f2abf 3365 Type* int_type = Type::lookup_integer_type("int");
3366 tree int_type_tree = type_to_tree(int_type->get_backend(gogo));
3367
3368 expr_tree = fold_convert(int_type_tree, expr_tree);
35ec552a 3369 if (tree_fits_shwi_p (expr_tree))
e440a328 3370 {
fcb97e84 3371 HOST_WIDE_INT intval = tree_to_shwi (expr_tree);
e440a328 3372 std::string s;
3373 Lex::append_char(intval, true, &s, this->location());
3374 Expression* se = Expression::make_string(s, this->location());
3375 return se->get_tree(context);
3376 }
3377
f16ab008 3378 Expression* i2s_expr =
6c252e42 3379 Runtime::make_call(Runtime::INT_TO_STRING, this->location(), 1,
3380 this->expr_);
f16ab008 3381 i2s_expr = Expression::make_cast(type, i2s_expr, this->location());
6c252e42 3382 ret = i2s_expr->get_tree(context);
e440a328 3383 }
55072f2b 3384 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3385 {
35a54f17 3386 Location location = this->location();
55072f2b 3387 Array_type* a = expr_type->array_type();
e440a328 3388 Type* e = a->element_type()->forwarded();
c484d925 3389 go_assert(e->integer_type() != NULL);
35a54f17 3390 go_assert(this->expr_->is_variable());
3391
3392 Runtime::Function code;
60963afd 3393 if (e->integer_type()->is_byte())
35a54f17 3394 code = Runtime::BYTE_ARRAY_TO_STRING;
e440a328 3395 else
35a54f17 3396 {
3397 go_assert(e->integer_type()->is_rune());
3398 code = Runtime::INT_ARRAY_TO_STRING;
3399 }
3400 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3401 Expression* len = a->get_length(gogo, this->expr_);
3402 Expression* a2s_expr = Runtime::make_call(code, location, 2, valptr, len);
3403 ret = a2s_expr->get_tree(context);
e440a328 3404 }
411eb89e 3405 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3406 {
3407 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3408 go_assert(e->integer_type() != NULL);
6c252e42 3409
f16ab008 3410 Expression* s2a_expr;
60963afd 3411 if (e->integer_type()->is_byte())
6c252e42 3412 s2a_expr = Runtime::make_call(Runtime::STRING_TO_BYTE_ARRAY,
3413 this->location(), 1, this->expr_);
e440a328 3414 else
3415 {
60963afd 3416 go_assert(e->integer_type()->is_rune());
6c252e42 3417 s2a_expr = Runtime::make_call(Runtime::STRING_TO_INT_ARRAY,
3418 this->location(), 1, this->expr_);
e440a328 3419 }
f16ab008 3420 s2a_expr = Expression::make_unsafe_cast(type, s2a_expr,
3421 this->location());
6c252e42 3422 ret = s2a_expr->get_tree(context);
e440a328 3423 }
3424 else if ((type->is_unsafe_pointer_type()
3425 && expr_type->points_to() != NULL)
3426 || (expr_type->is_unsafe_pointer_type()
3427 && type->points_to() != NULL))
3428 ret = fold_convert(type_tree, expr_tree);
3429 else if (type->is_unsafe_pointer_type()
3430 && expr_type->integer_type() != NULL)
3431 ret = convert_to_pointer(type_tree, expr_tree);
3432 else if (this->may_convert_function_types_
3433 && type->function_type() != NULL
3434 && expr_type->function_type() != NULL)
b13c66cd 3435 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3436 expr_tree);
e440a328 3437 else
3438 ret = Expression::convert_for_assignment(context, type, expr_type,
3439 expr_tree, this->location());
3440
3441 return ret;
3442}
3443
3444// Output a type conversion in a constant expression.
3445
3446void
3447Type_conversion_expression::do_export(Export* exp) const
3448{
3449 exp->write_c_string("convert(");
3450 exp->write_type(this->type_);
3451 exp->write_c_string(", ");
3452 this->expr_->export_expression(exp);
3453 exp->write_c_string(")");
3454}
3455
3456// Import a type conversion or a struct construction.
3457
3458Expression*
3459Type_conversion_expression::do_import(Import* imp)
3460{
3461 imp->require_c_string("convert(");
3462 Type* type = imp->read_type();
3463 imp->require_c_string(", ");
3464 Expression* val = Expression::import_expression(imp);
3465 imp->require_c_string(")");
3466 return Expression::make_cast(type, val, imp->location());
3467}
3468
d751bb78 3469// Dump ast representation for a type conversion expression.
3470
3471void
3472Type_conversion_expression::do_dump_expression(
3473 Ast_dump_context* ast_dump_context) const
3474{
3475 ast_dump_context->dump_type(this->type_);
3476 ast_dump_context->ostream() << "(";
3477 ast_dump_context->dump_expression(this->expr_);
3478 ast_dump_context->ostream() << ") ";
3479}
3480
e440a328 3481// Make a type cast expression.
3482
3483Expression*
b13c66cd 3484Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3485{
3486 if (type->is_error_type() || val->is_error_expression())
3487 return Expression::make_error(location);
3488 return new Type_conversion_expression(type, val, location);
3489}
3490
9581e91d 3491// An unsafe type conversion, used to pass values to builtin functions.
3492
3493class Unsafe_type_conversion_expression : public Expression
3494{
3495 public:
3496 Unsafe_type_conversion_expression(Type* type, Expression* expr,
b13c66cd 3497 Location location)
9581e91d 3498 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3499 type_(type), expr_(expr)
3500 { }
3501
3502 protected:
3503 int
3504 do_traverse(Traverse* traverse);
3505
3506 Type*
3507 do_type()
3508 { return this->type_; }
3509
3510 void
3511 do_determine_type(const Type_context*)
a9182619 3512 { this->expr_->determine_type_no_context(); }
9581e91d 3513
3514 Expression*
3515 do_copy()
3516 {
3517 return new Unsafe_type_conversion_expression(this->type_,
3518 this->expr_->copy(),
3519 this->location());
3520 }
3521
3522 tree
3523 do_get_tree(Translate_context*);
3524
d751bb78 3525 void
3526 do_dump_expression(Ast_dump_context*) const;
3527
9581e91d 3528 private:
3529 // The type to convert to.
3530 Type* type_;
3531 // The expression to convert.
3532 Expression* expr_;
3533};
3534
3535// Traversal.
3536
3537int
3538Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3539{
3540 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3541 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3542 return TRAVERSE_EXIT;
3543 return TRAVERSE_CONTINUE;
3544}
3545
3546// Convert to backend representation.
3547
3548tree
3549Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3550{
3551 // We are only called for a limited number of cases.
3552
3553 Type* t = this->type_;
3554 Type* et = this->expr_->type();
3555
9f0e0513 3556 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
9581e91d 3557 tree expr_tree = this->expr_->get_tree(context);
3558 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3559 return error_mark_node;
3560
b13c66cd 3561 Location loc = this->location();
9581e91d 3562
3563 bool use_view_convert = false;
411eb89e 3564 if (t->is_slice_type())
9581e91d 3565 {
411eb89e 3566 go_assert(et->is_slice_type());
9581e91d 3567 use_view_convert = true;
3568 }
3569 else if (t->map_type() != NULL)
c484d925 3570 go_assert(et->map_type() != NULL);
9581e91d 3571 else if (t->channel_type() != NULL)
c484d925 3572 go_assert(et->channel_type() != NULL);
09ea332d 3573 else if (t->points_to() != NULL)
c484d925 3574 go_assert(et->points_to() != NULL || et->is_nil_type());
9581e91d 3575 else if (et->is_unsafe_pointer_type())
c484d925 3576 go_assert(t->points_to() != NULL);
9581e91d 3577 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3578 {
c484d925 3579 go_assert(et->interface_type() != NULL
9581e91d 3580 && !et->interface_type()->is_empty());
3581 use_view_convert = true;
3582 }
3583 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3584 {
c484d925 3585 go_assert(et->interface_type() != NULL
9581e91d 3586 && et->interface_type()->is_empty());
3587 use_view_convert = true;
3588 }
588e3cf9 3589 else if (t->integer_type() != NULL)
3590 {
c484d925 3591 go_assert(et->is_boolean_type()
588e3cf9 3592 || et->integer_type() != NULL
3593 || et->function_type() != NULL
3594 || et->points_to() != NULL
3595 || et->map_type() != NULL
3596 || et->channel_type() != NULL);
3597 return convert_to_integer(type_tree, expr_tree);
3598 }
9581e91d 3599 else
c3e6f413 3600 go_unreachable();
9581e91d 3601
3602 if (use_view_convert)
b13c66cd 3603 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3604 expr_tree);
9581e91d 3605 else
b13c66cd 3606 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
9581e91d 3607}
3608
d751bb78 3609// Dump ast representation for an unsafe type conversion expression.
3610
3611void
3612Unsafe_type_conversion_expression::do_dump_expression(
3613 Ast_dump_context* ast_dump_context) const
3614{
3615 ast_dump_context->dump_type(this->type_);
3616 ast_dump_context->ostream() << "(";
3617 ast_dump_context->dump_expression(this->expr_);
3618 ast_dump_context->ostream() << ") ";
3619}
3620
9581e91d 3621// Make an unsafe type conversion expression.
3622
3623Expression*
3624Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3625 Location location)
9581e91d 3626{
3627 return new Unsafe_type_conversion_expression(type, expr, location);
3628}
3629
e440a328 3630// Unary expressions.
3631
3632class Unary_expression : public Expression
3633{
3634 public:
b13c66cd 3635 Unary_expression(Operator op, Expression* expr, Location location)
e440a328 3636 : Expression(EXPRESSION_UNARY, location),
56080003 3637 op_(op), escapes_(true), create_temp_(false), expr_(expr),
3638 issue_nil_check_(false)
e440a328 3639 { }
3640
3641 // Return the operator.
3642 Operator
3643 op() const
3644 { return this->op_; }
3645
3646 // Return the operand.
3647 Expression*
3648 operand() const
3649 { return this->expr_; }
3650
3651 // Record that an address expression does not escape.
3652 void
3653 set_does_not_escape()
3654 {
c484d925 3655 go_assert(this->op_ == OPERATOR_AND);
e440a328 3656 this->escapes_ = false;
3657 }
3658
09ea332d 3659 // Record that this is an address expression which should create a
3660 // temporary variable if necessary. This is used for method calls.
3661 void
3662 set_create_temp()
3663 {
3664 go_assert(this->op_ == OPERATOR_AND);
3665 this->create_temp_ = true;
3666 }
3667
0c77715b 3668 // Apply unary opcode OP to UNC, setting NC. Return true if this
3669 // could be done, false if not. Issue errors for overflow.
e440a328 3670 static bool
0c77715b 3671 eval_constant(Operator op, const Numeric_constant* unc,
3672 Location, Numeric_constant* nc);
e440a328 3673
3674 static Expression*
3675 do_import(Import*);
3676
3677 protected:
3678 int
3679 do_traverse(Traverse* traverse)
3680 { return Expression::traverse(&this->expr_, traverse); }
3681
3682 Expression*
ceeb4318 3683 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 3684
3685 bool
3686 do_is_constant() const;
3687
3688 bool
0c77715b 3689 do_numeric_constant_value(Numeric_constant*) const;
e440a328 3690
3691 Type*
3692 do_type();
3693
3694 void
3695 do_determine_type(const Type_context*);
3696
3697 void
3698 do_check_types(Gogo*);
3699
3700 Expression*
3701 do_copy()
3702 {
3703 return Expression::make_unary(this->op_, this->expr_->copy(),
3704 this->location());
3705 }
3706
baef9f7a 3707 bool
3708 do_must_eval_subexpressions_in_order(int*) const
3709 { return this->op_ == OPERATOR_MULT; }
3710
e440a328 3711 bool
3712 do_is_addressable() const
3713 { return this->op_ == OPERATOR_MULT; }
3714
3715 tree
3716 do_get_tree(Translate_context*);
3717
3718 void
3719 do_export(Export*) const;
3720
d751bb78 3721 void
3722 do_dump_expression(Ast_dump_context*) const;
3723
56080003 3724 void
3725 do_issue_nil_check()
3726 { this->issue_nil_check_ = (this->op_ == OPERATOR_MULT); }
3727
e440a328 3728 private:
3729 // The unary operator to apply.
3730 Operator op_;
3731 // Normally true. False if this is an address expression which does
3732 // not escape the current function.
3733 bool escapes_;
09ea332d 3734 // True if this is an address expression which should create a
3735 // temporary variable if necessary.
3736 bool create_temp_;
e440a328 3737 // The operand.
3738 Expression* expr_;
56080003 3739 // Whether or not to issue a nil check for this expression if its address
3740 // is being taken.
3741 bool issue_nil_check_;
e440a328 3742};
3743
3744// If we are taking the address of a composite literal, and the
3745// contents are not constant, then we want to make a heap composite
3746// instead.
3747
3748Expression*
ceeb4318 3749Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3750{
b13c66cd 3751 Location loc = this->location();
e440a328 3752 Operator op = this->op_;
3753 Expression* expr = this->expr_;
3754
3755 if (op == OPERATOR_MULT && expr->is_type_expression())
3756 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3757
3758 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3759 // moving x to the heap. FIXME: Is it worth doing a real escape
3760 // analysis here? This case is found in math/unsafe.go and is
3761 // therefore worth special casing.
3762 if (op == OPERATOR_MULT)
3763 {
3764 Expression* e = expr;
3765 while (e->classification() == EXPRESSION_CONVERSION)
3766 {
3767 Type_conversion_expression* te
3768 = static_cast<Type_conversion_expression*>(e);
3769 e = te->expr();
3770 }
3771
3772 if (e->classification() == EXPRESSION_UNARY)
3773 {
3774 Unary_expression* ue = static_cast<Unary_expression*>(e);
3775 if (ue->op_ == OPERATOR_AND)
3776 {
3777 if (e == expr)
3778 {
3779 // *&x == x.
3780 return ue->expr_;
3781 }
3782 ue->set_does_not_escape();
3783 }
3784 }
3785 }
3786
55661ce9 3787 // Catching an invalid indirection of unsafe.Pointer here avoid
3788 // having to deal with TYPE_VOID in other places.
3789 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3790 {
3791 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3792 return Expression::make_error(this->location());
3793 }
3794
59a401fe 3795 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3796 {
0c77715b 3797 Numeric_constant nc;
3798 if (expr->numeric_constant_value(&nc))
e440a328 3799 {
0c77715b 3800 Numeric_constant result;
3801 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3802 return result.expression(loc);
e440a328 3803 }
3804 }
3805
3806 return this;
3807}
3808
3809// Return whether a unary expression is a constant.
3810
3811bool
3812Unary_expression::do_is_constant() const
3813{
3814 if (this->op_ == OPERATOR_MULT)
3815 {
3816 // Indirecting through a pointer is only constant if the object
3817 // to which the expression points is constant, but we currently
3818 // have no way to determine that.
3819 return false;
3820 }
3821 else if (this->op_ == OPERATOR_AND)
3822 {
3823 // Taking the address of a variable is constant if it is a
3824 // global variable, not constant otherwise. In other cases
3825 // taking the address is probably not a constant.
3826 Var_expression* ve = this->expr_->var_expression();
3827 if (ve != NULL)
3828 {
3829 Named_object* no = ve->named_object();
3830 return no->is_variable() && no->var_value()->is_global();
3831 }
3832 return false;
3833 }
3834 else
3835 return this->expr_->is_constant();
3836}
3837
0c77715b 3838// Apply unary opcode OP to UNC, setting NC. Return true if this
3839// could be done, false if not. Issue errors for overflow.
e440a328 3840
3841bool
0c77715b 3842Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3843 Location location, Numeric_constant* nc)
e440a328 3844{
3845 switch (op)
3846 {
3847 case OPERATOR_PLUS:
0c77715b 3848 *nc = *unc;
e440a328 3849 return true;
0c77715b 3850
e440a328 3851 case OPERATOR_MINUS:
0c77715b 3852 if (unc->is_int() || unc->is_rune())
3853 break;
3854 else if (unc->is_float())
3855 {
3856 mpfr_t uval;
3857 unc->get_float(&uval);
3858 mpfr_t val;
3859 mpfr_init(val);
3860 mpfr_neg(val, uval, GMP_RNDN);
3861 nc->set_float(unc->type(), val);
3862 mpfr_clear(uval);
3863 mpfr_clear(val);
3864 return true;
3865 }
3866 else if (unc->is_complex())
3867 {
3868 mpfr_t ureal, uimag;
3869 unc->get_complex(&ureal, &uimag);
3870 mpfr_t real, imag;
3871 mpfr_init(real);
3872 mpfr_init(imag);
3873 mpfr_neg(real, ureal, GMP_RNDN);
3874 mpfr_neg(imag, uimag, GMP_RNDN);
3875 nc->set_complex(unc->type(), real, imag);
3876 mpfr_clear(ureal);
3877 mpfr_clear(uimag);
3878 mpfr_clear(real);
3879 mpfr_clear(imag);
3880 return true;
3881 }
e440a328 3882 else
0c77715b 3883 go_unreachable();
e440a328 3884
0c77715b 3885 case OPERATOR_XOR:
3886 break;
68448d53 3887
59a401fe 3888 case OPERATOR_NOT:
e440a328 3889 case OPERATOR_AND:
3890 case OPERATOR_MULT:
3891 return false;
0c77715b 3892
e440a328 3893 default:
c3e6f413 3894 go_unreachable();
e440a328 3895 }
e440a328 3896
0c77715b 3897 if (!unc->is_int() && !unc->is_rune())
3898 return false;
3899
3900 mpz_t uval;
8387e1df 3901 if (unc->is_rune())
3902 unc->get_rune(&uval);
3903 else
3904 unc->get_int(&uval);
0c77715b 3905 mpz_t val;
3906 mpz_init(val);
e440a328 3907
e440a328 3908 switch (op)
3909 {
e440a328 3910 case OPERATOR_MINUS:
0c77715b 3911 mpz_neg(val, uval);
3912 break;
3913
e440a328 3914 case OPERATOR_NOT:
0c77715b 3915 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3916 break;
3917
e440a328 3918 case OPERATOR_XOR:
0c77715b 3919 {
3920 Type* utype = unc->type();
3921 if (utype->integer_type() == NULL
3922 || utype->integer_type()->is_abstract())
3923 mpz_com(val, uval);
3924 else
3925 {
3926 // The number of HOST_WIDE_INTs that it takes to represent
3927 // UVAL.
3928 size_t count = ((mpz_sizeinbase(uval, 2)
3929 + HOST_BITS_PER_WIDE_INT
3930 - 1)
3931 / HOST_BITS_PER_WIDE_INT);
e440a328 3932
0c77715b 3933 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3934 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3935
3936 size_t obits = utype->integer_type()->bits();
3937
3938 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3939 {
3940 mpz_t adj;
3941 mpz_init_set_ui(adj, 1);
3942 mpz_mul_2exp(adj, adj, obits);
3943 mpz_add(uval, uval, adj);
3944 mpz_clear(adj);
3945 }
3946
3947 size_t ecount;
3948 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3949 go_assert(ecount <= count);
3950
3951 // Trim down to the number of words required by the type.
3952 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3953 / HOST_BITS_PER_WIDE_INT);
3954 go_assert(ocount <= count);
3955
3956 for (size_t i = 0; i < ocount; ++i)
3957 phwi[i] = ~phwi[i];
3958
3959 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3960 if (clearbits != 0)
3961 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3962 >> clearbits);
3963
3964 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3965
3966 if (!utype->integer_type()->is_unsigned()
3967 && mpz_tstbit(val, obits - 1))
3968 {
3969 mpz_t adj;
3970 mpz_init_set_ui(adj, 1);
3971 mpz_mul_2exp(adj, adj, obits);
3972 mpz_sub(val, val, adj);
3973 mpz_clear(adj);
3974 }
3975
3976 delete[] phwi;
3977 }
3978 }
3979 break;
e440a328 3980
e440a328 3981 default:
c3e6f413 3982 go_unreachable();
e440a328 3983 }
e440a328 3984
0c77715b 3985 if (unc->is_rune())
3986 nc->set_rune(NULL, val);
e440a328 3987 else
0c77715b 3988 nc->set_int(NULL, val);
e440a328 3989
0c77715b 3990 mpz_clear(uval);
3991 mpz_clear(val);
e440a328 3992
0c77715b 3993 return nc->set_type(unc->type(), true, location);
e440a328 3994}
3995
0c77715b 3996// Return the integral constant value of a unary expression, if it has one.
e440a328 3997
3998bool
0c77715b 3999Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 4000{
0c77715b 4001 Numeric_constant unc;
4002 if (!this->expr_->numeric_constant_value(&unc))
4003 return false;
4004 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4005 nc);
e440a328 4006}
4007
4008// Return the type of a unary expression.
4009
4010Type*
4011Unary_expression::do_type()
4012{
4013 switch (this->op_)
4014 {
4015 case OPERATOR_PLUS:
4016 case OPERATOR_MINUS:
4017 case OPERATOR_NOT:
4018 case OPERATOR_XOR:
4019 return this->expr_->type();
4020
4021 case OPERATOR_AND:
4022 return Type::make_pointer_type(this->expr_->type());
4023
4024 case OPERATOR_MULT:
4025 {
4026 Type* subtype = this->expr_->type();
4027 Type* points_to = subtype->points_to();
4028 if (points_to == NULL)
4029 return Type::make_error_type();
4030 return points_to;
4031 }
4032
4033 default:
c3e6f413 4034 go_unreachable();
e440a328 4035 }
4036}
4037
4038// Determine abstract types for a unary expression.
4039
4040void
4041Unary_expression::do_determine_type(const Type_context* context)
4042{
4043 switch (this->op_)
4044 {
4045 case OPERATOR_PLUS:
4046 case OPERATOR_MINUS:
4047 case OPERATOR_NOT:
4048 case OPERATOR_XOR:
4049 this->expr_->determine_type(context);
4050 break;
4051
4052 case OPERATOR_AND:
4053 // Taking the address of something.
4054 {
4055 Type* subtype = (context->type == NULL
4056 ? NULL
4057 : context->type->points_to());
4058 Type_context subcontext(subtype, false);
4059 this->expr_->determine_type(&subcontext);
4060 }
4061 break;
4062
4063 case OPERATOR_MULT:
4064 // Indirecting through a pointer.
4065 {
4066 Type* subtype = (context->type == NULL
4067 ? NULL
4068 : Type::make_pointer_type(context->type));
4069 Type_context subcontext(subtype, false);
4070 this->expr_->determine_type(&subcontext);
4071 }
4072 break;
4073
4074 default:
c3e6f413 4075 go_unreachable();
e440a328 4076 }
4077}
4078
4079// Check types for a unary expression.
4080
4081void
4082Unary_expression::do_check_types(Gogo*)
4083{
9fe897ef 4084 Type* type = this->expr_->type();
5c13bd80 4085 if (type->is_error())
9fe897ef 4086 {
4087 this->set_is_error();
4088 return;
4089 }
4090
e440a328 4091 switch (this->op_)
4092 {
4093 case OPERATOR_PLUS:
4094 case OPERATOR_MINUS:
9fe897ef 4095 if (type->integer_type() == NULL
4096 && type->float_type() == NULL
4097 && type->complex_type() == NULL)
4098 this->report_error(_("expected numeric type"));
e440a328 4099 break;
4100
4101 case OPERATOR_NOT:
59a401fe 4102 if (!type->is_boolean_type())
4103 this->report_error(_("expected boolean type"));
4104 break;
4105
e440a328 4106 case OPERATOR_XOR:
9fe897ef 4107 if (type->integer_type() == NULL
4108 && !type->is_boolean_type())
4109 this->report_error(_("expected integer or boolean type"));
e440a328 4110 break;
4111
4112 case OPERATOR_AND:
4113 if (!this->expr_->is_addressable())
09ea332d 4114 {
4115 if (!this->create_temp_)
4116 this->report_error(_("invalid operand for unary %<&%>"));
4117 }
e440a328 4118 else
56080003 4119 {
4120 this->expr_->address_taken(this->escapes_);
4121 this->expr_->issue_nil_check();
4122 }
e440a328 4123 break;
4124
4125 case OPERATOR_MULT:
4126 // Indirecting through a pointer.
9fe897ef 4127 if (type->points_to() == NULL)
4128 this->report_error(_("expected pointer"));
e440a328 4129 break;
4130
4131 default:
c3e6f413 4132 go_unreachable();
e440a328 4133 }
4134}
4135
4136// Get a tree for a unary expression.
4137
4138tree
4139Unary_expression::do_get_tree(Translate_context* context)
4140{
1b1f2abf 4141 Gogo* gogo = context->gogo();
e9d3367e 4142 Location loc = this->location();
4143
4144 // Taking the address of a set-and-use-temporary expression requires
4145 // setting the temporary and then taking the address.
4146 if (this->op_ == OPERATOR_AND)
4147 {
4148 Set_and_use_temporary_expression* sut =
4149 this->expr_->set_and_use_temporary_expression();
4150 if (sut != NULL)
4151 {
4152 Temporary_statement* temp = sut->temporary();
4153 Bvariable* bvar = temp->get_backend_variable(context);
4154 tree var_tree = var_to_tree(bvar);
4155 Expression* val = sut->expression();
4156 tree val_tree = val->get_tree(context);
4157 if (var_tree == error_mark_node || val_tree == error_mark_node)
4158 return error_mark_node;
4159 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
4160 var_tree);
4161 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4162 TREE_TYPE(addr_tree),
4163 build2_loc(sut->location().gcc_location(),
4164 MODIFY_EXPR, void_type_node,
4165 var_tree, val_tree),
4166 addr_tree);
4167 }
4168 }
4169
e440a328 4170 tree expr = this->expr_->get_tree(context);
4171 if (expr == error_mark_node)
4172 return error_mark_node;
4173
e440a328 4174 switch (this->op_)
4175 {
4176 case OPERATOR_PLUS:
4177 return expr;
4178
4179 case OPERATOR_MINUS:
4180 {
4181 tree type = TREE_TYPE(expr);
4182 tree compute_type = excess_precision_type(type);
4183 if (compute_type != NULL_TREE)
4184 expr = ::convert(compute_type, expr);
b13c66cd 4185 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
e440a328 4186 (compute_type != NULL_TREE
4187 ? compute_type
4188 : type),
4189 expr);
4190 if (compute_type != NULL_TREE)
4191 ret = ::convert(type, ret);
4192 return ret;
4193 }
4194
4195 case OPERATOR_NOT:
4196 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
b13c66cd 4197 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4198 TREE_TYPE(expr), expr);
e440a328 4199 else
b13c66cd 4200 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4201 expr, build_int_cst(TREE_TYPE(expr), 0));
e440a328 4202
4203 case OPERATOR_XOR:
b13c66cd 4204 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4205 expr);
e440a328 4206
4207 case OPERATOR_AND:
09ea332d 4208 if (!this->create_temp_)
4209 {
4210 // We should not see a non-constant constructor here; cases
4211 // where we would see one should have been moved onto the
4212 // heap at parse time. Taking the address of a nonconstant
4213 // constructor will not do what the programmer expects.
4214 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4215 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4216 }
e440a328 4217
4218 // Build a decl for a constant constructor.
4219 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4220 {
b13c66cd 4221 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
e440a328 4222 create_tmp_var_name("C"), TREE_TYPE(expr));
4223 DECL_EXTERNAL(decl) = 0;
4224 TREE_PUBLIC(decl) = 0;
4225 TREE_READONLY(decl) = 1;
4226 TREE_CONSTANT(decl) = 1;
4227 TREE_STATIC(decl) = 1;
4228 TREE_ADDRESSABLE(decl) = 1;
4229 DECL_ARTIFICIAL(decl) = 1;
4230 DECL_INITIAL(decl) = expr;
4231 rest_of_decl_compilation(decl, 1, 0);
4232 expr = decl;
4233 }
4234
09ea332d 4235 if (this->create_temp_
4236 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
dd28fd36 4237 && (TREE_CODE(expr) == CONST_DECL || !DECL_P(expr))
09ea332d 4238 && TREE_CODE(expr) != INDIRECT_REF
4239 && TREE_CODE(expr) != COMPONENT_REF)
4240 {
fc81003d 4241 if (current_function_decl != NULL)
4242 {
4243 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4244 DECL_IGNORED_P(tmp) = 1;
4245 DECL_INITIAL(tmp) = expr;
4246 TREE_ADDRESSABLE(tmp) = 1;
4247 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4248 build_pointer_type(TREE_TYPE(expr)),
4249 build1_loc(loc.gcc_location(), DECL_EXPR,
4250 void_type_node, tmp),
4251 build_fold_addr_expr_loc(loc.gcc_location(),
4252 tmp));
4253 }
4254 else
4255 {
4256 tree tmp = build_decl(loc.gcc_location(), VAR_DECL,
4257 create_tmp_var_name("A"), TREE_TYPE(expr));
4258 DECL_EXTERNAL(tmp) = 0;
4259 TREE_PUBLIC(tmp) = 0;
4260 TREE_STATIC(tmp) = 1;
4261 DECL_ARTIFICIAL(tmp) = 1;
4262 TREE_ADDRESSABLE(tmp) = 1;
4263 tree make_tmp;
4264 if (!TREE_CONSTANT(expr))
4265 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
4266 void_type_node, tmp, expr);
4267 else
4268 {
4269 TREE_READONLY(tmp) = 1;
4270 TREE_CONSTANT(tmp) = 1;
4271 DECL_INITIAL(tmp) = expr;
4272 make_tmp = NULL_TREE;
4273 }
4274 rest_of_decl_compilation(tmp, 1, 0);
4275 tree addr = build_fold_addr_expr_loc(loc.gcc_location(), tmp);
4276 if (make_tmp == NULL_TREE)
4277 return addr;
4278 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4279 TREE_TYPE(addr), make_tmp, addr);
4280 }
09ea332d 4281 }
4282
b13c66cd 4283 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
e440a328 4284
4285 case OPERATOR_MULT:
4286 {
c484d925 4287 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
e440a328 4288
4289 // If we are dereferencing the pointer to a large struct, we
4290 // need to check for nil. We don't bother to check for small
4291 // structs because we expect the system to crash on a nil
56080003 4292 // pointer dereference. However, if we know the address of this
4293 // expression is being taken, we must always check for nil.
19b4f09b 4294 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4295 if (!VOID_TYPE_P(target_type_tree))
e440a328 4296 {
19b4f09b 4297 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
56080003 4298 if (s == -1 || s >= 4096 || this->issue_nil_check_)
19b4f09b 4299 {
4300 if (!DECL_P(expr))
4301 expr = save_expr(expr);
4302 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4303 boolean_type_node,
4304 expr,
4305 fold_convert(TREE_TYPE(expr),
4306 null_pointer_node));
aff1f085 4307 Expression* crash_expr =
4308 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
4309 tree crash = crash_expr->get_tree(context);
19b4f09b 4310 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4311 TREE_TYPE(expr), build3(COND_EXPR,
4312 void_type_node,
4313 compare, crash,
4314 NULL_TREE),
4315 expr);
4316 }
e440a328 4317 }
4318
4319 // If the type of EXPR is a recursive pointer type, then we
4320 // need to insert a cast before indirecting.
19b4f09b 4321 if (VOID_TYPE_P(target_type_tree))
e440a328 4322 {
4323 Type* pt = this->expr_->type()->points_to();
1b1f2abf 4324 tree ind = type_to_tree(pt->get_backend(gogo));
b13c66cd 4325 expr = fold_convert_loc(loc.gcc_location(),
4326 build_pointer_type(ind), expr);
e440a328 4327 }
4328
b13c66cd 4329 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
e440a328 4330 }
4331
4332 default:
c3e6f413 4333 go_unreachable();
e440a328 4334 }
4335}
4336
4337// Export a unary expression.
4338
4339void
4340Unary_expression::do_export(Export* exp) const
4341{
4342 switch (this->op_)
4343 {
4344 case OPERATOR_PLUS:
4345 exp->write_c_string("+ ");
4346 break;
4347 case OPERATOR_MINUS:
4348 exp->write_c_string("- ");
4349 break;
4350 case OPERATOR_NOT:
4351 exp->write_c_string("! ");
4352 break;
4353 case OPERATOR_XOR:
4354 exp->write_c_string("^ ");
4355 break;
4356 case OPERATOR_AND:
4357 case OPERATOR_MULT:
4358 default:
c3e6f413 4359 go_unreachable();
e440a328 4360 }
4361 this->expr_->export_expression(exp);
4362}
4363
4364// Import a unary expression.
4365
4366Expression*
4367Unary_expression::do_import(Import* imp)
4368{
4369 Operator op;
4370 switch (imp->get_char())
4371 {
4372 case '+':
4373 op = OPERATOR_PLUS;
4374 break;
4375 case '-':
4376 op = OPERATOR_MINUS;
4377 break;
4378 case '!':
4379 op = OPERATOR_NOT;
4380 break;
4381 case '^':
4382 op = OPERATOR_XOR;
4383 break;
4384 default:
c3e6f413 4385 go_unreachable();
e440a328 4386 }
4387 imp->require_c_string(" ");
4388 Expression* expr = Expression::import_expression(imp);
4389 return Expression::make_unary(op, expr, imp->location());
4390}
4391
d751bb78 4392// Dump ast representation of an unary expression.
4393
4394void
4395Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4396{
4397 ast_dump_context->dump_operator(this->op_);
4398 ast_dump_context->ostream() << "(";
4399 ast_dump_context->dump_expression(this->expr_);
4400 ast_dump_context->ostream() << ") ";
4401}
4402
e440a328 4403// Make a unary expression.
4404
4405Expression*
b13c66cd 4406Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4407{
4408 return new Unary_expression(op, expr, location);
4409}
4410
4411// If this is an indirection through a pointer, return the expression
4412// being pointed through. Otherwise return this.
4413
4414Expression*
4415Expression::deref()
4416{
4417 if (this->classification_ == EXPRESSION_UNARY)
4418 {
4419 Unary_expression* ue = static_cast<Unary_expression*>(this);
4420 if (ue->op() == OPERATOR_MULT)
4421 return ue->operand();
4422 }
4423 return this;
4424}
4425
4426// Class Binary_expression.
4427
4428// Traversal.
4429
4430int
4431Binary_expression::do_traverse(Traverse* traverse)
4432{
4433 int t = Expression::traverse(&this->left_, traverse);
4434 if (t == TRAVERSE_EXIT)
4435 return TRAVERSE_EXIT;
4436 return Expression::traverse(&this->right_, traverse);
4437}
4438
0c77715b 4439// Return the type to use for a binary operation on operands of
4440// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4441// such may be NULL or abstract.
4442
4443bool
4444Binary_expression::operation_type(Operator op, Type* left_type,
4445 Type* right_type, Type** result_type)
4446{
4447 if (left_type != right_type
4448 && !left_type->is_abstract()
4449 && !right_type->is_abstract()
4450 && left_type->base() != right_type->base()
4451 && op != OPERATOR_LSHIFT
4452 && op != OPERATOR_RSHIFT)
4453 {
4454 // May be a type error--let it be diagnosed elsewhere.
4455 return false;
4456 }
4457
4458 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4459 {
4460 if (left_type->integer_type() != NULL)
4461 *result_type = left_type;
4462 else
4463 *result_type = Type::make_abstract_integer_type();
4464 }
4465 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4466 *result_type = left_type;
4467 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4468 *result_type = right_type;
4469 else if (!left_type->is_abstract())
4470 *result_type = left_type;
4471 else if (!right_type->is_abstract())
4472 *result_type = right_type;
4473 else if (left_type->complex_type() != NULL)
4474 *result_type = left_type;
4475 else if (right_type->complex_type() != NULL)
4476 *result_type = right_type;
4477 else if (left_type->float_type() != NULL)
4478 *result_type = left_type;
4479 else if (right_type->float_type() != NULL)
4480 *result_type = right_type;
4481 else if (left_type->integer_type() != NULL
4482 && left_type->integer_type()->is_rune())
4483 *result_type = left_type;
4484 else if (right_type->integer_type() != NULL
4485 && right_type->integer_type()->is_rune())
4486 *result_type = right_type;
4487 else
4488 *result_type = left_type;
4489
4490 return true;
4491}
4492
4493// Convert an integer comparison code and an operator to a boolean
4494// value.
e440a328 4495
4496bool
0c77715b 4497Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4498{
e440a328 4499 switch (op)
4500 {
4501 case OPERATOR_EQEQ:
0c77715b 4502 return cmp == 0;
4503 break;
e440a328 4504 case OPERATOR_NOTEQ:
0c77715b 4505 return cmp != 0;
4506 break;
e440a328 4507 case OPERATOR_LT:
0c77715b 4508 return cmp < 0;
4509 break;
e440a328 4510 case OPERATOR_LE:
0c77715b 4511 return cmp <= 0;
e440a328 4512 case OPERATOR_GT:
0c77715b 4513 return cmp > 0;
e440a328 4514 case OPERATOR_GE:
0c77715b 4515 return cmp >= 0;
e440a328 4516 default:
c3e6f413 4517 go_unreachable();
e440a328 4518 }
4519}
4520
0c77715b 4521// Compare constants according to OP.
e440a328 4522
4523bool
0c77715b 4524Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4525 Numeric_constant* right_nc,
4526 Location location, bool* result)
e440a328 4527{
0c77715b 4528 Type* left_type = left_nc->type();
4529 Type* right_type = right_nc->type();
4530
4531 Type* type;
4532 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4533 return false;
4534
4535 // When comparing an untyped operand to a typed operand, we are
4536 // effectively coercing the untyped operand to the other operand's
4537 // type, so make sure that is valid.
4538 if (!left_nc->set_type(type, true, location)
4539 || !right_nc->set_type(type, true, location))
4540 return false;
4541
4542 bool ret;
4543 int cmp;
4544 if (type->complex_type() != NULL)
4545 {
4546 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4547 return false;
4548 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4549 }
4550 else if (type->float_type() != NULL)
4551 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4552 else
0c77715b 4553 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4554
4555 if (ret)
4556 *result = Binary_expression::cmp_to_bool(op, cmp);
4557
4558 return ret;
4559}
4560
4561// Compare integer constants.
4562
4563bool
4564Binary_expression::compare_integer(const Numeric_constant* left_nc,
4565 const Numeric_constant* right_nc,
4566 int* cmp)
4567{
4568 mpz_t left_val;
4569 if (!left_nc->to_int(&left_val))
4570 return false;
4571 mpz_t right_val;
4572 if (!right_nc->to_int(&right_val))
e440a328 4573 {
0c77715b 4574 mpz_clear(left_val);
4575 return false;
e440a328 4576 }
0c77715b 4577
4578 *cmp = mpz_cmp(left_val, right_val);
4579
4580 mpz_clear(left_val);
4581 mpz_clear(right_val);
4582
4583 return true;
4584}
4585
4586// Compare floating point constants.
4587
4588bool
4589Binary_expression::compare_float(const Numeric_constant* left_nc,
4590 const Numeric_constant* right_nc,
4591 int* cmp)
4592{
4593 mpfr_t left_val;
4594 if (!left_nc->to_float(&left_val))
4595 return false;
4596 mpfr_t right_val;
4597 if (!right_nc->to_float(&right_val))
e440a328 4598 {
0c77715b 4599 mpfr_clear(left_val);
4600 return false;
4601 }
4602
4603 // We already coerced both operands to the same type. If that type
4604 // is not an abstract type, we need to round the values accordingly.
4605 Type* type = left_nc->type();
4606 if (!type->is_abstract() && type->float_type() != NULL)
4607 {
4608 int bits = type->float_type()->bits();
4609 mpfr_prec_round(left_val, bits, GMP_RNDN);
4610 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4611 }
0c77715b 4612
4613 *cmp = mpfr_cmp(left_val, right_val);
4614
4615 mpfr_clear(left_val);
4616 mpfr_clear(right_val);
4617
4618 return true;
e440a328 4619}
4620
0c77715b 4621// Compare complex constants. Complex numbers may only be compared
4622// for equality.
e440a328 4623
4624bool
0c77715b 4625Binary_expression::compare_complex(const Numeric_constant* left_nc,
4626 const Numeric_constant* right_nc,
4627 int* cmp)
e440a328 4628{
0c77715b 4629 mpfr_t left_real, left_imag;
4630 if (!left_nc->to_complex(&left_real, &left_imag))
4631 return false;
4632 mpfr_t right_real, right_imag;
4633 if (!right_nc->to_complex(&right_real, &right_imag))
e440a328 4634 {
0c77715b 4635 mpfr_clear(left_real);
4636 mpfr_clear(left_imag);
4637 return false;
e440a328 4638 }
0c77715b 4639
4640 // We already coerced both operands to the same type. If that type
4641 // is not an abstract type, we need to round the values accordingly.
4642 Type* type = left_nc->type();
4643 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4644 {
0c77715b 4645 int bits = type->complex_type()->bits();
4646 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4647 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4648 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4649 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
e440a328 4650 }
0c77715b 4651
4652 *cmp = (mpfr_cmp(left_real, right_real) != 0
4653 || mpfr_cmp(left_imag, right_imag) != 0);
4654
4655 mpfr_clear(left_real);
4656 mpfr_clear(left_imag);
4657 mpfr_clear(right_real);
4658 mpfr_clear(right_imag);
4659
4660 return true;
e440a328 4661}
4662
0c77715b 4663// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4664// true if this could be done, false if not. Issue errors at LOCATION
4665// as appropriate.
e440a328 4666
4667bool
0c77715b 4668Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4669 Numeric_constant* right_nc,
4670 Location location, Numeric_constant* nc)
e440a328 4671{
e440a328 4672 switch (op)
4673 {
4674 case OPERATOR_OROR:
4675 case OPERATOR_ANDAND:
4676 case OPERATOR_EQEQ:
4677 case OPERATOR_NOTEQ:
4678 case OPERATOR_LT:
4679 case OPERATOR_LE:
4680 case OPERATOR_GT:
4681 case OPERATOR_GE:
9767e2d3 4682 // These return boolean values, not numeric.
4683 return false;
0c77715b 4684 default:
4685 break;
4686 }
4687
4688 Type* left_type = left_nc->type();
4689 Type* right_type = right_nc->type();
4690
4691 Type* type;
4692 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4693 return false;
4694
4695 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4696
4697 // When combining an untyped operand with a typed operand, we are
4698 // effectively coercing the untyped operand to the other operand's
4699 // type, so make sure that is valid.
4700 if (!left_nc->set_type(type, true, location))
4701 return false;
4702 if (!is_shift && !right_nc->set_type(type, true, location))
4703 return false;
4704
4705 bool r;
4706 if (type->complex_type() != NULL)
4707 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4708 else if (type->float_type() != NULL)
4709 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4710 else
4711 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4712
4713 if (r)
4714 r = nc->set_type(type, true, location);
4715
4716 return r;
4717}
4718
4719// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4720// integer operations. Return true if this could be done, false if
4721// not.
4722
4723bool
4724Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4725 const Numeric_constant* right_nc,
4726 Location location, Numeric_constant* nc)
4727{
4728 mpz_t left_val;
4729 if (!left_nc->to_int(&left_val))
4730 return false;
4731 mpz_t right_val;
4732 if (!right_nc->to_int(&right_val))
4733 {
4734 mpz_clear(left_val);
e440a328 4735 return false;
0c77715b 4736 }
4737
4738 mpz_t val;
4739 mpz_init(val);
4740
4741 switch (op)
4742 {
e440a328 4743 case OPERATOR_PLUS:
4744 mpz_add(val, left_val, right_val);
4745 break;
4746 case OPERATOR_MINUS:
4747 mpz_sub(val, left_val, right_val);
4748 break;
4749 case OPERATOR_OR:
4750 mpz_ior(val, left_val, right_val);
4751 break;
4752 case OPERATOR_XOR:
4753 mpz_xor(val, left_val, right_val);
4754 break;
4755 case OPERATOR_MULT:
4756 mpz_mul(val, left_val, right_val);
4757 break;
4758 case OPERATOR_DIV:
4759 if (mpz_sgn(right_val) != 0)
4760 mpz_tdiv_q(val, left_val, right_val);
4761 else
4762 {
4763 error_at(location, "division by zero");
4764 mpz_set_ui(val, 0);
e440a328 4765 }
4766 break;
4767 case OPERATOR_MOD:
4768 if (mpz_sgn(right_val) != 0)
4769 mpz_tdiv_r(val, left_val, right_val);
4770 else
4771 {
4772 error_at(location, "division by zero");
4773 mpz_set_ui(val, 0);
e440a328 4774 }
4775 break;
4776 case OPERATOR_LSHIFT:
4777 {
4778 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4779 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4780 mpz_mul_2exp(val, left_val, shift);
4781 else
e440a328 4782 {
4783 error_at(location, "shift count overflow");
4784 mpz_set_ui(val, 0);
e440a328 4785 }
e440a328 4786 break;
4787 }
4788 break;
4789 case OPERATOR_RSHIFT:
4790 {
4791 unsigned long shift = mpz_get_ui(right_val);
4792 if (mpz_cmp_ui(right_val, shift) != 0)
4793 {
4794 error_at(location, "shift count overflow");
4795 mpz_set_ui(val, 0);
e440a328 4796 }
e440a328 4797 else
0c77715b 4798 {
4799 if (mpz_cmp_ui(left_val, 0) >= 0)
4800 mpz_tdiv_q_2exp(val, left_val, shift);
4801 else
4802 mpz_fdiv_q_2exp(val, left_val, shift);
4803 }
e440a328 4804 break;
4805 }
4806 break;
4807 case OPERATOR_AND:
4808 mpz_and(val, left_val, right_val);
4809 break;
4810 case OPERATOR_BITCLEAR:
4811 {
4812 mpz_t tval;
4813 mpz_init(tval);
4814 mpz_com(tval, right_val);
4815 mpz_and(val, left_val, tval);
4816 mpz_clear(tval);
4817 }
4818 break;
4819 default:
c3e6f413 4820 go_unreachable();
e440a328 4821 }
4822
0c77715b 4823 mpz_clear(left_val);
4824 mpz_clear(right_val);
e440a328 4825
0c77715b 4826 if (left_nc->is_rune()
4827 || (op != OPERATOR_LSHIFT
4828 && op != OPERATOR_RSHIFT
4829 && right_nc->is_rune()))
4830 nc->set_rune(NULL, val);
4831 else
4832 nc->set_int(NULL, val);
4833
4834 mpz_clear(val);
e440a328 4835
4836 return true;
4837}
4838
0c77715b 4839// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4840// floating point operations. Return true if this could be done,
4841// false if not.
e440a328 4842
4843bool
0c77715b 4844Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4845 const Numeric_constant* right_nc,
4846 Location location, Numeric_constant* nc)
e440a328 4847{
0c77715b 4848 mpfr_t left_val;
4849 if (!left_nc->to_float(&left_val))
4850 return false;
4851 mpfr_t right_val;
4852 if (!right_nc->to_float(&right_val))
e440a328 4853 {
0c77715b 4854 mpfr_clear(left_val);
e440a328 4855 return false;
0c77715b 4856 }
4857
4858 mpfr_t val;
4859 mpfr_init(val);
4860
4861 bool ret = true;
4862 switch (op)
4863 {
e440a328 4864 case OPERATOR_PLUS:
4865 mpfr_add(val, left_val, right_val, GMP_RNDN);
4866 break;
4867 case OPERATOR_MINUS:
4868 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4869 break;
4870 case OPERATOR_OR:
4871 case OPERATOR_XOR:
4872 case OPERATOR_AND:
4873 case OPERATOR_BITCLEAR:
0c77715b 4874 case OPERATOR_MOD:
4875 case OPERATOR_LSHIFT:
4876 case OPERATOR_RSHIFT:
4877 mpfr_set_ui(val, 0, GMP_RNDN);
4878 ret = false;
4879 break;
e440a328 4880 case OPERATOR_MULT:
4881 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4882 break;
4883 case OPERATOR_DIV:
0c77715b 4884 if (!mpfr_zero_p(right_val))
4885 mpfr_div(val, left_val, right_val, GMP_RNDN);
4886 else
4887 {
4888 error_at(location, "division by zero");
4889 mpfr_set_ui(val, 0, GMP_RNDN);
4890 }
e440a328 4891 break;
e440a328 4892 default:
c3e6f413 4893 go_unreachable();
e440a328 4894 }
4895
0c77715b 4896 mpfr_clear(left_val);
4897 mpfr_clear(right_val);
e440a328 4898
0c77715b 4899 nc->set_float(NULL, val);
4900 mpfr_clear(val);
e440a328 4901
0c77715b 4902 return ret;
e440a328 4903}
4904
0c77715b 4905// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4906// complex operations. Return true if this could be done, false if
4907// not.
e440a328 4908
4909bool
0c77715b 4910Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4911 const Numeric_constant* right_nc,
4912 Location location, Numeric_constant* nc)
e440a328 4913{
0c77715b 4914 mpfr_t left_real, left_imag;
4915 if (!left_nc->to_complex(&left_real, &left_imag))
4916 return false;
4917 mpfr_t right_real, right_imag;
4918 if (!right_nc->to_complex(&right_real, &right_imag))
e440a328 4919 {
0c77715b 4920 mpfr_clear(left_real);
4921 mpfr_clear(left_imag);
e440a328 4922 return false;
0c77715b 4923 }
4924
4925 mpfr_t real, imag;
4926 mpfr_init(real);
4927 mpfr_init(imag);
4928
4929 bool ret = true;
4930 switch (op)
4931 {
e440a328 4932 case OPERATOR_PLUS:
4933 mpfr_add(real, left_real, right_real, GMP_RNDN);
4934 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4935 break;
4936 case OPERATOR_MINUS:
4937 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4938 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4939 break;
4940 case OPERATOR_OR:
4941 case OPERATOR_XOR:
4942 case OPERATOR_AND:
4943 case OPERATOR_BITCLEAR:
0c77715b 4944 case OPERATOR_MOD:
4945 case OPERATOR_LSHIFT:
4946 case OPERATOR_RSHIFT:
4947 mpfr_set_ui(real, 0, GMP_RNDN);
4948 mpfr_set_ui(imag, 0, GMP_RNDN);
4949 ret = false;
4950 break;
e440a328 4951 case OPERATOR_MULT:
4952 {
4953 // You might think that multiplying two complex numbers would
4954 // be simple, and you would be right, until you start to think
4955 // about getting the right answer for infinity. If one
4956 // operand here is infinity and the other is anything other
4957 // than zero or NaN, then we are going to wind up subtracting
4958 // two infinity values. That will give us a NaN, but the
4959 // correct answer is infinity.
4960
4961 mpfr_t lrrr;
4962 mpfr_init(lrrr);
4963 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4964
4965 mpfr_t lrri;
4966 mpfr_init(lrri);
4967 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4968
4969 mpfr_t lirr;
4970 mpfr_init(lirr);
4971 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4972
4973 mpfr_t liri;
4974 mpfr_init(liri);
4975 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4976
4977 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4978 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4979
4980 // If we get NaN on both sides, check whether it should really
4981 // be infinity. The rule is that if either side of the
4982 // complex number is infinity, then the whole value is
4983 // infinity, even if the other side is NaN. So the only case
4984 // we have to fix is the one in which both sides are NaN.
4985 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4986 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4987 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4988 {
4989 bool is_infinity = false;
4990
4991 mpfr_t lr;
4992 mpfr_t li;
4993 mpfr_init_set(lr, left_real, GMP_RNDN);
4994 mpfr_init_set(li, left_imag, GMP_RNDN);
4995
4996 mpfr_t rr;
4997 mpfr_t ri;
4998 mpfr_init_set(rr, right_real, GMP_RNDN);
4999 mpfr_init_set(ri, right_imag, GMP_RNDN);
5000
5001 // If the left side is infinity, then the result is
5002 // infinity.
5003 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
5004 {
5005 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
5006 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5007 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
5008 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5009 if (mpfr_nan_p(rr))
5010 {
5011 mpfr_set_ui(rr, 0, GMP_RNDN);
5012 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5013 }
5014 if (mpfr_nan_p(ri))
5015 {
5016 mpfr_set_ui(ri, 0, GMP_RNDN);
5017 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5018 }
5019 is_infinity = true;
5020 }
5021
5022 // If the right side is infinity, then the result is
5023 // infinity.
5024 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
5025 {
5026 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5027 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5028 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5029 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5030 if (mpfr_nan_p(lr))
5031 {
5032 mpfr_set_ui(lr, 0, GMP_RNDN);
5033 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5034 }
5035 if (mpfr_nan_p(li))
5036 {
5037 mpfr_set_ui(li, 0, GMP_RNDN);
5038 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5039 }
5040 is_infinity = true;
5041 }
5042
5043 // If we got an overflow in the intermediate computations,
5044 // then the result is infinity.
5045 if (!is_infinity
5046 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
5047 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
5048 {
5049 if (mpfr_nan_p(lr))
5050 {
5051 mpfr_set_ui(lr, 0, GMP_RNDN);
5052 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5053 }
5054 if (mpfr_nan_p(li))
5055 {
5056 mpfr_set_ui(li, 0, GMP_RNDN);
5057 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5058 }
5059 if (mpfr_nan_p(rr))
5060 {
5061 mpfr_set_ui(rr, 0, GMP_RNDN);
5062 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5063 }
5064 if (mpfr_nan_p(ri))
5065 {
5066 mpfr_set_ui(ri, 0, GMP_RNDN);
5067 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5068 }
5069 is_infinity = true;
5070 }
5071
5072 if (is_infinity)
5073 {
5074 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
5075 mpfr_mul(lrri, lr, ri, GMP_RNDN);
5076 mpfr_mul(lirr, li, rr, GMP_RNDN);
5077 mpfr_mul(liri, li, ri, GMP_RNDN);
5078 mpfr_sub(real, lrrr, liri, GMP_RNDN);
5079 mpfr_add(imag, lrri, lirr, GMP_RNDN);
5080 mpfr_set_inf(real, mpfr_sgn(real));
5081 mpfr_set_inf(imag, mpfr_sgn(imag));
5082 }
5083
5084 mpfr_clear(lr);
5085 mpfr_clear(li);
5086 mpfr_clear(rr);
5087 mpfr_clear(ri);
5088 }
5089
5090 mpfr_clear(lrrr);
5091 mpfr_clear(lrri);
5092 mpfr_clear(lirr);
5093 mpfr_clear(liri);
5094 }
5095 break;
5096 case OPERATOR_DIV:
5097 {
5098 // For complex division we want to avoid having an
5099 // intermediate overflow turn the whole result in a NaN. We
5100 // scale the values to try to avoid this.
5101
5102 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
0c77715b 5103 {
5104 error_at(location, "division by zero");
5105 mpfr_set_ui(real, 0, GMP_RNDN);
5106 mpfr_set_ui(imag, 0, GMP_RNDN);
5107 break;
5108 }
e440a328 5109
5110 mpfr_t rra;
5111 mpfr_t ria;
5112 mpfr_init(rra);
5113 mpfr_init(ria);
5114 mpfr_abs(rra, right_real, GMP_RNDN);
5115 mpfr_abs(ria, right_imag, GMP_RNDN);
5116 mpfr_t t;
5117 mpfr_init(t);
5118 mpfr_max(t, rra, ria, GMP_RNDN);
5119
5120 mpfr_t rr;
5121 mpfr_t ri;
5122 mpfr_init_set(rr, right_real, GMP_RNDN);
5123 mpfr_init_set(ri, right_imag, GMP_RNDN);
5124 long ilogbw = 0;
5125 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5126 {
5127 ilogbw = mpfr_get_exp(t);
5128 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5129 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5130 }
5131
5132 mpfr_t denom;
5133 mpfr_init(denom);
5134 mpfr_mul(denom, rr, rr, GMP_RNDN);
5135 mpfr_mul(t, ri, ri, GMP_RNDN);
5136 mpfr_add(denom, denom, t, GMP_RNDN);
5137
5138 mpfr_mul(real, left_real, rr, GMP_RNDN);
5139 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5140 mpfr_add(real, real, t, GMP_RNDN);
5141 mpfr_div(real, real, denom, GMP_RNDN);
5142 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5143
5144 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5145 mpfr_mul(t, left_real, ri, GMP_RNDN);
5146 mpfr_sub(imag, imag, t, GMP_RNDN);
5147 mpfr_div(imag, imag, denom, GMP_RNDN);
5148 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5149
5150 // If we wind up with NaN on both sides, check whether we
5151 // should really have infinity. The rule is that if either
5152 // side of the complex number is infinity, then the whole
5153 // value is infinity, even if the other side is NaN. So the
5154 // only case we have to fix is the one in which both sides are
5155 // NaN.
5156 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5157 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5158 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5159 {
5160 if (mpfr_zero_p(denom))
5161 {
5162 mpfr_set_inf(real, mpfr_sgn(rr));
5163 mpfr_mul(real, real, left_real, GMP_RNDN);
5164 mpfr_set_inf(imag, mpfr_sgn(rr));
5165 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5166 }
5167 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5168 && mpfr_number_p(rr) && mpfr_number_p(ri))
5169 {
5170 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5171 mpfr_copysign(t, t, left_real, GMP_RNDN);
5172
5173 mpfr_t t2;
5174 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5175 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5176
5177 mpfr_t t3;
5178 mpfr_init(t3);
5179 mpfr_mul(t3, t, rr, GMP_RNDN);
5180
5181 mpfr_t t4;
5182 mpfr_init(t4);
5183 mpfr_mul(t4, t2, ri, GMP_RNDN);
5184
5185 mpfr_add(t3, t3, t4, GMP_RNDN);
5186 mpfr_set_inf(real, mpfr_sgn(t3));
5187
5188 mpfr_mul(t3, t2, rr, GMP_RNDN);
5189 mpfr_mul(t4, t, ri, GMP_RNDN);
5190 mpfr_sub(t3, t3, t4, GMP_RNDN);
5191 mpfr_set_inf(imag, mpfr_sgn(t3));
5192
5193 mpfr_clear(t2);
5194 mpfr_clear(t3);
5195 mpfr_clear(t4);
5196 }
5197 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5198 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5199 {
5200 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5201 mpfr_copysign(t, t, rr, GMP_RNDN);
5202
5203 mpfr_t t2;
5204 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5205 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5206
5207 mpfr_t t3;
5208 mpfr_init(t3);
5209 mpfr_mul(t3, left_real, t, GMP_RNDN);
5210
5211 mpfr_t t4;
5212 mpfr_init(t4);
5213 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5214
5215 mpfr_add(t3, t3, t4, GMP_RNDN);
5216 mpfr_set_ui(real, 0, GMP_RNDN);
5217 mpfr_mul(real, real, t3, GMP_RNDN);
5218
5219 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5220 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5221 mpfr_sub(t3, t3, t4, GMP_RNDN);
5222 mpfr_set_ui(imag, 0, GMP_RNDN);
5223 mpfr_mul(imag, imag, t3, GMP_RNDN);
5224
5225 mpfr_clear(t2);
5226 mpfr_clear(t3);
5227 mpfr_clear(t4);
5228 }
5229 }
5230
5231 mpfr_clear(denom);
5232 mpfr_clear(rr);
5233 mpfr_clear(ri);
5234 mpfr_clear(t);
5235 mpfr_clear(rra);
5236 mpfr_clear(ria);
5237 }
5238 break;
e440a328 5239 default:
c3e6f413 5240 go_unreachable();
e440a328 5241 }
5242
0c77715b 5243 mpfr_clear(left_real);
5244 mpfr_clear(left_imag);
5245 mpfr_clear(right_real);
5246 mpfr_clear(right_imag);
e440a328 5247
0c77715b 5248 nc->set_complex(NULL, real, imag);
5249 mpfr_clear(real);
5250 mpfr_clear(imag);
e440a328 5251
0c77715b 5252 return ret;
e440a328 5253}
5254
5255// Lower a binary expression. We have to evaluate constant
5256// expressions now, in order to implement Go's unlimited precision
5257// constants.
5258
5259Expression*
e9d3367e 5260Binary_expression::do_lower(Gogo* gogo, Named_object*,
5261 Statement_inserter* inserter, int)
e440a328 5262{
b13c66cd 5263 Location location = this->location();
e440a328 5264 Operator op = this->op_;
5265 Expression* left = this->left_;
5266 Expression* right = this->right_;
5267
5268 const bool is_comparison = (op == OPERATOR_EQEQ
5269 || op == OPERATOR_NOTEQ
5270 || op == OPERATOR_LT
5271 || op == OPERATOR_LE
5272 || op == OPERATOR_GT
5273 || op == OPERATOR_GE);
5274
0c77715b 5275 // Numeric constant expressions.
e440a328 5276 {
0c77715b 5277 Numeric_constant left_nc;
5278 Numeric_constant right_nc;
5279 if (left->numeric_constant_value(&left_nc)
5280 && right->numeric_constant_value(&right_nc))
e440a328 5281 {
0c77715b 5282 if (is_comparison)
e440a328 5283 {
0c77715b 5284 bool result;
5285 if (!Binary_expression::compare_constant(op, &left_nc,
5286 &right_nc, location,
5287 &result))
5288 return this;
e90c9dfc 5289 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 5290 Expression::make_boolean(result,
5291 location),
5292 location);
e440a328 5293 }
5294 else
5295 {
0c77715b 5296 Numeric_constant nc;
5297 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5298 location, &nc))
5299 return this;
5300 return nc.expression(location);
e440a328 5301 }
5302 }
e440a328 5303 }
5304
5305 // String constant expressions.
315fa98d 5306 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 5307 {
5308 std::string left_string;
5309 std::string right_string;
5310 if (left->string_constant_value(&left_string)
5311 && right->string_constant_value(&right_string))
315fa98d 5312 {
5313 if (op == OPERATOR_PLUS)
5314 return Expression::make_string(left_string + right_string,
5315 location);
5316 else if (is_comparison)
5317 {
5318 int cmp = left_string.compare(right_string);
0c77715b 5319 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 5320 return Expression::make_boolean(r, location);
b40dc774 5321 }
5322 }
b40dc774 5323 }
5324
ceeb12d7 5325 // Lower struct, array, and some interface comparisons.
e9d3367e 5326 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5327 {
5328 if (left->type()->struct_type() != NULL)
5329 return this->lower_struct_comparison(gogo, inserter);
5330 else if (left->type()->array_type() != NULL
5331 && !left->type()->is_slice_type())
5332 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 5333 else if ((left->type()->interface_type() != NULL
5334 && right->type()->interface_type() == NULL)
5335 || (left->type()->interface_type() == NULL
5336 && right->type()->interface_type() != NULL))
5337 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 5338 }
5339
e440a328 5340 return this;
5341}
5342
e9d3367e 5343// Lower a struct comparison.
5344
5345Expression*
5346Binary_expression::lower_struct_comparison(Gogo* gogo,
5347 Statement_inserter* inserter)
5348{
5349 Struct_type* st = this->left_->type()->struct_type();
5350 Struct_type* st2 = this->right_->type()->struct_type();
5351 if (st2 == NULL)
5352 return this;
5353 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5354 return this;
5355 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5356 this->right_->type(), NULL))
5357 return this;
5358
5359 // See if we can compare using memcmp. As a heuristic, we use
5360 // memcmp rather than field references and comparisons if there are
5361 // more than two fields.
113ef6a5 5362 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 5363 return this->lower_compare_to_memcmp(gogo, inserter);
5364
5365 Location loc = this->location();
5366
5367 Expression* left = this->left_;
5368 Temporary_statement* left_temp = NULL;
5369 if (left->var_expression() == NULL
5370 && left->temporary_reference_expression() == NULL)
5371 {
5372 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5373 inserter->insert(left_temp);
5374 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5375 }
5376
5377 Expression* right = this->right_;
5378 Temporary_statement* right_temp = NULL;
5379 if (right->var_expression() == NULL
5380 && right->temporary_reference_expression() == NULL)
5381 {
5382 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5383 inserter->insert(right_temp);
5384 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5385 }
5386
5387 Expression* ret = Expression::make_boolean(true, loc);
5388 const Struct_field_list* fields = st->fields();
5389 unsigned int field_index = 0;
5390 for (Struct_field_list::const_iterator pf = fields->begin();
5391 pf != fields->end();
5392 ++pf, ++field_index)
5393 {
f5165c05 5394 if (Gogo::is_sink_name(pf->field_name()))
5395 continue;
5396
e9d3367e 5397 if (field_index > 0)
5398 {
5399 if (left_temp == NULL)
5400 left = left->copy();
5401 else
5402 left = Expression::make_temporary_reference(left_temp, loc);
5403 if (right_temp == NULL)
5404 right = right->copy();
5405 else
5406 right = Expression::make_temporary_reference(right_temp, loc);
5407 }
5408 Expression* f1 = Expression::make_field_reference(left, field_index,
5409 loc);
5410 Expression* f2 = Expression::make_field_reference(right, field_index,
5411 loc);
5412 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5413 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5414 }
5415
5416 if (this->op_ == OPERATOR_NOTEQ)
5417 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5418
5419 return ret;
5420}
5421
5422// Lower an array comparison.
5423
5424Expression*
5425Binary_expression::lower_array_comparison(Gogo* gogo,
5426 Statement_inserter* inserter)
5427{
5428 Array_type* at = this->left_->type()->array_type();
5429 Array_type* at2 = this->right_->type()->array_type();
5430 if (at2 == NULL)
5431 return this;
5432 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5433 return this;
5434 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5435 this->right_->type(), NULL))
5436 return this;
5437
5438 // Call memcmp directly if possible. This may let the middle-end
5439 // optimize the call.
113ef6a5 5440 if (at->compare_is_identity(gogo))
e9d3367e 5441 return this->lower_compare_to_memcmp(gogo, inserter);
5442
5443 // Call the array comparison function.
5444 Named_object* hash_fn;
5445 Named_object* equal_fn;
5446 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5447 &hash_fn, &equal_fn);
5448
5449 Location loc = this->location();
5450
5451 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5452
5453 Expression_list* args = new Expression_list();
5454 args->push_back(this->operand_address(inserter, this->left_));
5455 args->push_back(this->operand_address(inserter, this->right_));
5456 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5457
5458 Expression* ret = Expression::make_call(func, args, false, loc);
5459
5460 if (this->op_ == OPERATOR_NOTEQ)
5461 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5462
5463 return ret;
5464}
5465
ceeb12d7 5466// Lower an interface to value comparison.
5467
5468Expression*
5469Binary_expression::lower_interface_value_comparison(Gogo*,
5470 Statement_inserter* inserter)
5471{
5472 Type* left_type = this->left_->type();
5473 Type* right_type = this->right_->type();
5474 Interface_type* ift;
5475 if (left_type->interface_type() != NULL)
5476 {
5477 ift = left_type->interface_type();
5478 if (!ift->implements_interface(right_type, NULL))
5479 return this;
5480 }
5481 else
5482 {
5483 ift = right_type->interface_type();
5484 if (!ift->implements_interface(left_type, NULL))
5485 return this;
5486 }
5487 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5488 return this;
5489
5490 Location loc = this->location();
5491
5492 if (left_type->interface_type() == NULL
5493 && left_type->points_to() == NULL
5494 && !this->left_->is_addressable())
5495 {
5496 Temporary_statement* temp =
5497 Statement::make_temporary(left_type, NULL, loc);
5498 inserter->insert(temp);
5499 this->left_ =
5500 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5501 }
5502
5503 if (right_type->interface_type() == NULL
5504 && right_type->points_to() == NULL
5505 && !this->right_->is_addressable())
5506 {
5507 Temporary_statement* temp =
5508 Statement::make_temporary(right_type, NULL, loc);
5509 inserter->insert(temp);
5510 this->right_ =
5511 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5512 }
5513
5514 return this;
5515}
5516
e9d3367e 5517// Lower a struct or array comparison to a call to memcmp.
5518
5519Expression*
5520Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5521{
5522 Location loc = this->location();
5523
5524 Expression* a1 = this->operand_address(inserter, this->left_);
5525 Expression* a2 = this->operand_address(inserter, this->right_);
5526 Expression* len = Expression::make_type_info(this->left_->type(),
5527 TYPE_INFO_SIZE);
5528
5529 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5530
5531 mpz_t zval;
5532 mpz_init_set_ui(zval, 0);
5533 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5534 mpz_clear(zval);
5535
5536 return Expression::make_binary(this->op_, call, zero, loc);
5537}
5538
a32698ee 5539Expression*
5540Binary_expression::do_flatten(Gogo*, Named_object*,
5541 Statement_inserter* inserter)
5542{
5543 Location loc = this->location();
5544 Temporary_statement* temp;
5545 if (this->left_->type()->is_string_type()
5546 && this->op_ == OPERATOR_PLUS)
5547 {
5548 if (!this->left_->is_variable())
5549 {
5550 temp = Statement::make_temporary(NULL, this->left_, loc);
5551 inserter->insert(temp);
5552 this->left_ = Expression::make_temporary_reference(temp, loc);
5553 }
5554 if (!this->right_->is_variable())
5555 {
5556 temp =
5557 Statement::make_temporary(this->left_->type(), this->right_, loc);
5558 this->right_ = Expression::make_temporary_reference(temp, loc);
5559 inserter->insert(temp);
5560 }
5561 }
5562
5563 Type* left_type = this->left_->type();
5564 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5565 || this->op_ == OPERATOR_RSHIFT);
5566 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5567 left_type->integer_type() != NULL)
5568 || this->op_ == OPERATOR_MOD);
5569
5570 // FIXME: go_check_divide_zero and go_check_divide_overflow are globals
5571 // defined in gcc/go/lang.opt. These should be defined in go_create_gogo
5572 // and accessed from the Gogo* passed to do_flatten.
5573 if (is_shift_op
5574 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5575 {
5576 if (!this->left_->is_variable())
5577 {
5578 temp = Statement::make_temporary(NULL, this->left_, loc);
5579 inserter->insert(temp);
5580 this->left_ = Expression::make_temporary_reference(temp, loc);
5581 }
5582 if (!this->right_->is_variable())
5583 {
5584 temp =
5585 Statement::make_temporary(NULL, this->right_, loc);
5586 this->right_ = Expression::make_temporary_reference(temp, loc);
5587 inserter->insert(temp);
5588 }
5589 }
5590 return this;
5591}
5592
5593
e9d3367e 5594// Return the address of EXPR, cast to unsafe.Pointer.
5595
5596Expression*
5597Binary_expression::operand_address(Statement_inserter* inserter,
5598 Expression* expr)
5599{
5600 Location loc = this->location();
5601
5602 if (!expr->is_addressable())
5603 {
5604 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5605 loc);
5606 inserter->insert(temp);
5607 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5608 }
5609 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5610 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5611 Type* void_type = Type::make_void_type();
5612 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5613 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5614}
5615
0c77715b 5616// Return the numeric constant value, if it has one.
e440a328 5617
5618bool
0c77715b 5619Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5620{
0c77715b 5621 Numeric_constant left_nc;
5622 if (!this->left_->numeric_constant_value(&left_nc))
5623 return false;
5624 Numeric_constant right_nc;
5625 if (!this->right_->numeric_constant_value(&right_nc))
5626 return false;
9767e2d3 5627 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5628 this->location(), nc);
e440a328 5629}
5630
5631// Note that the value is being discarded.
5632
4f2138d7 5633bool
e440a328 5634Binary_expression::do_discarding_value()
5635{
5636 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5637 return this->right_->discarding_value();
e440a328 5638 else
4f2138d7 5639 {
5640 this->unused_value_error();
5641 return false;
5642 }
e440a328 5643}
5644
5645// Get type.
5646
5647Type*
5648Binary_expression::do_type()
5649{
5f5fea79 5650 if (this->classification() == EXPRESSION_ERROR)
5651 return Type::make_error_type();
5652
e440a328 5653 switch (this->op_)
5654 {
e440a328 5655 case OPERATOR_EQEQ:
5656 case OPERATOR_NOTEQ:
5657 case OPERATOR_LT:
5658 case OPERATOR_LE:
5659 case OPERATOR_GT:
5660 case OPERATOR_GE:
e90c9dfc 5661 if (this->type_ == NULL)
5662 this->type_ = Type::make_boolean_type();
5663 return this->type_;
e440a328 5664
5665 case OPERATOR_PLUS:
5666 case OPERATOR_MINUS:
5667 case OPERATOR_OR:
5668 case OPERATOR_XOR:
5669 case OPERATOR_MULT:
5670 case OPERATOR_DIV:
5671 case OPERATOR_MOD:
5672 case OPERATOR_AND:
5673 case OPERATOR_BITCLEAR:
e90c9dfc 5674 case OPERATOR_OROR:
5675 case OPERATOR_ANDAND:
e440a328 5676 {
0c77715b 5677 Type* type;
5678 if (!Binary_expression::operation_type(this->op_,
5679 this->left_->type(),
5680 this->right_->type(),
5681 &type))
5682 return Type::make_error_type();
5683 return type;
e440a328 5684 }
5685
5686 case OPERATOR_LSHIFT:
5687 case OPERATOR_RSHIFT:
5688 return this->left_->type();
5689
5690 default:
c3e6f413 5691 go_unreachable();
e440a328 5692 }
5693}
5694
5695// Set type for a binary expression.
5696
5697void
5698Binary_expression::do_determine_type(const Type_context* context)
5699{
5700 Type* tleft = this->left_->type();
5701 Type* tright = this->right_->type();
5702
5703 // Both sides should have the same type, except for the shift
5704 // operations. For a comparison, we should ignore the incoming
5705 // type.
5706
5707 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5708 || this->op_ == OPERATOR_RSHIFT);
5709
5710 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5711 || this->op_ == OPERATOR_NOTEQ
5712 || this->op_ == OPERATOR_LT
5713 || this->op_ == OPERATOR_LE
5714 || this->op_ == OPERATOR_GT
5715 || this->op_ == OPERATOR_GE);
5716
5717 Type_context subcontext(*context);
5718
5719 if (is_comparison)
5720 {
5721 // In a comparison, the context does not determine the types of
5722 // the operands.
5723 subcontext.type = NULL;
5724 }
5725
02ffd97f 5726 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5727 {
5728 // For a logical operation, the context does not determine the
5729 // types of the operands. The operands must be some boolean
5730 // type but if the context has a boolean type they do not
5731 // inherit it. See http://golang.org/issue/3924.
5732 subcontext.type = NULL;
5733 }
5734
e440a328 5735 // Set the context for the left hand operand.
5736 if (is_shift_op)
5737 {
b40dc774 5738 // The right hand operand of a shift plays no role in
5739 // determining the type of the left hand operand.
e440a328 5740 }
5741 else if (!tleft->is_abstract())
5742 subcontext.type = tleft;
5743 else if (!tright->is_abstract())
5744 subcontext.type = tright;
5745 else if (subcontext.type == NULL)
5746 {
5747 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5748 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5749 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5750 {
5751 // Both sides have an abstract integer, abstract float, or
5752 // abstract complex type. Just let CONTEXT determine
5753 // whether they may remain abstract or not.
5754 }
5755 else if (tleft->complex_type() != NULL)
5756 subcontext.type = tleft;
5757 else if (tright->complex_type() != NULL)
5758 subcontext.type = tright;
5759 else if (tleft->float_type() != NULL)
5760 subcontext.type = tleft;
5761 else if (tright->float_type() != NULL)
5762 subcontext.type = tright;
5763 else
5764 subcontext.type = tleft;
f58a23ae 5765
5766 if (subcontext.type != NULL && !context->may_be_abstract)
5767 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5768 }
5769
5770 this->left_->determine_type(&subcontext);
5771
e440a328 5772 if (is_shift_op)
5773 {
b40dc774 5774 // We may have inherited an unusable type for the shift operand.
5775 // Give a useful error if that happened.
5776 if (tleft->is_abstract()
5777 && subcontext.type != NULL
8ab6effb 5778 && !subcontext.may_be_abstract
f6bc81e6 5779 && subcontext.type->interface_type() == NULL
8ab6effb 5780 && subcontext.type->integer_type() == NULL)
b40dc774 5781 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5782 "for left operand of shift"));
b40dc774 5783
5784 // The context for the right hand operand is the same as for the
5785 // left hand operand, except for a shift operator.
e440a328 5786 subcontext.type = Type::lookup_integer_type("uint");
5787 subcontext.may_be_abstract = false;
5788 }
5789
5790 this->right_->determine_type(&subcontext);
e90c9dfc 5791
5792 if (is_comparison)
5793 {
5794 if (this->type_ != NULL && !this->type_->is_abstract())
5795 ;
5796 else if (context->type != NULL && context->type->is_boolean_type())
5797 this->type_ = context->type;
5798 else if (!context->may_be_abstract)
5799 this->type_ = Type::lookup_bool_type();
5800 }
e440a328 5801}
5802
5803// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5804// OTYPE is the type of the other operand. Return whether the
5805// operation is OK. This should not be used for shift.
e440a328 5806
5807bool
be8b5eee 5808Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5809 Location location)
e440a328 5810{
5811 switch (op)
5812 {
5813 case OPERATOR_OROR:
5814 case OPERATOR_ANDAND:
5815 if (!type->is_boolean_type())
5816 {
5817 error_at(location, "expected boolean type");
5818 return false;
5819 }
5820 break;
5821
5822 case OPERATOR_EQEQ:
5823 case OPERATOR_NOTEQ:
e9d3367e 5824 {
5825 std::string reason;
5826 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5827 {
5828 error_at(location, "%s", reason.c_str());
5829 return false;
5830 }
5831 }
e440a328 5832 break;
5833
5834 case OPERATOR_LT:
5835 case OPERATOR_LE:
5836 case OPERATOR_GT:
5837 case OPERATOR_GE:
e9d3367e 5838 {
5839 std::string reason;
5840 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5841 {
5842 error_at(location, "%s", reason.c_str());
5843 return false;
5844 }
5845 }
e440a328 5846 break;
5847
5848 case OPERATOR_PLUS:
5849 case OPERATOR_PLUSEQ:
5850 if (type->integer_type() == NULL
5851 && type->float_type() == NULL
5852 && type->complex_type() == NULL
5853 && !type->is_string_type())
5854 {
5855 error_at(location,
5856 "expected integer, floating, complex, or string type");
5857 return false;
5858 }
5859 break;
5860
5861 case OPERATOR_MINUS:
5862 case OPERATOR_MINUSEQ:
5863 case OPERATOR_MULT:
5864 case OPERATOR_MULTEQ:
5865 case OPERATOR_DIV:
5866 case OPERATOR_DIVEQ:
5867 if (type->integer_type() == NULL
5868 && type->float_type() == NULL
5869 && type->complex_type() == NULL)
5870 {
5871 error_at(location, "expected integer, floating, or complex type");
5872 return false;
5873 }
5874 break;
5875
5876 case OPERATOR_MOD:
5877 case OPERATOR_MODEQ:
5878 case OPERATOR_OR:
5879 case OPERATOR_OREQ:
5880 case OPERATOR_AND:
5881 case OPERATOR_ANDEQ:
5882 case OPERATOR_XOR:
5883 case OPERATOR_XOREQ:
5884 case OPERATOR_BITCLEAR:
5885 case OPERATOR_BITCLEAREQ:
5886 if (type->integer_type() == NULL)
5887 {
5888 error_at(location, "expected integer type");
5889 return false;
5890 }
5891 break;
5892
5893 default:
c3e6f413 5894 go_unreachable();
e440a328 5895 }
5896
5897 return true;
5898}
5899
5900// Check types.
5901
5902void
5903Binary_expression::do_check_types(Gogo*)
5904{
5f5fea79 5905 if (this->classification() == EXPRESSION_ERROR)
5906 return;
5907
e440a328 5908 Type* left_type = this->left_->type();
5909 Type* right_type = this->right_->type();
5c13bd80 5910 if (left_type->is_error() || right_type->is_error())
9fe897ef 5911 {
5912 this->set_is_error();
5913 return;
5914 }
e440a328 5915
5916 if (this->op_ == OPERATOR_EQEQ
5917 || this->op_ == OPERATOR_NOTEQ
5918 || this->op_ == OPERATOR_LT
5919 || this->op_ == OPERATOR_LE
5920 || this->op_ == OPERATOR_GT
5921 || this->op_ == OPERATOR_GE)
5922 {
907c5ecd 5923 if (left_type->is_nil_type() && right_type->is_nil_type())
5924 {
5925 this->report_error(_("invalid comparison of nil with nil"));
5926 return;
5927 }
e440a328 5928 if (!Type::are_assignable(left_type, right_type, NULL)
5929 && !Type::are_assignable(right_type, left_type, NULL))
5930 {
5931 this->report_error(_("incompatible types in binary expression"));
5932 return;
5933 }
5934 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5935 right_type,
e440a328 5936 this->location())
5937 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5938 left_type,
e440a328 5939 this->location()))
5940 {
5941 this->set_is_error();
5942 return;
5943 }
5944 }
5945 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5946 {
5947 if (!Type::are_compatible_for_binop(left_type, right_type))
5948 {
5949 this->report_error(_("incompatible types in binary expression"));
5950 return;
5951 }
5952 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5953 right_type,
e440a328 5954 this->location()))
5955 {
5956 this->set_is_error();
5957 return;
5958 }
5c65b19d 5959 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5960 {
5961 // Division by a zero integer constant is an error.
5962 Numeric_constant rconst;
5963 unsigned long rval;
5964 if (left_type->integer_type() != NULL
5965 && this->right_->numeric_constant_value(&rconst)
5966 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5967 && rval == 0)
5968 {
5969 this->report_error(_("integer division by zero"));
5970 return;
5971 }
5972 }
e440a328 5973 }
5974 else
5975 {
5976 if (left_type->integer_type() == NULL)
5977 this->report_error(_("shift of non-integer operand"));
5978
5979 if (!right_type->is_abstract()
5980 && (right_type->integer_type() == NULL
5981 || !right_type->integer_type()->is_unsigned()))
5982 this->report_error(_("shift count not unsigned integer"));
5983 else
5984 {
0c77715b 5985 Numeric_constant nc;
5986 if (this->right_->numeric_constant_value(&nc))
e440a328 5987 {
0c77715b 5988 mpz_t val;
5989 if (!nc.to_int(&val))
5990 this->report_error(_("shift count not unsigned integer"));
5991 else
a4eba91b 5992 {
0c77715b 5993 if (mpz_sgn(val) < 0)
5994 {
5995 this->report_error(_("negative shift count"));
5996 mpz_set_ui(val, 0);
5997 Location rloc = this->right_->location();
5998 this->right_ = Expression::make_integer(&val, right_type,
5999 rloc);
6000 }
6001 mpz_clear(val);
a4eba91b 6002 }
e440a328 6003 }
e440a328 6004 }
6005 }
6006}
6007
6008// Get a tree for a binary expression.
6009
6010tree
6011Binary_expression::do_get_tree(Translate_context* context)
6012{
1b1f2abf 6013 Gogo* gogo = context->gogo();
a32698ee 6014 Location loc = this->location();
6015 Type* left_type = this->left_->type();
6016 Type* right_type = this->right_->type();
1b1f2abf 6017
e440a328 6018 bool use_left_type = true;
6019 bool is_shift_op = false;
29a2d1d8 6020 bool is_idiv_op = false;
e440a328 6021 switch (this->op_)
6022 {
6023 case OPERATOR_EQEQ:
6024 case OPERATOR_NOTEQ:
6025 case OPERATOR_LT:
6026 case OPERATOR_LE:
6027 case OPERATOR_GT:
6028 case OPERATOR_GE:
a32698ee 6029 {
6030 Bexpression* ret =
6031 Expression::comparison(context, this->type_, this->op_,
6032 this->left_, this->right_, loc);
6033 return expr_to_tree(ret);
6034 }
e440a328 6035
6036 case OPERATOR_OROR:
e440a328 6037 case OPERATOR_ANDAND:
e440a328 6038 use_left_type = false;
6039 break;
6040 case OPERATOR_PLUS:
e440a328 6041 case OPERATOR_MINUS:
e440a328 6042 case OPERATOR_OR:
e440a328 6043 case OPERATOR_XOR:
e440a328 6044 case OPERATOR_MULT:
e440a328 6045 break;
6046 case OPERATOR_DIV:
a32698ee 6047 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6048 break;
e440a328 6049 case OPERATOR_MOD:
29a2d1d8 6050 is_idiv_op = true;
e440a328 6051 break;
6052 case OPERATOR_LSHIFT:
e440a328 6053 case OPERATOR_RSHIFT:
e440a328 6054 is_shift_op = true;
6055 break;
e440a328 6056 case OPERATOR_BITCLEAR:
a32698ee 6057 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6058 case OPERATOR_AND:
e440a328 6059 break;
6060 default:
c3e6f413 6061 go_unreachable();
e440a328 6062 }
6063
a32698ee 6064 if (left_type->is_string_type())
e440a328 6065 {
c484d925 6066 go_assert(this->op_ == OPERATOR_PLUS);
a32698ee 6067 Expression* string_plus =
6068 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
6069 this->left_, this->right_);
6070 return string_plus->get_tree(context);
6071 }
6072
6073 // For complex division Go might want slightly different results than the
6074 // backend implementation provides, so we have our own runtime routine.
1850e20c 6075 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6076 {
a32698ee 6077 Runtime::Function complex_code;
1850e20c 6078 switch (this->left_->type()->complex_type()->bits())
6079 {
6080 case 64:
a32698ee 6081 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 6082 break;
6083 case 128:
a32698ee 6084 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 6085 break;
6086 default:
6087 go_unreachable();
6088 }
a32698ee 6089 Expression* complex_div =
6090 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6091 return complex_div->get_tree(context);
1850e20c 6092 }
6093
a32698ee 6094 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
6095 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
e440a328 6096
a32698ee 6097 Type* type = use_left_type ? left_type : right_type;
6098 Btype* btype = type->get_backend(gogo);
6099
6100 Bexpression* ret =
6101 gogo->backend()->binary_expression(this->op_, left, right, loc);
6102 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 6103
a32698ee 6104 // Initialize overflow constants.
6105 Bexpression* overflow;
6106 mpz_t zero;
6107 mpz_init_set_ui(zero, 0UL);
6108 mpz_t one;
6109 mpz_init_set_ui(one, 1UL);
6110 mpz_t neg_one;
6111 mpz_init_set_si(neg_one, -1);
e440a328 6112
a32698ee 6113 Btype* left_btype = left_type->get_backend(gogo);
6114 Btype* right_btype = right_type->get_backend(gogo);
e440a328 6115
6116 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 6117 // This is not true in C, so we need to insert a conditional.
e440a328 6118 if (is_shift_op)
6119 {
a32698ee 6120 go_assert(left_type->integer_type() != NULL);
e440a328 6121
a32698ee 6122 mpz_t bitsval;
6123 int bits = left_type->integer_type()->bits();
6124 mpz_init_set_ui(bitsval, bits);
6125 Bexpression* bits_expr =
6126 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6127 Bexpression* compare =
6128 gogo->backend()->binary_expression(OPERATOR_LT,
6129 right, bits_expr, loc);
e440a328 6130
a32698ee 6131 Bexpression* zero_expr =
6132 gogo->backend()->integer_constant_expression(left_btype, zero);
6133 overflow = zero_expr;
e440a328 6134 if (this->op_ == OPERATOR_RSHIFT
a32698ee 6135 && !left_type->integer_type()->is_unsigned())
e440a328 6136 {
a32698ee 6137 Bexpression* neg_expr =
6138 gogo->backend()->binary_expression(OPERATOR_LT, left,
6139 zero_expr, loc);
6140 Bexpression* neg_one_expr =
6141 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6142 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6143 neg_one_expr,
6144 zero_expr, loc);
29a2d1d8 6145 }
a32698ee 6146 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6147 overflow, loc);
6148 mpz_clear(bitsval);
29a2d1d8 6149 }
6150
6151 // Add checks for division by zero and division overflow as needed.
6152 if (is_idiv_op)
6153 {
6154 if (go_check_divide_zero)
6155 {
6156 // right == 0
a32698ee 6157 Bexpression* zero_expr =
6158 gogo->backend()->integer_constant_expression(right_btype, zero);
6159 Bexpression* check =
6160 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6161 right, zero_expr, loc);
29a2d1d8 6162
a32698ee 6163 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 6164 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
a32698ee 6165 Expression* crash = gogo->runtime_error(errcode, loc);
6166 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
29a2d1d8 6167
6168 // right == 0 ? (__go_runtime_error(...), 0) : ret
a32698ee 6169 ret = gogo->backend()->conditional_expression(btype, check,
6170 crash_expr, ret, loc);
b13c66cd 6171 }
6172
29a2d1d8 6173 if (go_check_divide_overflow)
6174 {
6175 // right == -1
6176 // FIXME: It would be nice to say that this test is expected
6177 // to return false.
a32698ee 6178
6179 Bexpression* neg_one_expr =
6180 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6181 Bexpression* check =
6182 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6183 right, neg_one_expr, loc);
6184
6185 Bexpression* zero_expr =
6186 gogo->backend()->integer_constant_expression(btype, zero);
6187 Bexpression* one_expr =
6188 gogo->backend()->integer_constant_expression(btype, one);
6189
6190 if (type->integer_type()->is_unsigned())
29a2d1d8 6191 {
6192 // An unsigned -1 is the largest possible number, so
6193 // dividing is always 1 or 0.
a32698ee 6194
6195 Bexpression* cmp =
6196 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6197 left, right, loc);
29a2d1d8 6198 if (this->op_ == OPERATOR_DIV)
a32698ee 6199 overflow =
6200 gogo->backend()->conditional_expression(btype, cmp,
6201 one_expr, zero_expr,
6202 loc);
29a2d1d8 6203 else
a32698ee 6204 overflow =
6205 gogo->backend()->conditional_expression(btype, cmp,
6206 zero_expr, left,
6207 loc);
29a2d1d8 6208 }
6209 else
6210 {
6211 // Computing left / -1 is the same as computing - left,
6212 // which does not overflow since Go sets -fwrapv.
6213 if (this->op_ == OPERATOR_DIV)
a32698ee 6214 {
6215 Expression* negate_expr =
6216 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6217 overflow = tree_to_expr(negate_expr->get_tree(context));
6218 }
29a2d1d8 6219 else
a32698ee 6220 overflow = zero_expr;
29a2d1d8 6221 }
a32698ee 6222 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 6223
6224 // right == -1 ? - left : ret
a32698ee 6225 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6226 ret, loc);
29a2d1d8 6227 }
e440a328 6228 }
6229
a32698ee 6230 mpz_clear(zero);
6231 mpz_clear(one);
6232 mpz_clear(neg_one);
6233 return expr_to_tree(ret);
e440a328 6234}
6235
6236// Export a binary expression.
6237
6238void
6239Binary_expression::do_export(Export* exp) const
6240{
6241 exp->write_c_string("(");
6242 this->left_->export_expression(exp);
6243 switch (this->op_)
6244 {
6245 case OPERATOR_OROR:
6246 exp->write_c_string(" || ");
6247 break;
6248 case OPERATOR_ANDAND:
6249 exp->write_c_string(" && ");
6250 break;
6251 case OPERATOR_EQEQ:
6252 exp->write_c_string(" == ");
6253 break;
6254 case OPERATOR_NOTEQ:
6255 exp->write_c_string(" != ");
6256 break;
6257 case OPERATOR_LT:
6258 exp->write_c_string(" < ");
6259 break;
6260 case OPERATOR_LE:
6261 exp->write_c_string(" <= ");
6262 break;
6263 case OPERATOR_GT:
6264 exp->write_c_string(" > ");
6265 break;
6266 case OPERATOR_GE:
6267 exp->write_c_string(" >= ");
6268 break;
6269 case OPERATOR_PLUS:
6270 exp->write_c_string(" + ");
6271 break;
6272 case OPERATOR_MINUS:
6273 exp->write_c_string(" - ");
6274 break;
6275 case OPERATOR_OR:
6276 exp->write_c_string(" | ");
6277 break;
6278 case OPERATOR_XOR:
6279 exp->write_c_string(" ^ ");
6280 break;
6281 case OPERATOR_MULT:
6282 exp->write_c_string(" * ");
6283 break;
6284 case OPERATOR_DIV:
6285 exp->write_c_string(" / ");
6286 break;
6287 case OPERATOR_MOD:
6288 exp->write_c_string(" % ");
6289 break;
6290 case OPERATOR_LSHIFT:
6291 exp->write_c_string(" << ");
6292 break;
6293 case OPERATOR_RSHIFT:
6294 exp->write_c_string(" >> ");
6295 break;
6296 case OPERATOR_AND:
6297 exp->write_c_string(" & ");
6298 break;
6299 case OPERATOR_BITCLEAR:
6300 exp->write_c_string(" &^ ");
6301 break;
6302 default:
c3e6f413 6303 go_unreachable();
e440a328 6304 }
6305 this->right_->export_expression(exp);
6306 exp->write_c_string(")");
6307}
6308
6309// Import a binary expression.
6310
6311Expression*
6312Binary_expression::do_import(Import* imp)
6313{
6314 imp->require_c_string("(");
6315
6316 Expression* left = Expression::import_expression(imp);
6317
6318 Operator op;
6319 if (imp->match_c_string(" || "))
6320 {
6321 op = OPERATOR_OROR;
6322 imp->advance(4);
6323 }
6324 else if (imp->match_c_string(" && "))
6325 {
6326 op = OPERATOR_ANDAND;
6327 imp->advance(4);
6328 }
6329 else if (imp->match_c_string(" == "))
6330 {
6331 op = OPERATOR_EQEQ;
6332 imp->advance(4);
6333 }
6334 else if (imp->match_c_string(" != "))
6335 {
6336 op = OPERATOR_NOTEQ;
6337 imp->advance(4);
6338 }
6339 else if (imp->match_c_string(" < "))
6340 {
6341 op = OPERATOR_LT;
6342 imp->advance(3);
6343 }
6344 else if (imp->match_c_string(" <= "))
6345 {
6346 op = OPERATOR_LE;
6347 imp->advance(4);
6348 }
6349 else if (imp->match_c_string(" > "))
6350 {
6351 op = OPERATOR_GT;
6352 imp->advance(3);
6353 }
6354 else if (imp->match_c_string(" >= "))
6355 {
6356 op = OPERATOR_GE;
6357 imp->advance(4);
6358 }
6359 else if (imp->match_c_string(" + "))
6360 {
6361 op = OPERATOR_PLUS;
6362 imp->advance(3);
6363 }
6364 else if (imp->match_c_string(" - "))
6365 {
6366 op = OPERATOR_MINUS;
6367 imp->advance(3);
6368 }
6369 else if (imp->match_c_string(" | "))
6370 {
6371 op = OPERATOR_OR;
6372 imp->advance(3);
6373 }
6374 else if (imp->match_c_string(" ^ "))
6375 {
6376 op = OPERATOR_XOR;
6377 imp->advance(3);
6378 }
6379 else if (imp->match_c_string(" * "))
6380 {
6381 op = OPERATOR_MULT;
6382 imp->advance(3);
6383 }
6384 else if (imp->match_c_string(" / "))
6385 {
6386 op = OPERATOR_DIV;
6387 imp->advance(3);
6388 }
6389 else if (imp->match_c_string(" % "))
6390 {
6391 op = OPERATOR_MOD;
6392 imp->advance(3);
6393 }
6394 else if (imp->match_c_string(" << "))
6395 {
6396 op = OPERATOR_LSHIFT;
6397 imp->advance(4);
6398 }
6399 else if (imp->match_c_string(" >> "))
6400 {
6401 op = OPERATOR_RSHIFT;
6402 imp->advance(4);
6403 }
6404 else if (imp->match_c_string(" & "))
6405 {
6406 op = OPERATOR_AND;
6407 imp->advance(3);
6408 }
6409 else if (imp->match_c_string(" &^ "))
6410 {
6411 op = OPERATOR_BITCLEAR;
6412 imp->advance(4);
6413 }
6414 else
6415 {
6416 error_at(imp->location(), "unrecognized binary operator");
6417 return Expression::make_error(imp->location());
6418 }
6419
6420 Expression* right = Expression::import_expression(imp);
6421
6422 imp->require_c_string(")");
6423
6424 return Expression::make_binary(op, left, right, imp->location());
6425}
6426
d751bb78 6427// Dump ast representation of a binary expression.
6428
6429void
6430Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6431{
6432 ast_dump_context->ostream() << "(";
6433 ast_dump_context->dump_expression(this->left_);
6434 ast_dump_context->ostream() << " ";
6435 ast_dump_context->dump_operator(this->op_);
6436 ast_dump_context->ostream() << " ";
6437 ast_dump_context->dump_expression(this->right_);
6438 ast_dump_context->ostream() << ") ";
6439}
6440
e440a328 6441// Make a binary expression.
6442
6443Expression*
6444Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6445 Location location)
e440a328 6446{
6447 return new Binary_expression(op, left, right, location);
6448}
6449
6450// Implement a comparison.
6451
a32698ee 6452Bexpression*
6453Expression::comparison(Translate_context* context, Type* result_type,
6454 Operator op, Expression* left, Expression* right,
6455 Location location)
e440a328 6456{
2387f644 6457 Type* left_type = left->type();
6458 Type* right_type = right->type();
ceeb12d7 6459
6460 mpz_t zval;
6461 mpz_init_set_ui(zval, 0UL);
6462 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6463 mpz_clear(zval);
1b1f2abf 6464
15c67ee2 6465 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6466 {
2387f644 6467 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6468 left, right);
6469 right = zexpr;
e440a328 6470 }
15c67ee2 6471 else if ((left_type->interface_type() != NULL
6472 && right_type->interface_type() == NULL
6473 && !right_type->is_nil_type())
6474 || (left_type->interface_type() == NULL
6475 && !left_type->is_nil_type()
6476 && right_type->interface_type() != NULL))
e440a328 6477 {
6478 // Comparing an interface value to a non-interface value.
6479 if (left_type->interface_type() == NULL)
6480 {
6481 std::swap(left_type, right_type);
2387f644 6482 std::swap(left, right);
e440a328 6483 }
6484
6485 // The right operand is not an interface. We need to take its
6486 // address if it is not a pointer.
ceeb12d7 6487 Expression* pointer_arg = NULL;
e440a328 6488 if (right_type->points_to() != NULL)
2387f644 6489 pointer_arg = right;
e440a328 6490 else
6491 {
2387f644 6492 go_assert(right->is_addressable());
6493 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6494 location);
e440a328 6495 }
e440a328 6496
2387f644 6497 Expression* descriptor =
6498 Expression::make_type_descriptor(right_type, location);
6499 left =
ceeb12d7 6500 Runtime::make_call((left_type->interface_type()->is_empty()
6501 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6502 : Runtime::INTERFACE_VALUE_COMPARE),
2387f644 6503 location, 3, left, descriptor,
ceeb12d7 6504 pointer_arg);
2387f644 6505 right = zexpr;
e440a328 6506 }
6507 else if (left_type->interface_type() != NULL
6508 && right_type->interface_type() != NULL)
6509 {
ceeb12d7 6510 Runtime::Function compare_function;
739bad04 6511 if (left_type->interface_type()->is_empty()
6512 && right_type->interface_type()->is_empty())
ceeb12d7 6513 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
739bad04 6514 else if (!left_type->interface_type()->is_empty()
6515 && !right_type->interface_type()->is_empty())
ceeb12d7 6516 compare_function = Runtime::INTERFACE_COMPARE;
739bad04 6517 else
6518 {
6519 if (left_type->interface_type()->is_empty())
6520 {
c484d925 6521 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
739bad04 6522 std::swap(left_type, right_type);
2387f644 6523 std::swap(left, right);
739bad04 6524 }
c484d925 6525 go_assert(!left_type->interface_type()->is_empty());
6526 go_assert(right_type->interface_type()->is_empty());
ceeb12d7 6527 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
739bad04 6528 }
6529
2387f644 6530 left = Runtime::make_call(compare_function, location, 2, left, right);
6531 right = zexpr;
e440a328 6532 }
6533
6534 if (left_type->is_nil_type()
6535 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6536 {
6537 std::swap(left_type, right_type);
2387f644 6538 std::swap(left, right);
e440a328 6539 }
6540
6541 if (right_type->is_nil_type())
6542 {
2387f644 6543 right = Expression::make_nil(location);
e440a328 6544 if (left_type->array_type() != NULL
6545 && left_type->array_type()->length() == NULL)
6546 {
6547 Array_type* at = left_type->array_type();
2387f644 6548 left = at->get_value_pointer(context->gogo(), left);
e440a328 6549 }
6550 else if (left_type->interface_type() != NULL)
6551 {
6552 // An interface is nil if the first field is nil.
2387f644 6553 left = Expression::make_field_reference(left, 0, location);
e440a328 6554 }
6555 }
6556
a32698ee 6557 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6558 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
e90c9dfc 6559
a32698ee 6560 Gogo* gogo = context->gogo();
6561 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6562 right_bexpr, location);
6563 if (result_type != NULL)
6564 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6565 ret, location);
e440a328 6566 return ret;
6567}
6568
6569// Class Bound_method_expression.
6570
6571// Traversal.
6572
6573int
6574Bound_method_expression::do_traverse(Traverse* traverse)
6575{
e0659c9e 6576 return Expression::traverse(&this->expr_, traverse);
e440a328 6577}
6578
0afbb937 6579// Lower the expression. If this is a method value rather than being
6580// called, and the method is accessed via a pointer, we may need to
6581// add nil checks. Introduce a temporary variable so that those nil
6582// checks do not cause multiple evaluation.
6583
6584Expression*
6585Bound_method_expression::do_lower(Gogo*, Named_object*,
6586 Statement_inserter* inserter, int)
6587{
6588 // For simplicity we use a temporary for every call to an embedded
6589 // method, even though some of them might be pure value methods and
6590 // not require a temporary.
6591 if (this->expr_->var_expression() == NULL
6592 && this->expr_->temporary_reference_expression() == NULL
6593 && this->expr_->set_and_use_temporary_expression() == NULL
6594 && (this->method_->field_indexes() != NULL
6595 || (this->method_->is_value_method()
6596 && this->expr_->type()->points_to() != NULL)))
6597 {
6598 Temporary_statement* temp =
6599 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6600 inserter->insert(temp);
6601 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6602 this->location());
6603 }
6604 return this;
6605}
6606
e440a328 6607// Return the type of a bound method expression. The type of this
0afbb937 6608// object is simply the type of the method with no receiver.
e440a328 6609
6610Type*
6611Bound_method_expression::do_type()
6612{
0afbb937 6613 Named_object* fn = this->method_->named_object();
6614 Function_type* fntype;
6615 if (fn->is_function())
6616 fntype = fn->func_value()->type();
6617 else if (fn->is_function_declaration())
6618 fntype = fn->func_declaration_value()->type();
e0659c9e 6619 else
6620 return Type::make_error_type();
0afbb937 6621 return fntype->copy_without_receiver();
e440a328 6622}
6623
6624// Determine the types of a method expression.
6625
6626void
6627Bound_method_expression::do_determine_type(const Type_context*)
6628{
0afbb937 6629 Named_object* fn = this->method_->named_object();
6630 Function_type* fntype;
6631 if (fn->is_function())
6632 fntype = fn->func_value()->type();
6633 else if (fn->is_function_declaration())
6634 fntype = fn->func_declaration_value()->type();
6635 else
6636 fntype = NULL;
e440a328 6637 if (fntype == NULL || !fntype->is_method())
6638 this->expr_->determine_type_no_context();
6639 else
6640 {
6641 Type_context subcontext(fntype->receiver()->type(), false);
6642 this->expr_->determine_type(&subcontext);
6643 }
6644}
6645
6646// Check the types of a method expression.
6647
6648void
6649Bound_method_expression::do_check_types(Gogo*)
6650{
0afbb937 6651 Named_object* fn = this->method_->named_object();
6652 if (!fn->is_function() && !fn->is_function_declaration())
6653 {
6654 this->report_error(_("object is not a method"));
6655 return;
6656 }
6657
6658 Function_type* fntype;
6659 if (fn->is_function())
6660 fntype = fn->func_value()->type();
6661 else if (fn->is_function_declaration())
6662 fntype = fn->func_declaration_value()->type();
e440a328 6663 else
0afbb937 6664 go_unreachable();
6665 Type* rtype = fntype->receiver()->type()->deref();
6666 Type* etype = (this->expr_type_ != NULL
6667 ? this->expr_type_
6668 : this->expr_->type());
6669 etype = etype->deref();
6670 if (!Type::are_identical(rtype, etype, true, NULL))
6671 this->report_error(_("method type does not match object type"));
6672}
6673
6674// If a bound method expression is not simply called, then it is
6675// represented as a closure. The closure will hold a single variable,
6676// the receiver to pass to the method. The function will be a simple
6677// thunk that pulls that value from the closure and calls the method
6678// with the remaining arguments.
6679//
6680// Because method values are not common, we don't build all thunks for
6681// every methods, but instead only build them as we need them. In
6682// particular, we even build them on demand for methods defined in
6683// other packages.
6684
6685Bound_method_expression::Method_value_thunks
6686 Bound_method_expression::method_value_thunks;
6687
6688// Find or create the thunk for METHOD.
6689
6690Named_object*
6691Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6692 Named_object* fn)
6693{
6694 std::pair<Named_object*, Named_object*> val(fn, NULL);
6695 std::pair<Method_value_thunks::iterator, bool> ins =
6696 Bound_method_expression::method_value_thunks.insert(val);
6697 if (!ins.second)
6698 {
6699 // We have seen this method before.
6700 go_assert(ins.first->second != NULL);
6701 return ins.first->second;
6702 }
6703
6704 Location loc = fn->location();
6705
6706 Function_type* orig_fntype;
6707 if (fn->is_function())
6708 orig_fntype = fn->func_value()->type();
6709 else if (fn->is_function_declaration())
6710 orig_fntype = fn->func_declaration_value()->type();
6711 else
6712 orig_fntype = NULL;
6713
6714 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6715 {
0afbb937 6716 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6717 return ins.first->second;
e440a328 6718 }
0afbb937 6719
6720 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6721 // The type here is wrong--it should be the C function type. But it
6722 // doesn't really matter.
0afbb937 6723 Type* vt = Type::make_pointer_type(Type::make_void_type());
6724 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6725 sfl->push_back(Struct_field(Typed_identifier("val.1",
6726 orig_fntype->receiver()->type(),
6727 loc)));
6728 Type* closure_type = Type::make_struct_type(sfl, loc);
6729 closure_type = Type::make_pointer_type(closure_type);
6730
f8bdf81a 6731 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6732
6733 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6734 false, loc);
6735
f8bdf81a 6736 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6737 cvar->set_is_used();
6738 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6739 new_no->func_value()->set_closure_var(cp);
0afbb937 6740
f8bdf81a 6741 gogo->start_block(loc);
0afbb937 6742
6743 // Field 0 of the closure is the function code pointer, field 1 is
6744 // the value on which to invoke the method.
6745 Expression* arg = Expression::make_var_reference(cp, loc);
6746 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6747 arg = Expression::make_field_reference(arg, 1, loc);
6748
6749 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6750
6751 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6752 Expression_list* args;
6753 if (orig_params == NULL || orig_params->empty())
6754 args = NULL;
6755 else
6756 {
6757 const Typed_identifier_list* new_params = new_fntype->parameters();
6758 args = new Expression_list();
6759 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6760 p != new_params->end();
0afbb937 6761 ++p)
6762 {
6763 Named_object* p_no = gogo->lookup(p->name(), NULL);
6764 go_assert(p_no != NULL
6765 && p_no->is_variable()
6766 && p_no->var_value()->is_parameter());
6767 args->push_back(Expression::make_var_reference(p_no, loc));
6768 }
6769 }
6770
6771 Call_expression* call = Expression::make_call(bme, args,
6772 orig_fntype->is_varargs(),
6773 loc);
6774 call->set_varargs_are_lowered();
6775
6776 Statement* s = Statement::make_return_from_call(call, loc);
6777 gogo->add_statement(s);
6778 Block* b = gogo->finish_block(loc);
6779 gogo->add_block(b, loc);
6780 gogo->lower_block(new_no, b);
a32698ee 6781 gogo->flatten_block(new_no, b);
0afbb937 6782 gogo->finish_function(loc);
6783
6784 ins.first->second = new_no;
6785 return new_no;
6786}
6787
6788// Return an expression to check *REF for nil while dereferencing
6789// according to FIELD_INDEXES. Update *REF to build up the field
6790// reference. This is a static function so that we don't have to
6791// worry about declaring Field_indexes in expressions.h.
6792
6793static Expression*
6794bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6795 Expression** ref)
6796{
6797 if (field_indexes == NULL)
6798 return Expression::make_boolean(false, loc);
6799 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6800 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6801 go_assert(stype != NULL
6802 && field_indexes->field_index < stype->field_count());
6803 if ((*ref)->type()->struct_type() == NULL)
6804 {
6805 go_assert((*ref)->type()->points_to() != NULL);
6806 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6807 Expression::make_nil(loc),
6808 loc);
6809 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6810 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6811 go_assert((*ref)->type()->struct_type() == stype);
6812 }
6813 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6814 loc);
6815 return cond;
e440a328 6816}
6817
0afbb937 6818// Get the tree for a method value.
e440a328 6819
6820tree
0afbb937 6821Bound_method_expression::do_get_tree(Translate_context* context)
e440a328 6822{
0afbb937 6823 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6824 this->method_,
6825 this->function_);
6826 if (thunk->is_erroneous())
6827 {
6828 go_assert(saw_errors());
6829 return error_mark_node;
6830 }
6831
6832 // FIXME: We should lower this earlier, but we can't lower it in the
6833 // lowering pass because at that point we don't know whether we need
6834 // to create the thunk or not. If the expression is called, we
6835 // don't need the thunk.
6836
6837 Location loc = this->location();
6838
6839 // If the method expects a value, and we have a pointer, we need to
6840 // dereference the pointer.
6841
6842 Named_object* fn = this->method_->named_object();
6843 Function_type* fntype;
6844 if (fn->is_function())
6845 fntype = fn->func_value()->type();
6846 else if (fn->is_function_declaration())
6847 fntype = fn->func_declaration_value()->type();
6848 else
6849 go_unreachable();
6850
6851 Expression* val = this->expr_;
6852 if (fntype->receiver()->type()->points_to() == NULL
6853 && val->type()->points_to() != NULL)
6854 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6855
6856 // Note that we are ignoring this->expr_type_ here. The thunk will
6857 // expect a closure whose second field has type this->expr_type_ (if
6858 // that is not NULL). We are going to pass it a closure whose
6859 // second field has type this->expr_->type(). Since
6860 // this->expr_type_ is only not-NULL for pointer types, we can get
6861 // away with this.
6862
6863 Struct_field_list* fields = new Struct_field_list();
6864 fields->push_back(Struct_field(Typed_identifier("fn.0",
6865 thunk->func_value()->type(),
6866 loc)));
6867 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6868 Struct_type* st = Type::make_struct_type(fields, loc);
6869
6870 Expression_list* vals = new Expression_list();
6871 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6872 vals->push_back(val);
6873
6874 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6875 ret = Expression::make_heap_composite(ret, loc);
6876
6877 tree ret_tree = ret->get_tree(context);
6878
6879 Expression* nil_check = NULL;
6880
6881 // See whether the expression or any embedded pointers are nil.
6882
6883 Expression* expr = this->expr_;
6884 if (this->method_->field_indexes() != NULL)
6885 {
6886 // Note that we are evaluating this->expr_ twice, but that is OK
6887 // because in the lowering pass we forced it into a temporary
6888 // variable.
6889 Expression* ref = expr;
6890 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6891 expr = ref;
6892 }
6893
6894 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6895 {
6896 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6897 Expression::make_nil(loc),
6898 loc);
6899 if (nil_check == NULL)
6900 nil_check = n;
6901 else
6902 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6903 }
6904
6905 if (nil_check != NULL)
6906 {
6907 tree nil_check_tree = nil_check->get_tree(context);
aff1f085 6908 Expression* crash_expr =
0afbb937 6909 context->gogo()->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
aff1f085 6910 tree crash = crash_expr->get_tree(context);
0afbb937 6911 if (ret_tree == error_mark_node
6912 || nil_check_tree == error_mark_node
6913 || crash == error_mark_node)
6914 return error_mark_node;
6915
6916 ret_tree = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
6917 TREE_TYPE(ret_tree),
6918 build3_loc(loc.gcc_location(), COND_EXPR,
6919 void_type_node, nil_check_tree,
6920 crash, NULL_TREE),
6921 ret_tree);
6922 }
6923
6924 return ret_tree;
e440a328 6925}
6926
d751bb78 6927// Dump ast representation of a bound method expression.
6928
6929void
6930Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6931 const
6932{
6933 if (this->expr_type_ != NULL)
6934 ast_dump_context->ostream() << "(";
6935 ast_dump_context->dump_expression(this->expr_);
6936 if (this->expr_type_ != NULL)
6937 {
6938 ast_dump_context->ostream() << ":";
6939 ast_dump_context->dump_type(this->expr_type_);
6940 ast_dump_context->ostream() << ")";
6941 }
6942
0afbb937 6943 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6944}
6945
e440a328 6946// Make a method expression.
6947
6948Bound_method_expression*
0afbb937 6949Expression::make_bound_method(Expression* expr, const Method* method,
6950 Named_object* function, Location location)
e440a328 6951{
0afbb937 6952 return new Bound_method_expression(expr, method, function, location);
e440a328 6953}
6954
6955// Class Builtin_call_expression. This is used for a call to a
6956// builtin function.
6957
6958class Builtin_call_expression : public Call_expression
6959{
6960 public:
6961 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6962 bool is_varargs, Location location);
e440a328 6963
6964 protected:
6965 // This overrides Call_expression::do_lower.
6966 Expression*
ceeb4318 6967 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6968
35a54f17 6969 Expression*
6970 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6971
e440a328 6972 bool
6973 do_is_constant() const;
6974
6975 bool
0c77715b 6976 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6977
4f2138d7 6978 bool
a7549a6a 6979 do_discarding_value();
6980
e440a328 6981 Type*
6982 do_type();
6983
6984 void
6985 do_determine_type(const Type_context*);
6986
6987 void
6988 do_check_types(Gogo*);
6989
6990 Expression*
6991 do_copy()
6992 {
6993 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6994 this->args()->copy(),
6995 this->is_varargs(),
6996 this->location());
6997 }
6998
6999 tree
7000 do_get_tree(Translate_context*);
7001
7002 void
7003 do_export(Export*) const;
7004
7005 virtual bool
7006 do_is_recover_call() const;
7007
7008 virtual void
7009 do_set_recover_arg(Expression*);
7010
7011 private:
7012 // The builtin functions.
7013 enum Builtin_function_code
7014 {
7015 BUILTIN_INVALID,
7016
7017 // Predeclared builtin functions.
7018 BUILTIN_APPEND,
7019 BUILTIN_CAP,
7020 BUILTIN_CLOSE,
48080209 7021 BUILTIN_COMPLEX,
e440a328 7022 BUILTIN_COPY,
1cce762f 7023 BUILTIN_DELETE,
e440a328 7024 BUILTIN_IMAG,
7025 BUILTIN_LEN,
7026 BUILTIN_MAKE,
7027 BUILTIN_NEW,
7028 BUILTIN_PANIC,
7029 BUILTIN_PRINT,
7030 BUILTIN_PRINTLN,
7031 BUILTIN_REAL,
7032 BUILTIN_RECOVER,
7033
7034 // Builtin functions from the unsafe package.
7035 BUILTIN_ALIGNOF,
7036 BUILTIN_OFFSETOF,
7037 BUILTIN_SIZEOF
7038 };
7039
7040 Expression*
7041 one_arg() const;
7042
7043 bool
7044 check_one_arg();
7045
7046 static Type*
7047 real_imag_type(Type*);
7048
7049 static Type*
48080209 7050 complex_type(Type*);
e440a328 7051
a9182619 7052 Expression*
7053 lower_make();
7054
7055 bool
1ad00fd4 7056 check_int_value(Expression*, bool is_length);
a9182619 7057
e440a328 7058 // A pointer back to the general IR structure. This avoids a global
7059 // variable, or passing it around everywhere.
7060 Gogo* gogo_;
7061 // The builtin function being called.
7062 Builtin_function_code code_;
0f914071 7063 // Used to stop endless loops when the length of an array uses len
7064 // or cap of the array itself.
7065 mutable bool seen_;
e440a328 7066};
7067
7068Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7069 Expression* fn,
7070 Expression_list* args,
7071 bool is_varargs,
b13c66cd 7072 Location location)
e440a328 7073 : Call_expression(fn, args, is_varargs, location),
0f914071 7074 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
e440a328 7075{
7076 Func_expression* fnexp = this->fn()->func_expression();
c484d925 7077 go_assert(fnexp != NULL);
e440a328 7078 const std::string& name(fnexp->named_object()->name());
7079 if (name == "append")
7080 this->code_ = BUILTIN_APPEND;
7081 else if (name == "cap")
7082 this->code_ = BUILTIN_CAP;
7083 else if (name == "close")
7084 this->code_ = BUILTIN_CLOSE;
48080209 7085 else if (name == "complex")
7086 this->code_ = BUILTIN_COMPLEX;
e440a328 7087 else if (name == "copy")
7088 this->code_ = BUILTIN_COPY;
1cce762f 7089 else if (name == "delete")
7090 this->code_ = BUILTIN_DELETE;
e440a328 7091 else if (name == "imag")
7092 this->code_ = BUILTIN_IMAG;
7093 else if (name == "len")
7094 this->code_ = BUILTIN_LEN;
7095 else if (name == "make")
7096 this->code_ = BUILTIN_MAKE;
7097 else if (name == "new")
7098 this->code_ = BUILTIN_NEW;
7099 else if (name == "panic")
7100 this->code_ = BUILTIN_PANIC;
7101 else if (name == "print")
7102 this->code_ = BUILTIN_PRINT;
7103 else if (name == "println")
7104 this->code_ = BUILTIN_PRINTLN;
7105 else if (name == "real")
7106 this->code_ = BUILTIN_REAL;
7107 else if (name == "recover")
7108 this->code_ = BUILTIN_RECOVER;
7109 else if (name == "Alignof")
7110 this->code_ = BUILTIN_ALIGNOF;
7111 else if (name == "Offsetof")
7112 this->code_ = BUILTIN_OFFSETOF;
7113 else if (name == "Sizeof")
7114 this->code_ = BUILTIN_SIZEOF;
7115 else
c3e6f413 7116 go_unreachable();
e440a328 7117}
7118
7119// Return whether this is a call to recover. This is a virtual
7120// function called from the parent class.
7121
7122bool
7123Builtin_call_expression::do_is_recover_call() const
7124{
7125 if (this->classification() == EXPRESSION_ERROR)
7126 return false;
7127 return this->code_ == BUILTIN_RECOVER;
7128}
7129
7130// Set the argument for a call to recover.
7131
7132void
7133Builtin_call_expression::do_set_recover_arg(Expression* arg)
7134{
7135 const Expression_list* args = this->args();
c484d925 7136 go_assert(args == NULL || args->empty());
e440a328 7137 Expression_list* new_args = new Expression_list();
7138 new_args->push_back(arg);
7139 this->set_args(new_args);
7140}
7141
e440a328 7142// Lower a builtin call expression. This turns new and make into
7143// specific expressions. We also convert to a constant if we can.
7144
7145Expression*
ceeb4318 7146Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7147 Statement_inserter* inserter, int)
e440a328 7148{
a9182619 7149 if (this->classification() == EXPRESSION_ERROR)
7150 return this;
7151
b13c66cd 7152 Location loc = this->location();
1cce762f 7153
a8725655 7154 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7155 {
7156 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7157 return Expression::make_error(loc);
a8725655 7158 }
7159
393ba00b 7160 if (this->code_ == BUILTIN_OFFSETOF)
7161 {
7162 Expression* arg = this->one_arg();
12e69faa 7163
7164 if (arg->bound_method_expression() != NULL
7165 || arg->interface_field_reference_expression() != NULL)
7166 {
7167 this->report_error(_("invalid use of method value as argument "
7168 "of Offsetof"));
7169 return this;
7170 }
7171
393ba00b 7172 Field_reference_expression* farg = arg->field_reference_expression();
7173 while (farg != NULL)
7174 {
7175 if (!farg->implicit())
7176 break;
7177 // When the selector refers to an embedded field,
7178 // it must not be reached through pointer indirections.
7179 if (farg->expr()->deref() != farg->expr())
7180 {
12e69faa 7181 this->report_error(_("argument of Offsetof implies "
7182 "indirection of an embedded field"));
393ba00b 7183 return this;
7184 }
7185 // Go up until we reach the original base.
7186 farg = farg->expr()->field_reference_expression();
7187 }
7188 }
7189
1cce762f 7190 if (this->is_constant())
e440a328 7191 {
0c77715b 7192 Numeric_constant nc;
7193 if (this->numeric_constant_value(&nc))
7194 return nc.expression(loc);
e440a328 7195 }
1cce762f 7196
7197 switch (this->code_)
e440a328 7198 {
1cce762f 7199 default:
7200 break;
7201
7202 case BUILTIN_NEW:
7203 {
7204 const Expression_list* args = this->args();
7205 if (args == NULL || args->size() < 1)
7206 this->report_error(_("not enough arguments"));
7207 else if (args->size() > 1)
7208 this->report_error(_("too many arguments"));
7209 else
7210 {
7211 Expression* arg = args->front();
7212 if (!arg->is_type_expression())
7213 {
7214 error_at(arg->location(), "expected type");
7215 this->set_is_error();
7216 }
7217 else
7218 return Expression::make_allocation(arg->type(), loc);
7219 }
7220 }
7221 break;
7222
7223 case BUILTIN_MAKE:
7224 return this->lower_make();
7225
7226 case BUILTIN_RECOVER:
e440a328 7227 if (function != NULL)
7228 function->func_value()->set_calls_recover();
7229 else
7230 {
7231 // Calling recover outside of a function always returns the
7232 // nil empty interface.
823c7e3d 7233 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7234 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7235 }
1cce762f 7236 break;
7237
7238 case BUILTIN_APPEND:
7239 {
7240 // Lower the varargs.
7241 const Expression_list* args = this->args();
7242 if (args == NULL || args->empty())
e440a328 7243 return this;
1cce762f 7244 Type* slice_type = args->front()->type();
7245 if (!slice_type->is_slice_type())
7246 {
3ff4863b 7247 if (slice_type->is_nil_type())
7248 error_at(args->front()->location(), "use of untyped nil");
7249 else
7250 error_at(args->front()->location(),
7251 "argument 1 must be a slice");
1cce762f 7252 this->set_is_error();
7253 return this;
7254 }
19fd40c3 7255 Type* element_type = slice_type->array_type()->element_type();
7256 this->lower_varargs(gogo, function, inserter,
7257 Type::make_array_type(element_type, NULL),
7258 2);
1cce762f 7259 }
7260 break;
7261
7262 case BUILTIN_DELETE:
7263 {
7264 // Lower to a runtime function call.
7265 const Expression_list* args = this->args();
7266 if (args == NULL || args->size() < 2)
7267 this->report_error(_("not enough arguments"));
7268 else if (args->size() > 2)
7269 this->report_error(_("too many arguments"));
7270 else if (args->front()->type()->map_type() == NULL)
7271 this->report_error(_("argument 1 must be a map"));
7272 else
7273 {
7274 // Since this function returns no value it must appear in
7275 // a statement by itself, so we don't have to worry about
7276 // order of evaluation of values around it. Evaluate the
7277 // map first to get order of evaluation right.
7278 Map_type* mt = args->front()->type()->map_type();
7279 Temporary_statement* map_temp =
7280 Statement::make_temporary(mt, args->front(), loc);
7281 inserter->insert(map_temp);
7282
7283 Temporary_statement* key_temp =
7284 Statement::make_temporary(mt->key_type(), args->back(), loc);
7285 inserter->insert(key_temp);
7286
7287 Expression* e1 = Expression::make_temporary_reference(map_temp,
7288 loc);
7289 Expression* e2 = Expression::make_temporary_reference(key_temp,
7290 loc);
7291 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7292 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7293 2, e1, e2);
7294 }
7295 }
7296 break;
e440a328 7297 }
7298
7299 return this;
7300}
7301
35a54f17 7302// Flatten a builtin call expression. This turns the arguments of copy and
7303// append into temporary expressions.
7304
7305Expression*
7306Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7307 Statement_inserter* inserter)
7308{
7309 if (this->code_ == BUILTIN_APPEND
7310 || this->code_ == BUILTIN_COPY)
7311 {
7312 Location loc = this->location();
7313 Type* at = this->args()->front()->type();
7314 for (Expression_list::iterator pa = this->args()->begin();
7315 pa != this->args()->end();
7316 ++pa)
7317 {
7318 if ((*pa)->is_nil_expression())
7319 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7320 if (!(*pa)->is_variable())
7321 {
7322 Temporary_statement* temp =
7323 Statement::make_temporary(NULL, *pa, loc);
7324 inserter->insert(temp);
7325 *pa = Expression::make_temporary_reference(temp, loc);
7326 }
7327 }
7328 }
7329 return this;
7330}
7331
a9182619 7332// Lower a make expression.
7333
7334Expression*
7335Builtin_call_expression::lower_make()
7336{
b13c66cd 7337 Location loc = this->location();
a9182619 7338
7339 const Expression_list* args = this->args();
7340 if (args == NULL || args->size() < 1)
7341 {
7342 this->report_error(_("not enough arguments"));
7343 return Expression::make_error(this->location());
7344 }
7345
7346 Expression_list::const_iterator parg = args->begin();
7347
7348 Expression* first_arg = *parg;
7349 if (!first_arg->is_type_expression())
7350 {
7351 error_at(first_arg->location(), "expected type");
7352 this->set_is_error();
7353 return Expression::make_error(this->location());
7354 }
7355 Type* type = first_arg->type();
7356
7357 bool is_slice = false;
7358 bool is_map = false;
7359 bool is_chan = false;
411eb89e 7360 if (type->is_slice_type())
a9182619 7361 is_slice = true;
7362 else if (type->map_type() != NULL)
7363 is_map = true;
7364 else if (type->channel_type() != NULL)
7365 is_chan = true;
7366 else
7367 {
7368 this->report_error(_("invalid type for make function"));
7369 return Expression::make_error(this->location());
7370 }
7371
ac84c822 7372 bool have_big_args = false;
7373 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7374 int uintptr_bits = uintptr_type->integer_type()->bits();
7375
f6bc81e6 7376 Type_context int_context(Type::lookup_integer_type("int"), false);
7377
a9182619 7378 ++parg;
7379 Expression* len_arg;
7380 if (parg == args->end())
7381 {
7382 if (is_slice)
7383 {
7384 this->report_error(_("length required when allocating a slice"));
7385 return Expression::make_error(this->location());
7386 }
7387
7388 mpz_t zval;
7389 mpz_init_set_ui(zval, 0);
7390 len_arg = Expression::make_integer(&zval, NULL, loc);
7391 mpz_clear(zval);
7392 }
7393 else
7394 {
7395 len_arg = *parg;
f6bc81e6 7396 len_arg->determine_type(&int_context);
1ad00fd4 7397 if (!this->check_int_value(len_arg, true))
7398 return Expression::make_error(this->location());
ac84c822 7399 if (len_arg->type()->integer_type() != NULL
7400 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7401 have_big_args = true;
a9182619 7402 ++parg;
7403 }
7404
7405 Expression* cap_arg = NULL;
7406 if (is_slice && parg != args->end())
7407 {
7408 cap_arg = *parg;
f6bc81e6 7409 cap_arg->determine_type(&int_context);
1ad00fd4 7410 if (!this->check_int_value(cap_arg, false))
7411 return Expression::make_error(this->location());
7412
7413 Numeric_constant nclen;
7414 Numeric_constant nccap;
7415 unsigned long vlen;
7416 unsigned long vcap;
7417 if (len_arg->numeric_constant_value(&nclen)
7418 && cap_arg->numeric_constant_value(&nccap)
7419 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7420 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7421 && vlen > vcap)
a9182619 7422 {
1ad00fd4 7423 this->report_error(_("len larger than cap"));
a9182619 7424 return Expression::make_error(this->location());
7425 }
1ad00fd4 7426
ac84c822 7427 if (cap_arg->type()->integer_type() != NULL
7428 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7429 have_big_args = true;
a9182619 7430 ++parg;
7431 }
7432
7433 if (parg != args->end())
7434 {
7435 this->report_error(_("too many arguments to make"));
7436 return Expression::make_error(this->location());
7437 }
7438
b13c66cd 7439 Location type_loc = first_arg->location();
a9182619 7440 Expression* type_arg;
7441 if (is_slice || is_chan)
7442 type_arg = Expression::make_type_descriptor(type, type_loc);
7443 else if (is_map)
7444 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7445 else
7446 go_unreachable();
7447
7448 Expression* call;
7449 if (is_slice)
7450 {
7451 if (cap_arg == NULL)
ac84c822 7452 call = Runtime::make_call((have_big_args
7453 ? Runtime::MAKESLICE1BIG
7454 : Runtime::MAKESLICE1),
7455 loc, 2, type_arg, len_arg);
a9182619 7456 else
ac84c822 7457 call = Runtime::make_call((have_big_args
7458 ? Runtime::MAKESLICE2BIG
7459 : Runtime::MAKESLICE2),
7460 loc, 3, type_arg, len_arg, cap_arg);
a9182619 7461 }
7462 else if (is_map)
ac84c822 7463 call = Runtime::make_call((have_big_args
7464 ? Runtime::MAKEMAPBIG
7465 : Runtime::MAKEMAP),
7466 loc, 2, type_arg, len_arg);
a9182619 7467 else if (is_chan)
ac84c822 7468 call = Runtime::make_call((have_big_args
7469 ? Runtime::MAKECHANBIG
7470 : Runtime::MAKECHAN),
7471 loc, 2, type_arg, len_arg);
a9182619 7472 else
7473 go_unreachable();
7474
7475 return Expression::make_unsafe_cast(type, call, loc);
7476}
7477
7478// Return whether an expression has an integer value. Report an error
7479// if not. This is used when handling calls to the predeclared make
7480// function.
7481
7482bool
1ad00fd4 7483Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7484{
0c77715b 7485 Numeric_constant nc;
1ad00fd4 7486 if (e->numeric_constant_value(&nc))
a9182619 7487 {
1ad00fd4 7488 unsigned long v;
7489 switch (nc.to_unsigned_long(&v))
7490 {
7491 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7492 break;
1ad00fd4 7493 case Numeric_constant::NC_UL_NOTINT:
7494 error_at(e->location(), "non-integer %s argument to make",
7495 is_length ? "len" : "cap");
7496 return false;
7497 case Numeric_constant::NC_UL_NEGATIVE:
7498 error_at(e->location(), "negative %s argument to make",
7499 is_length ? "len" : "cap");
7500 return false;
7501 case Numeric_constant::NC_UL_BIG:
7502 // We don't want to give a compile-time error for a 64-bit
7503 // value on a 32-bit target.
1b10c5e7 7504 break;
1ad00fd4 7505 }
1b10c5e7 7506
7507 mpz_t val;
7508 if (!nc.to_int(&val))
7509 go_unreachable();
7510 int bits = mpz_sizeinbase(val, 2);
7511 mpz_clear(val);
7512 Type* int_type = Type::lookup_integer_type("int");
7513 if (bits >= int_type->integer_type()->bits())
7514 {
7515 error_at(e->location(), "%s argument too large for make",
7516 is_length ? "len" : "cap");
7517 return false;
7518 }
7519
7520 return true;
a9182619 7521 }
7522
1ad00fd4 7523 if (e->type()->integer_type() != NULL)
7524 return true;
7525
7526 error_at(e->location(), "non-integer %s argument to make",
7527 is_length ? "len" : "cap");
a9182619 7528 return false;
7529}
7530
e440a328 7531// Return the type of the real or imag functions, given the type of
7532// the argument. We need to map complex to float, complex64 to
7533// float32, and complex128 to float64, so it has to be done by name.
7534// This returns NULL if it can't figure out the type.
7535
7536Type*
7537Builtin_call_expression::real_imag_type(Type* arg_type)
7538{
7539 if (arg_type == NULL || arg_type->is_abstract())
7540 return NULL;
7541 Named_type* nt = arg_type->named_type();
7542 if (nt == NULL)
7543 return NULL;
7544 while (nt->real_type()->named_type() != NULL)
7545 nt = nt->real_type()->named_type();
48080209 7546 if (nt->name() == "complex64")
e440a328 7547 return Type::lookup_float_type("float32");
7548 else if (nt->name() == "complex128")
7549 return Type::lookup_float_type("float64");
7550 else
7551 return NULL;
7552}
7553
48080209 7554// Return the type of the complex function, given the type of one of the
e440a328 7555// argments. Like real_imag_type, we have to map by name.
7556
7557Type*
48080209 7558Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7559{
7560 if (arg_type == NULL || arg_type->is_abstract())
7561 return NULL;
7562 Named_type* nt = arg_type->named_type();
7563 if (nt == NULL)
7564 return NULL;
7565 while (nt->real_type()->named_type() != NULL)
7566 nt = nt->real_type()->named_type();
48080209 7567 if (nt->name() == "float32")
e440a328 7568 return Type::lookup_complex_type("complex64");
7569 else if (nt->name() == "float64")
7570 return Type::lookup_complex_type("complex128");
7571 else
7572 return NULL;
7573}
7574
7575// Return a single argument, or NULL if there isn't one.
7576
7577Expression*
7578Builtin_call_expression::one_arg() const
7579{
7580 const Expression_list* args = this->args();
aa615cb3 7581 if (args == NULL || args->size() != 1)
e440a328 7582 return NULL;
7583 return args->front();
7584}
7585
83921647 7586// A traversal class which looks for a call or receive expression.
7587
7588class Find_call_expression : public Traverse
7589{
7590 public:
7591 Find_call_expression()
7592 : Traverse(traverse_expressions),
7593 found_(false)
7594 { }
7595
7596 int
7597 expression(Expression**);
7598
7599 bool
7600 found()
7601 { return this->found_; }
7602
7603 private:
7604 bool found_;
7605};
7606
7607int
7608Find_call_expression::expression(Expression** pexpr)
7609{
7610 if ((*pexpr)->call_expression() != NULL
7611 || (*pexpr)->receive_expression() != NULL)
7612 {
7613 this->found_ = true;
7614 return TRAVERSE_EXIT;
7615 }
7616 return TRAVERSE_CONTINUE;
7617}
7618
7619// Return whether this is constant: len of a string constant, or len
7620// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7621// unsafe.Alignof.
e440a328 7622
7623bool
7624Builtin_call_expression::do_is_constant() const
7625{
12e69faa 7626 if (this->is_error_expression())
7627 return true;
e440a328 7628 switch (this->code_)
7629 {
7630 case BUILTIN_LEN:
7631 case BUILTIN_CAP:
7632 {
0f914071 7633 if (this->seen_)
7634 return false;
7635
e440a328 7636 Expression* arg = this->one_arg();
7637 if (arg == NULL)
7638 return false;
7639 Type* arg_type = arg->type();
7640
7641 if (arg_type->points_to() != NULL
7642 && arg_type->points_to()->array_type() != NULL
411eb89e 7643 && !arg_type->points_to()->is_slice_type())
e440a328 7644 arg_type = arg_type->points_to();
7645
83921647 7646 // The len and cap functions are only constant if there are no
7647 // function calls or channel operations in the arguments.
7648 // Otherwise we have to make the call.
7649 if (!arg->is_constant())
7650 {
7651 Find_call_expression find_call;
7652 Expression::traverse(&arg, &find_call);
7653 if (find_call.found())
7654 return false;
7655 }
7656
e440a328 7657 if (arg_type->array_type() != NULL
7658 && arg_type->array_type()->length() != NULL)
0f914071 7659 return true;
e440a328 7660
7661 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7662 {
7663 this->seen_ = true;
7664 bool ret = arg->is_constant();
7665 this->seen_ = false;
7666 return ret;
7667 }
e440a328 7668 }
7669 break;
7670
7671 case BUILTIN_SIZEOF:
7672 case BUILTIN_ALIGNOF:
7673 return this->one_arg() != NULL;
7674
7675 case BUILTIN_OFFSETOF:
7676 {
7677 Expression* arg = this->one_arg();
7678 if (arg == NULL)
7679 return false;
7680 return arg->field_reference_expression() != NULL;
7681 }
7682
48080209 7683 case BUILTIN_COMPLEX:
e440a328 7684 {
7685 const Expression_list* args = this->args();
7686 if (args != NULL && args->size() == 2)
7687 return args->front()->is_constant() && args->back()->is_constant();
7688 }
7689 break;
7690
7691 case BUILTIN_REAL:
7692 case BUILTIN_IMAG:
7693 {
7694 Expression* arg = this->one_arg();
7695 return arg != NULL && arg->is_constant();
7696 }
7697
7698 default:
7699 break;
7700 }
7701
7702 return false;
7703}
7704
0c77715b 7705// Return a numeric constant if possible.
e440a328 7706
7707bool
0c77715b 7708Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7709{
7710 if (this->code_ == BUILTIN_LEN
7711 || this->code_ == BUILTIN_CAP)
7712 {
7713 Expression* arg = this->one_arg();
7714 if (arg == NULL)
7715 return false;
7716 Type* arg_type = arg->type();
7717
7718 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7719 {
7720 std::string sval;
7721 if (arg->string_constant_value(&sval))
7722 {
0c77715b 7723 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7724 sval.length());
e440a328 7725 return true;
7726 }
7727 }
7728
7729 if (arg_type->points_to() != NULL
7730 && arg_type->points_to()->array_type() != NULL
411eb89e 7731 && !arg_type->points_to()->is_slice_type())
e440a328 7732 arg_type = arg_type->points_to();
7733
7734 if (arg_type->array_type() != NULL
7735 && arg_type->array_type()->length() != NULL)
7736 {
0f914071 7737 if (this->seen_)
7738 return false;
e440a328 7739 Expression* e = arg_type->array_type()->length();
0f914071 7740 this->seen_ = true;
0c77715b 7741 bool r = e->numeric_constant_value(nc);
0f914071 7742 this->seen_ = false;
7743 if (r)
e440a328 7744 {
0c77715b 7745 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7746 this->location()))
7747 r = false;
e440a328 7748 }
0c77715b 7749 return r;
e440a328 7750 }
7751 }
7752 else if (this->code_ == BUILTIN_SIZEOF
7753 || this->code_ == BUILTIN_ALIGNOF)
7754 {
7755 Expression* arg = this->one_arg();
7756 if (arg == NULL)
7757 return false;
7758 Type* arg_type = arg->type();
5c13bd80 7759 if (arg_type->is_error())
e440a328 7760 return false;
7761 if (arg_type->is_abstract())
7762 return false;
927a01eb 7763
7764 unsigned int ret;
e440a328 7765 if (this->code_ == BUILTIN_SIZEOF)
7766 {
927a01eb 7767 if (!arg_type->backend_type_size(this->gogo_, &ret))
e440a328 7768 return false;
7769 }
7770 else if (this->code_ == BUILTIN_ALIGNOF)
7771 {
637bd3af 7772 if (arg->field_reference_expression() == NULL)
927a01eb 7773 {
7774 if (!arg_type->backend_type_align(this->gogo_, &ret))
7775 return false;
7776 }
637bd3af 7777 else
e440a328 7778 {
7779 // Calling unsafe.Alignof(s.f) returns the alignment of
7780 // the type of f when it is used as a field in a struct.
927a01eb 7781 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7782 return false;
e440a328 7783 }
e440a328 7784 }
7785 else
c3e6f413 7786 go_unreachable();
927a01eb 7787
7ba86326 7788 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7789 static_cast<unsigned long>(ret));
e440a328 7790 return true;
7791 }
7792 else if (this->code_ == BUILTIN_OFFSETOF)
7793 {
7794 Expression* arg = this->one_arg();
7795 if (arg == NULL)
7796 return false;
7797 Field_reference_expression* farg = arg->field_reference_expression();
7798 if (farg == NULL)
7799 return false;
9a4bd570 7800 unsigned int total_offset = 0;
7801 while (true)
7802 {
7803 Expression* struct_expr = farg->expr();
7804 Type* st = struct_expr->type();
7805 if (st->struct_type() == NULL)
7806 return false;
7807 if (st->named_type() != NULL)
7808 st->named_type()->convert(this->gogo_);
7809 unsigned int offset;
7810 if (!st->struct_type()->backend_field_offset(this->gogo_,
7811 farg->field_index(),
7812 &offset))
7813 return false;
7814 total_offset += offset;
7815 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7816 {
7817 // Go up until we reach the original base.
7818 farg = struct_expr->field_reference_expression();
7819 continue;
7820 }
7821 break;
7822 }
7ba86326 7823 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
9a4bd570 7824 static_cast<unsigned long>(total_offset));
e440a328 7825 return true;
7826 }
0c77715b 7827 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 7828 {
7829 Expression* arg = this->one_arg();
7830 if (arg == NULL)
7831 return false;
7832
0c77715b 7833 Numeric_constant argnc;
7834 if (!arg->numeric_constant_value(&argnc))
7835 return false;
7836
e440a328 7837 mpfr_t real;
7838 mpfr_t imag;
0c77715b 7839 if (!argnc.to_complex(&real, &imag))
7840 return false;
e440a328 7841
0c77715b 7842 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7843 if (this->code_ == BUILTIN_REAL)
7844 nc->set_float(type, real);
7845 else
7846 nc->set_float(type, imag);
7847 return true;
e440a328 7848 }
0c77715b 7849 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 7850 {
7851 const Expression_list* args = this->args();
7852 if (args == NULL || args->size() != 2)
7853 return false;
7854
0c77715b 7855 Numeric_constant rnc;
7856 if (!args->front()->numeric_constant_value(&rnc))
7857 return false;
7858 Numeric_constant inc;
7859 if (!args->back()->numeric_constant_value(&inc))
7860 return false;
7861
7862 if (rnc.type() != NULL
7863 && !rnc.type()->is_abstract()
7864 && inc.type() != NULL
7865 && !inc.type()->is_abstract()
7866 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7867 return false;
7868
e440a328 7869 mpfr_t r;
0c77715b 7870 if (!rnc.to_float(&r))
7871 return false;
7872 mpfr_t i;
7873 if (!inc.to_float(&i))
e440a328 7874 {
7875 mpfr_clear(r);
7876 return false;
7877 }
7878
0c77715b 7879 Type* arg_type = rnc.type();
7880 if (arg_type == NULL || arg_type->is_abstract())
7881 arg_type = inc.type();
e440a328 7882
0c77715b 7883 Type* type = Builtin_call_expression::complex_type(arg_type);
7884 nc->set_complex(type, r, i);
e440a328 7885
7886 mpfr_clear(r);
7887 mpfr_clear(i);
7888
0c77715b 7889 return true;
e440a328 7890 }
7891
7892 return false;
7893}
7894
a7549a6a 7895// Give an error if we are discarding the value of an expression which
7896// should not normally be discarded. We don't give an error for
7897// discarding the value of an ordinary function call, but we do for
7898// builtin functions, purely for consistency with the gc compiler.
7899
4f2138d7 7900bool
a7549a6a 7901Builtin_call_expression::do_discarding_value()
7902{
7903 switch (this->code_)
7904 {
7905 case BUILTIN_INVALID:
7906 default:
7907 go_unreachable();
7908
7909 case BUILTIN_APPEND:
7910 case BUILTIN_CAP:
7911 case BUILTIN_COMPLEX:
7912 case BUILTIN_IMAG:
7913 case BUILTIN_LEN:
7914 case BUILTIN_MAKE:
7915 case BUILTIN_NEW:
7916 case BUILTIN_REAL:
7917 case BUILTIN_ALIGNOF:
7918 case BUILTIN_OFFSETOF:
7919 case BUILTIN_SIZEOF:
7920 this->unused_value_error();
4f2138d7 7921 return false;
a7549a6a 7922
7923 case BUILTIN_CLOSE:
7924 case BUILTIN_COPY:
1cce762f 7925 case BUILTIN_DELETE:
a7549a6a 7926 case BUILTIN_PANIC:
7927 case BUILTIN_PRINT:
7928 case BUILTIN_PRINTLN:
7929 case BUILTIN_RECOVER:
4f2138d7 7930 return true;
a7549a6a 7931 }
7932}
7933
e440a328 7934// Return the type.
7935
7936Type*
7937Builtin_call_expression::do_type()
7938{
7939 switch (this->code_)
7940 {
7941 case BUILTIN_INVALID:
7942 default:
c3e6f413 7943 go_unreachable();
e440a328 7944
7945 case BUILTIN_NEW:
7946 case BUILTIN_MAKE:
7947 {
7948 const Expression_list* args = this->args();
7949 if (args == NULL || args->empty())
7950 return Type::make_error_type();
7951 return Type::make_pointer_type(args->front()->type());
7952 }
7953
7954 case BUILTIN_CAP:
7955 case BUILTIN_COPY:
7956 case BUILTIN_LEN:
7ba86326 7957 return Type::lookup_integer_type("int");
7958
e440a328 7959 case BUILTIN_ALIGNOF:
7960 case BUILTIN_OFFSETOF:
7961 case BUILTIN_SIZEOF:
7ba86326 7962 return Type::lookup_integer_type("uintptr");
e440a328 7963
7964 case BUILTIN_CLOSE:
1cce762f 7965 case BUILTIN_DELETE:
e440a328 7966 case BUILTIN_PANIC:
7967 case BUILTIN_PRINT:
7968 case BUILTIN_PRINTLN:
7969 return Type::make_void_type();
7970
e440a328 7971 case BUILTIN_RECOVER:
823c7e3d 7972 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 7973
7974 case BUILTIN_APPEND:
7975 {
7976 const Expression_list* args = this->args();
7977 if (args == NULL || args->empty())
7978 return Type::make_error_type();
3ff4863b 7979 Type *ret = args->front()->type();
7980 if (!ret->is_slice_type())
7981 return Type::make_error_type();
7982 return ret;
e440a328 7983 }
7984
7985 case BUILTIN_REAL:
7986 case BUILTIN_IMAG:
7987 {
7988 Expression* arg = this->one_arg();
7989 if (arg == NULL)
7990 return Type::make_error_type();
7991 Type* t = arg->type();
7992 if (t->is_abstract())
7993 t = t->make_non_abstract_type();
7994 t = Builtin_call_expression::real_imag_type(t);
7995 if (t == NULL)
7996 t = Type::make_error_type();
7997 return t;
7998 }
7999
48080209 8000 case BUILTIN_COMPLEX:
e440a328 8001 {
8002 const Expression_list* args = this->args();
8003 if (args == NULL || args->size() != 2)
8004 return Type::make_error_type();
8005 Type* t = args->front()->type();
8006 if (t->is_abstract())
8007 {
8008 t = args->back()->type();
8009 if (t->is_abstract())
8010 t = t->make_non_abstract_type();
8011 }
48080209 8012 t = Builtin_call_expression::complex_type(t);
e440a328 8013 if (t == NULL)
8014 t = Type::make_error_type();
8015 return t;
8016 }
8017 }
8018}
8019
8020// Determine the type.
8021
8022void
8023Builtin_call_expression::do_determine_type(const Type_context* context)
8024{
fb94b0ca 8025 if (!this->determining_types())
8026 return;
8027
e440a328 8028 this->fn()->determine_type_no_context();
8029
8030 const Expression_list* args = this->args();
8031
8032 bool is_print;
8033 Type* arg_type = NULL;
8034 switch (this->code_)
8035 {
8036 case BUILTIN_PRINT:
8037 case BUILTIN_PRINTLN:
8038 // Do not force a large integer constant to "int".
8039 is_print = true;
8040 break;
8041
8042 case BUILTIN_REAL:
8043 case BUILTIN_IMAG:
48080209 8044 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 8045 if (arg_type == NULL)
8046 arg_type = Type::lookup_complex_type("complex128");
e440a328 8047 is_print = false;
8048 break;
8049
48080209 8050 case BUILTIN_COMPLEX:
e440a328 8051 {
48080209 8052 // For the complex function the type of one operand can
e440a328 8053 // determine the type of the other, as in a binary expression.
8054 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 8055 if (arg_type == NULL)
8056 arg_type = Type::lookup_float_type("float64");
e440a328 8057 if (args != NULL && args->size() == 2)
8058 {
8059 Type* t1 = args->front()->type();
c849bb59 8060 Type* t2 = args->back()->type();
e440a328 8061 if (!t1->is_abstract())
8062 arg_type = t1;
8063 else if (!t2->is_abstract())
8064 arg_type = t2;
8065 }
8066 is_print = false;
8067 }
8068 break;
8069
8070 default:
8071 is_print = false;
8072 break;
8073 }
8074
8075 if (args != NULL)
8076 {
8077 for (Expression_list::const_iterator pa = args->begin();
8078 pa != args->end();
8079 ++pa)
8080 {
8081 Type_context subcontext;
8082 subcontext.type = arg_type;
8083
8084 if (is_print)
8085 {
8086 // We want to print large constants, we so can't just
8087 // use the appropriate nonabstract type. Use uint64 for
8088 // an integer if we know it is nonnegative, otherwise
8089 // use int64 for a integer, otherwise use float64 for a
8090 // float or complex128 for a complex.
8091 Type* want_type = NULL;
8092 Type* atype = (*pa)->type();
8093 if (atype->is_abstract())
8094 {
8095 if (atype->integer_type() != NULL)
8096 {
0c77715b 8097 Numeric_constant nc;
8098 if (this->numeric_constant_value(&nc))
8099 {
8100 mpz_t val;
8101 if (nc.to_int(&val))
8102 {
8103 if (mpz_sgn(val) >= 0)
8104 want_type = Type::lookup_integer_type("uint64");
8105 mpz_clear(val);
8106 }
8107 }
8108 if (want_type == NULL)
e440a328 8109 want_type = Type::lookup_integer_type("int64");
e440a328 8110 }
8111 else if (atype->float_type() != NULL)
8112 want_type = Type::lookup_float_type("float64");
8113 else if (atype->complex_type() != NULL)
8114 want_type = Type::lookup_complex_type("complex128");
8115 else if (atype->is_abstract_string_type())
8116 want_type = Type::lookup_string_type();
8117 else if (atype->is_abstract_boolean_type())
8118 want_type = Type::lookup_bool_type();
8119 else
c3e6f413 8120 go_unreachable();
e440a328 8121 subcontext.type = want_type;
8122 }
8123 }
8124
8125 (*pa)->determine_type(&subcontext);
8126 }
8127 }
8128}
8129
8130// If there is exactly one argument, return true. Otherwise give an
8131// error message and return false.
8132
8133bool
8134Builtin_call_expression::check_one_arg()
8135{
8136 const Expression_list* args = this->args();
8137 if (args == NULL || args->size() < 1)
8138 {
8139 this->report_error(_("not enough arguments"));
8140 return false;
8141 }
8142 else if (args->size() > 1)
8143 {
8144 this->report_error(_("too many arguments"));
8145 return false;
8146 }
8147 if (args->front()->is_error_expression()
5c13bd80 8148 || args->front()->type()->is_error())
e440a328 8149 {
8150 this->set_is_error();
8151 return false;
8152 }
8153 return true;
8154}
8155
8156// Check argument types for a builtin function.
8157
8158void
8159Builtin_call_expression::do_check_types(Gogo*)
8160{
375646ea 8161 if (this->is_error_expression())
8162 return;
e440a328 8163 switch (this->code_)
8164 {
8165 case BUILTIN_INVALID:
8166 case BUILTIN_NEW:
8167 case BUILTIN_MAKE:
cd238b8d 8168 case BUILTIN_DELETE:
e440a328 8169 return;
8170
8171 case BUILTIN_LEN:
8172 case BUILTIN_CAP:
8173 {
8174 // The single argument may be either a string or an array or a
8175 // map or a channel, or a pointer to a closed array.
8176 if (this->check_one_arg())
8177 {
8178 Type* arg_type = this->one_arg()->type();
8179 if (arg_type->points_to() != NULL
8180 && arg_type->points_to()->array_type() != NULL
411eb89e 8181 && !arg_type->points_to()->is_slice_type())
e440a328 8182 arg_type = arg_type->points_to();
8183 if (this->code_ == BUILTIN_CAP)
8184 {
5c13bd80 8185 if (!arg_type->is_error()
e440a328 8186 && arg_type->array_type() == NULL
8187 && arg_type->channel_type() == NULL)
8188 this->report_error(_("argument must be array or slice "
8189 "or channel"));
8190 }
8191 else
8192 {
5c13bd80 8193 if (!arg_type->is_error()
e440a328 8194 && !arg_type->is_string_type()
8195 && arg_type->array_type() == NULL
8196 && arg_type->map_type() == NULL
8197 && arg_type->channel_type() == NULL)
8198 this->report_error(_("argument must be string or "
8199 "array or slice or map or channel"));
8200 }
8201 }
8202 }
8203 break;
8204
8205 case BUILTIN_PRINT:
8206 case BUILTIN_PRINTLN:
8207 {
8208 const Expression_list* args = this->args();
8209 if (args == NULL)
8210 {
8211 if (this->code_ == BUILTIN_PRINT)
8212 warning_at(this->location(), 0,
8213 "no arguments for builtin function %<%s%>",
8214 (this->code_ == BUILTIN_PRINT
8215 ? "print"
8216 : "println"));
8217 }
8218 else
8219 {
8220 for (Expression_list::const_iterator p = args->begin();
8221 p != args->end();
8222 ++p)
8223 {
8224 Type* type = (*p)->type();
5c13bd80 8225 if (type->is_error()
e440a328 8226 || type->is_string_type()
8227 || type->integer_type() != NULL
8228 || type->float_type() != NULL
8229 || type->complex_type() != NULL
8230 || type->is_boolean_type()
8231 || type->points_to() != NULL
8232 || type->interface_type() != NULL
8233 || type->channel_type() != NULL
8234 || type->map_type() != NULL
8235 || type->function_type() != NULL
411eb89e 8236 || type->is_slice_type())
e440a328 8237 ;
acf8e158 8238 else if ((*p)->is_type_expression())
8239 {
8240 // If this is a type expression it's going to give
8241 // an error anyhow, so we don't need one here.
8242 }
e440a328 8243 else
8244 this->report_error(_("unsupported argument type to "
8245 "builtin function"));
8246 }
8247 }
8248 }
8249 break;
8250
8251 case BUILTIN_CLOSE:
e440a328 8252 if (this->check_one_arg())
8253 {
8254 if (this->one_arg()->type()->channel_type() == NULL)
8255 this->report_error(_("argument must be channel"));
5202d986 8256 else if (!this->one_arg()->type()->channel_type()->may_send())
8257 this->report_error(_("cannot close receive-only channel"));
e440a328 8258 }
8259 break;
8260
8261 case BUILTIN_PANIC:
8262 case BUILTIN_SIZEOF:
8263 case BUILTIN_ALIGNOF:
8264 this->check_one_arg();
8265 break;
8266
8267 case BUILTIN_RECOVER:
8268 if (this->args() != NULL && !this->args()->empty())
8269 this->report_error(_("too many arguments"));
8270 break;
8271
8272 case BUILTIN_OFFSETOF:
8273 if (this->check_one_arg())
8274 {
8275 Expression* arg = this->one_arg();
8276 if (arg->field_reference_expression() == NULL)
8277 this->report_error(_("argument must be a field reference"));
8278 }
8279 break;
8280
8281 case BUILTIN_COPY:
8282 {
8283 const Expression_list* args = this->args();
8284 if (args == NULL || args->size() < 2)
8285 {
8286 this->report_error(_("not enough arguments"));
8287 break;
8288 }
8289 else if (args->size() > 2)
8290 {
8291 this->report_error(_("too many arguments"));
8292 break;
8293 }
8294 Type* arg1_type = args->front()->type();
8295 Type* arg2_type = args->back()->type();
5c13bd80 8296 if (arg1_type->is_error() || arg2_type->is_error())
e440a328 8297 break;
8298
8299 Type* e1;
411eb89e 8300 if (arg1_type->is_slice_type())
e440a328 8301 e1 = arg1_type->array_type()->element_type();
8302 else
8303 {
8304 this->report_error(_("left argument must be a slice"));
8305 break;
8306 }
8307
411eb89e 8308 if (arg2_type->is_slice_type())
60963afd 8309 {
8310 Type* e2 = arg2_type->array_type()->element_type();
8311 if (!Type::are_identical(e1, e2, true, NULL))
8312 this->report_error(_("element types must be the same"));
8313 }
e440a328 8314 else if (arg2_type->is_string_type())
e440a328 8315 {
60963afd 8316 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8317 this->report_error(_("first argument must be []byte"));
e440a328 8318 }
60963afd 8319 else
8320 this->report_error(_("second argument must be slice or string"));
e440a328 8321 }
8322 break;
8323
8324 case BUILTIN_APPEND:
8325 {
8326 const Expression_list* args = this->args();
b0d311a1 8327 if (args == NULL || args->size() < 2)
e440a328 8328 {
8329 this->report_error(_("not enough arguments"));
8330 break;
8331 }
0b7755ec 8332 if (args->size() > 2)
8333 {
8334 this->report_error(_("too many arguments"));
8335 break;
8336 }
cd238b8d 8337 if (args->front()->type()->is_error()
8338 || args->back()->type()->is_error())
8339 break;
8340
8341 Array_type* at = args->front()->type()->array_type();
8342 Type* e = at->element_type();
4fd4fcf4 8343
8344 // The language permits appending a string to a []byte, as a
8345 // special case.
8346 if (args->back()->type()->is_string_type())
8347 {
60963afd 8348 if (e->integer_type() != NULL && e->integer_type()->is_byte())
4fd4fcf4 8349 break;
8350 }
8351
19fd40c3 8352 // The language says that the second argument must be
8353 // assignable to a slice of the element type of the first
8354 // argument. We already know the first argument is a slice
8355 // type.
cd238b8d 8356 Type* arg2_type = Type::make_array_type(e, NULL);
e440a328 8357 std::string reason;
19fd40c3 8358 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
e440a328 8359 {
8360 if (reason.empty())
19fd40c3 8361 this->report_error(_("argument 2 has invalid type"));
e440a328 8362 else
8363 {
19fd40c3 8364 error_at(this->location(), "argument 2 has invalid type (%s)",
e440a328 8365 reason.c_str());
8366 this->set_is_error();
8367 }
8368 }
8369 break;
8370 }
8371
8372 case BUILTIN_REAL:
8373 case BUILTIN_IMAG:
8374 if (this->check_one_arg())
8375 {
8376 if (this->one_arg()->type()->complex_type() == NULL)
8377 this->report_error(_("argument must have complex type"));
8378 }
8379 break;
8380
48080209 8381 case BUILTIN_COMPLEX:
e440a328 8382 {
8383 const Expression_list* args = this->args();
8384 if (args == NULL || args->size() < 2)
8385 this->report_error(_("not enough arguments"));
8386 else if (args->size() > 2)
8387 this->report_error(_("too many arguments"));
8388 else if (args->front()->is_error_expression()
5c13bd80 8389 || args->front()->type()->is_error()
e440a328 8390 || args->back()->is_error_expression()
5c13bd80 8391 || args->back()->type()->is_error())
e440a328 8392 this->set_is_error();
8393 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8394 args->back()->type(), true, NULL))
48080209 8395 this->report_error(_("complex arguments must have identical types"));
e440a328 8396 else if (args->front()->type()->float_type() == NULL)
48080209 8397 this->report_error(_("complex arguments must have "
e440a328 8398 "floating-point type"));
8399 }
8400 break;
8401
8402 default:
c3e6f413 8403 go_unreachable();
e440a328 8404 }
8405}
8406
8407// Return the tree for a builtin function.
8408
8409tree
8410Builtin_call_expression::do_get_tree(Translate_context* context)
8411{
8412 Gogo* gogo = context->gogo();
b13c66cd 8413 Location location = this->location();
e440a328 8414 switch (this->code_)
8415 {
8416 case BUILTIN_INVALID:
8417 case BUILTIN_NEW:
8418 case BUILTIN_MAKE:
c3e6f413 8419 go_unreachable();
e440a328 8420
8421 case BUILTIN_LEN:
8422 case BUILTIN_CAP:
8423 {
8424 const Expression_list* args = this->args();
c484d925 8425 go_assert(args != NULL && args->size() == 1);
e440a328 8426 Expression* arg = *args->begin();
8427 Type* arg_type = arg->type();
0f914071 8428
8429 if (this->seen_)
8430 {
c484d925 8431 go_assert(saw_errors());
0f914071 8432 return error_mark_node;
8433 }
8434 this->seen_ = true;
8435
e440a328 8436 tree arg_tree = arg->get_tree(context);
0f914071 8437
8438 this->seen_ = false;
8439
e440a328 8440 if (arg_tree == error_mark_node)
8441 return error_mark_node;
8442
8443 if (arg_type->points_to() != NULL)
8444 {
8445 arg_type = arg_type->points_to();
c484d925 8446 go_assert(arg_type->array_type() != NULL
411eb89e 8447 && !arg_type->is_slice_type());
c484d925 8448 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
e440a328 8449 arg_tree = build_fold_indirect_ref(arg_tree);
8450 }
8451
1b1f2abf 8452 Type* int_type = Type::lookup_integer_type("int");
8453 tree int_type_tree = type_to_tree(int_type->get_backend(gogo));
8454
e440a328 8455 tree val_tree;
8456 if (this->code_ == BUILTIN_LEN)
8457 {
8458 if (arg_type->is_string_type())
8459 val_tree = String_type::length_tree(gogo, arg_tree);
8460 else if (arg_type->array_type() != NULL)
0f914071 8461 {
8462 if (this->seen_)
8463 {
c484d925 8464 go_assert(saw_errors());
0f914071 8465 return error_mark_node;
8466 }
8467 this->seen_ = true;
35a54f17 8468 Expression* len = arg_type->array_type()->get_length(gogo, arg);
8469 val_tree = len->get_tree(context);
0f914071 8470 this->seen_ = false;
8471 }
e440a328 8472 else if (arg_type->map_type() != NULL)
8473 {
9f0e0513 8474 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
e440a328 8475 static tree map_len_fndecl;
8476 val_tree = Gogo::call_builtin(&map_len_fndecl,
8477 location,
8478 "__go_map_len",
8479 1,
1b1f2abf 8480 int_type_tree,
9f0e0513 8481 arg_type_tree,
e440a328 8482 arg_tree);
8483 }
8484 else if (arg_type->channel_type() != NULL)
8485 {
9f0e0513 8486 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
e440a328 8487 static tree chan_len_fndecl;
8488 val_tree = Gogo::call_builtin(&chan_len_fndecl,
8489 location,
8490 "__go_chan_len",
8491 1,
1b1f2abf 8492 int_type_tree,
9f0e0513 8493 arg_type_tree,
e440a328 8494 arg_tree);
8495 }
8496 else
c3e6f413 8497 go_unreachable();
e440a328 8498 }
8499 else
8500 {
8501 if (arg_type->array_type() != NULL)
0f914071 8502 {
8503 if (this->seen_)
8504 {
c484d925 8505 go_assert(saw_errors());
0f914071 8506 return error_mark_node;
8507 }
8508 this->seen_ = true;
35a54f17 8509 Expression* cap =
8510 arg_type->array_type()->get_capacity(gogo, arg);
8511 val_tree = cap->get_tree(context);
0f914071 8512 this->seen_ = false;
8513 }
e440a328 8514 else if (arg_type->channel_type() != NULL)
8515 {
9f0e0513 8516 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
e440a328 8517 static tree chan_cap_fndecl;
8518 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
8519 location,
8520 "__go_chan_cap",
8521 1,
1b1f2abf 8522 int_type_tree,
9f0e0513 8523 arg_type_tree,
e440a328 8524 arg_tree);
8525 }
8526 else
c3e6f413 8527 go_unreachable();
e440a328 8528 }
8529
1b1f2abf 8530 return fold_convert_loc(location.gcc_location(), int_type_tree,
8531 val_tree);
e440a328 8532 }
8533
8534 case BUILTIN_PRINT:
8535 case BUILTIN_PRINTLN:
8536 {
8537 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8538 tree stmt_list = NULL_TREE;
8539
8540 const Expression_list* call_args = this->args();
8541 if (call_args != NULL)
8542 {
8543 for (Expression_list::const_iterator p = call_args->begin();
8544 p != call_args->end();
8545 ++p)
8546 {
8547 if (is_ln && p != call_args->begin())
8548 {
8549 static tree print_space_fndecl;
8550 tree call = Gogo::call_builtin(&print_space_fndecl,
8551 location,
8552 "__go_print_space",
8553 0,
8554 void_type_node);
5fb82b5e 8555 if (call == error_mark_node)
8556 return error_mark_node;
e440a328 8557 append_to_statement_list(call, &stmt_list);
8558 }
8559
8560 Type* type = (*p)->type();
8561
8562 tree arg = (*p)->get_tree(context);
8563 if (arg == error_mark_node)
8564 return error_mark_node;
8565
8566 tree* pfndecl;
8567 const char* fnname;
8568 if (type->is_string_type())
8569 {
8570 static tree print_string_fndecl;
8571 pfndecl = &print_string_fndecl;
8572 fnname = "__go_print_string";
8573 }
8574 else if (type->integer_type() != NULL
8575 && type->integer_type()->is_unsigned())
8576 {
8577 static tree print_uint64_fndecl;
8578 pfndecl = &print_uint64_fndecl;
8579 fnname = "__go_print_uint64";
8580 Type* itype = Type::lookup_integer_type("uint64");
9f0e0513 8581 Btype* bitype = itype->get_backend(gogo);
b13c66cd 8582 arg = fold_convert_loc(location.gcc_location(),
8583 type_to_tree(bitype), arg);
e440a328 8584 }
8585 else if (type->integer_type() != NULL)
8586 {
8587 static tree print_int64_fndecl;
8588 pfndecl = &print_int64_fndecl;
8589 fnname = "__go_print_int64";
8590 Type* itype = Type::lookup_integer_type("int64");
9f0e0513 8591 Btype* bitype = itype->get_backend(gogo);
b13c66cd 8592 arg = fold_convert_loc(location.gcc_location(),
8593 type_to_tree(bitype), arg);
e440a328 8594 }
8595 else if (type->float_type() != NULL)
8596 {
8597 static tree print_double_fndecl;
8598 pfndecl = &print_double_fndecl;
8599 fnname = "__go_print_double";
b13c66cd 8600 arg = fold_convert_loc(location.gcc_location(),
8601 double_type_node, arg);
e440a328 8602 }
8603 else if (type->complex_type() != NULL)
8604 {
8605 static tree print_complex_fndecl;
8606 pfndecl = &print_complex_fndecl;
8607 fnname = "__go_print_complex";
b13c66cd 8608 arg = fold_convert_loc(location.gcc_location(),
8609 complex_double_type_node, arg);
e440a328 8610 }
8611 else if (type->is_boolean_type())
8612 {
8613 static tree print_bool_fndecl;
8614 pfndecl = &print_bool_fndecl;
8615 fnname = "__go_print_bool";
8616 }
8617 else if (type->points_to() != NULL
8618 || type->channel_type() != NULL
8619 || type->map_type() != NULL
8620 || type->function_type() != NULL)
8621 {
8622 static tree print_pointer_fndecl;
8623 pfndecl = &print_pointer_fndecl;
8624 fnname = "__go_print_pointer";
b13c66cd 8625 arg = fold_convert_loc(location.gcc_location(),
8626 ptr_type_node, arg);
e440a328 8627 }
8628 else if (type->interface_type() != NULL)
8629 {
8630 if (type->interface_type()->is_empty())
8631 {
8632 static tree print_empty_interface_fndecl;
8633 pfndecl = &print_empty_interface_fndecl;
8634 fnname = "__go_print_empty_interface";
8635 }
8636 else
8637 {
8638 static tree print_interface_fndecl;
8639 pfndecl = &print_interface_fndecl;
8640 fnname = "__go_print_interface";
8641 }
8642 }
411eb89e 8643 else if (type->is_slice_type())
e440a328 8644 {
8645 static tree print_slice_fndecl;
8646 pfndecl = &print_slice_fndecl;
8647 fnname = "__go_print_slice";
8648 }
8649 else
cd238b8d 8650 {
8651 go_assert(saw_errors());
8652 return error_mark_node;
8653 }
e440a328 8654
8655 tree call = Gogo::call_builtin(pfndecl,
8656 location,
8657 fnname,
8658 1,
8659 void_type_node,
8660 TREE_TYPE(arg),
8661 arg);
5fb82b5e 8662 if (call == error_mark_node)
8663 return error_mark_node;
8664 append_to_statement_list(call, &stmt_list);
e440a328 8665 }
8666 }
8667
8668 if (is_ln)
8669 {
8670 static tree print_nl_fndecl;
8671 tree call = Gogo::call_builtin(&print_nl_fndecl,
8672 location,
8673 "__go_print_nl",
8674 0,
8675 void_type_node);
5fb82b5e 8676 if (call == error_mark_node)
8677 return error_mark_node;
e440a328 8678 append_to_statement_list(call, &stmt_list);
8679 }
8680
8681 return stmt_list;
8682 }
8683
8684 case BUILTIN_PANIC:
8685 {
8686 const Expression_list* args = this->args();
c484d925 8687 go_assert(args != NULL && args->size() == 1);
e440a328 8688 Expression* arg = args->front();
8689 tree arg_tree = arg->get_tree(context);
8690 if (arg_tree == error_mark_node)
8691 return error_mark_node;
b13c66cd 8692 Type *empty =
823c7e3d 8693 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8694 arg_tree = Expression::convert_for_assignment(context, empty,
8695 arg->type(),
8696 arg_tree, location);
8697 static tree panic_fndecl;
8698 tree call = Gogo::call_builtin(&panic_fndecl,
8699 location,
8700 "__go_panic",
8701 1,
8702 void_type_node,
8703 TREE_TYPE(arg_tree),
8704 arg_tree);
5fb82b5e 8705 if (call == error_mark_node)
8706 return error_mark_node;
e440a328 8707 // This function will throw an exception.
8708 TREE_NOTHROW(panic_fndecl) = 0;
8709 // This function will not return.
8710 TREE_THIS_VOLATILE(panic_fndecl) = 1;
8711 return call;
8712 }
8713
8714 case BUILTIN_RECOVER:
8715 {
8716 // The argument is set when building recover thunks. It's a
8717 // boolean value which is true if we can recover a value now.
8718 const Expression_list* args = this->args();
c484d925 8719 go_assert(args != NULL && args->size() == 1);
e440a328 8720 Expression* arg = args->front();
8721 tree arg_tree = arg->get_tree(context);
8722 if (arg_tree == error_mark_node)
8723 return error_mark_node;
8724
b13c66cd 8725 Type *empty =
823c7e3d 8726 Type::make_empty_interface_type(Linemap::predeclared_location());
9f0e0513 8727 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
e440a328 8728
8729 Type* nil_type = Type::make_nil_type();
8730 Expression* nil = Expression::make_nil(location);
8731 tree nil_tree = nil->get_tree(context);
8732 tree empty_nil_tree = Expression::convert_for_assignment(context,
8733 empty,
8734 nil_type,
8735 nil_tree,
8736 location);
8737
8738 // We need to handle a deferred call to recover specially,
8739 // because it changes whether it can recover a panic or not.
8740 // See test7 in test/recover1.go.
8741 tree call;
8742 if (this->is_deferred())
8743 {
8744 static tree deferred_recover_fndecl;
8745 call = Gogo::call_builtin(&deferred_recover_fndecl,
8746 location,
8747 "__go_deferred_recover",
8748 0,
8749 empty_tree);
8750 }
8751 else
8752 {
8753 static tree recover_fndecl;
8754 call = Gogo::call_builtin(&recover_fndecl,
8755 location,
8756 "__go_recover",
8757 0,
8758 empty_tree);
8759 }
5fb82b5e 8760 if (call == error_mark_node)
8761 return error_mark_node;
b13c66cd 8762 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8763 arg_tree, call, empty_nil_tree);
e440a328 8764 }
8765
8766 case BUILTIN_CLOSE:
e440a328 8767 {
8768 const Expression_list* args = this->args();
c484d925 8769 go_assert(args != NULL && args->size() == 1);
e440a328 8770 Expression* arg = args->front();
8771 tree arg_tree = arg->get_tree(context);
8772 if (arg_tree == error_mark_node)
8773 return error_mark_node;
0dc2f918 8774 static tree close_fndecl;
8775 return Gogo::call_builtin(&close_fndecl,
8776 location,
8777 "__go_builtin_close",
8778 1,
8779 void_type_node,
8780 TREE_TYPE(arg_tree),
8781 arg_tree);
e440a328 8782 }
8783
8784 case BUILTIN_SIZEOF:
8785 case BUILTIN_OFFSETOF:
8786 case BUILTIN_ALIGNOF:
8787 {
0c77715b 8788 Numeric_constant nc;
8789 unsigned long val;
8790 if (!this->numeric_constant_value(&nc)
8791 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 8792 {
c484d925 8793 go_assert(saw_errors());
7f1d9abd 8794 return error_mark_node;
8795 }
7ba86326 8796 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8797 tree type = type_to_tree(uintptr_type->get_backend(gogo));
0c77715b 8798 return build_int_cst(type, val);
e440a328 8799 }
8800
8801 case BUILTIN_COPY:
8802 {
8803 const Expression_list* args = this->args();
c484d925 8804 go_assert(args != NULL && args->size() == 2);
e440a328 8805 Expression* arg1 = args->front();
8806 Expression* arg2 = args->back();
8807
8808 tree arg1_tree = arg1->get_tree(context);
8809 tree arg2_tree = arg2->get_tree(context);
8810 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8811 return error_mark_node;
8812
8813 Type* arg1_type = arg1->type();
8814 Array_type* at = arg1_type->array_type();
35a54f17 8815 go_assert(arg1->is_variable());
8816 Expression* arg1_valptr = at->get_value_pointer(gogo, arg1);
8817 Expression* arg1_len_expr = at->get_length(gogo, arg1);
8818 tree arg1_val = arg1_valptr->get_tree(context);
8819 tree arg1_len = arg1_len_expr->get_tree(context);
d8ccb1e3 8820 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8821 return error_mark_node;
e440a328 8822
8823 Type* arg2_type = arg2->type();
8824 tree arg2_val;
8825 tree arg2_len;
411eb89e 8826 if (arg2_type->is_slice_type())
e440a328 8827 {
8828 at = arg2_type->array_type();
35a54f17 8829 go_assert(arg2->is_variable());
8830 Expression* arg2_valptr = at->get_value_pointer(gogo, arg2);
8831 Expression* arg2_len_expr = at->get_length(gogo, arg2);
8832 arg2_val = arg2_valptr->get_tree(context);
8833 arg2_len = arg2_len_expr->get_tree(context);
e440a328 8834 }
8835 else
8836 {
8837 arg2_tree = save_expr(arg2_tree);
8838 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8839 arg2_len = String_type::length_tree(gogo, arg2_tree);
8840 }
d8ccb1e3 8841 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8842 return error_mark_node;
e440a328 8843
8844 arg1_len = save_expr(arg1_len);
8845 arg2_len = save_expr(arg2_len);
b13c66cd 8846 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8847 TREE_TYPE(arg1_len),
8848 fold_build2_loc(location.gcc_location(),
8849 LT_EXPR, boolean_type_node,
e440a328 8850 arg1_len, arg2_len),
8851 arg1_len, arg2_len);
8852 len = save_expr(len);
8853
8854 Type* element_type = at->element_type();
9f0e0513 8855 Btype* element_btype = element_type->get_backend(gogo);
8856 tree element_type_tree = type_to_tree(element_btype);
d8ccb1e3 8857 if (element_type_tree == error_mark_node)
8858 return error_mark_node;
e440a328 8859 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
b13c66cd 8860 tree bytecount = fold_convert_loc(location.gcc_location(),
8861 TREE_TYPE(element_size), len);
8862 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
e440a328 8863 TREE_TYPE(element_size),
8864 bytecount, element_size);
b13c66cd 8865 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8866 bytecount);
e440a328 8867
b13c66cd 8868 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8869 arg1_val);
8870 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8871 arg2_val);
3991cb03 8872
8873 static tree copy_fndecl;
8874 tree call = Gogo::call_builtin(&copy_fndecl,
8875 location,
8876 "__go_copy",
8877 3,
8878 void_type_node,
8879 ptr_type_node,
8880 arg1_val,
8881 ptr_type_node,
8882 arg2_val,
8883 size_type_node,
8884 bytecount);
8885 if (call == error_mark_node)
8886 return error_mark_node;
e440a328 8887
b13c66cd 8888 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8889 TREE_TYPE(len), call, len);
e440a328 8890 }
8891
8892 case BUILTIN_APPEND:
8893 {
8894 const Expression_list* args = this->args();
c484d925 8895 go_assert(args != NULL && args->size() == 2);
e440a328 8896 Expression* arg1 = args->front();
8897 Expression* arg2 = args->back();
8898
8899 tree arg1_tree = arg1->get_tree(context);
8900 tree arg2_tree = arg2->get_tree(context);
8901 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8902 return error_mark_node;
8903
9d44fbe3 8904 Array_type* at = arg1->type()->array_type();
4fd4fcf4 8905 Type* element_type = at->element_type()->forwarded();
9d44fbe3 8906
4fd4fcf4 8907 tree arg2_val;
8908 tree arg2_len;
8909 tree element_size;
8910 if (arg2->type()->is_string_type()
60963afd 8911 && element_type->integer_type() != NULL
8912 && element_type->integer_type()->is_byte())
4fd4fcf4 8913 {
8914 arg2_tree = save_expr(arg2_tree);
8915 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8916 arg2_len = String_type::length_tree(gogo, arg2_tree);
8917 element_size = size_int(1);
8918 }
8919 else
8920 {
35a54f17 8921 go_assert(arg2->is_variable());
8922 arg2_val =
8923 at->get_value_pointer(gogo, arg2)->get_tree(context);
8924 arg2_len = at->get_length(gogo, arg2)->get_tree(context);
8925 Btype* element_btype = element_type->get_backend(gogo);
8926 tree element_type_tree = type_to_tree(element_btype);
8927 if (element_type_tree == error_mark_node)
4fd4fcf4 8928 return error_mark_node;
35a54f17 8929 element_size = TYPE_SIZE_UNIT(element_type_tree);
4fd4fcf4 8930 }
ed64c8e5 8931
b13c66cd 8932 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8933 arg2_val);
8934 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8935 arg2_len);
8936 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
3991cb03 8937 element_size);
e440a328 8938
4fd4fcf4 8939 if (arg2_val == error_mark_node
8940 || arg2_len == error_mark_node
8941 || element_size == error_mark_node)
8942 return error_mark_node;
8943
e440a328 8944 // We rebuild the decl each time since the slice types may
8945 // change.
8946 tree append_fndecl = NULL_TREE;
8947 return Gogo::call_builtin(&append_fndecl,
8948 location,
8949 "__go_append",
3991cb03 8950 4,
e440a328 8951 TREE_TYPE(arg1_tree),
e440a328 8952 TREE_TYPE(arg1_tree),
8953 arg1_tree,
3991cb03 8954 ptr_type_node,
8955 arg2_val,
8956 size_type_node,
8957 arg2_len,
8958 size_type_node,
8959 element_size);
e440a328 8960 }
8961
8962 case BUILTIN_REAL:
8963 case BUILTIN_IMAG:
8964 {
8965 const Expression_list* args = this->args();
c484d925 8966 go_assert(args != NULL && args->size() == 1);
e440a328 8967 Expression* arg = args->front();
8968 tree arg_tree = arg->get_tree(context);
8969 if (arg_tree == error_mark_node)
8970 return error_mark_node;
c484d925 8971 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
e440a328 8972 if (this->code_ == BUILTIN_REAL)
b13c66cd 8973 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
e440a328 8974 TREE_TYPE(TREE_TYPE(arg_tree)),
8975 arg_tree);
8976 else
b13c66cd 8977 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
e440a328 8978 TREE_TYPE(TREE_TYPE(arg_tree)),
8979 arg_tree);
8980 }
8981
48080209 8982 case BUILTIN_COMPLEX:
e440a328 8983 {
8984 const Expression_list* args = this->args();
c484d925 8985 go_assert(args != NULL && args->size() == 2);
e440a328 8986 tree r = args->front()->get_tree(context);
8987 tree i = args->back()->get_tree(context);
8988 if (r == error_mark_node || i == error_mark_node)
8989 return error_mark_node;
c484d925 8990 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
e440a328 8991 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
c484d925 8992 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
b13c66cd 8993 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
e440a328 8994 build_complex_type(TREE_TYPE(r)),
8995 r, i);
8996 }
8997
8998 default:
c3e6f413 8999 go_unreachable();
e440a328 9000 }
9001}
9002
9003// We have to support exporting a builtin call expression, because
9004// code can set a constant to the result of a builtin expression.
9005
9006void
9007Builtin_call_expression::do_export(Export* exp) const
9008{
0c77715b 9009 Numeric_constant nc;
9010 if (!this->numeric_constant_value(&nc))
9011 {
9012 error_at(this->location(), "value is not constant");
9013 return;
9014 }
e440a328 9015
0c77715b 9016 if (nc.is_int())
e440a328 9017 {
0c77715b 9018 mpz_t val;
9019 nc.get_int(&val);
e440a328 9020 Integer_expression::export_integer(exp, val);
0c77715b 9021 mpz_clear(val);
e440a328 9022 }
0c77715b 9023 else if (nc.is_float())
e440a328 9024 {
9025 mpfr_t fval;
0c77715b 9026 nc.get_float(&fval);
9027 Float_expression::export_float(exp, fval);
e440a328 9028 mpfr_clear(fval);
9029 }
0c77715b 9030 else if (nc.is_complex())
e440a328 9031 {
9032 mpfr_t real;
9033 mpfr_t imag;
0c77715b 9034 Complex_expression::export_complex(exp, real, imag);
e440a328 9035 mpfr_clear(real);
9036 mpfr_clear(imag);
9037 }
0c77715b 9038 else
9039 go_unreachable();
e440a328 9040
9041 // A trailing space lets us reliably identify the end of the number.
9042 exp->write_c_string(" ");
9043}
9044
9045// Class Call_expression.
9046
8381eda7 9047// A Go function can be viewed in a couple of different ways. The
9048// code of a Go function becomes a backend function with parameters
9049// whose types are simply the backend representation of the Go types.
9050// If there are multiple results, they are returned as a backend
9051// struct.
9052
9053// However, when Go code refers to a function other than simply
9054// calling it, the backend type of that function is actually a struct.
9055// The first field of the struct points to the Go function code
9056// (sometimes a wrapper as described below). The remaining fields
9057// hold addresses of closed-over variables. This struct is called a
9058// closure.
9059
9060// There are a few cases to consider.
9061
9062// A direct function call of a known function in package scope. In
9063// this case there are no closed-over variables, and we know the name
9064// of the function code. We can simply produce a backend call to the
9065// function directly, and not worry about the closure.
9066
9067// A direct function call of a known function literal. In this case
9068// we know the function code and we know the closure. We generate the
9069// function code such that it expects an additional final argument of
9070// the closure type. We pass the closure as the last argument, after
9071// the other arguments.
9072
9073// An indirect function call. In this case we have a closure. We
9074// load the pointer to the function code from the first field of the
9075// closure. We pass the address of the closure as the last argument.
9076
9077// A call to a method of an interface. Type methods are always at
9078// package scope, so we call the function directly, and don't worry
9079// about the closure.
9080
9081// This means that for a function at package scope we have two cases.
9082// One is the direct call, which has no closure. The other is the
9083// indirect call, which does have a closure. We can't simply ignore
9084// the closure, even though it is the last argument, because that will
9085// fail on targets where the function pops its arguments. So when
9086// generating a closure for a package-scope function we set the
9087// function code pointer in the closure to point to a wrapper
9088// function. This wrapper function accepts a final argument that
9089// points to the closure, ignores it, and calls the real function as a
9090// direct function call. This wrapper will normally be efficient, and
9091// can often simply be a tail call to the real function.
9092
9093// We don't use GCC's static chain pointer because 1) we don't need
9094// it; 2) GCC only permits using a static chain to call a known
9095// function, so we can't use it for an indirect call anyhow. Since we
9096// can't use it for an indirect call, we may as well not worry about
9097// using it for a direct call either.
9098
9099// We pass the closure last rather than first because it means that
9100// the function wrapper we put into a closure for a package-scope
9101// function can normally just be a tail call to the real function.
9102
9103// For method expressions we generate a wrapper that loads the
9104// receiver from the closure and then calls the method. This
9105// unfortunately forces reshuffling the arguments, since there is a
9106// new first argument, but we can't avoid reshuffling either for
9107// method expressions or for indirect calls of package-scope
9108// functions, and since the latter are more common we reshuffle for
9109// method expressions.
9110
9111// Note that the Go code retains the Go types. The extra final
9112// argument only appears when we convert to the backend
9113// representation.
9114
e440a328 9115// Traversal.
9116
9117int
9118Call_expression::do_traverse(Traverse* traverse)
9119{
9120 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9121 return TRAVERSE_EXIT;
9122 if (this->args_ != NULL)
9123 {
9124 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9125 return TRAVERSE_EXIT;
9126 }
9127 return TRAVERSE_CONTINUE;
9128}
9129
9130// Lower a call statement.
9131
9132Expression*
ceeb4318 9133Call_expression::do_lower(Gogo* gogo, Named_object* function,
9134 Statement_inserter* inserter, int)
e440a328 9135{
b13c66cd 9136 Location loc = this->location();
09ea332d 9137
ceeb4318 9138 // A type cast can look like a function call.
e440a328 9139 if (this->fn_->is_type_expression()
9140 && this->args_ != NULL
9141 && this->args_->size() == 1)
9142 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 9143 loc);
e440a328 9144
88f06749 9145 // Because do_type will return an error type and thus prevent future
9146 // errors, check for that case now to ensure that the error gets
9147 // reported.
37448b10 9148 Function_type* fntype = this->get_function_type();
9149 if (fntype == NULL)
88f06749 9150 {
9151 if (!this->fn_->type()->is_error())
9152 this->report_error(_("expected function"));
9153 return Expression::make_error(loc);
9154 }
9155
e440a328 9156 // Handle an argument which is a call to a function which returns
9157 // multiple results.
9158 if (this->args_ != NULL
9159 && this->args_->size() == 1
37448b10 9160 && this->args_->front()->call_expression() != NULL)
e440a328 9161 {
e440a328 9162 size_t rc = this->args_->front()->call_expression()->result_count();
9163 if (rc > 1
37448b10 9164 && ((fntype->parameters() != NULL
9165 && (fntype->parameters()->size() == rc
9166 || (fntype->is_varargs()
9167 && fntype->parameters()->size() - 1 <= rc)))
9168 || fntype->is_builtin()))
e440a328 9169 {
9170 Call_expression* call = this->args_->front()->call_expression();
9171 Expression_list* args = new Expression_list;
9172 for (size_t i = 0; i < rc; ++i)
9173 args->push_back(Expression::make_call_result(call, i));
9174 // We can't return a new call expression here, because this
42535814 9175 // one may be referenced by Call_result expressions. We
9176 // also can't delete the old arguments, because we may still
9177 // traverse them somewhere up the call stack. FIXME.
e440a328 9178 this->args_ = args;
9179 }
9180 }
9181
37448b10 9182 // Recognize a call to a builtin function.
9183 if (fntype->is_builtin())
9184 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9185 this->is_varargs_, loc);
9186
ceeb4318 9187 // If this call returns multiple results, create a temporary
9188 // variable for each result.
9189 size_t rc = this->result_count();
9190 if (rc > 1 && this->results_ == NULL)
9191 {
9192 std::vector<Temporary_statement*>* temps =
9193 new std::vector<Temporary_statement*>;
9194 temps->reserve(rc);
37448b10 9195 const Typed_identifier_list* results = fntype->results();
ceeb4318 9196 for (Typed_identifier_list::const_iterator p = results->begin();
9197 p != results->end();
9198 ++p)
9199 {
9200 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 9201 NULL, loc);
ceeb4318 9202 inserter->insert(temp);
9203 temps->push_back(temp);
9204 }
9205 this->results_ = temps;
9206 }
9207
e440a328 9208 // Handle a call to a varargs function by packaging up the extra
9209 // parameters.
37448b10 9210 if (fntype->is_varargs())
e440a328 9211 {
e440a328 9212 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 9213 go_assert(parameters != NULL && !parameters->empty());
e440a328 9214 Type* varargs_type = parameters->back().type();
09ea332d 9215 this->lower_varargs(gogo, function, inserter, varargs_type,
9216 parameters->size());
9217 }
9218
9219 // If this is call to a method, call the method directly passing the
9220 // object as the first parameter.
9221 Bound_method_expression* bme = this->fn_->bound_method_expression();
9222 if (bme != NULL)
9223 {
0afbb937 9224 Named_object* methodfn = bme->function();
09ea332d 9225 Expression* first_arg = bme->first_argument();
9226
9227 // We always pass a pointer when calling a method.
9228 if (first_arg->type()->points_to() == NULL
9229 && !first_arg->type()->is_error())
9230 {
9231 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9232 // We may need to create a temporary variable so that we can
9233 // take the address. We can't do that here because it will
9234 // mess up the order of evaluation.
9235 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9236 ue->set_create_temp();
9237 }
9238
9239 // If we are calling a method which was inherited from an
9240 // embedded struct, and the method did not get a stub, then the
9241 // first type may be wrong.
9242 Type* fatype = bme->first_argument_type();
9243 if (fatype != NULL)
9244 {
9245 if (fatype->points_to() == NULL)
9246 fatype = Type::make_pointer_type(fatype);
9247 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9248 }
9249
9250 Expression_list* new_args = new Expression_list();
9251 new_args->push_back(first_arg);
9252 if (this->args_ != NULL)
9253 {
9254 for (Expression_list::const_iterator p = this->args_->begin();
9255 p != this->args_->end();
9256 ++p)
9257 new_args->push_back(*p);
9258 }
9259
9260 // We have to change in place because this structure may be
9261 // referenced by Call_result_expressions. We can't delete the
9262 // old arguments, because we may be traversing them up in some
9263 // caller. FIXME.
9264 this->args_ = new_args;
0afbb937 9265 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 9266 bme->location());
e440a328 9267 }
9268
9269 return this;
9270}
9271
9272// Lower a call to a varargs function. FUNCTION is the function in
9273// which the call occurs--it's not the function we are calling.
9274// VARARGS_TYPE is the type of the varargs parameter, a slice type.
9275// PARAM_COUNT is the number of parameters of the function we are
9276// calling; the last of these parameters will be the varargs
9277// parameter.
9278
09ea332d 9279void
e440a328 9280Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 9281 Statement_inserter* inserter,
e440a328 9282 Type* varargs_type, size_t param_count)
9283{
9284 if (this->varargs_are_lowered_)
09ea332d 9285 return;
e440a328 9286
b13c66cd 9287 Location loc = this->location();
e440a328 9288
c484d925 9289 go_assert(param_count > 0);
411eb89e 9290 go_assert(varargs_type->is_slice_type());
e440a328 9291
9292 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9293 if (arg_count < param_count - 1)
9294 {
9295 // Not enough arguments; will be caught in check_types.
09ea332d 9296 return;
e440a328 9297 }
9298
9299 Expression_list* old_args = this->args_;
9300 Expression_list* new_args = new Expression_list();
9301 bool push_empty_arg = false;
9302 if (old_args == NULL || old_args->empty())
9303 {
c484d925 9304 go_assert(param_count == 1);
e440a328 9305 push_empty_arg = true;
9306 }
9307 else
9308 {
9309 Expression_list::const_iterator pa;
9310 int i = 1;
9311 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9312 {
9313 if (static_cast<size_t>(i) == param_count)
9314 break;
9315 new_args->push_back(*pa);
9316 }
9317
9318 // We have reached the varargs parameter.
9319
9320 bool issued_error = false;
9321 if (pa == old_args->end())
9322 push_empty_arg = true;
9323 else if (pa + 1 == old_args->end() && this->is_varargs_)
9324 new_args->push_back(*pa);
9325 else if (this->is_varargs_)
9326 {
a6645f74 9327 if ((*pa)->type()->is_slice_type())
9328 this->report_error(_("too many arguments"));
9329 else
9330 {
9331 error_at(this->location(),
9332 _("invalid use of %<...%> with non-slice"));
9333 this->set_is_error();
9334 }
09ea332d 9335 return;
e440a328 9336 }
e440a328 9337 else
9338 {
9339 Type* element_type = varargs_type->array_type()->element_type();
9340 Expression_list* vals = new Expression_list;
9341 for (; pa != old_args->end(); ++pa, ++i)
9342 {
9343 // Check types here so that we get a better message.
9344 Type* patype = (*pa)->type();
b13c66cd 9345 Location paloc = (*pa)->location();
e440a328 9346 if (!this->check_argument_type(i, element_type, patype,
9347 paloc, issued_error))
9348 continue;
9349 vals->push_back(*pa);
9350 }
9351 Expression* val =
9352 Expression::make_slice_composite_literal(varargs_type, vals, loc);
09ea332d 9353 gogo->lower_expression(function, inserter, &val);
e440a328 9354 new_args->push_back(val);
9355 }
9356 }
9357
9358 if (push_empty_arg)
9359 new_args->push_back(Expression::make_nil(loc));
9360
9361 // We can't return a new call expression here, because this one may
6d4c2432 9362 // be referenced by Call_result expressions. FIXME. We can't
9363 // delete OLD_ARGS because we may have both a Call_expression and a
9364 // Builtin_call_expression which refer to them. FIXME.
e440a328 9365 this->args_ = new_args;
9366 this->varargs_are_lowered_ = true;
e440a328 9367}
9368
ceeb4318 9369// Get the function type. This can return NULL in error cases.
e440a328 9370
9371Function_type*
9372Call_expression::get_function_type() const
9373{
9374 return this->fn_->type()->function_type();
9375}
9376
9377// Return the number of values which this call will return.
9378
9379size_t
9380Call_expression::result_count() const
9381{
9382 const Function_type* fntype = this->get_function_type();
9383 if (fntype == NULL)
9384 return 0;
9385 if (fntype->results() == NULL)
9386 return 0;
9387 return fntype->results()->size();
9388}
9389
ceeb4318 9390// Return the temporary which holds a result.
9391
9392Temporary_statement*
9393Call_expression::result(size_t i) const
9394{
cd238b8d 9395 if (this->results_ == NULL || this->results_->size() <= i)
9396 {
9397 go_assert(saw_errors());
9398 return NULL;
9399 }
ceeb4318 9400 return (*this->results_)[i];
9401}
9402
e440a328 9403// Return whether this is a call to the predeclared function recover.
9404
9405bool
9406Call_expression::is_recover_call() const
9407{
9408 return this->do_is_recover_call();
9409}
9410
9411// Set the argument to the recover function.
9412
9413void
9414Call_expression::set_recover_arg(Expression* arg)
9415{
9416 this->do_set_recover_arg(arg);
9417}
9418
9419// Virtual functions also implemented by Builtin_call_expression.
9420
9421bool
9422Call_expression::do_is_recover_call() const
9423{
9424 return false;
9425}
9426
9427void
9428Call_expression::do_set_recover_arg(Expression*)
9429{
c3e6f413 9430 go_unreachable();
e440a328 9431}
9432
ceeb4318 9433// We have found an error with this call expression; return true if
9434// we should report it.
9435
9436bool
9437Call_expression::issue_error()
9438{
9439 if (this->issued_error_)
9440 return false;
9441 else
9442 {
9443 this->issued_error_ = true;
9444 return true;
9445 }
9446}
9447
e440a328 9448// Get the type.
9449
9450Type*
9451Call_expression::do_type()
9452{
9453 if (this->type_ != NULL)
9454 return this->type_;
9455
9456 Type* ret;
9457 Function_type* fntype = this->get_function_type();
9458 if (fntype == NULL)
9459 return Type::make_error_type();
9460
9461 const Typed_identifier_list* results = fntype->results();
9462 if (results == NULL)
9463 ret = Type::make_void_type();
9464 else if (results->size() == 1)
9465 ret = results->begin()->type();
9466 else
9467 ret = Type::make_call_multiple_result_type(this);
9468
9469 this->type_ = ret;
9470
9471 return this->type_;
9472}
9473
9474// Determine types for a call expression. We can use the function
9475// parameter types to set the types of the arguments.
9476
9477void
9478Call_expression::do_determine_type(const Type_context*)
9479{
fb94b0ca 9480 if (!this->determining_types())
9481 return;
9482
e440a328 9483 this->fn_->determine_type_no_context();
9484 Function_type* fntype = this->get_function_type();
9485 const Typed_identifier_list* parameters = NULL;
9486 if (fntype != NULL)
9487 parameters = fntype->parameters();
9488 if (this->args_ != NULL)
9489 {
9490 Typed_identifier_list::const_iterator pt;
9491 if (parameters != NULL)
9492 pt = parameters->begin();
09ea332d 9493 bool first = true;
e440a328 9494 for (Expression_list::const_iterator pa = this->args_->begin();
9495 pa != this->args_->end();
9496 ++pa)
9497 {
09ea332d 9498 if (first)
9499 {
9500 first = false;
9501 // If this is a method, the first argument is the
9502 // receiver.
9503 if (fntype != NULL && fntype->is_method())
9504 {
9505 Type* rtype = fntype->receiver()->type();
9506 // The receiver is always passed as a pointer.
9507 if (rtype->points_to() == NULL)
9508 rtype = Type::make_pointer_type(rtype);
9509 Type_context subcontext(rtype, false);
9510 (*pa)->determine_type(&subcontext);
9511 continue;
9512 }
9513 }
9514
e440a328 9515 if (parameters != NULL && pt != parameters->end())
9516 {
9517 Type_context subcontext(pt->type(), false);
9518 (*pa)->determine_type(&subcontext);
9519 ++pt;
9520 }
9521 else
9522 (*pa)->determine_type_no_context();
9523 }
9524 }
9525}
9526
fb94b0ca 9527// Called when determining types for a Call_expression. Return true
9528// if we should go ahead, false if they have already been determined.
9529
9530bool
9531Call_expression::determining_types()
9532{
9533 if (this->types_are_determined_)
9534 return false;
9535 else
9536 {
9537 this->types_are_determined_ = true;
9538 return true;
9539 }
9540}
9541
e440a328 9542// Check types for parameter I.
9543
9544bool
9545Call_expression::check_argument_type(int i, const Type* parameter_type,
9546 const Type* argument_type,
b13c66cd 9547 Location argument_location,
e440a328 9548 bool issued_error)
9549{
9550 std::string reason;
053ee6ca 9551 bool ok;
9552 if (this->are_hidden_fields_ok_)
9553 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9554 &reason);
9555 else
9556 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9557 if (!ok)
e440a328 9558 {
9559 if (!issued_error)
9560 {
9561 if (reason.empty())
9562 error_at(argument_location, "argument %d has incompatible type", i);
9563 else
9564 error_at(argument_location,
9565 "argument %d has incompatible type (%s)",
9566 i, reason.c_str());
9567 }
9568 this->set_is_error();
9569 return false;
9570 }
9571 return true;
9572}
9573
9574// Check types.
9575
9576void
9577Call_expression::do_check_types(Gogo*)
9578{
a6645f74 9579 if (this->classification() == EXPRESSION_ERROR)
9580 return;
9581
e440a328 9582 Function_type* fntype = this->get_function_type();
9583 if (fntype == NULL)
9584 {
5c13bd80 9585 if (!this->fn_->type()->is_error())
e440a328 9586 this->report_error(_("expected function"));
9587 return;
9588 }
9589
09ea332d 9590 bool is_method = fntype->is_method();
9591 if (is_method)
e440a328 9592 {
09ea332d 9593 go_assert(this->args_ != NULL && !this->args_->empty());
9594 Type* rtype = fntype->receiver()->type();
9595 Expression* first_arg = this->args_->front();
9596 // The language permits copying hidden fields for a method
9597 // receiver. We dereference the values since receivers are
9598 // always passed as pointers.
9599 std::string reason;
9600 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9601 first_arg->type()->deref(),
9602 &reason))
e440a328 9603 {
09ea332d 9604 if (reason.empty())
9605 this->report_error(_("incompatible type for receiver"));
9606 else
e440a328 9607 {
09ea332d 9608 error_at(this->location(),
9609 "incompatible type for receiver (%s)",
9610 reason.c_str());
9611 this->set_is_error();
e440a328 9612 }
9613 }
9614 }
9615
9616 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9617 // we don't have to worry about it here unless something is wrong.
9618 if (this->is_varargs_ && !this->varargs_are_lowered_)
9619 {
9620 if (!fntype->is_varargs())
9621 {
9622 error_at(this->location(),
9623 _("invalid use of %<...%> calling non-variadic function"));
9624 this->set_is_error();
9625 return;
9626 }
9627 }
e440a328 9628
9629 const Typed_identifier_list* parameters = fntype->parameters();
9630 if (this->args_ == NULL)
9631 {
9632 if (parameters != NULL && !parameters->empty())
9633 this->report_error(_("not enough arguments"));
9634 }
9635 else if (parameters == NULL)
09ea332d 9636 {
9637 if (!is_method || this->args_->size() > 1)
9638 this->report_error(_("too many arguments"));
9639 }
e440a328 9640 else
9641 {
9642 int i = 0;
09ea332d 9643 Expression_list::const_iterator pa = this->args_->begin();
9644 if (is_method)
9645 ++pa;
9646 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9647 pt != parameters->end();
9648 ++pt, ++pa, ++i)
e440a328 9649 {
09ea332d 9650 if (pa == this->args_->end())
e440a328 9651 {
09ea332d 9652 this->report_error(_("not enough arguments"));
e440a328 9653 return;
9654 }
9655 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9656 (*pa)->location(), false);
9657 }
09ea332d 9658 if (pa != this->args_->end())
9659 this->report_error(_("too many arguments"));
e440a328 9660 }
9661}
9662
9663// Return whether we have to use a temporary variable to ensure that
9664// we evaluate this call expression in order. If the call returns no
ceeb4318 9665// results then it will inevitably be executed last.
e440a328 9666
9667bool
9668Call_expression::do_must_eval_in_order() const
9669{
ceeb4318 9670 return this->result_count() > 0;
e440a328 9671}
9672
e440a328 9673// Get the function and the first argument to use when calling an
9674// interface method.
9675
2387f644 9676Expression*
e440a328 9677Call_expression::interface_method_function(
e440a328 9678 Interface_field_reference_expression* interface_method,
2387f644 9679 Expression** first_arg_ptr)
e440a328 9680{
2387f644 9681 *first_arg_ptr = interface_method->get_underlying_object();
9682 return interface_method->get_function();
e440a328 9683}
9684
9685// Build the call expression.
9686
9687tree
9688Call_expression::do_get_tree(Translate_context* context)
9689{
9690 if (this->tree_ != NULL_TREE)
9691 return this->tree_;
9692
9693 Function_type* fntype = this->get_function_type();
9694 if (fntype == NULL)
9695 return error_mark_node;
9696
9697 if (this->fn_->is_error_expression())
9698 return error_mark_node;
9699
9700 Gogo* gogo = context->gogo();
b13c66cd 9701 Location location = this->location();
e440a328 9702
9703 Func_expression* func = this->fn_->func_expression();
e440a328 9704 Interface_field_reference_expression* interface_method =
9705 this->fn_->interface_field_reference_expression();
9706 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 9707 const bool is_interface_method = interface_method != NULL;
e440a328 9708
f8bdf81a 9709 bool has_closure_arg;
8381eda7 9710 if (has_closure)
f8bdf81a 9711 has_closure_arg = true;
8381eda7 9712 else if (func != NULL)
f8bdf81a 9713 has_closure_arg = false;
8381eda7 9714 else if (is_interface_method)
f8bdf81a 9715 has_closure_arg = false;
8381eda7 9716 else
f8bdf81a 9717 has_closure_arg = true;
8381eda7 9718
e440a328 9719 int nargs;
9720 tree* args;
9721 if (this->args_ == NULL || this->args_->empty())
9722 {
f8bdf81a 9723 nargs = is_interface_method ? 1 : 0;
e440a328 9724 args = nargs == 0 ? NULL : new tree[nargs];
9725 }
09ea332d 9726 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9727 {
9728 // Passing a receiver parameter.
9729 go_assert(!is_interface_method
9730 && fntype->is_method()
9731 && this->args_->size() == 1);
f8bdf81a 9732 nargs = 1;
09ea332d 9733 args = new tree[nargs];
9734 args[0] = this->args_->front()->get_tree(context);
9735 }
e440a328 9736 else
9737 {
9738 const Typed_identifier_list* params = fntype->parameters();
e440a328 9739
9740 nargs = this->args_->size();
09ea332d 9741 int i = is_interface_method ? 1 : 0;
e440a328 9742 nargs += i;
9743 args = new tree[nargs];
9744
9745 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 9746 Expression_list::const_iterator pe = this->args_->begin();
9747 if (!is_interface_method && fntype->is_method())
9748 {
9749 args[i] = (*pe)->get_tree(context);
9750 ++pe;
9751 ++i;
9752 }
9753 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 9754 {
c484d925 9755 go_assert(pp != params->end());
e440a328 9756 tree arg_val = (*pe)->get_tree(context);
9757 args[i] = Expression::convert_for_assignment(context,
9758 pp->type(),
9759 (*pe)->type(),
9760 arg_val,
9761 location);
9762 if (args[i] == error_mark_node)
8381eda7 9763 return error_mark_node;
e440a328 9764 }
c484d925 9765 go_assert(pp == params->end());
f8bdf81a 9766 go_assert(i == nargs);
e440a328 9767 }
9768
8381eda7 9769 tree fntype_tree = type_to_tree(fntype->get_backend(gogo));
cf3cae55 9770 tree fnfield_type = type_to_tree(fntype->get_backend_fntype(gogo));
9771 if (fntype_tree == error_mark_node || fnfield_type == error_mark_node)
8381eda7 9772 return error_mark_node;
9773 go_assert(FUNCTION_POINTER_TYPE_P(fnfield_type));
9774 tree rettype = TREE_TYPE(TREE_TYPE(fnfield_type));
e440a328 9775 if (rettype == error_mark_node)
8381eda7 9776 return error_mark_node;
e440a328 9777
9778 tree fn;
f8bdf81a 9779 tree closure_tree;
8381eda7 9780 if (func != NULL)
9781 {
9782 Named_object* no = func->named_object();
97267c39 9783 fn = expr_to_tree(Func_expression::get_code_pointer(gogo, no, location));
f8bdf81a 9784 if (!has_closure)
9785 closure_tree = NULL_TREE;
9786 else
8381eda7 9787 {
f8bdf81a 9788 closure_tree = func->closure()->get_tree(context);
9789 if (closure_tree == error_mark_node)
9790 return error_mark_node;
8381eda7 9791 }
9792 }
09ea332d 9793 else if (!is_interface_method)
8381eda7 9794 {
f8bdf81a 9795 closure_tree = this->fn_->get_tree(context);
8381eda7 9796 if (closure_tree == error_mark_node)
9797 return error_mark_node;
9798 tree fnc = fold_convert_loc(location.gcc_location(), fntype_tree,
9799 closure_tree);
9800 go_assert(POINTER_TYPE_P(TREE_TYPE(fnc))
9801 && (TREE_CODE(TREE_TYPE(TREE_TYPE(fnc)))
9802 == RECORD_TYPE));
9803 tree field = TYPE_FIELDS(TREE_TYPE(TREE_TYPE(fnc)));
9804 fn = fold_build3_loc(location.gcc_location(), COMPONENT_REF,
9805 TREE_TYPE(field),
9806 build_fold_indirect_ref_loc(location.gcc_location(),
9807 fnc),
9808 field, NULL_TREE);
8381eda7 9809 }
e440a328 9810 else
cf609de4 9811 {
2387f644 9812 Expression* first_arg;
9813 Expression* fn_expr =
9814 this->interface_method_function(interface_method, &first_arg);
9815 args[0] = first_arg->get_tree(context);
9816 fn = fn_expr->get_tree(context);
9817
8381eda7 9818 if (fn == error_mark_node)
9819 return error_mark_node;
f8bdf81a 9820 closure_tree = NULL_TREE;
cf609de4 9821 }
e440a328 9822
8381eda7 9823 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9824 return error_mark_node;
9825
e440a328 9826 tree fndecl = fn;
9827 if (TREE_CODE(fndecl) == ADDR_EXPR)
9828 fndecl = TREE_OPERAND(fndecl, 0);
9aa9e2df 9829
9830 // Add a type cast in case the type of the function is a recursive
e4329d20 9831 // type which refers to itself. We don't do this for an interface
9832 // method because 1) an interface method never refers to itself, so
9833 // we always have a function type here; 2) we pass an extra first
9834 // argument to an interface method, so fnfield_type is not correct.
9835 if ((!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl)) && !is_interface_method)
8381eda7 9836 fn = fold_convert_loc(location.gcc_location(), fnfield_type, fn);
9aa9e2df 9837
9838 // This is to support builtin math functions when using 80387 math.
e440a328 9839 tree excess_type = NULL_TREE;
68e1881d 9840 if (optimize
9841 && TREE_CODE(fndecl) == FUNCTION_DECL
e440a328 9842 && DECL_IS_BUILTIN(fndecl)
9843 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9844 && nargs > 0
9845 && ((SCALAR_FLOAT_TYPE_P(rettype)
9846 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9847 || (COMPLEX_FLOAT_TYPE_P(rettype)
9848 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9849 {
9850 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9851 if (excess_type != NULL_TREE)
9852 {
9853 tree excess_fndecl = mathfn_built_in(excess_type,
9854 DECL_FUNCTION_CODE(fndecl));
9855 if (excess_fndecl == NULL_TREE)
9856 excess_type = NULL_TREE;
9857 else
9858 {
b13c66cd 9859 fn = build_fold_addr_expr_loc(location.gcc_location(),
9860 excess_fndecl);
e440a328 9861 for (int i = 0; i < nargs; ++i)
26ae0101 9862 {
9863 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9864 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9865 args[i] = ::convert(excess_type, args[i]);
9866 }
e440a328 9867 }
9868 }
9869 }
9870
d0bcce51 9871 if (func == NULL)
9872 fn = save_expr(fn);
9873
f8bdf81a 9874 if (!has_closure_arg)
9875 go_assert(closure_tree == NULL_TREE);
9876 else
9877 {
9878 // Pass the closure argument by calling the function function
9879 // __go_set_closure. In the order_evaluations pass we have
9880 // ensured that if any parameters contain call expressions, they
9881 // will have been moved out to temporary variables.
9882
9883 go_assert(closure_tree != NULL_TREE);
9884 closure_tree = fold_convert_loc(location.gcc_location(), ptr_type_node,
9885 closure_tree);
9886 static tree set_closure_fndecl;
9887 tree set_closure = Gogo::call_builtin(&set_closure_fndecl,
9888 location,
9889 "__go_set_closure",
9890 1,
9891 void_type_node,
9892 ptr_type_node,
9893 closure_tree);
9894 if (set_closure == error_mark_node)
9895 return error_mark_node;
9896 fn = build2_loc(location.gcc_location(), COMPOUND_EXPR,
9897 TREE_TYPE(fn), set_closure, fn);
9898 }
9899
e440a328 9900 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9901 fn, nargs, args);
9902 delete[] args;
9903
b13c66cd 9904 SET_EXPR_LOCATION(ret, location.gcc_location());
e440a328 9905
e440a328 9906 // If this is a recursive function type which returns itself, as in
9907 // type F func() F
9908 // we have used ptr_type_node for the return type. Add a cast here
9909 // to the correct type.
9910 if (TREE_TYPE(ret) == ptr_type_node)
9911 {
9f0e0513 9912 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
b13c66cd 9913 ret = fold_convert_loc(location.gcc_location(), t, ret);
e440a328 9914 }
9915
9916 if (excess_type != NULL_TREE)
9917 {
9918 // Calling convert here can undo our excess precision change.
9919 // That may or may not be a bug in convert_to_real.
9920 ret = build1(NOP_EXPR, rettype, ret);
9921 }
9922
ceeb4318 9923 if (this->results_ != NULL)
9924 ret = this->set_results(context, ret);
e440a328 9925
9926 this->tree_ = ret;
9927
9928 return ret;
9929}
9930
ceeb4318 9931// Set the result variables if this call returns multiple results.
9932
9933tree
9934Call_expression::set_results(Translate_context* context, tree call_tree)
9935{
9936 tree stmt_list = NULL_TREE;
9937
9938 call_tree = save_expr(call_tree);
9939
9940 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9941 {
9942 go_assert(saw_errors());
9943 return call_tree;
9944 }
9945
b13c66cd 9946 Location loc = this->location();
ceeb4318 9947 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9948 size_t rc = this->result_count();
9949 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9950 {
9951 go_assert(field != NULL_TREE);
9952
9953 Temporary_statement* temp = this->result(i);
cd238b8d 9954 if (temp == NULL)
9955 {
9956 go_assert(saw_errors());
9957 return error_mark_node;
9958 }
ceeb4318 9959 Temporary_reference_expression* ref =
9960 Expression::make_temporary_reference(temp, loc);
9961 ref->set_is_lvalue();
9962 tree temp_tree = ref->get_tree(context);
9963 if (temp_tree == error_mark_node)
423d1705 9964 return error_mark_node;
ceeb4318 9965
b13c66cd 9966 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9967 TREE_TYPE(field), call_tree, field, NULL_TREE);
9968 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9969 void_type_node, temp_tree, val_tree);
ceeb4318 9970
9971 append_to_statement_list(set_tree, &stmt_list);
9972 }
9973 go_assert(field == NULL_TREE);
9974
9975 return save_expr(stmt_list);
9976}
9977
d751bb78 9978// Dump ast representation for a call expressin.
9979
9980void
9981Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9982{
9983 this->fn_->dump_expression(ast_dump_context);
9984 ast_dump_context->ostream() << "(";
9985 if (args_ != NULL)
9986 ast_dump_context->dump_expression_list(this->args_);
9987
9988 ast_dump_context->ostream() << ") ";
9989}
9990
e440a328 9991// Make a call expression.
9992
9993Call_expression*
9994Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 9995 Location location)
e440a328 9996{
9997 return new Call_expression(fn, args, is_varargs, location);
9998}
9999
10000// A single result from a call which returns multiple results.
10001
10002class Call_result_expression : public Expression
10003{
10004 public:
10005 Call_result_expression(Call_expression* call, unsigned int index)
10006 : Expression(EXPRESSION_CALL_RESULT, call->location()),
10007 call_(call), index_(index)
10008 { }
10009
10010 protected:
10011 int
10012 do_traverse(Traverse*);
10013
10014 Type*
10015 do_type();
10016
10017 void
10018 do_determine_type(const Type_context*);
10019
10020 void
10021 do_check_types(Gogo*);
10022
10023 Expression*
10024 do_copy()
10025 {
10026 return new Call_result_expression(this->call_->call_expression(),
10027 this->index_);
10028 }
10029
10030 bool
10031 do_must_eval_in_order() const
10032 { return true; }
10033
10034 tree
10035 do_get_tree(Translate_context*);
10036
d751bb78 10037 void
10038 do_dump_expression(Ast_dump_context*) const;
10039
e440a328 10040 private:
10041 // The underlying call expression.
10042 Expression* call_;
10043 // Which result we want.
10044 unsigned int index_;
10045};
10046
10047// Traverse a call result.
10048
10049int
10050Call_result_expression::do_traverse(Traverse* traverse)
10051{
10052 if (traverse->remember_expression(this->call_))
10053 {
10054 // We have already traversed the call expression.
10055 return TRAVERSE_CONTINUE;
10056 }
10057 return Expression::traverse(&this->call_, traverse);
10058}
10059
10060// Get the type.
10061
10062Type*
10063Call_result_expression::do_type()
10064{
425dd051 10065 if (this->classification() == EXPRESSION_ERROR)
10066 return Type::make_error_type();
10067
e440a328 10068 // THIS->CALL_ can be replaced with a temporary reference due to
10069 // Call_expression::do_must_eval_in_order when there is an error.
10070 Call_expression* ce = this->call_->call_expression();
10071 if (ce == NULL)
5e85f268 10072 {
10073 this->set_is_error();
10074 return Type::make_error_type();
10075 }
e440a328 10076 Function_type* fntype = ce->get_function_type();
10077 if (fntype == NULL)
5e85f268 10078 {
e37658e2 10079 if (ce->issue_error())
99b3f06f 10080 {
10081 if (!ce->fn()->type()->is_error())
10082 this->report_error(_("expected function"));
10083 }
5e85f268 10084 this->set_is_error();
10085 return Type::make_error_type();
10086 }
e440a328 10087 const Typed_identifier_list* results = fntype->results();
ceeb4318 10088 if (results == NULL || results->size() < 2)
7b8d861f 10089 {
ceeb4318 10090 if (ce->issue_error())
10091 this->report_error(_("number of results does not match "
10092 "number of values"));
7b8d861f 10093 return Type::make_error_type();
10094 }
e440a328 10095 Typed_identifier_list::const_iterator pr = results->begin();
10096 for (unsigned int i = 0; i < this->index_; ++i)
10097 {
10098 if (pr == results->end())
425dd051 10099 break;
e440a328 10100 ++pr;
10101 }
10102 if (pr == results->end())
425dd051 10103 {
ceeb4318 10104 if (ce->issue_error())
10105 this->report_error(_("number of results does not match "
10106 "number of values"));
425dd051 10107 return Type::make_error_type();
10108 }
e440a328 10109 return pr->type();
10110}
10111
425dd051 10112// Check the type. Just make sure that we trigger the warning in
10113// do_type.
e440a328 10114
10115void
10116Call_result_expression::do_check_types(Gogo*)
10117{
425dd051 10118 this->type();
e440a328 10119}
10120
10121// Determine the type. We have nothing to do here, but the 0 result
10122// needs to pass down to the caller.
10123
10124void
10125Call_result_expression::do_determine_type(const Type_context*)
10126{
fb94b0ca 10127 this->call_->determine_type_no_context();
e440a328 10128}
10129
ceeb4318 10130// Return the tree. We just refer to the temporary set by the call
10131// expression. We don't do this at lowering time because it makes it
10132// hard to evaluate the call at the right time.
e440a328 10133
10134tree
10135Call_result_expression::do_get_tree(Translate_context* context)
10136{
ceeb4318 10137 Call_expression* ce = this->call_->call_expression();
cd238b8d 10138 if (ce == NULL)
10139 {
10140 go_assert(this->call_->is_error_expression());
10141 return error_mark_node;
10142 }
ceeb4318 10143 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 10144 if (ts == NULL)
10145 {
10146 go_assert(saw_errors());
10147 return error_mark_node;
10148 }
ceeb4318 10149 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10150 return ref->get_tree(context);
e440a328 10151}
10152
d751bb78 10153// Dump ast representation for a call result expression.
10154
10155void
10156Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10157 const
10158{
10159 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10160 // (struct) and the fields are referenced instead.
10161 ast_dump_context->ostream() << this->index_ << "@(";
10162 ast_dump_context->dump_expression(this->call_);
10163 ast_dump_context->ostream() << ")";
10164}
10165
e440a328 10166// Make a reference to a single result of a call which returns
10167// multiple results.
10168
10169Expression*
10170Expression::make_call_result(Call_expression* call, unsigned int index)
10171{
10172 return new Call_result_expression(call, index);
10173}
10174
10175// Class Index_expression.
10176
10177// Traversal.
10178
10179int
10180Index_expression::do_traverse(Traverse* traverse)
10181{
10182 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10183 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10184 || (this->end_ != NULL
acf2b673 10185 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10186 || (this->cap_ != NULL
10187 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 10188 return TRAVERSE_EXIT;
10189 return TRAVERSE_CONTINUE;
10190}
10191
10192// Lower an index expression. This converts the generic index
10193// expression into an array index, a string index, or a map index.
10194
10195Expression*
ceeb4318 10196Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 10197{
b13c66cd 10198 Location location = this->location();
e440a328 10199 Expression* left = this->left_;
10200 Expression* start = this->start_;
10201 Expression* end = this->end_;
acf2b673 10202 Expression* cap = this->cap_;
e440a328 10203
10204 Type* type = left->type();
5c13bd80 10205 if (type->is_error())
e440a328 10206 return Expression::make_error(location);
b0cf7ddd 10207 else if (left->is_type_expression())
10208 {
10209 error_at(location, "attempt to index type expression");
10210 return Expression::make_error(location);
10211 }
e440a328 10212 else if (type->array_type() != NULL)
acf2b673 10213 return Expression::make_array_index(left, start, end, cap, location);
e440a328 10214 else if (type->points_to() != NULL
10215 && type->points_to()->array_type() != NULL
411eb89e 10216 && !type->points_to()->is_slice_type())
e440a328 10217 {
10218 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10219 location);
38092374 10220
10221 // For an ordinary index into the array, the pointer will be
10222 // dereferenced. For a slice it will not--the resulting slice
10223 // will simply reuse the pointer, which is incorrect if that
10224 // pointer is nil.
10225 if (end != NULL || cap != NULL)
10226 deref->issue_nil_check();
10227
acf2b673 10228 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 10229 }
10230 else if (type->is_string_type())
acf2b673 10231 {
10232 if (cap != NULL)
10233 {
10234 error_at(location, "invalid 3-index slice of string");
10235 return Expression::make_error(location);
10236 }
10237 return Expression::make_string_index(left, start, end, location);
10238 }
e440a328 10239 else if (type->map_type() != NULL)
10240 {
acf2b673 10241 if (end != NULL || cap != NULL)
e440a328 10242 {
10243 error_at(location, "invalid slice of map");
10244 return Expression::make_error(location);
10245 }
6d4c2432 10246 Map_index_expression* ret = Expression::make_map_index(left, start,
10247 location);
e440a328 10248 if (this->is_lvalue_)
10249 ret->set_is_lvalue();
10250 return ret;
10251 }
10252 else
10253 {
10254 error_at(location,
10255 "attempt to index object which is not array, string, or map");
10256 return Expression::make_error(location);
10257 }
10258}
10259
acf2b673 10260// Write an indexed expression
10261// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 10262
10263void
10264Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10265 const Expression* expr,
10266 const Expression* start,
acf2b673 10267 const Expression* end,
10268 const Expression* cap)
d751bb78 10269{
10270 expr->dump_expression(ast_dump_context);
10271 ast_dump_context->ostream() << "[";
10272 start->dump_expression(ast_dump_context);
10273 if (end != NULL)
10274 {
10275 ast_dump_context->ostream() << ":";
10276 end->dump_expression(ast_dump_context);
10277 }
acf2b673 10278 if (cap != NULL)
10279 {
10280 ast_dump_context->ostream() << ":";
10281 cap->dump_expression(ast_dump_context);
10282 }
d751bb78 10283 ast_dump_context->ostream() << "]";
10284}
10285
10286// Dump ast representation for an index expression.
10287
10288void
10289Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10290 const
10291{
10292 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 10293 this->start_, this->end_, this->cap_);
d751bb78 10294}
10295
e440a328 10296// Make an index expression.
10297
10298Expression*
10299Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 10300 Expression* cap, Location location)
e440a328 10301{
acf2b673 10302 return new Index_expression(left, start, end, cap, location);
e440a328 10303}
10304
10305// An array index. This is used for both indexing and slicing.
10306
10307class Array_index_expression : public Expression
10308{
10309 public:
10310 Array_index_expression(Expression* array, Expression* start,
acf2b673 10311 Expression* end, Expression* cap, Location location)
e440a328 10312 : Expression(EXPRESSION_ARRAY_INDEX, location),
acf2b673 10313 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
e440a328 10314 { }
10315
10316 protected:
10317 int
10318 do_traverse(Traverse*);
10319
10320 Type*
10321 do_type();
10322
10323 void
10324 do_determine_type(const Type_context*);
10325
10326 void
10327 do_check_types(Gogo*);
10328
35a54f17 10329 Expression*
10330 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10331
e440a328 10332 Expression*
10333 do_copy()
10334 {
10335 return Expression::make_array_index(this->array_->copy(),
10336 this->start_->copy(),
10337 (this->end_ == NULL
10338 ? NULL
10339 : this->end_->copy()),
acf2b673 10340 (this->cap_ == NULL
10341 ? NULL
10342 : this->cap_->copy()),
e440a328 10343 this->location());
10344 }
10345
baef9f7a 10346 bool
10347 do_must_eval_subexpressions_in_order(int* skip) const
10348 {
10349 *skip = 1;
10350 return true;
10351 }
10352
e440a328 10353 bool
10354 do_is_addressable() const;
10355
10356 void
10357 do_address_taken(bool escapes)
10358 { this->array_->address_taken(escapes); }
10359
56080003 10360 void
10361 do_issue_nil_check()
10362 { this->array_->issue_nil_check(); }
10363
e440a328 10364 tree
10365 do_get_tree(Translate_context*);
10366
d751bb78 10367 void
10368 do_dump_expression(Ast_dump_context*) const;
10369
e440a328 10370 private:
10371 // The array we are getting a value from.
10372 Expression* array_;
10373 // The start or only index.
10374 Expression* start_;
10375 // The end index of a slice. This may be NULL for a simple array
10376 // index, or it may be a nil expression for the length of the array.
10377 Expression* end_;
acf2b673 10378 // The capacity argument of a slice. This may be NULL for an array index or
10379 // slice.
10380 Expression* cap_;
e440a328 10381 // The type of the expression.
10382 Type* type_;
10383};
10384
10385// Array index traversal.
10386
10387int
10388Array_index_expression::do_traverse(Traverse* traverse)
10389{
10390 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10391 return TRAVERSE_EXIT;
10392 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10393 return TRAVERSE_EXIT;
10394 if (this->end_ != NULL)
10395 {
10396 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10397 return TRAVERSE_EXIT;
10398 }
acf2b673 10399 if (this->cap_ != NULL)
10400 {
10401 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10402 return TRAVERSE_EXIT;
10403 }
e440a328 10404 return TRAVERSE_CONTINUE;
10405}
10406
10407// Return the type of an array index.
10408
10409Type*
10410Array_index_expression::do_type()
10411{
10412 if (this->type_ == NULL)
10413 {
10414 Array_type* type = this->array_->type()->array_type();
10415 if (type == NULL)
10416 this->type_ = Type::make_error_type();
10417 else if (this->end_ == NULL)
10418 this->type_ = type->element_type();
411eb89e 10419 else if (type->is_slice_type())
e440a328 10420 {
10421 // A slice of a slice has the same type as the original
10422 // slice.
10423 this->type_ = this->array_->type()->deref();
10424 }
10425 else
10426 {
10427 // A slice of an array is a slice.
10428 this->type_ = Type::make_array_type(type->element_type(), NULL);
10429 }
10430 }
10431 return this->type_;
10432}
10433
10434// Set the type of an array index.
10435
10436void
10437Array_index_expression::do_determine_type(const Type_context*)
10438{
10439 this->array_->determine_type_no_context();
7917ad68 10440 this->start_->determine_type_no_context();
e440a328 10441 if (this->end_ != NULL)
7917ad68 10442 this->end_->determine_type_no_context();
acf2b673 10443 if (this->cap_ != NULL)
10444 this->cap_->determine_type_no_context();
e440a328 10445}
10446
10447// Check types of an array index.
10448
10449void
10450Array_index_expression::do_check_types(Gogo*)
10451{
f6bc81e6 10452 Numeric_constant nc;
10453 unsigned long v;
10454 if (this->start_->type()->integer_type() == NULL
10455 && !this->start_->type()->is_error()
10456 && (!this->start_->numeric_constant_value(&nc)
10457 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10458 this->report_error(_("index must be integer"));
10459 if (this->end_ != NULL
10460 && this->end_->type()->integer_type() == NULL
99b3f06f 10461 && !this->end_->type()->is_error()
10462 && !this->end_->is_nil_expression()
f6bc81e6 10463 && !this->end_->is_error_expression()
10464 && (!this->end_->numeric_constant_value(&nc)
10465 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10466 this->report_error(_("slice end must be integer"));
acf2b673 10467 if (this->cap_ != NULL
10468 && this->cap_->type()->integer_type() == NULL
10469 && !this->cap_->type()->is_error()
10470 && !this->cap_->is_nil_expression()
10471 && !this->cap_->is_error_expression()
10472 && (!this->cap_->numeric_constant_value(&nc)
10473 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10474 this->report_error(_("slice capacity must be integer"));
e440a328 10475
10476 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10477 if (array_type == NULL)
10478 {
c484d925 10479 go_assert(this->array_->type()->is_error());
f9c68f17 10480 return;
10481 }
e440a328 10482
10483 unsigned int int_bits =
10484 Type::lookup_integer_type("int")->integer_type()->bits();
10485
0c77715b 10486 Numeric_constant lvalnc;
e440a328 10487 mpz_t lval;
e440a328 10488 bool lval_valid = (array_type->length() != NULL
0c77715b 10489 && array_type->length()->numeric_constant_value(&lvalnc)
10490 && lvalnc.to_int(&lval));
10491 Numeric_constant inc;
e440a328 10492 mpz_t ival;
0bd5d859 10493 bool ival_valid = false;
0c77715b 10494 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10495 {
0bd5d859 10496 ival_valid = true;
e440a328 10497 if (mpz_sgn(ival) < 0
10498 || mpz_sizeinbase(ival, 2) >= int_bits
10499 || (lval_valid
10500 && (this->end_ == NULL
10501 ? mpz_cmp(ival, lval) >= 0
10502 : mpz_cmp(ival, lval) > 0)))
10503 {
10504 error_at(this->start_->location(), "array index out of bounds");
10505 this->set_is_error();
10506 }
10507 }
10508 if (this->end_ != NULL && !this->end_->is_nil_expression())
10509 {
0c77715b 10510 Numeric_constant enc;
10511 mpz_t eval;
acf2b673 10512 bool eval_valid = false;
0c77715b 10513 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10514 {
acf2b673 10515 eval_valid = true;
0c77715b 10516 if (mpz_sgn(eval) < 0
10517 || mpz_sizeinbase(eval, 2) >= int_bits
10518 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10519 {
10520 error_at(this->end_->location(), "array index out of bounds");
10521 this->set_is_error();
10522 }
0bd5d859 10523 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10524 this->report_error(_("inverted slice range"));
e440a328 10525 }
acf2b673 10526
10527 Numeric_constant cnc;
10528 mpz_t cval;
10529 if (this->cap_ != NULL
10530 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10531 {
10532 if (mpz_sgn(cval) < 0
10533 || mpz_sizeinbase(cval, 2) >= int_bits
10534 || (lval_valid && mpz_cmp(cval, lval) > 0))
10535 {
10536 error_at(this->cap_->location(), "array index out of bounds");
10537 this->set_is_error();
10538 }
10539 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10540 {
10541 error_at(this->cap_->location(),
10542 "invalid slice index: capacity less than start");
10543 this->set_is_error();
10544 }
10545 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10546 {
10547 error_at(this->cap_->location(),
10548 "invalid slice index: capacity less than length");
10549 this->set_is_error();
10550 }
10551 mpz_clear(cval);
10552 }
10553
10554 if (eval_valid)
10555 mpz_clear(eval);
e440a328 10556 }
0bd5d859 10557 if (ival_valid)
10558 mpz_clear(ival);
0c77715b 10559 if (lval_valid)
10560 mpz_clear(lval);
e440a328 10561
10562 // A slice of an array requires an addressable array. A slice of a
10563 // slice is always possible.
411eb89e 10564 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10565 {
10566 if (!this->array_->is_addressable())
8da39c3b 10567 this->report_error(_("slice of unaddressable value"));
88ec30c8 10568 else
10569 this->array_->address_taken(true);
10570 }
e440a328 10571}
10572
35a54f17 10573// Flatten array indexing by using a temporary variable for slices.
10574
10575Expression*
10576Array_index_expression::do_flatten(Gogo*, Named_object*,
10577 Statement_inserter* inserter)
10578{
10579 Location loc = this->location();
10580 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10581 {
10582 Temporary_statement* temp = Statement::make_temporary(NULL, this->array_, loc);
10583 inserter->insert(temp);
10584 this->array_ = Expression::make_temporary_reference(temp, loc);
10585 }
10586 return this;
10587}
10588
e440a328 10589// Return whether this expression is addressable.
10590
10591bool
10592Array_index_expression::do_is_addressable() const
10593{
10594 // A slice expression is not addressable.
10595 if (this->end_ != NULL)
10596 return false;
10597
10598 // An index into a slice is addressable.
411eb89e 10599 if (this->array_->type()->is_slice_type())
e440a328 10600 return true;
10601
10602 // An index into an array is addressable if the array is
10603 // addressable.
10604 return this->array_->is_addressable();
10605}
10606
10607// Get a tree for an array index.
10608
10609tree
10610Array_index_expression::do_get_tree(Translate_context* context)
10611{
10612 Gogo* gogo = context->gogo();
b13c66cd 10613 Location loc = this->location();
e440a328 10614
10615 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10616 if (array_type == NULL)
10617 {
c484d925 10618 go_assert(this->array_->type()->is_error());
d8cd8e2d 10619 return error_mark_node;
10620 }
35a54f17 10621 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10622
9f0e0513 10623 tree type_tree = type_to_tree(array_type->get_backend(gogo));
c65212a0 10624 if (type_tree == error_mark_node)
10625 return error_mark_node;
e440a328 10626
a04bfdfc 10627 tree length_tree = NULL_TREE;
10628 if (this->end_ == NULL || this->end_->is_nil_expression())
10629 {
35a54f17 10630 Expression* len = array_type->get_length(gogo, this->array_);
10631 length_tree = len->get_tree(context);
a04bfdfc 10632 if (length_tree == error_mark_node)
10633 return error_mark_node;
10634 length_tree = save_expr(length_tree);
10635 }
10636
10637 tree capacity_tree = NULL_TREE;
10638 if (this->end_ != NULL)
10639 {
35a54f17 10640 Expression* cap = array_type->get_capacity(gogo, this->array_);
10641 capacity_tree = cap->get_tree(context);
a04bfdfc 10642 if (capacity_tree == error_mark_node)
10643 return error_mark_node;
10644 capacity_tree = save_expr(capacity_tree);
10645 }
10646
acf2b673 10647 tree cap_arg = capacity_tree;
10648 if (this->cap_ != NULL)
10649 {
10650 cap_arg = this->cap_->get_tree(context);
10651 if (cap_arg == error_mark_node)
10652 return error_mark_node;
10653 }
10654
a04bfdfc 10655 tree length_type = (length_tree != NULL_TREE
10656 ? TREE_TYPE(length_tree)
acf2b673 10657 : TREE_TYPE(cap_arg));
e440a328 10658
10659 tree bad_index = boolean_false_node;
10660
10661 tree start_tree = this->start_->get_tree(context);
10662 if (start_tree == error_mark_node)
10663 return error_mark_node;
10664 if (!DECL_P(start_tree))
10665 start_tree = save_expr(start_tree);
10666 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10667 start_tree = convert_to_integer(length_type, start_tree);
10668
10669 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10670 loc);
10671
b13c66cd 10672 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10673 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10674 boolean_type_node, bad_index,
10675 fold_build2_loc(loc.gcc_location(),
e440a328 10676 (this->end_ == NULL
10677 ? GE_EXPR
10678 : GT_EXPR),
10679 boolean_type_node, start_tree,
a04bfdfc 10680 (this->end_ == NULL
10681 ? length_tree
10682 : capacity_tree)));
e440a328 10683
10684 int code = (array_type->length() != NULL
10685 ? (this->end_ == NULL
10686 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10687 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10688 : (this->end_ == NULL
10689 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10690 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
aff1f085 10691 tree crash = gogo->runtime_error(code, loc)->get_tree(context);
e440a328 10692
10693 if (this->end_ == NULL)
10694 {
10695 // Simple array indexing. This has to return an l-value, so
10696 // wrap the index check into START_TREE.
10697 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
10698 build3(COND_EXPR, void_type_node,
10699 bad_index, crash, NULL_TREE),
10700 start_tree);
b13c66cd 10701 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
e440a328 10702
10703 if (array_type->length() != NULL)
10704 {
10705 // Fixed array.
35a54f17 10706 tree array_tree = this->array_->get_tree(context);
10707 if (array_tree == error_mark_node)
10708 return error_mark_node;
e440a328 10709 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
10710 start_tree, NULL_TREE, NULL_TREE);
10711 }
10712 else
10713 {
10714 // Open array.
35a54f17 10715 Expression* valptr =
10716 array_type->get_value_pointer(gogo, this->array_);
10717 tree values = valptr->get_tree(context);
9f0e0513 10718 Type* element_type = array_type->element_type();
10719 Btype* belement_type = element_type->get_backend(gogo);
10720 tree element_type_tree = type_to_tree(belement_type);
c65212a0 10721 if (element_type_tree == error_mark_node)
10722 return error_mark_node;
e440a328 10723 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
b13c66cd 10724 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
e440a328 10725 start_tree, element_size);
b13c66cd 10726 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
e440a328 10727 TREE_TYPE(values), values, offset);
10728 return build_fold_indirect_ref(ptr);
10729 }
10730 }
10731
10732 // Array slice.
10733
acf2b673 10734 if (this->cap_ != NULL)
10735 {
10736 if (!DECL_P(cap_arg))
10737 cap_arg = save_expr(cap_arg);
10738 if (!INTEGRAL_TYPE_P(TREE_TYPE(cap_arg)))
10739 cap_arg = convert_to_integer(length_type, cap_arg);
10740
10741 bad_index = Expression::check_bounds(cap_arg, length_type, bad_index,
10742 loc);
10743 cap_arg = fold_convert_loc(loc.gcc_location(), length_type, cap_arg);
10744
10745 tree bad_cap = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10746 boolean_type_node,
10747 fold_build2_loc(loc.gcc_location(),
10748 LT_EXPR, boolean_type_node,
10749 cap_arg, start_tree),
10750 fold_build2_loc(loc.gcc_location(),
10751 GT_EXPR, boolean_type_node,
10752 cap_arg, capacity_tree));
10753 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10754 boolean_type_node, bad_index, bad_cap);
10755 }
10756
e440a328 10757 tree end_tree;
10758 if (this->end_->is_nil_expression())
10759 end_tree = length_tree;
10760 else
10761 {
10762 end_tree = this->end_->get_tree(context);
10763 if (end_tree == error_mark_node)
10764 return error_mark_node;
10765 if (!DECL_P(end_tree))
10766 end_tree = save_expr(end_tree);
10767 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10768 end_tree = convert_to_integer(length_type, end_tree);
10769
10770 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
10771 loc);
10772
b13c66cd 10773 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
e440a328 10774
b13c66cd 10775 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10776 boolean_type_node,
10777 fold_build2_loc(loc.gcc_location(),
10778 LT_EXPR, boolean_type_node,
e440a328 10779 end_tree, start_tree),
b13c66cd 10780 fold_build2_loc(loc.gcc_location(),
10781 GT_EXPR, boolean_type_node,
acf2b673 10782 end_tree, cap_arg));
b13c66cd 10783 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10784 boolean_type_node, bad_index, bad_end);
e440a328 10785 }
10786
acf2b673 10787
9f0e0513 10788 Type* element_type = array_type->element_type();
10789 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
c65212a0 10790 if (element_type_tree == error_mark_node)
10791 return error_mark_node;
e440a328 10792 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10793
b13c66cd 10794 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10795 fold_convert_loc(loc.gcc_location(), sizetype,
10796 start_tree),
e440a328 10797 element_size);
10798
35a54f17 10799 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10800 tree value_pointer = valptr->get_tree(context);
c65212a0 10801 if (value_pointer == error_mark_node)
10802 return error_mark_node;
e440a328 10803
b13c66cd 10804 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
e440a328 10805 TREE_TYPE(value_pointer),
10806 value_pointer, offset);
10807
b13c66cd 10808 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10809 length_type, end_tree, start_tree);
e440a328 10810
b13c66cd 10811 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
acf2b673 10812 length_type, cap_arg, start_tree);
e440a328 10813
9f0e0513 10814 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
c484d925 10815 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
e440a328 10816
95f84544 10817 vec<constructor_elt, va_gc> *init;
10818 vec_alloc (init, 3);
e440a328 10819
e82e4eb5 10820 constructor_elt empty = {NULL, NULL};
95f84544 10821 constructor_elt* elt = init->quick_push(empty);
e440a328 10822 tree field = TYPE_FIELDS(struct_tree);
c484d925 10823 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
e440a328 10824 elt->index = field;
10825 elt->value = value_pointer;
10826
95f84544 10827 elt = init->quick_push(empty);
e440a328 10828 field = DECL_CHAIN(field);
c484d925 10829 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
e440a328 10830 elt->index = field;
b13c66cd 10831 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10832 result_length_tree);
e440a328 10833
95f84544 10834 elt = init->quick_push(empty);
e440a328 10835 field = DECL_CHAIN(field);
c484d925 10836 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
e440a328 10837 elt->index = field;
b13c66cd 10838 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10839 result_capacity_tree);
e440a328 10840
10841 tree constructor = build_constructor(struct_tree, init);
10842
10843 if (TREE_CONSTANT(value_pointer)
10844 && TREE_CONSTANT(result_length_tree)
10845 && TREE_CONSTANT(result_capacity_tree))
10846 TREE_CONSTANT(constructor) = 1;
10847
b13c66cd 10848 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
10849 TREE_TYPE(constructor),
e440a328 10850 build3(COND_EXPR, void_type_node,
10851 bad_index, crash, NULL_TREE),
10852 constructor);
10853}
10854
d751bb78 10855// Dump ast representation for an array index expression.
10856
10857void
10858Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10859 const
10860{
10861 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10862 this->start_, this->end_, this->cap_);
d751bb78 10863}
10864
acf2b673 10865// Make an array index expression. END and CAP may be NULL.
e440a328 10866
10867Expression*
10868Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10869 Expression* end, Expression* cap,
10870 Location location)
e440a328 10871{
acf2b673 10872 return new Array_index_expression(array, start, end, cap, location);
e440a328 10873}
10874
10875// A string index. This is used for both indexing and slicing.
10876
10877class String_index_expression : public Expression
10878{
10879 public:
10880 String_index_expression(Expression* string, Expression* start,
b13c66cd 10881 Expression* end, Location location)
e440a328 10882 : Expression(EXPRESSION_STRING_INDEX, location),
10883 string_(string), start_(start), end_(end)
10884 { }
10885
10886 protected:
10887 int
10888 do_traverse(Traverse*);
10889
10890 Type*
10891 do_type();
10892
10893 void
10894 do_determine_type(const Type_context*);
10895
10896 void
10897 do_check_types(Gogo*);
10898
10899 Expression*
10900 do_copy()
10901 {
10902 return Expression::make_string_index(this->string_->copy(),
10903 this->start_->copy(),
10904 (this->end_ == NULL
10905 ? NULL
10906 : this->end_->copy()),
10907 this->location());
10908 }
10909
baef9f7a 10910 bool
10911 do_must_eval_subexpressions_in_order(int* skip) const
10912 {
10913 *skip = 1;
10914 return true;
10915 }
10916
e440a328 10917 tree
10918 do_get_tree(Translate_context*);
10919
d751bb78 10920 void
10921 do_dump_expression(Ast_dump_context*) const;
10922
e440a328 10923 private:
10924 // The string we are getting a value from.
10925 Expression* string_;
10926 // The start or only index.
10927 Expression* start_;
10928 // The end index of a slice. This may be NULL for a single index,
10929 // or it may be a nil expression for the length of the string.
10930 Expression* end_;
10931};
10932
10933// String index traversal.
10934
10935int
10936String_index_expression::do_traverse(Traverse* traverse)
10937{
10938 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10939 return TRAVERSE_EXIT;
10940 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10941 return TRAVERSE_EXIT;
10942 if (this->end_ != NULL)
10943 {
10944 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10945 return TRAVERSE_EXIT;
10946 }
10947 return TRAVERSE_CONTINUE;
10948}
10949
10950// Return the type of a string index.
10951
10952Type*
10953String_index_expression::do_type()
10954{
10955 if (this->end_ == NULL)
10956 return Type::lookup_integer_type("uint8");
10957 else
7672d35f 10958 return this->string_->type();
e440a328 10959}
10960
10961// Determine the type of a string index.
10962
10963void
10964String_index_expression::do_determine_type(const Type_context*)
10965{
10966 this->string_->determine_type_no_context();
93000773 10967 this->start_->determine_type_no_context();
e440a328 10968 if (this->end_ != NULL)
93000773 10969 this->end_->determine_type_no_context();
e440a328 10970}
10971
10972// Check types of a string index.
10973
10974void
10975String_index_expression::do_check_types(Gogo*)
10976{
acdc230d 10977 Numeric_constant nc;
10978 unsigned long v;
10979 if (this->start_->type()->integer_type() == NULL
10980 && !this->start_->type()->is_error()
10981 && (!this->start_->numeric_constant_value(&nc)
10982 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10983 this->report_error(_("index must be integer"));
10984 if (this->end_ != NULL
10985 && this->end_->type()->integer_type() == NULL
acdc230d 10986 && !this->end_->type()->is_error()
10987 && !this->end_->is_nil_expression()
10988 && !this->end_->is_error_expression()
10989 && (!this->end_->numeric_constant_value(&nc)
10990 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10991 this->report_error(_("slice end must be integer"));
10992
10993 std::string sval;
10994 bool sval_valid = this->string_->string_constant_value(&sval);
10995
0c77715b 10996 Numeric_constant inc;
e440a328 10997 mpz_t ival;
0bd5d859 10998 bool ival_valid = false;
0c77715b 10999 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 11000 {
0bd5d859 11001 ival_valid = true;
e440a328 11002 if (mpz_sgn(ival) < 0
11003 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
11004 {
11005 error_at(this->start_->location(), "string index out of bounds");
11006 this->set_is_error();
11007 }
11008 }
11009 if (this->end_ != NULL && !this->end_->is_nil_expression())
11010 {
0c77715b 11011 Numeric_constant enc;
11012 mpz_t eval;
11013 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 11014 {
0c77715b 11015 if (mpz_sgn(eval) < 0
11016 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 11017 {
11018 error_at(this->end_->location(), "string index out of bounds");
11019 this->set_is_error();
11020 }
0bd5d859 11021 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11022 this->report_error(_("inverted slice range"));
0c77715b 11023 mpz_clear(eval);
e440a328 11024 }
11025 }
0bd5d859 11026 if (ival_valid)
11027 mpz_clear(ival);
e440a328 11028}
11029
11030// Get a tree for a string index.
11031
11032tree
11033String_index_expression::do_get_tree(Translate_context* context)
11034{
b13c66cd 11035 Location loc = this->location();
e440a328 11036
11037 tree string_tree = this->string_->get_tree(context);
11038 if (string_tree == error_mark_node)
11039 return error_mark_node;
11040
11041 if (this->string_->type()->points_to() != NULL)
11042 string_tree = build_fold_indirect_ref(string_tree);
11043 if (!DECL_P(string_tree))
11044 string_tree = save_expr(string_tree);
11045 tree string_type = TREE_TYPE(string_tree);
11046
11047 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
11048 length_tree = save_expr(length_tree);
1b1f2abf 11049
11050 Type* int_type = Type::lookup_integer_type("int");
11051 tree length_type = type_to_tree(int_type->get_backend(context->gogo()));
e440a328 11052
11053 tree bad_index = boolean_false_node;
11054
11055 tree start_tree = this->start_->get_tree(context);
11056 if (start_tree == error_mark_node)
11057 return error_mark_node;
11058 if (!DECL_P(start_tree))
11059 start_tree = save_expr(start_tree);
11060 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
11061 start_tree = convert_to_integer(length_type, start_tree);
11062
11063 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
11064 loc);
11065
b13c66cd 11066 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
e440a328 11067
11068 int code = (this->end_ == NULL
11069 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11070 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
aff1f085 11071 tree crash = context->gogo()->runtime_error(code, loc)->get_tree(context);
e440a328 11072
11073 if (this->end_ == NULL)
11074 {
b13c66cd 11075 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
11076 boolean_type_node, bad_index,
11077 fold_build2_loc(loc.gcc_location(), GE_EXPR,
e440a328 11078 boolean_type_node,
11079 start_tree, length_tree));
11080
11081 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
b13c66cd 11082 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
11083 TREE_TYPE(bytes_tree),
e440a328 11084 bytes_tree,
b13c66cd 11085 fold_convert_loc(loc.gcc_location(), sizetype,
11086 start_tree));
11087 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
e440a328 11088
11089 return build2(COMPOUND_EXPR, TREE_TYPE(index),
11090 build3(COND_EXPR, void_type_node,
11091 bad_index, crash, NULL_TREE),
11092 index);
11093 }
11094 else
11095 {
11096 tree end_tree;
11097 if (this->end_->is_nil_expression())
11098 end_tree = build_int_cst(length_type, -1);
11099 else
11100 {
11101 end_tree = this->end_->get_tree(context);
11102 if (end_tree == error_mark_node)
11103 return error_mark_node;
11104 if (!DECL_P(end_tree))
11105 end_tree = save_expr(end_tree);
11106 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
11107 end_tree = convert_to_integer(length_type, end_tree);
11108
11109 bad_index = Expression::check_bounds(end_tree, length_type,
11110 bad_index, loc);
11111
b13c66cd 11112 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
11113 end_tree);
e440a328 11114 }
11115
11116 static tree strslice_fndecl;
11117 tree ret = Gogo::call_builtin(&strslice_fndecl,
11118 loc,
11119 "__go_string_slice",
11120 3,
11121 string_type,
11122 string_type,
11123 string_tree,
11124 length_type,
11125 start_tree,
11126 length_type,
11127 end_tree);
5fb82b5e 11128 if (ret == error_mark_node)
11129 return error_mark_node;
e440a328 11130 // This will panic if the bounds are out of range for the
11131 // string.
11132 TREE_NOTHROW(strslice_fndecl) = 0;
11133
11134 if (bad_index == boolean_false_node)
11135 return ret;
11136 else
11137 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
11138 build3(COND_EXPR, void_type_node,
11139 bad_index, crash, NULL_TREE),
11140 ret);
11141 }
11142}
11143
d751bb78 11144// Dump ast representation for a string index expression.
11145
11146void
11147String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11148 const
11149{
acf2b673 11150 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11151 this->start_, this->end_, NULL);
d751bb78 11152}
11153
e440a328 11154// Make a string index expression. END may be NULL.
11155
11156Expression*
11157Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 11158 Expression* end, Location location)
e440a328 11159{
11160 return new String_index_expression(string, start, end, location);
11161}
11162
11163// Class Map_index.
11164
11165// Get the type of the map.
11166
11167Map_type*
11168Map_index_expression::get_map_type() const
11169{
11170 Map_type* mt = this->map_->type()->deref()->map_type();
c7524fae 11171 if (mt == NULL)
c484d925 11172 go_assert(saw_errors());
e440a328 11173 return mt;
11174}
11175
11176// Map index traversal.
11177
11178int
11179Map_index_expression::do_traverse(Traverse* traverse)
11180{
11181 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11182 return TRAVERSE_EXIT;
11183 return Expression::traverse(&this->index_, traverse);
11184}
11185
11186// Return the type of a map index.
11187
11188Type*
11189Map_index_expression::do_type()
11190{
c7524fae 11191 Map_type* mt = this->get_map_type();
11192 if (mt == NULL)
11193 return Type::make_error_type();
11194 Type* type = mt->val_type();
e440a328 11195 // If this map index is in a tuple assignment, we actually return a
11196 // pointer to the value type. Tuple_map_assignment_statement is
11197 // responsible for handling this correctly. We need to get the type
11198 // right in case this gets assigned to a temporary variable.
11199 if (this->is_in_tuple_assignment_)
11200 type = Type::make_pointer_type(type);
11201 return type;
11202}
11203
11204// Fix the type of a map index.
11205
11206void
11207Map_index_expression::do_determine_type(const Type_context*)
11208{
11209 this->map_->determine_type_no_context();
c7524fae 11210 Map_type* mt = this->get_map_type();
11211 Type* key_type = mt == NULL ? NULL : mt->key_type();
11212 Type_context subcontext(key_type, false);
e440a328 11213 this->index_->determine_type(&subcontext);
11214}
11215
11216// Check types of a map index.
11217
11218void
11219Map_index_expression::do_check_types(Gogo*)
11220{
11221 std::string reason;
c7524fae 11222 Map_type* mt = this->get_map_type();
11223 if (mt == NULL)
11224 return;
11225 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 11226 {
11227 if (reason.empty())
11228 this->report_error(_("incompatible type for map index"));
11229 else
11230 {
11231 error_at(this->location(), "incompatible type for map index (%s)",
11232 reason.c_str());
11233 this->set_is_error();
11234 }
11235 }
11236}
11237
11238// Get a tree for a map index.
11239
11240tree
11241Map_index_expression::do_get_tree(Translate_context* context)
11242{
11243 Map_type* type = this->get_map_type();
c7524fae 11244 if (type == NULL)
11245 return error_mark_node;
e440a328 11246
11247 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
11248 if (valptr == error_mark_node)
11249 return error_mark_node;
11250 valptr = save_expr(valptr);
11251
11252 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
11253
11254 if (this->is_lvalue_)
11255 return build_fold_indirect_ref(valptr);
11256 else if (this->is_in_tuple_assignment_)
11257 {
11258 // Tuple_map_assignment_statement is responsible for using this
11259 // appropriately.
11260 return valptr;
11261 }
11262 else
11263 {
63697958 11264 Gogo* gogo = context->gogo();
11265 Btype* val_btype = type->val_type()->get_backend(gogo);
11266 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
e440a328 11267 return fold_build3(COND_EXPR, val_type_tree,
11268 fold_build2(EQ_EXPR, boolean_type_node, valptr,
11269 fold_convert(TREE_TYPE(valptr),
11270 null_pointer_node)),
63697958 11271 expr_to_tree(val_zero),
e440a328 11272 build_fold_indirect_ref(valptr));
11273 }
11274}
11275
11276// Get a tree for the map index. This returns a tree which evaluates
11277// to a pointer to a value. The pointer will be NULL if the key is
11278// not in the map.
11279
11280tree
11281Map_index_expression::get_value_pointer(Translate_context* context,
11282 bool insert)
11283{
11284 Map_type* type = this->get_map_type();
c7524fae 11285 if (type == NULL)
11286 return error_mark_node;
e440a328 11287
11288 tree map_tree = this->map_->get_tree(context);
11289 tree index_tree = this->index_->get_tree(context);
11290 index_tree = Expression::convert_for_assignment(context, type->key_type(),
11291 this->index_->type(),
11292 index_tree,
11293 this->location());
11294 if (map_tree == error_mark_node || index_tree == error_mark_node)
11295 return error_mark_node;
11296
11297 if (this->map_->type()->points_to() != NULL)
11298 map_tree = build_fold_indirect_ref(map_tree);
11299
11300 // We need to pass in a pointer to the key, so stuff it into a
11301 // variable.
746d2e73 11302 tree tmp;
11303 tree make_tmp;
11304 if (current_function_decl != NULL)
11305 {
11306 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
11307 DECL_IGNORED_P(tmp) = 0;
11308 DECL_INITIAL(tmp) = index_tree;
11309 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
11310 TREE_ADDRESSABLE(tmp) = 1;
11311 }
11312 else
11313 {
b13c66cd 11314 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11315 create_tmp_var_name("M"),
746d2e73 11316 TREE_TYPE(index_tree));
11317 DECL_EXTERNAL(tmp) = 0;
11318 TREE_PUBLIC(tmp) = 0;
11319 TREE_STATIC(tmp) = 1;
11320 DECL_ARTIFICIAL(tmp) = 1;
11321 if (!TREE_CONSTANT(index_tree))
b13c66cd 11322 make_tmp = fold_build2_loc(this->location().gcc_location(),
11323 INIT_EXPR, void_type_node,
746d2e73 11324 tmp, index_tree);
11325 else
11326 {
11327 TREE_READONLY(tmp) = 1;
11328 TREE_CONSTANT(tmp) = 1;
11329 DECL_INITIAL(tmp) = index_tree;
11330 make_tmp = NULL_TREE;
11331 }
11332 rest_of_decl_compilation(tmp, 1, 0);
11333 }
b13c66cd 11334 tree tmpref =
11335 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
11336 build_fold_addr_expr_loc(this->location().gcc_location(),
11337 tmp));
e440a328 11338
11339 static tree map_index_fndecl;
11340 tree call = Gogo::call_builtin(&map_index_fndecl,
11341 this->location(),
11342 "__go_map_index",
11343 3,
11344 const_ptr_type_node,
11345 TREE_TYPE(map_tree),
11346 map_tree,
11347 const_ptr_type_node,
11348 tmpref,
11349 boolean_type_node,
11350 (insert
11351 ? boolean_true_node
11352 : boolean_false_node));
5fb82b5e 11353 if (call == error_mark_node)
11354 return error_mark_node;
e440a328 11355 // This can panic on a map of interface type if the interface holds
11356 // an uncomparable or unhashable type.
11357 TREE_NOTHROW(map_index_fndecl) = 0;
11358
9f0e0513 11359 Type* val_type = type->val_type();
11360 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
e440a328 11361 if (val_type_tree == error_mark_node)
11362 return error_mark_node;
11363 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
11364
b13c66cd 11365 tree ret = fold_convert_loc(this->location().gcc_location(),
11366 ptr_val_type_tree, call);
746d2e73 11367 if (make_tmp != NULL_TREE)
11368 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
11369 return ret;
e440a328 11370}
11371
d751bb78 11372// Dump ast representation for a map index expression
11373
11374void
11375Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11376 const
11377{
acf2b673 11378 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11379 this->index_, NULL, NULL);
d751bb78 11380}
11381
e440a328 11382// Make a map index expression.
11383
11384Map_index_expression*
11385Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 11386 Location location)
e440a328 11387{
11388 return new Map_index_expression(map, index, location);
11389}
11390
11391// Class Field_reference_expression.
11392
149eabc5 11393// Lower a field reference expression. There is nothing to lower, but
11394// this is where we generate the tracking information for fields with
11395// the magic go:"track" tag.
11396
11397Expression*
11398Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11399 Statement_inserter* inserter, int)
11400{
11401 Struct_type* struct_type = this->expr_->type()->struct_type();
11402 if (struct_type == NULL)
11403 {
11404 // Error will be reported elsewhere.
11405 return this;
11406 }
11407 const Struct_field* field = struct_type->field(this->field_index_);
11408 if (field == NULL)
11409 return this;
11410 if (!field->has_tag())
11411 return this;
11412 if (field->tag().find("go:\"track\"") == std::string::npos)
11413 return this;
11414
11415 // We have found a reference to a tracked field. Build a call to
11416 // the runtime function __go_fieldtrack with a string that describes
11417 // the field. FIXME: We should only call this once per referenced
11418 // field per function, not once for each reference to the field.
11419
11420 if (this->called_fieldtrack_)
11421 return this;
11422 this->called_fieldtrack_ = true;
11423
11424 Location loc = this->location();
11425
11426 std::string s = "fieldtrack \"";
11427 Named_type* nt = this->expr_->type()->named_type();
11428 if (nt == NULL || nt->named_object()->package() == NULL)
11429 s.append(gogo->pkgpath());
11430 else
11431 s.append(nt->named_object()->package()->pkgpath());
11432 s.push_back('.');
11433 if (nt != NULL)
5c29ad36 11434 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11435 s.push_back('.');
11436 s.append(field->field_name());
11437 s.push_back('"');
11438
11439 // We can't use a string here, because internally a string holds a
11440 // pointer to the actual bytes; when the linker garbage collects the
11441 // string, it won't garbage collect the bytes. So we use a
11442 // [...]byte.
11443
11444 mpz_t val;
11445 mpz_init_set_ui(val, s.length());
11446 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11447 mpz_clear(val);
11448
11449 Type* byte_type = gogo->lookup_global("byte")->type_value();
11450 Type* array_type = Type::make_array_type(byte_type, length_expr);
11451
11452 Expression_list* bytes = new Expression_list();
11453 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11454 {
11455 mpz_init_set_ui(val, *p);
11456 Expression* byte = Expression::make_integer(&val, NULL, loc);
11457 mpz_clear(val);
11458 bytes->push_back(byte);
11459 }
11460
11461 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11462 bytes, false, loc);
149eabc5 11463
11464 Variable* var = new Variable(array_type, e, true, false, false, loc);
11465
11466 static int count;
11467 char buf[50];
11468 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11469 ++count;
11470
11471 Named_object* no = gogo->add_variable(buf, var);
11472 e = Expression::make_var_reference(no, loc);
11473 e = Expression::make_unary(OPERATOR_AND, e, loc);
11474
11475 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11476 inserter->insert(Statement::make_statement(call, false));
11477
11478 // Put this function, and the global variable we just created, into
11479 // unique sections. This will permit the linker to garbage collect
11480 // them if they are not referenced. The effect is that the only
11481 // strings, indicating field references, that will wind up in the
11482 // executable will be those for functions that are actually needed.
66a6be58 11483 if (function != NULL)
11484 function->func_value()->set_in_unique_section();
149eabc5 11485 var->set_in_unique_section();
11486
11487 return this;
11488}
11489
e440a328 11490// Return the type of a field reference.
11491
11492Type*
11493Field_reference_expression::do_type()
11494{
b0e628fb 11495 Type* type = this->expr_->type();
5c13bd80 11496 if (type->is_error())
b0e628fb 11497 return type;
11498 Struct_type* struct_type = type->struct_type();
c484d925 11499 go_assert(struct_type != NULL);
e440a328 11500 return struct_type->field(this->field_index_)->type();
11501}
11502
11503// Check the types for a field reference.
11504
11505void
11506Field_reference_expression::do_check_types(Gogo*)
11507{
b0e628fb 11508 Type* type = this->expr_->type();
5c13bd80 11509 if (type->is_error())
b0e628fb 11510 return;
11511 Struct_type* struct_type = type->struct_type();
c484d925 11512 go_assert(struct_type != NULL);
11513 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11514}
11515
11516// Get a tree for a field reference.
11517
11518tree
11519Field_reference_expression::do_get_tree(Translate_context* context)
11520{
fbb851c5 11521 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11522 Bexpression* ret =
11523 context->gogo()->backend()->struct_field_expression(bstruct,
11524 this->field_index_,
11525 this->location());
11526 return expr_to_tree(ret);
e440a328 11527}
11528
d751bb78 11529// Dump ast representation for a field reference expression.
11530
11531void
11532Field_reference_expression::do_dump_expression(
11533 Ast_dump_context* ast_dump_context) const
11534{
11535 this->expr_->dump_expression(ast_dump_context);
11536 ast_dump_context->ostream() << "." << this->field_index_;
11537}
11538
e440a328 11539// Make a reference to a qualified identifier in an expression.
11540
11541Field_reference_expression*
11542Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11543 Location location)
e440a328 11544{
11545 return new Field_reference_expression(expr, field_index, location);
11546}
11547
11548// Class Interface_field_reference_expression.
11549
2387f644 11550// Return an expression for the pointer to the function to call.
e440a328 11551
2387f644 11552Expression*
11553Interface_field_reference_expression::get_function()
e440a328 11554{
2387f644 11555 Expression* ref = this->expr_;
11556 Location loc = this->location();
11557 if (ref->type()->points_to() != NULL)
11558 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11559
2387f644 11560 Expression* mtable =
11561 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11562 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11563
11564 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11565 unsigned int index;
11566 const Struct_field* field = mtable_type->find_local_field(name, &index);
11567 go_assert(field != NULL);
11568 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11569 return Expression::make_field_reference(mtable, index, loc);
e440a328 11570}
11571
2387f644 11572// Return an expression for the first argument to pass to the interface
e440a328 11573// function.
11574
2387f644 11575Expression*
11576Interface_field_reference_expression::get_underlying_object()
e440a328 11577{
2387f644 11578 Expression* expr = this->expr_;
11579 if (expr->type()->points_to() != NULL)
11580 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11581 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11582 this->location());
e440a328 11583}
11584
11585// Traversal.
11586
11587int
11588Interface_field_reference_expression::do_traverse(Traverse* traverse)
11589{
11590 return Expression::traverse(&this->expr_, traverse);
11591}
11592
0afbb937 11593// Lower the expression. If this expression is not called, we need to
11594// evaluate the expression twice when converting to the backend
11595// interface. So introduce a temporary variable if necessary.
11596
11597Expression*
11598Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11599 Statement_inserter* inserter,
11600 int)
11601{
2387f644 11602 if (!this->expr_->is_variable())
0afbb937 11603 {
11604 Temporary_statement* temp =
11605 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11606 inserter->insert(temp);
11607 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11608 this->location());
11609 }
11610 return this;
11611}
11612
e440a328 11613// Return the type of an interface field reference.
11614
11615Type*
11616Interface_field_reference_expression::do_type()
11617{
11618 Type* expr_type = this->expr_->type();
11619
11620 Type* points_to = expr_type->points_to();
11621 if (points_to != NULL)
11622 expr_type = points_to;
11623
11624 Interface_type* interface_type = expr_type->interface_type();
11625 if (interface_type == NULL)
11626 return Type::make_error_type();
11627
11628 const Typed_identifier* method = interface_type->find_method(this->name_);
11629 if (method == NULL)
11630 return Type::make_error_type();
11631
11632 return method->type();
11633}
11634
11635// Determine types.
11636
11637void
11638Interface_field_reference_expression::do_determine_type(const Type_context*)
11639{
11640 this->expr_->determine_type_no_context();
11641}
11642
11643// Check the types for an interface field reference.
11644
11645void
11646Interface_field_reference_expression::do_check_types(Gogo*)
11647{
11648 Type* type = this->expr_->type();
11649
11650 Type* points_to = type->points_to();
11651 if (points_to != NULL)
11652 type = points_to;
11653
11654 Interface_type* interface_type = type->interface_type();
11655 if (interface_type == NULL)
5c491127 11656 {
11657 if (!type->is_error_type())
11658 this->report_error(_("expected interface or pointer to interface"));
11659 }
e440a328 11660 else
11661 {
11662 const Typed_identifier* method =
11663 interface_type->find_method(this->name_);
11664 if (method == NULL)
11665 {
11666 error_at(this->location(), "method %qs not in interface",
11667 Gogo::message_name(this->name_).c_str());
11668 this->set_is_error();
11669 }
11670 }
11671}
11672
0afbb937 11673// If an interface field reference is not simply called, then it is
11674// represented as a closure. The closure will hold a single variable,
11675// the value of the interface on which the method should be called.
11676// The function will be a simple thunk that pulls the value from the
11677// closure and calls the method with the remaining arguments.
11678
11679// Because method values are not common, we don't build all thunks for
11680// all possible interface methods, but instead only build them as we
11681// need them. In particular, we even build them on demand for
11682// interface methods defined in other packages.
11683
11684Interface_field_reference_expression::Interface_method_thunks
11685 Interface_field_reference_expression::interface_method_thunks;
11686
11687// Find or create the thunk to call method NAME on TYPE.
11688
11689Named_object*
11690Interface_field_reference_expression::create_thunk(Gogo* gogo,
11691 Interface_type* type,
11692 const std::string& name)
11693{
11694 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11695 std::pair<Interface_method_thunks::iterator, bool> ins =
11696 Interface_field_reference_expression::interface_method_thunks.insert(val);
11697 if (ins.second)
11698 {
11699 // This is the first time we have seen this interface.
11700 ins.first->second = new Method_thunks();
11701 }
11702
11703 for (Method_thunks::const_iterator p = ins.first->second->begin();
11704 p != ins.first->second->end();
11705 p++)
11706 if (p->first == name)
11707 return p->second;
11708
11709 Location loc = type->location();
11710
11711 const Typed_identifier* method_id = type->find_method(name);
11712 if (method_id == NULL)
11713 return Named_object::make_erroneous_name(Gogo::thunk_name());
11714
11715 Function_type* orig_fntype = method_id->type()->function_type();
11716 if (orig_fntype == NULL)
11717 return Named_object::make_erroneous_name(Gogo::thunk_name());
11718
11719 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11720 // The type here is wrong--it should be the C function type. But it
11721 // doesn't really matter.
0afbb937 11722 Type* vt = Type::make_pointer_type(Type::make_void_type());
11723 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11724 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11725 Type* closure_type = Type::make_struct_type(sfl, loc);
11726 closure_type = Type::make_pointer_type(closure_type);
11727
f8bdf81a 11728 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11729
11730 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11731 false, loc);
11732
f8bdf81a 11733 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11734 cvar->set_is_used();
11735 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11736 new_no->func_value()->set_closure_var(cp);
0afbb937 11737
f8bdf81a 11738 gogo->start_block(loc);
0afbb937 11739
11740 // Field 0 of the closure is the function code pointer, field 1 is
11741 // the value on which to invoke the method.
11742 Expression* arg = Expression::make_var_reference(cp, loc);
11743 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11744 arg = Expression::make_field_reference(arg, 1, loc);
11745
11746 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11747 loc);
11748
11749 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11750 Expression_list* args;
11751 if (orig_params == NULL || orig_params->empty())
11752 args = NULL;
11753 else
11754 {
11755 const Typed_identifier_list* new_params = new_fntype->parameters();
11756 args = new Expression_list();
11757 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11758 p != new_params->end();
0afbb937 11759 ++p)
11760 {
11761 Named_object* p_no = gogo->lookup(p->name(), NULL);
11762 go_assert(p_no != NULL
11763 && p_no->is_variable()
11764 && p_no->var_value()->is_parameter());
11765 args->push_back(Expression::make_var_reference(p_no, loc));
11766 }
11767 }
11768
11769 Call_expression* call = Expression::make_call(ifre, args,
11770 orig_fntype->is_varargs(),
11771 loc);
11772 call->set_varargs_are_lowered();
11773
11774 Statement* s = Statement::make_return_from_call(call, loc);
11775 gogo->add_statement(s);
11776 Block* b = gogo->finish_block(loc);
11777 gogo->add_block(b, loc);
11778 gogo->lower_block(new_no, b);
a32698ee 11779 gogo->flatten_block(new_no, b);
0afbb937 11780 gogo->finish_function(loc);
11781
11782 ins.first->second->push_back(std::make_pair(name, new_no));
11783 return new_no;
11784}
11785
11786// Get a tree for a method value.
e440a328 11787
11788tree
0afbb937 11789Interface_field_reference_expression::do_get_tree(Translate_context* context)
e440a328 11790{
0afbb937 11791 Interface_type* type = this->expr_->type()->interface_type();
11792 if (type == NULL)
11793 {
11794 go_assert(saw_errors());
11795 return error_mark_node;
11796 }
11797
11798 Named_object* thunk =
11799 Interface_field_reference_expression::create_thunk(context->gogo(),
11800 type, this->name_);
11801 if (thunk->is_erroneous())
11802 {
11803 go_assert(saw_errors());
11804 return error_mark_node;
11805 }
11806
11807 // FIXME: We should lower this earlier, but we can't it lower it in
11808 // the lowering pass because at that point we don't know whether we
11809 // need to create the thunk or not. If the expression is called, we
11810 // don't need the thunk.
11811
11812 Location loc = this->location();
11813
11814 Struct_field_list* fields = new Struct_field_list();
11815 fields->push_back(Struct_field(Typed_identifier("fn.0",
11816 thunk->func_value()->type(),
11817 loc)));
11818 fields->push_back(Struct_field(Typed_identifier("val.1",
11819 this->expr_->type(),
11820 loc)));
11821 Struct_type* st = Type::make_struct_type(fields, loc);
11822
11823 Expression_list* vals = new Expression_list();
11824 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11825 vals->push_back(this->expr_);
11826
11827 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11828 expr = Expression::make_heap_composite(expr, loc);
11829
2387f644 11830 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11831 Expression* nil_check =
11832 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11833 Expression::make_nil(loc), loc);
11834 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
0afbb937 11835
2387f644 11836 Gogo* gogo = context->gogo();
11837 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11838 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11839
11840 Bexpression* bcond =
a32698ee 11841 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11842 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11843 Bexpression* ret =
11844 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11845 return expr_to_tree(ret);
e440a328 11846}
11847
d751bb78 11848// Dump ast representation for an interface field reference.
11849
11850void
11851Interface_field_reference_expression::do_dump_expression(
11852 Ast_dump_context* ast_dump_context) const
11853{
11854 this->expr_->dump_expression(ast_dump_context);
11855 ast_dump_context->ostream() << "." << this->name_;
11856}
11857
e440a328 11858// Make a reference to a field in an interface.
11859
11860Expression*
11861Expression::make_interface_field_reference(Expression* expr,
11862 const std::string& field,
b13c66cd 11863 Location location)
e440a328 11864{
11865 return new Interface_field_reference_expression(expr, field, location);
11866}
11867
11868// A general selector. This is a Parser_expression for LEFT.NAME. It
11869// is lowered after we know the type of the left hand side.
11870
11871class Selector_expression : public Parser_expression
11872{
11873 public:
11874 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11875 Location location)
e440a328 11876 : Parser_expression(EXPRESSION_SELECTOR, location),
11877 left_(left), name_(name)
11878 { }
11879
11880 protected:
11881 int
11882 do_traverse(Traverse* traverse)
11883 { return Expression::traverse(&this->left_, traverse); }
11884
11885 Expression*
ceeb4318 11886 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11887
11888 Expression*
11889 do_copy()
11890 {
11891 return new Selector_expression(this->left_->copy(), this->name_,
11892 this->location());
11893 }
11894
d751bb78 11895 void
11896 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11897
e440a328 11898 private:
11899 Expression*
11900 lower_method_expression(Gogo*);
11901
11902 // The expression on the left hand side.
11903 Expression* left_;
11904 // The name on the right hand side.
11905 std::string name_;
11906};
11907
11908// Lower a selector expression once we know the real type of the left
11909// hand side.
11910
11911Expression*
ceeb4318 11912Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11913 int)
e440a328 11914{
11915 Expression* left = this->left_;
11916 if (left->is_type_expression())
11917 return this->lower_method_expression(gogo);
11918 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11919 this->location());
11920}
11921
11922// Lower a method expression T.M or (*T).M. We turn this into a
11923// function literal.
11924
11925Expression*
11926Selector_expression::lower_method_expression(Gogo* gogo)
11927{
b13c66cd 11928 Location location = this->location();
e440a328 11929 Type* type = this->left_->type();
11930 const std::string& name(this->name_);
11931
11932 bool is_pointer;
11933 if (type->points_to() == NULL)
11934 is_pointer = false;
11935 else
11936 {
11937 is_pointer = true;
11938 type = type->points_to();
11939 }
11940 Named_type* nt = type->named_type();
11941 if (nt == NULL)
11942 {
11943 error_at(location,
11944 ("method expression requires named type or "
11945 "pointer to named type"));
11946 return Expression::make_error(location);
11947 }
11948
11949 bool is_ambiguous;
11950 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 11951 const Typed_identifier* imethod = NULL;
dcc8506b 11952 if (method == NULL && !is_pointer)
ab1468c3 11953 {
11954 Interface_type* it = nt->interface_type();
11955 if (it != NULL)
11956 imethod = it->find_method(name);
11957 }
11958
11959 if (method == NULL && imethod == NULL)
e440a328 11960 {
11961 if (!is_ambiguous)
dcc8506b 11962 error_at(location, "type %<%s%s%> has no method %<%s%>",
11963 is_pointer ? "*" : "",
e440a328 11964 nt->message_name().c_str(),
11965 Gogo::message_name(name).c_str());
11966 else
dcc8506b 11967 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
e440a328 11968 Gogo::message_name(name).c_str(),
dcc8506b 11969 is_pointer ? "*" : "",
e440a328 11970 nt->message_name().c_str());
11971 return Expression::make_error(location);
11972 }
11973
ab1468c3 11974 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 11975 {
11976 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11977 nt->message_name().c_str(),
11978 Gogo::message_name(name).c_str());
11979 return Expression::make_error(location);
11980 }
11981
11982 // Build a new function type in which the receiver becomes the first
11983 // argument.
ab1468c3 11984 Function_type* method_type;
11985 if (method != NULL)
11986 {
11987 method_type = method->type();
c484d925 11988 go_assert(method_type->is_method());
ab1468c3 11989 }
11990 else
11991 {
11992 method_type = imethod->type()->function_type();
c484d925 11993 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 11994 }
e440a328 11995
11996 const char* const receiver_name = "$this";
11997 Typed_identifier_list* parameters = new Typed_identifier_list();
11998 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11999 location));
12000
12001 const Typed_identifier_list* method_parameters = method_type->parameters();
12002 if (method_parameters != NULL)
12003 {
f470da59 12004 int i = 0;
e440a328 12005 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12006 p != method_parameters->end();
f470da59 12007 ++p, ++i)
12008 {
68883531 12009 if (!p->name().empty())
f470da59 12010 parameters->push_back(*p);
12011 else
12012 {
12013 char buf[20];
12014 snprintf(buf, sizeof buf, "$param%d", i);
12015 parameters->push_back(Typed_identifier(buf, p->type(),
12016 p->location()));
12017 }
12018 }
e440a328 12019 }
12020
12021 const Typed_identifier_list* method_results = method_type->results();
12022 Typed_identifier_list* results;
12023 if (method_results == NULL)
12024 results = NULL;
12025 else
12026 {
12027 results = new Typed_identifier_list();
12028 for (Typed_identifier_list::const_iterator p = method_results->begin();
12029 p != method_results->end();
12030 ++p)
12031 results->push_back(*p);
12032 }
12033
12034 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12035 location);
12036 if (method_type->is_varargs())
12037 fntype->set_is_varargs();
12038
12039 // We generate methods which always takes a pointer to the receiver
12040 // as their first argument. If this is for a pointer type, we can
12041 // simply reuse the existing function. We use an internal hack to
12042 // get the right type.
8381eda7 12043 // FIXME: This optimization is disabled because it doesn't yet work
12044 // with function descriptors when the method expression is not
12045 // directly called.
12046 if (method != NULL && is_pointer && false)
e440a328 12047 {
12048 Named_object* mno = (method->needs_stub_method()
12049 ? method->stub_object()
12050 : method->named_object());
12051 Expression* f = Expression::make_func_reference(mno, NULL, location);
12052 f = Expression::make_cast(fntype, f, location);
12053 Type_conversion_expression* tce =
12054 static_cast<Type_conversion_expression*>(f);
12055 tce->set_may_convert_function_types();
12056 return f;
12057 }
12058
12059 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12060 location);
12061
12062 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 12063 go_assert(vno != NULL);
e440a328 12064 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 12065 Expression* bm;
12066 if (method != NULL)
12067 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12068 else
12069 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 12070
12071 // Even though we found the method above, if it has an error type we
12072 // may see an error here.
12073 if (bm->is_error_expression())
463fe805 12074 {
12075 gogo->finish_function(location);
12076 return bm;
12077 }
e440a328 12078
12079 Expression_list* args;
f470da59 12080 if (parameters->size() <= 1)
e440a328 12081 args = NULL;
12082 else
12083 {
12084 args = new Expression_list();
f470da59 12085 Typed_identifier_list::const_iterator p = parameters->begin();
12086 ++p;
12087 for (; p != parameters->end(); ++p)
e440a328 12088 {
12089 vno = gogo->lookup(p->name(), NULL);
c484d925 12090 go_assert(vno != NULL);
e440a328 12091 args->push_back(Expression::make_var_reference(vno, location));
12092 }
12093 }
12094
ceeb4318 12095 gogo->start_block(location);
12096
e440a328 12097 Call_expression* call = Expression::make_call(bm, args,
12098 method_type->is_varargs(),
12099 location);
12100
0afbb937 12101 Statement* s = Statement::make_return_from_call(call, location);
e440a328 12102 gogo->add_statement(s);
12103
ceeb4318 12104 Block* b = gogo->finish_block(location);
12105
12106 gogo->add_block(b, location);
12107
12108 // Lower the call in case there are multiple results.
12109 gogo->lower_block(no, b);
a32698ee 12110 gogo->flatten_block(no, b);
ceeb4318 12111
e440a328 12112 gogo->finish_function(location);
12113
12114 return Expression::make_func_reference(no, NULL, location);
12115}
12116
d751bb78 12117// Dump the ast for a selector expression.
12118
12119void
12120Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12121 const
12122{
12123 ast_dump_context->dump_expression(this->left_);
12124 ast_dump_context->ostream() << ".";
12125 ast_dump_context->ostream() << this->name_;
12126}
12127
e440a328 12128// Make a selector expression.
12129
12130Expression*
12131Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 12132 Location location)
e440a328 12133{
12134 return new Selector_expression(left, name, location);
12135}
12136
12137// Implement the builtin function new.
12138
12139class Allocation_expression : public Expression
12140{
12141 public:
b13c66cd 12142 Allocation_expression(Type* type, Location location)
e440a328 12143 : Expression(EXPRESSION_ALLOCATION, location),
12144 type_(type)
12145 { }
12146
12147 protected:
12148 int
12149 do_traverse(Traverse* traverse)
12150 { return Type::traverse(this->type_, traverse); }
12151
12152 Type*
12153 do_type()
12154 { return Type::make_pointer_type(this->type_); }
12155
12156 void
12157 do_determine_type(const Type_context*)
12158 { }
12159
e440a328 12160 Expression*
12161 do_copy()
12162 { return new Allocation_expression(this->type_, this->location()); }
12163
12164 tree
12165 do_get_tree(Translate_context*);
12166
d751bb78 12167 void
12168 do_dump_expression(Ast_dump_context*) const;
12169
e440a328 12170 private:
12171 // The type we are allocating.
12172 Type* type_;
12173};
12174
e440a328 12175// Return a tree for an allocation expression.
12176
12177tree
12178Allocation_expression::do_get_tree(Translate_context* context)
12179{
9f0e0513 12180 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
19824ddb 12181 if (type_tree == error_mark_node)
12182 return error_mark_node;
e440a328 12183 tree size_tree = TYPE_SIZE_UNIT(type_tree);
12184 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
12185 this->location());
19824ddb 12186 if (space == error_mark_node)
12187 return error_mark_node;
e440a328 12188 return fold_convert(build_pointer_type(type_tree), space);
12189}
12190
d751bb78 12191// Dump ast representation for an allocation expression.
12192
12193void
12194Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12195 const
12196{
12197 ast_dump_context->ostream() << "new(";
12198 ast_dump_context->dump_type(this->type_);
12199 ast_dump_context->ostream() << ")";
12200}
12201
e440a328 12202// Make an allocation expression.
12203
12204Expression*
b13c66cd 12205Expression::make_allocation(Type* type, Location location)
e440a328 12206{
12207 return new Allocation_expression(type, location);
12208}
12209
e440a328 12210// Construct a struct.
12211
12212class Struct_construction_expression : public Expression
12213{
12214 public:
12215 Struct_construction_expression(Type* type, Expression_list* vals,
b13c66cd 12216 Location location)
e440a328 12217 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
0c4f5a19 12218 type_(type), vals_(vals), traverse_order_(NULL)
e440a328 12219 { }
12220
0c4f5a19 12221 // Set the traversal order, used to ensure that we implement the
12222 // order of evaluation rules. Takes ownership of the argument.
12223 void
12224 set_traverse_order(std::vector<int>* traverse_order)
12225 { this->traverse_order_ = traverse_order; }
12226
e440a328 12227 // Return whether this is a constant initializer.
12228 bool
12229 is_constant_struct() const;
12230
12231 protected:
12232 int
12233 do_traverse(Traverse* traverse);
12234
12235 Type*
12236 do_type()
12237 { return this->type_; }
12238
12239 void
12240 do_determine_type(const Type_context*);
12241
12242 void
12243 do_check_types(Gogo*);
12244
12245 Expression*
12246 do_copy()
12247 {
0c4f5a19 12248 Struct_construction_expression* ret =
12249 new Struct_construction_expression(this->type_, this->vals_->copy(),
12250 this->location());
12251 if (this->traverse_order_ != NULL)
12252 ret->set_traverse_order(this->traverse_order_);
12253 return ret;
e440a328 12254 }
12255
e440a328 12256 tree
12257 do_get_tree(Translate_context*);
12258
12259 void
12260 do_export(Export*) const;
12261
d751bb78 12262 void
12263 do_dump_expression(Ast_dump_context*) const;
12264
e440a328 12265 private:
12266 // The type of the struct to construct.
12267 Type* type_;
12268 // The list of values, in order of the fields in the struct. A NULL
12269 // entry means that the field should be zero-initialized.
12270 Expression_list* vals_;
0c4f5a19 12271 // If not NULL, the order in which to traverse vals_. This is used
12272 // so that we implement the order of evaluation rules correctly.
12273 std::vector<int>* traverse_order_;
e440a328 12274};
12275
12276// Traversal.
12277
12278int
12279Struct_construction_expression::do_traverse(Traverse* traverse)
12280{
0c4f5a19 12281 if (this->vals_ != NULL)
12282 {
12283 if (this->traverse_order_ == NULL)
12284 {
12285 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12286 return TRAVERSE_EXIT;
12287 }
12288 else
12289 {
12290 for (std::vector<int>::const_iterator p =
12291 this->traverse_order_->begin();
12292 p != this->traverse_order_->end();
12293 ++p)
12294 {
12295 if (Expression::traverse(&this->vals_->at(*p), traverse)
12296 == TRAVERSE_EXIT)
12297 return TRAVERSE_EXIT;
12298 }
12299 }
12300 }
e440a328 12301 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12302 return TRAVERSE_EXIT;
12303 return TRAVERSE_CONTINUE;
12304}
12305
12306// Return whether this is a constant initializer.
12307
12308bool
12309Struct_construction_expression::is_constant_struct() const
12310{
12311 if (this->vals_ == NULL)
12312 return true;
12313 for (Expression_list::const_iterator pv = this->vals_->begin();
12314 pv != this->vals_->end();
12315 ++pv)
12316 {
12317 if (*pv != NULL
12318 && !(*pv)->is_constant()
12319 && (!(*pv)->is_composite_literal()
12320 || (*pv)->is_nonconstant_composite_literal()))
12321 return false;
12322 }
12323
12324 const Struct_field_list* fields = this->type_->struct_type()->fields();
12325 for (Struct_field_list::const_iterator pf = fields->begin();
12326 pf != fields->end();
12327 ++pf)
12328 {
12329 // There are no constant constructors for interfaces.
12330 if (pf->type()->interface_type() != NULL)
12331 return false;
12332 }
12333
12334 return true;
12335}
12336
12337// Final type determination.
12338
12339void
12340Struct_construction_expression::do_determine_type(const Type_context*)
12341{
12342 if (this->vals_ == NULL)
12343 return;
12344 const Struct_field_list* fields = this->type_->struct_type()->fields();
12345 Expression_list::const_iterator pv = this->vals_->begin();
12346 for (Struct_field_list::const_iterator pf = fields->begin();
12347 pf != fields->end();
12348 ++pf, ++pv)
12349 {
12350 if (pv == this->vals_->end())
12351 return;
12352 if (*pv != NULL)
12353 {
12354 Type_context subcontext(pf->type(), false);
12355 (*pv)->determine_type(&subcontext);
12356 }
12357 }
a6cb4c0e 12358 // Extra values are an error we will report elsewhere; we still want
12359 // to determine the type to avoid knockon errors.
12360 for (; pv != this->vals_->end(); ++pv)
12361 (*pv)->determine_type_no_context();
e440a328 12362}
12363
12364// Check types.
12365
12366void
12367Struct_construction_expression::do_check_types(Gogo*)
12368{
12369 if (this->vals_ == NULL)
12370 return;
12371
12372 Struct_type* st = this->type_->struct_type();
12373 if (this->vals_->size() > st->field_count())
12374 {
12375 this->report_error(_("too many expressions for struct"));
12376 return;
12377 }
12378
12379 const Struct_field_list* fields = st->fields();
12380 Expression_list::const_iterator pv = this->vals_->begin();
12381 int i = 0;
12382 for (Struct_field_list::const_iterator pf = fields->begin();
12383 pf != fields->end();
12384 ++pf, ++pv, ++i)
12385 {
12386 if (pv == this->vals_->end())
12387 {
12388 this->report_error(_("too few expressions for struct"));
12389 break;
12390 }
12391
12392 if (*pv == NULL)
12393 continue;
12394
12395 std::string reason;
12396 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12397 {
12398 if (reason.empty())
12399 error_at((*pv)->location(),
12400 "incompatible type for field %d in struct construction",
12401 i + 1);
12402 else
12403 error_at((*pv)->location(),
12404 ("incompatible type for field %d in "
12405 "struct construction (%s)"),
12406 i + 1, reason.c_str());
12407 this->set_is_error();
12408 }
12409 }
c484d925 12410 go_assert(pv == this->vals_->end());
e440a328 12411}
12412
12413// Return a tree for constructing a struct.
12414
12415tree
12416Struct_construction_expression::do_get_tree(Translate_context* context)
12417{
12418 Gogo* gogo = context->gogo();
12419
12420 if (this->vals_ == NULL)
63697958 12421 {
12422 Btype* btype = this->type_->get_backend(gogo);
12423 return expr_to_tree(gogo->backend()->zero_expression(btype));
12424 }
e440a328 12425
9f0e0513 12426 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
e440a328 12427 if (type_tree == error_mark_node)
12428 return error_mark_node;
c484d925 12429 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
e440a328 12430
12431 bool is_constant = true;
12432 const Struct_field_list* fields = this->type_->struct_type()->fields();
95f84544 12433 vec<constructor_elt, va_gc> *elts;
12434 vec_alloc (elts, fields->size());
e440a328 12435 Struct_field_list::const_iterator pf = fields->begin();
12436 Expression_list::const_iterator pv = this->vals_->begin();
12437 for (tree field = TYPE_FIELDS(type_tree);
12438 field != NULL_TREE;
12439 field = DECL_CHAIN(field), ++pf)
12440 {
c484d925 12441 go_assert(pf != fields->end());
e440a328 12442
63697958 12443 Btype* fbtype = pf->type()->get_backend(gogo);
12444
e440a328 12445 tree val;
12446 if (pv == this->vals_->end())
63697958 12447 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
e440a328 12448 else if (*pv == NULL)
12449 {
63697958 12450 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
e440a328 12451 ++pv;
12452 }
12453 else
12454 {
12455 val = Expression::convert_for_assignment(context, pf->type(),
12456 (*pv)->type(),
12457 (*pv)->get_tree(context),
12458 this->location());
12459 ++pv;
12460 }
12461
12462 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
12463 return error_mark_node;
12464
e82e4eb5 12465 constructor_elt empty = {NULL, NULL};
95f84544 12466 constructor_elt* elt = elts->quick_push(empty);
e440a328 12467 elt->index = field;
12468 elt->value = val;
12469 if (!TREE_CONSTANT(val))
12470 is_constant = false;
12471 }
c484d925 12472 go_assert(pf == fields->end());
e440a328 12473
12474 tree ret = build_constructor(type_tree, elts);
12475 if (is_constant)
12476 TREE_CONSTANT(ret) = 1;
12477 return ret;
12478}
12479
12480// Export a struct construction.
12481
12482void
12483Struct_construction_expression::do_export(Export* exp) const
12484{
12485 exp->write_c_string("convert(");
12486 exp->write_type(this->type_);
12487 for (Expression_list::const_iterator pv = this->vals_->begin();
12488 pv != this->vals_->end();
12489 ++pv)
12490 {
12491 exp->write_c_string(", ");
12492 if (*pv != NULL)
12493 (*pv)->export_expression(exp);
12494 }
12495 exp->write_c_string(")");
12496}
12497
d751bb78 12498// Dump ast representation of a struct construction expression.
12499
12500void
12501Struct_construction_expression::do_dump_expression(
12502 Ast_dump_context* ast_dump_context) const
12503{
d751bb78 12504 ast_dump_context->dump_type(this->type_);
12505 ast_dump_context->ostream() << "{";
12506 ast_dump_context->dump_expression_list(this->vals_);
12507 ast_dump_context->ostream() << "}";
12508}
12509
e440a328 12510// Make a struct composite literal. This used by the thunk code.
12511
12512Expression*
12513Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12514 Location location)
e440a328 12515{
c484d925 12516 go_assert(type->struct_type() != NULL);
e440a328 12517 return new Struct_construction_expression(type, vals, location);
12518}
12519
12520// Construct an array. This class is not used directly; instead we
12521// use the child classes, Fixed_array_construction_expression and
12522// Open_array_construction_expression.
12523
12524class Array_construction_expression : public Expression
12525{
12526 protected:
12527 Array_construction_expression(Expression_classification classification,
ffe743ca 12528 Type* type,
12529 const std::vector<unsigned long>* indexes,
12530 Expression_list* vals, Location location)
e440a328 12531 : Expression(classification, location),
ffe743ca 12532 type_(type), indexes_(indexes), vals_(vals)
12533 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
e440a328 12534
12535 public:
12536 // Return whether this is a constant initializer.
12537 bool
12538 is_constant_array() const;
12539
12540 // Return the number of elements.
12541 size_t
12542 element_count() const
12543 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12544
12545protected:
12546 int
12547 do_traverse(Traverse* traverse);
12548
12549 Type*
12550 do_type()
12551 { return this->type_; }
12552
12553 void
12554 do_determine_type(const Type_context*);
12555
12556 void
12557 do_check_types(Gogo*);
12558
e440a328 12559 void
12560 do_export(Export*) const;
12561
ffe743ca 12562 // The indexes.
12563 const std::vector<unsigned long>*
12564 indexes()
12565 { return this->indexes_; }
12566
e440a328 12567 // The list of values.
12568 Expression_list*
12569 vals()
12570 { return this->vals_; }
12571
12572 // Get a constructor tree for the array values.
12573 tree
12574 get_constructor_tree(Translate_context* context, tree type_tree);
12575
d751bb78 12576 void
12577 do_dump_expression(Ast_dump_context*) const;
12578
e440a328 12579 private:
12580 // The type of the array to construct.
12581 Type* type_;
ffe743ca 12582 // The list of indexes into the array, one for each value. This may
12583 // be NULL, in which case the indexes start at zero and increment.
12584 const std::vector<unsigned long>* indexes_;
12585 // The list of values. This may be NULL if there are no values.
e440a328 12586 Expression_list* vals_;
12587};
12588
12589// Traversal.
12590
12591int
12592Array_construction_expression::do_traverse(Traverse* traverse)
12593{
12594 if (this->vals_ != NULL
12595 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12596 return TRAVERSE_EXIT;
12597 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12598 return TRAVERSE_EXIT;
12599 return TRAVERSE_CONTINUE;
12600}
12601
12602// Return whether this is a constant initializer.
12603
12604bool
12605Array_construction_expression::is_constant_array() const
12606{
12607 if (this->vals_ == NULL)
12608 return true;
12609
12610 // There are no constant constructors for interfaces.
12611 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12612 return false;
12613
12614 for (Expression_list::const_iterator pv = this->vals_->begin();
12615 pv != this->vals_->end();
12616 ++pv)
12617 {
12618 if (*pv != NULL
12619 && !(*pv)->is_constant()
12620 && (!(*pv)->is_composite_literal()
12621 || (*pv)->is_nonconstant_composite_literal()))
12622 return false;
12623 }
12624 return true;
12625}
12626
12627// Final type determination.
12628
12629void
12630Array_construction_expression::do_determine_type(const Type_context*)
12631{
12632 if (this->vals_ == NULL)
12633 return;
12634 Type_context subcontext(this->type_->array_type()->element_type(), false);
12635 for (Expression_list::const_iterator pv = this->vals_->begin();
12636 pv != this->vals_->end();
12637 ++pv)
12638 {
12639 if (*pv != NULL)
12640 (*pv)->determine_type(&subcontext);
12641 }
12642}
12643
12644// Check types.
12645
12646void
12647Array_construction_expression::do_check_types(Gogo*)
12648{
12649 if (this->vals_ == NULL)
12650 return;
12651
12652 Array_type* at = this->type_->array_type();
12653 int i = 0;
12654 Type* element_type = at->element_type();
12655 for (Expression_list::const_iterator pv = this->vals_->begin();
12656 pv != this->vals_->end();
12657 ++pv, ++i)
12658 {
12659 if (*pv != NULL
12660 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12661 {
12662 error_at((*pv)->location(),
12663 "incompatible type for element %d in composite literal",
12664 i + 1);
12665 this->set_is_error();
12666 }
12667 }
e440a328 12668}
12669
12670// Get a constructor tree for the array values.
12671
12672tree
12673Array_construction_expression::get_constructor_tree(Translate_context* context,
12674 tree type_tree)
12675{
95f84544 12676 vec<constructor_elt, va_gc> *values;
12677 vec_alloc (values, (this->vals_ == NULL ? 0 : this->vals_->size()));
e440a328 12678 Type* element_type = this->type_->array_type()->element_type();
12679 bool is_constant = true;
12680 if (this->vals_ != NULL)
12681 {
12682 size_t i = 0;
ffe743ca 12683 std::vector<unsigned long>::const_iterator pi;
12684 if (this->indexes_ != NULL)
12685 pi = this->indexes_->begin();
e440a328 12686 for (Expression_list::const_iterator pv = this->vals_->begin();
12687 pv != this->vals_->end();
12688 ++pv, ++i)
12689 {
ffe743ca 12690 if (this->indexes_ != NULL)
12691 go_assert(pi != this->indexes_->end());
e82e4eb5 12692 constructor_elt empty = {NULL, NULL};
95f84544 12693 constructor_elt* elt = values->quick_push(empty);
ffe743ca 12694
12695 if (this->indexes_ == NULL)
12696 elt->index = size_int(i);
12697 else
12698 elt->index = size_int(*pi);
12699
e440a328 12700 if (*pv == NULL)
63697958 12701 {
12702 Gogo* gogo = context->gogo();
12703 Btype* ebtype = element_type->get_backend(gogo);
12704 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12705 elt->value = expr_to_tree(zv);
12706 }
e440a328 12707 else
12708 {
12709 tree value_tree = (*pv)->get_tree(context);
12710 elt->value = Expression::convert_for_assignment(context,
12711 element_type,
12712 (*pv)->type(),
12713 value_tree,
12714 this->location());
12715 }
12716 if (elt->value == error_mark_node)
12717 return error_mark_node;
12718 if (!TREE_CONSTANT(elt->value))
12719 is_constant = false;
ffe743ca 12720 if (this->indexes_ != NULL)
12721 ++pi;
e440a328 12722 }
ffe743ca 12723 if (this->indexes_ != NULL)
12724 go_assert(pi == this->indexes_->end());
e440a328 12725 }
12726
12727 tree ret = build_constructor(type_tree, values);
12728 if (is_constant)
12729 TREE_CONSTANT(ret) = 1;
12730 return ret;
12731}
12732
12733// Export an array construction.
12734
12735void
12736Array_construction_expression::do_export(Export* exp) const
12737{
12738 exp->write_c_string("convert(");
12739 exp->write_type(this->type_);
12740 if (this->vals_ != NULL)
12741 {
ffe743ca 12742 std::vector<unsigned long>::const_iterator pi;
12743 if (this->indexes_ != NULL)
12744 pi = this->indexes_->begin();
e440a328 12745 for (Expression_list::const_iterator pv = this->vals_->begin();
12746 pv != this->vals_->end();
12747 ++pv)
12748 {
12749 exp->write_c_string(", ");
ffe743ca 12750
12751 if (this->indexes_ != NULL)
12752 {
12753 char buf[100];
12754 snprintf(buf, sizeof buf, "%lu", *pi);
12755 exp->write_c_string(buf);
12756 exp->write_c_string(":");
12757 }
12758
e440a328 12759 if (*pv != NULL)
12760 (*pv)->export_expression(exp);
ffe743ca 12761
12762 if (this->indexes_ != NULL)
12763 ++pi;
e440a328 12764 }
12765 }
12766 exp->write_c_string(")");
12767}
12768
d751bb78 12769// Dump ast representation of an array construction expressin.
12770
12771void
12772Array_construction_expression::do_dump_expression(
12773 Ast_dump_context* ast_dump_context) const
12774{
ffe743ca 12775 Expression* length = this->type_->array_type()->length();
8b1c301d 12776
12777 ast_dump_context->ostream() << "[" ;
12778 if (length != NULL)
12779 {
12780 ast_dump_context->dump_expression(length);
12781 }
12782 ast_dump_context->ostream() << "]" ;
d751bb78 12783 ast_dump_context->dump_type(this->type_);
12784 ast_dump_context->ostream() << "{" ;
ffe743ca 12785 if (this->indexes_ == NULL)
12786 ast_dump_context->dump_expression_list(this->vals_);
12787 else
12788 {
12789 Expression_list::const_iterator pv = this->vals_->begin();
12790 for (std::vector<unsigned long>::const_iterator pi =
12791 this->indexes_->begin();
12792 pi != this->indexes_->end();
12793 ++pi, ++pv)
12794 {
12795 if (pi != this->indexes_->begin())
12796 ast_dump_context->ostream() << ", ";
12797 ast_dump_context->ostream() << *pi << ':';
12798 ast_dump_context->dump_expression(*pv);
12799 }
12800 }
d751bb78 12801 ast_dump_context->ostream() << "}" ;
12802
12803}
12804
e440a328 12805// Construct a fixed array.
12806
12807class Fixed_array_construction_expression :
12808 public Array_construction_expression
12809{
12810 public:
ffe743ca 12811 Fixed_array_construction_expression(Type* type,
12812 const std::vector<unsigned long>* indexes,
12813 Expression_list* vals, Location location)
e440a328 12814 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
ffe743ca 12815 type, indexes, vals, location)
12816 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12817
12818 protected:
12819 Expression*
12820 do_copy()
12821 {
12822 return new Fixed_array_construction_expression(this->type(),
ffe743ca 12823 this->indexes(),
e440a328 12824 (this->vals() == NULL
12825 ? NULL
12826 : this->vals()->copy()),
12827 this->location());
12828 }
12829
12830 tree
12831 do_get_tree(Translate_context*);
12832};
12833
12834// Return a tree for constructing a fixed array.
12835
12836tree
12837Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12838{
9f0e0513 12839 Type* type = this->type();
12840 Btype* btype = type->get_backend(context->gogo());
12841 return this->get_constructor_tree(context, type_to_tree(btype));
e440a328 12842}
12843
12844// Construct an open array.
12845
12846class Open_array_construction_expression : public Array_construction_expression
12847{
12848 public:
ffe743ca 12849 Open_array_construction_expression(Type* type,
12850 const std::vector<unsigned long>* indexes,
12851 Expression_list* vals, Location location)
e440a328 12852 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
ffe743ca 12853 type, indexes, vals, location)
12854 { go_assert(type->is_slice_type()); }
e440a328 12855
12856 protected:
12857 // Note that taking the address of an open array literal is invalid.
12858
12859 Expression*
12860 do_copy()
12861 {
12862 return new Open_array_construction_expression(this->type(),
ffe743ca 12863 this->indexes(),
e440a328 12864 (this->vals() == NULL
12865 ? NULL
12866 : this->vals()->copy()),
12867 this->location());
12868 }
12869
12870 tree
12871 do_get_tree(Translate_context*);
12872};
12873
12874// Return a tree for constructing an open array.
12875
12876tree
12877Open_array_construction_expression::do_get_tree(Translate_context* context)
12878{
f9c68f17 12879 Array_type* array_type = this->type()->array_type();
12880 if (array_type == NULL)
12881 {
c484d925 12882 go_assert(this->type()->is_error());
f9c68f17 12883 return error_mark_node;
12884 }
12885
12886 Type* element_type = array_type->element_type();
9f0e0513 12887 Btype* belement_type = element_type->get_backend(context->gogo());
12888 tree element_type_tree = type_to_tree(belement_type);
3d60812e 12889 if (element_type_tree == error_mark_node)
12890 return error_mark_node;
12891
e440a328 12892 tree values;
12893 tree length_tree;
12894 if (this->vals() == NULL || this->vals()->empty())
12895 {
12896 // We need to create a unique value.
12897 tree max = size_int(0);
12898 tree constructor_type = build_array_type(element_type_tree,
12899 build_index_type(max));
12900 if (constructor_type == error_mark_node)
12901 return error_mark_node;
95f84544 12902 vec<constructor_elt, va_gc> *vec;
12903 vec_alloc(vec, 1);
e82e4eb5 12904 constructor_elt empty = {NULL, NULL};
95f84544 12905 constructor_elt* elt = vec->quick_push(empty);
e440a328 12906 elt->index = size_int(0);
63697958 12907 Gogo* gogo = context->gogo();
12908 Btype* btype = element_type->get_backend(gogo);
12909 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
e440a328 12910 values = build_constructor(constructor_type, vec);
12911 if (TREE_CONSTANT(elt->value))
12912 TREE_CONSTANT(values) = 1;
12913 length_tree = size_int(0);
12914 }
12915 else
12916 {
ffe743ca 12917 unsigned long max_index;
12918 if (this->indexes() == NULL)
12919 max_index = this->vals()->size() - 1;
12920 else
00773463 12921 max_index = this->indexes()->back();
ffe743ca 12922 tree max_tree = size_int(max_index);
e440a328 12923 tree constructor_type = build_array_type(element_type_tree,
ffe743ca 12924 build_index_type(max_tree));
e440a328 12925 if (constructor_type == error_mark_node)
12926 return error_mark_node;
12927 values = this->get_constructor_tree(context, constructor_type);
ffe743ca 12928 length_tree = size_int(max_index + 1);
e440a328 12929 }
12930
12931 if (values == error_mark_node)
12932 return error_mark_node;
12933
12934 bool is_constant_initializer = TREE_CONSTANT(values);
d8829beb 12935
12936 // We have to copy the initial values into heap memory if we are in
12937 // a function or if the values are not constants. We also have to
12938 // copy them if they may contain pointers in a non-constant context,
12939 // as otherwise the garbage collector won't see them.
12940 bool copy_to_heap = (context->function() != NULL
12941 || !is_constant_initializer
12942 || (element_type->has_pointer()
12943 && !context->is_const()));
e440a328 12944
12945 if (is_constant_initializer)
12946 {
b13c66cd 12947 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
e440a328 12948 create_tmp_var_name("C"), TREE_TYPE(values));
12949 DECL_EXTERNAL(tmp) = 0;
12950 TREE_PUBLIC(tmp) = 0;
12951 TREE_STATIC(tmp) = 1;
12952 DECL_ARTIFICIAL(tmp) = 1;
d8829beb 12953 if (copy_to_heap)
e440a328 12954 {
d8829beb 12955 // If we are not copying the value to the heap, we will only
12956 // initialize the value once, so we can use this directly
12957 // rather than copying it. In that case we can't make it
12958 // read-only, because the program is permitted to change it.
e440a328 12959 TREE_READONLY(tmp) = 1;
12960 TREE_CONSTANT(tmp) = 1;
12961 }
12962 DECL_INITIAL(tmp) = values;
12963 rest_of_decl_compilation(tmp, 1, 0);
12964 values = tmp;
12965 }
12966
12967 tree space;
12968 tree set;
d8829beb 12969 if (!copy_to_heap)
e440a328 12970 {
d8829beb 12971 // the initializer will only run once.
e440a328 12972 space = build_fold_addr_expr(values);
12973 set = NULL_TREE;
12974 }
12975 else
12976 {
12977 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
12978 space = context->gogo()->allocate_memory(element_type, memsize,
12979 this->location());
12980 space = save_expr(space);
12981
12982 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
b13c66cd 12983 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12984 s);
e440a328 12985 TREE_THIS_NOTRAP(ref) = 1;
12986 set = build2(MODIFY_EXPR, void_type_node, ref, values);
12987 }
12988
12989 // Build a constructor for the open array.
12990
9f0e0513 12991 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
3d60812e 12992 if (type_tree == error_mark_node)
12993 return error_mark_node;
c484d925 12994 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
e440a328 12995
95f84544 12996 vec<constructor_elt, va_gc> *init;
12997 vec_alloc(init, 3);
e440a328 12998
e82e4eb5 12999 constructor_elt empty = {NULL, NULL};
95f84544 13000 constructor_elt* elt = init->quick_push(empty);
e440a328 13001 tree field = TYPE_FIELDS(type_tree);
c484d925 13002 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
e440a328 13003 elt->index = field;
13004 elt->value = fold_convert(TREE_TYPE(field), space);
13005
95f84544 13006 elt = init->quick_push(empty);
e440a328 13007 field = DECL_CHAIN(field);
c484d925 13008 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
e440a328 13009 elt->index = field;
13010 elt->value = fold_convert(TREE_TYPE(field), length_tree);
13011
95f84544 13012 elt = init->quick_push(empty);
e440a328 13013 field = DECL_CHAIN(field);
c484d925 13014 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
e440a328 13015 elt->index = field;
13016 elt->value = fold_convert(TREE_TYPE(field), length_tree);
13017
13018 tree constructor = build_constructor(type_tree, init);
3d60812e 13019 if (constructor == error_mark_node)
13020 return error_mark_node;
d8829beb 13021 if (!copy_to_heap)
e440a328 13022 TREE_CONSTANT(constructor) = 1;
13023
13024 if (set == NULL_TREE)
13025 return constructor;
13026 else
13027 return build2(COMPOUND_EXPR, type_tree, set, constructor);
13028}
13029
13030// Make a slice composite literal. This is used by the type
13031// descriptor code.
13032
13033Expression*
13034Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 13035 Location location)
e440a328 13036{
411eb89e 13037 go_assert(type->is_slice_type());
ffe743ca 13038 return new Open_array_construction_expression(type, NULL, vals, location);
e440a328 13039}
13040
13041// Construct a map.
13042
13043class Map_construction_expression : public Expression
13044{
13045 public:
13046 Map_construction_expression(Type* type, Expression_list* vals,
b13c66cd 13047 Location location)
e440a328 13048 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
13049 type_(type), vals_(vals)
c484d925 13050 { go_assert(vals == NULL || vals->size() % 2 == 0); }
e440a328 13051
13052 protected:
13053 int
13054 do_traverse(Traverse* traverse);
13055
13056 Type*
13057 do_type()
13058 { return this->type_; }
13059
13060 void
13061 do_determine_type(const Type_context*);
13062
13063 void
13064 do_check_types(Gogo*);
13065
13066 Expression*
13067 do_copy()
13068 {
13069 return new Map_construction_expression(this->type_, this->vals_->copy(),
13070 this->location());
13071 }
13072
13073 tree
13074 do_get_tree(Translate_context*);
13075
13076 void
13077 do_export(Export*) const;
13078
d751bb78 13079 void
13080 do_dump_expression(Ast_dump_context*) const;
13081
e440a328 13082 private:
13083 // The type of the map to construct.
13084 Type* type_;
13085 // The list of values.
13086 Expression_list* vals_;
13087};
13088
13089// Traversal.
13090
13091int
13092Map_construction_expression::do_traverse(Traverse* traverse)
13093{
13094 if (this->vals_ != NULL
13095 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13096 return TRAVERSE_EXIT;
13097 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13098 return TRAVERSE_EXIT;
13099 return TRAVERSE_CONTINUE;
13100}
13101
13102// Final type determination.
13103
13104void
13105Map_construction_expression::do_determine_type(const Type_context*)
13106{
13107 if (this->vals_ == NULL)
13108 return;
13109
13110 Map_type* mt = this->type_->map_type();
13111 Type_context key_context(mt->key_type(), false);
13112 Type_context val_context(mt->val_type(), false);
13113 for (Expression_list::const_iterator pv = this->vals_->begin();
13114 pv != this->vals_->end();
13115 ++pv)
13116 {
13117 (*pv)->determine_type(&key_context);
13118 ++pv;
13119 (*pv)->determine_type(&val_context);
13120 }
13121}
13122
13123// Check types.
13124
13125void
13126Map_construction_expression::do_check_types(Gogo*)
13127{
13128 if (this->vals_ == NULL)
13129 return;
13130
13131 Map_type* mt = this->type_->map_type();
13132 int i = 0;
13133 Type* key_type = mt->key_type();
13134 Type* val_type = mt->val_type();
13135 for (Expression_list::const_iterator pv = this->vals_->begin();
13136 pv != this->vals_->end();
13137 ++pv, ++i)
13138 {
13139 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13140 {
13141 error_at((*pv)->location(),
13142 "incompatible type for element %d key in map construction",
13143 i + 1);
13144 this->set_is_error();
13145 }
13146 ++pv;
13147 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13148 {
13149 error_at((*pv)->location(),
13150 ("incompatible type for element %d value "
13151 "in map construction"),
13152 i + 1);
13153 this->set_is_error();
13154 }
13155 }
13156}
13157
13158// Return a tree for constructing a map.
13159
13160tree
13161Map_construction_expression::do_get_tree(Translate_context* context)
13162{
13163 Gogo* gogo = context->gogo();
b13c66cd 13164 Location loc = this->location();
e440a328 13165
13166 Map_type* mt = this->type_->map_type();
13167
13168 // Build a struct to hold the key and value.
13169 tree struct_type = make_node(RECORD_TYPE);
13170
13171 Type* key_type = mt->key_type();
13172 tree id = get_identifier("__key");
9f0e0513 13173 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
5845bde6 13174 if (key_type_tree == error_mark_node)
13175 return error_mark_node;
b13c66cd 13176 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
13177 key_type_tree);
e440a328 13178 DECL_CONTEXT(key_field) = struct_type;
13179 TYPE_FIELDS(struct_type) = key_field;
13180
13181 Type* val_type = mt->val_type();
13182 id = get_identifier("__val");
9f0e0513 13183 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
5845bde6 13184 if (val_type_tree == error_mark_node)
13185 return error_mark_node;
b13c66cd 13186 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
13187 val_type_tree);
e440a328 13188 DECL_CONTEXT(val_field) = struct_type;
13189 DECL_CHAIN(key_field) = val_field;
13190
13191 layout_type(struct_type);
13192
13193 bool is_constant = true;
13194 size_t i = 0;
13195 tree valaddr;
13196 tree make_tmp;
13197
13198 if (this->vals_ == NULL || this->vals_->empty())
13199 {
13200 valaddr = null_pointer_node;
13201 make_tmp = NULL_TREE;
13202 }
13203 else
13204 {
95f84544 13205 vec<constructor_elt, va_gc> *values;
13206 vec_alloc(values, this->vals_->size() / 2);
e440a328 13207
13208 for (Expression_list::const_iterator pv = this->vals_->begin();
13209 pv != this->vals_->end();
13210 ++pv, ++i)
13211 {
13212 bool one_is_constant = true;
13213
95f84544 13214 vec<constructor_elt, va_gc> *one;
13215 vec_alloc(one, 2);
e440a328 13216
e82e4eb5 13217 constructor_elt empty = {NULL, NULL};
95f84544 13218 constructor_elt* elt = one->quick_push(empty);
e440a328 13219 elt->index = key_field;
13220 tree val_tree = (*pv)->get_tree(context);
13221 elt->value = Expression::convert_for_assignment(context, key_type,
13222 (*pv)->type(),
13223 val_tree, loc);
13224 if (elt->value == error_mark_node)
13225 return error_mark_node;
13226 if (!TREE_CONSTANT(elt->value))
13227 one_is_constant = false;
13228
13229 ++pv;
13230
95f84544 13231 elt = one->quick_push(empty);
e440a328 13232 elt->index = val_field;
13233 val_tree = (*pv)->get_tree(context);
13234 elt->value = Expression::convert_for_assignment(context, val_type,
13235 (*pv)->type(),
13236 val_tree, loc);
13237 if (elt->value == error_mark_node)
13238 return error_mark_node;
13239 if (!TREE_CONSTANT(elt->value))
13240 one_is_constant = false;
13241
95f84544 13242 elt = values->quick_push(empty);
e440a328 13243 elt->index = size_int(i);
13244 elt->value = build_constructor(struct_type, one);
13245 if (one_is_constant)
13246 TREE_CONSTANT(elt->value) = 1;
13247 else
13248 is_constant = false;
13249 }
13250
13251 tree index_type = build_index_type(size_int(i - 1));
13252 tree array_type = build_array_type(struct_type, index_type);
13253 tree init = build_constructor(array_type, values);
13254 if (is_constant)
13255 TREE_CONSTANT(init) = 1;
13256 tree tmp;
13257 if (current_function_decl != NULL)
13258 {
13259 tmp = create_tmp_var(array_type, get_name(array_type));
13260 DECL_INITIAL(tmp) = init;
b13c66cd 13261 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
13262 void_type_node, tmp);
e440a328 13263 TREE_ADDRESSABLE(tmp) = 1;
13264 }
13265 else
13266 {
b13c66cd 13267 tmp = build_decl(loc.gcc_location(), VAR_DECL,
13268 create_tmp_var_name("M"), array_type);
e440a328 13269 DECL_EXTERNAL(tmp) = 0;
13270 TREE_PUBLIC(tmp) = 0;
13271 TREE_STATIC(tmp) = 1;
13272 DECL_ARTIFICIAL(tmp) = 1;
13273 if (!TREE_CONSTANT(init))
b13c66cd 13274 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
13275 void_type_node, tmp, init);
e440a328 13276 else
13277 {
13278 TREE_READONLY(tmp) = 1;
13279 TREE_CONSTANT(tmp) = 1;
13280 DECL_INITIAL(tmp) = init;
13281 make_tmp = NULL_TREE;
13282 }
13283 rest_of_decl_compilation(tmp, 1, 0);
13284 }
13285
13286 valaddr = build_fold_addr_expr(tmp);
13287 }
13288
175a4612 13289 Bexpression* bdescriptor = mt->map_descriptor_pointer(gogo, loc);
13290 tree descriptor = expr_to_tree(bdescriptor);
e440a328 13291
9f0e0513 13292 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
5845bde6 13293 if (type_tree == error_mark_node)
13294 return error_mark_node;
e440a328 13295
13296 static tree construct_map_fndecl;
13297 tree call = Gogo::call_builtin(&construct_map_fndecl,
13298 loc,
13299 "__go_construct_map",
13300 6,
13301 type_tree,
13302 TREE_TYPE(descriptor),
13303 descriptor,
13304 sizetype,
13305 size_int(i),
13306 sizetype,
13307 TYPE_SIZE_UNIT(struct_type),
13308 sizetype,
13309 byte_position(val_field),
13310 sizetype,
13311 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
13312 const_ptr_type_node,
13313 fold_convert(const_ptr_type_node, valaddr));
5fb82b5e 13314 if (call == error_mark_node)
13315 return error_mark_node;
e440a328 13316
13317 tree ret;
13318 if (make_tmp == NULL)
13319 ret = call;
13320 else
b13c66cd 13321 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
13322 make_tmp, call);
e440a328 13323 return ret;
13324}
13325
13326// Export an array construction.
13327
13328void
13329Map_construction_expression::do_export(Export* exp) const
13330{
13331 exp->write_c_string("convert(");
13332 exp->write_type(this->type_);
13333 for (Expression_list::const_iterator pv = this->vals_->begin();
13334 pv != this->vals_->end();
13335 ++pv)
13336 {
13337 exp->write_c_string(", ");
13338 (*pv)->export_expression(exp);
13339 }
13340 exp->write_c_string(")");
13341}
13342
d751bb78 13343// Dump ast representation for a map construction expression.
13344
13345void
13346Map_construction_expression::do_dump_expression(
13347 Ast_dump_context* ast_dump_context) const
13348{
d751bb78 13349 ast_dump_context->ostream() << "{" ;
8b1c301d 13350 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 13351 ast_dump_context->ostream() << "}";
13352}
13353
e440a328 13354// A general composite literal. This is lowered to a type specific
13355// version.
13356
13357class Composite_literal_expression : public Parser_expression
13358{
13359 public:
13360 Composite_literal_expression(Type* type, int depth, bool has_keys,
62750cd5 13361 Expression_list* vals, bool all_are_names,
13362 Location location)
e440a328 13363 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
62750cd5 13364 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
13365 all_are_names_(all_are_names)
e440a328 13366 { }
13367
13368 protected:
13369 int
13370 do_traverse(Traverse* traverse);
13371
13372 Expression*
ceeb4318 13373 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 13374
13375 Expression*
13376 do_copy()
13377 {
13378 return new Composite_literal_expression(this->type_, this->depth_,
13379 this->has_keys_,
13380 (this->vals_ == NULL
13381 ? NULL
13382 : this->vals_->copy()),
62750cd5 13383 this->all_are_names_,
e440a328 13384 this->location());
13385 }
13386
d751bb78 13387 void
13388 do_dump_expression(Ast_dump_context*) const;
13389
e440a328 13390 private:
13391 Expression*
81c4b26b 13392 lower_struct(Gogo*, Type*);
e440a328 13393
13394 Expression*
113ef6a5 13395 lower_array(Type*);
e440a328 13396
13397 Expression*
ffe743ca 13398 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
e440a328 13399
13400 Expression*
ceeb4318 13401 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
e440a328 13402
13403 // The type of the composite literal.
13404 Type* type_;
13405 // The depth within a list of composite literals within a composite
13406 // literal, when the type is omitted.
13407 int depth_;
13408 // The values to put in the composite literal.
13409 Expression_list* vals_;
13410 // If this is true, then VALS_ is a list of pairs: a key and a
13411 // value. In an array initializer, a missing key will be NULL.
13412 bool has_keys_;
62750cd5 13413 // If this is true, then HAS_KEYS_ is true, and every key is a
13414 // simple identifier.
13415 bool all_are_names_;
e440a328 13416};
13417
13418// Traversal.
13419
13420int
13421Composite_literal_expression::do_traverse(Traverse* traverse)
13422{
dbffccfc 13423 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 13424 return TRAVERSE_EXIT;
dbffccfc 13425
13426 // If this is a struct composite literal with keys, then the keys
13427 // are field names, not expressions. We don't want to traverse them
13428 // in that case. If we do, we can give an erroneous error "variable
13429 // initializer refers to itself." See bug482.go in the testsuite.
13430 if (this->has_keys_ && this->vals_ != NULL)
13431 {
13432 // The type may not be resolvable at this point.
13433 Type* type = this->type_;
13434 while (true)
13435 {
13436 if (type->classification() == Type::TYPE_NAMED)
13437 type = type->named_type()->real_type();
13438 else if (type->classification() == Type::TYPE_FORWARD)
13439 {
13440 Type* t = type->forwarded();
13441 if (t == type)
13442 break;
13443 type = t;
13444 }
13445 else
13446 break;
13447 }
13448
13449 if (type->classification() == Type::TYPE_STRUCT)
13450 {
13451 Expression_list::iterator p = this->vals_->begin();
13452 while (p != this->vals_->end())
13453 {
13454 // Skip key.
13455 ++p;
13456 go_assert(p != this->vals_->end());
13457 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13458 return TRAVERSE_EXIT;
13459 ++p;
13460 }
13461 return TRAVERSE_CONTINUE;
13462 }
13463 }
13464
13465 if (this->vals_ != NULL)
13466 return this->vals_->traverse(traverse);
13467
13468 return TRAVERSE_CONTINUE;
e440a328 13469}
13470
13471// Lower a generic composite literal into a specific version based on
13472// the type.
13473
13474Expression*
ceeb4318 13475Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13476 Statement_inserter* inserter, int)
e440a328 13477{
13478 Type* type = this->type_;
13479
13480 for (int depth = this->depth_; depth > 0; --depth)
13481 {
13482 if (type->array_type() != NULL)
13483 type = type->array_type()->element_type();
13484 else if (type->map_type() != NULL)
13485 type = type->map_type()->val_type();
13486 else
13487 {
5c13bd80 13488 if (!type->is_error())
e440a328 13489 error_at(this->location(),
13490 ("may only omit types within composite literals "
13491 "of slice, array, or map type"));
13492 return Expression::make_error(this->location());
13493 }
13494 }
13495
e00772b3 13496 Type *pt = type->points_to();
13497 bool is_pointer = false;
13498 if (pt != NULL)
13499 {
13500 is_pointer = true;
13501 type = pt;
13502 }
13503
13504 Expression* ret;
5c13bd80 13505 if (type->is_error())
e440a328 13506 return Expression::make_error(this->location());
13507 else if (type->struct_type() != NULL)
e00772b3 13508 ret = this->lower_struct(gogo, type);
e440a328 13509 else if (type->array_type() != NULL)
113ef6a5 13510 ret = this->lower_array(type);
e440a328 13511 else if (type->map_type() != NULL)
e00772b3 13512 ret = this->lower_map(gogo, function, inserter, type);
e440a328 13513 else
13514 {
13515 error_at(this->location(),
13516 ("expected struct, slice, array, or map type "
13517 "for composite literal"));
13518 return Expression::make_error(this->location());
13519 }
e00772b3 13520
13521 if (is_pointer)
13522 ret = Expression::make_heap_composite(ret, this->location());
13523
13524 return ret;
e440a328 13525}
13526
13527// Lower a struct composite literal.
13528
13529Expression*
81c4b26b 13530Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13531{
b13c66cd 13532 Location location = this->location();
e440a328 13533 Struct_type* st = type->struct_type();
13534 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13535 {
e6013c28 13536 if (this->vals_ != NULL
13537 && !this->vals_->empty()
13538 && type->named_type() != NULL
13539 && type->named_type()->named_object()->package() != NULL)
13540 {
13541 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13542 pf != st->fields()->end();
13543 ++pf)
07daa4e7 13544 {
e6013c28 13545 if (Gogo::is_hidden_name(pf->field_name()))
07daa4e7 13546 error_at(this->location(),
e6013c28 13547 "assignment of unexported field %qs in %qs literal",
13548 Gogo::message_name(pf->field_name()).c_str(),
13549 type->named_type()->message_name().c_str());
07daa4e7 13550 }
13551 }
13552
13553 return new Struct_construction_expression(type, this->vals_, location);
13554 }
e440a328 13555
13556 size_t field_count = st->field_count();
13557 std::vector<Expression*> vals(field_count);
0c4f5a19 13558 std::vector<int>* traverse_order = new(std::vector<int>);
e440a328 13559 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13560 Expression* external_expr = NULL;
13561 const Named_object* external_no = NULL;
e440a328 13562 while (p != this->vals_->end())
13563 {
13564 Expression* name_expr = *p;
13565
13566 ++p;
c484d925 13567 go_assert(p != this->vals_->end());
e440a328 13568 Expression* val = *p;
13569
13570 ++p;
13571
13572 if (name_expr == NULL)
13573 {
13574 error_at(val->location(), "mixture of field and value initializers");
13575 return Expression::make_error(location);
13576 }
13577
13578 bool bad_key = false;
13579 std::string name;
81c4b26b 13580 const Named_object* no = NULL;
e440a328 13581 switch (name_expr->classification())
13582 {
13583 case EXPRESSION_UNKNOWN_REFERENCE:
13584 name = name_expr->unknown_expression()->name();
13585 break;
13586
13587 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13588 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13589 break;
13590
13591 case EXPRESSION_TYPE:
13592 {
13593 Type* t = name_expr->type();
13594 Named_type* nt = t->named_type();
13595 if (nt == NULL)
13596 bad_key = true;
13597 else
81c4b26b 13598 no = nt->named_object();
e440a328 13599 }
13600 break;
13601
13602 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13603 no = name_expr->var_expression()->named_object();
e440a328 13604 break;
13605
13606 case EXPRESSION_FUNC_REFERENCE:
81c4b26b 13607 no = name_expr->func_expression()->named_object();
e440a328 13608 break;
13609
13610 case EXPRESSION_UNARY:
13611 // If there is a local variable around with the same name as
13612 // the field, and this occurs in the closure, then the
13613 // parser may turn the field reference into an indirection
13614 // through the closure. FIXME: This is a mess.
13615 {
13616 bad_key = true;
13617 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13618 if (ue->op() == OPERATOR_MULT)
13619 {
13620 Field_reference_expression* fre =
13621 ue->operand()->field_reference_expression();
13622 if (fre != NULL)
13623 {
13624 Struct_type* st =
13625 fre->expr()->type()->deref()->struct_type();
13626 if (st != NULL)
13627 {
13628 const Struct_field* sf = st->field(fre->field_index());
13629 name = sf->field_name();
2d29d278 13630
13631 // See below. FIXME.
13632 if (!Gogo::is_hidden_name(name)
13633 && name[0] >= 'a'
13634 && name[0] <= 'z')
13635 {
13636 if (gogo->lookup_global(name.c_str()) != NULL)
13637 name = gogo->pack_hidden_name(name, false);
13638 }
13639
e440a328 13640 char buf[20];
13641 snprintf(buf, sizeof buf, "%u", fre->field_index());
13642 size_t buflen = strlen(buf);
13643 if (name.compare(name.length() - buflen, buflen, buf)
13644 == 0)
13645 {
13646 name = name.substr(0, name.length() - buflen);
13647 bad_key = false;
13648 }
13649 }
13650 }
13651 }
13652 }
13653 break;
13654
13655 default:
13656 bad_key = true;
13657 break;
13658 }
13659 if (bad_key)
13660 {
13661 error_at(name_expr->location(), "expected struct field name");
13662 return Expression::make_error(location);
13663 }
13664
81c4b26b 13665 if (no != NULL)
13666 {
62750cd5 13667 if (no->package() != NULL && external_expr == NULL)
13668 {
13669 external_expr = name_expr;
13670 external_no = no;
13671 }
13672
81c4b26b 13673 name = no->name();
13674
13675 // A predefined name won't be packed. If it starts with a
13676 // lower case letter we need to check for that case, because
2d29d278 13677 // the field name will be packed. FIXME.
81c4b26b 13678 if (!Gogo::is_hidden_name(name)
13679 && name[0] >= 'a'
13680 && name[0] <= 'z')
13681 {
13682 Named_object* gno = gogo->lookup_global(name.c_str());
13683 if (gno == no)
13684 name = gogo->pack_hidden_name(name, false);
13685 }
13686 }
13687
e440a328 13688 unsigned int index;
13689 const Struct_field* sf = st->find_local_field(name, &index);
13690 if (sf == NULL)
13691 {
13692 error_at(name_expr->location(), "unknown field %qs in %qs",
13693 Gogo::message_name(name).c_str(),
13694 (type->named_type() != NULL
13695 ? type->named_type()->message_name().c_str()
13696 : "unnamed struct"));
13697 return Expression::make_error(location);
13698 }
13699 if (vals[index] != NULL)
13700 {
13701 error_at(name_expr->location(),
13702 "duplicate value for field %qs in %qs",
13703 Gogo::message_name(name).c_str(),
13704 (type->named_type() != NULL
13705 ? type->named_type()->message_name().c_str()
13706 : "unnamed struct"));
13707 return Expression::make_error(location);
13708 }
13709
07daa4e7 13710 if (type->named_type() != NULL
13711 && type->named_type()->named_object()->package() != NULL
13712 && Gogo::is_hidden_name(sf->field_name()))
13713 error_at(name_expr->location(),
13714 "assignment of unexported field %qs in %qs literal",
13715 Gogo::message_name(sf->field_name()).c_str(),
13716 type->named_type()->message_name().c_str());
07daa4e7 13717
e440a328 13718 vals[index] = val;
0c4f5a19 13719 traverse_order->push_back(index);
e440a328 13720 }
13721
62750cd5 13722 if (!this->all_are_names_)
13723 {
13724 // This is a weird case like bug462 in the testsuite.
13725 if (external_expr == NULL)
13726 error_at(this->location(), "unknown field in %qs literal",
13727 (type->named_type() != NULL
13728 ? type->named_type()->message_name().c_str()
13729 : "unnamed struct"));
13730 else
13731 error_at(external_expr->location(), "unknown field %qs in %qs",
13732 external_no->message_name().c_str(),
13733 (type->named_type() != NULL
13734 ? type->named_type()->message_name().c_str()
13735 : "unnamed struct"));
13736 return Expression::make_error(location);
13737 }
13738
e440a328 13739 Expression_list* list = new Expression_list;
13740 list->reserve(field_count);
13741 for (size_t i = 0; i < field_count; ++i)
13742 list->push_back(vals[i]);
13743
0c4f5a19 13744 Struct_construction_expression* ret =
13745 new Struct_construction_expression(type, list, location);
13746 ret->set_traverse_order(traverse_order);
13747 return ret;
e440a328 13748}
13749
00773463 13750// Used to sort an index/value array.
13751
13752class Index_value_compare
13753{
13754 public:
13755 bool
13756 operator()(const std::pair<unsigned long, Expression*>& a,
13757 const std::pair<unsigned long, Expression*>& b)
13758 { return a.first < b.first; }
13759};
13760
e440a328 13761// Lower an array composite literal.
13762
13763Expression*
113ef6a5 13764Composite_literal_expression::lower_array(Type* type)
e440a328 13765{
b13c66cd 13766 Location location = this->location();
e440a328 13767 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13768 return this->make_array(type, NULL, this->vals_);
e440a328 13769
ffe743ca 13770 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13771 indexes->reserve(this->vals_->size());
00773463 13772 bool indexes_out_of_order = false;
ffe743ca 13773 Expression_list* vals = new Expression_list();
13774 vals->reserve(this->vals_->size());
e440a328 13775 unsigned long index = 0;
13776 Expression_list::const_iterator p = this->vals_->begin();
13777 while (p != this->vals_->end())
13778 {
13779 Expression* index_expr = *p;
13780
13781 ++p;
c484d925 13782 go_assert(p != this->vals_->end());
e440a328 13783 Expression* val = *p;
13784
13785 ++p;
13786
ffe743ca 13787 if (index_expr == NULL)
13788 {
13789 if (!indexes->empty())
13790 indexes->push_back(index);
13791 }
13792 else
e440a328 13793 {
ffe743ca 13794 if (indexes->empty() && !vals->empty())
13795 {
13796 for (size_t i = 0; i < vals->size(); ++i)
13797 indexes->push_back(i);
13798 }
13799
0c77715b 13800 Numeric_constant nc;
13801 if (!index_expr->numeric_constant_value(&nc))
e440a328 13802 {
e440a328 13803 error_at(index_expr->location(),
13804 "index expression is not integer constant");
13805 return Expression::make_error(location);
13806 }
6f6d9955 13807
0c77715b 13808 switch (nc.to_unsigned_long(&index))
e440a328 13809 {
0c77715b 13810 case Numeric_constant::NC_UL_VALID:
13811 break;
13812 case Numeric_constant::NC_UL_NOTINT:
13813 error_at(index_expr->location(),
13814 "index expression is not integer constant");
13815 return Expression::make_error(location);
13816 case Numeric_constant::NC_UL_NEGATIVE:
e440a328 13817 error_at(index_expr->location(), "index expression is negative");
13818 return Expression::make_error(location);
0c77715b 13819 case Numeric_constant::NC_UL_BIG:
e440a328 13820 error_at(index_expr->location(), "index value overflow");
13821 return Expression::make_error(location);
0c77715b 13822 default:
13823 go_unreachable();
e440a328 13824 }
6f6d9955 13825
13826 Named_type* ntype = Type::lookup_integer_type("int");
13827 Integer_type* inttype = ntype->integer_type();
0c77715b 13828 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13829 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13830 {
6f6d9955 13831 error_at(index_expr->location(), "index value overflow");
13832 return Expression::make_error(location);
13833 }
13834
ffe743ca 13835 if (std::find(indexes->begin(), indexes->end(), index)
13836 != indexes->end())
e440a328 13837 {
ffe743ca 13838 error_at(index_expr->location(), "duplicate value for index %lu",
e440a328 13839 index);
13840 return Expression::make_error(location);
13841 }
ffe743ca 13842
00773463 13843 if (!indexes->empty() && index < indexes->back())
13844 indexes_out_of_order = true;
13845
ffe743ca 13846 indexes->push_back(index);
e440a328 13847 }
13848
ffe743ca 13849 vals->push_back(val);
13850
e440a328 13851 ++index;
13852 }
13853
ffe743ca 13854 if (indexes->empty())
13855 {
13856 delete indexes;
13857 indexes = NULL;
13858 }
e440a328 13859
00773463 13860 if (indexes_out_of_order)
13861 {
13862 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13863
13864 V v;
13865 v.reserve(indexes->size());
13866 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13867 for (Expression_list::const_iterator pe = vals->begin();
13868 pe != vals->end();
13869 ++pe, ++pi)
13870 v.push_back(std::make_pair(*pi, *pe));
13871
13872 std::sort(v.begin(), v.end(), Index_value_compare());
13873
13874 delete indexes;
13875 delete vals;
13876 indexes = new std::vector<unsigned long>();
13877 indexes->reserve(v.size());
13878 vals = new Expression_list();
13879 vals->reserve(v.size());
13880
13881 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13882 {
13883 indexes->push_back(p->first);
13884 vals->push_back(p->second);
13885 }
13886 }
13887
ffe743ca 13888 return this->make_array(type, indexes, vals);
e440a328 13889}
13890
13891// Actually build the array composite literal. This handles
13892// [...]{...}.
13893
13894Expression*
ffe743ca 13895Composite_literal_expression::make_array(
13896 Type* type,
13897 const std::vector<unsigned long>* indexes,
13898 Expression_list* vals)
e440a328 13899{
b13c66cd 13900 Location location = this->location();
e440a328 13901 Array_type* at = type->array_type();
ffe743ca 13902
e440a328 13903 if (at->length() != NULL && at->length()->is_nil_expression())
13904 {
ffe743ca 13905 size_t size;
13906 if (vals == NULL)
13907 size = 0;
00773463 13908 else if (indexes != NULL)
13909 size = indexes->back() + 1;
13910 else
ffe743ca 13911 {
13912 size = vals->size();
13913 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13914 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13915 && size >> (it->bits() - 1) != 0)
13916 {
13917 error_at(location, "too many elements in composite literal");
13918 return Expression::make_error(location);
13919 }
13920 }
ffe743ca 13921
e440a328 13922 mpz_t vlen;
13923 mpz_init_set_ui(vlen, size);
13924 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13925 mpz_clear(vlen);
13926 at = Type::make_array_type(at->element_type(), elen);
13927 type = at;
13928 }
ffe743ca 13929 else if (at->length() != NULL
13930 && !at->length()->is_error_expression()
13931 && this->vals_ != NULL)
13932 {
13933 Numeric_constant nc;
13934 unsigned long val;
13935 if (at->length()->numeric_constant_value(&nc)
13936 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13937 {
13938 if (indexes == NULL)
13939 {
13940 if (this->vals_->size() > val)
13941 {
13942 error_at(location, "too many elements in composite literal");
13943 return Expression::make_error(location);
13944 }
13945 }
13946 else
13947 {
00773463 13948 unsigned long max = indexes->back();
ffe743ca 13949 if (max >= val)
13950 {
13951 error_at(location,
13952 ("some element keys in composite literal "
13953 "are out of range"));
13954 return Expression::make_error(location);
13955 }
13956 }
13957 }
13958 }
13959
e440a328 13960 if (at->length() != NULL)
ffe743ca 13961 return new Fixed_array_construction_expression(type, indexes, vals,
13962 location);
e440a328 13963 else
ffe743ca 13964 return new Open_array_construction_expression(type, indexes, vals,
13965 location);
e440a328 13966}
13967
13968// Lower a map composite literal.
13969
13970Expression*
a287720d 13971Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13972 Statement_inserter* inserter,
a287720d 13973 Type* type)
e440a328 13974{
b13c66cd 13975 Location location = this->location();
e440a328 13976 if (this->vals_ != NULL)
13977 {
13978 if (!this->has_keys_)
13979 {
13980 error_at(location, "map composite literal must have keys");
13981 return Expression::make_error(location);
13982 }
13983
a287720d 13984 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13985 p != this->vals_->end();
13986 p += 2)
13987 {
13988 if (*p == NULL)
13989 {
13990 ++p;
13991 error_at((*p)->location(),
13992 "map composite literal must have keys for every value");
13993 return Expression::make_error(location);
13994 }
a287720d 13995 // Make sure we have lowered the key; it may not have been
13996 // lowered in order to handle keys for struct composite
13997 // literals. Lower it now to get the right error message.
13998 if ((*p)->unknown_expression() != NULL)
13999 {
14000 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 14001 gogo->lower_expression(function, inserter, &*p);
c484d925 14002 go_assert((*p)->is_error_expression());
a287720d 14003 return Expression::make_error(location);
14004 }
e440a328 14005 }
14006 }
14007
14008 return new Map_construction_expression(type, this->vals_, location);
14009}
14010
d751bb78 14011// Dump ast representation for a composite literal expression.
14012
14013void
14014Composite_literal_expression::do_dump_expression(
14015 Ast_dump_context* ast_dump_context) const
14016{
8b1c301d 14017 ast_dump_context->ostream() << "composite(";
d751bb78 14018 ast_dump_context->dump_type(this->type_);
14019 ast_dump_context->ostream() << ", {";
8b1c301d 14020 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 14021 ast_dump_context->ostream() << "})";
14022}
14023
e440a328 14024// Make a composite literal expression.
14025
14026Expression*
14027Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 14028 Expression_list* vals, bool all_are_names,
b13c66cd 14029 Location location)
e440a328 14030{
14031 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 14032 all_are_names, location);
e440a328 14033}
14034
14035// Return whether this expression is a composite literal.
14036
14037bool
14038Expression::is_composite_literal() const
14039{
14040 switch (this->classification_)
14041 {
14042 case EXPRESSION_COMPOSITE_LITERAL:
14043 case EXPRESSION_STRUCT_CONSTRUCTION:
14044 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14045 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
14046 case EXPRESSION_MAP_CONSTRUCTION:
14047 return true;
14048 default:
14049 return false;
14050 }
14051}
14052
14053// Return whether this expression is a composite literal which is not
14054// constant.
14055
14056bool
14057Expression::is_nonconstant_composite_literal() const
14058{
14059 switch (this->classification_)
14060 {
14061 case EXPRESSION_STRUCT_CONSTRUCTION:
14062 {
14063 const Struct_construction_expression *psce =
14064 static_cast<const Struct_construction_expression*>(this);
14065 return !psce->is_constant_struct();
14066 }
14067 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14068 {
14069 const Fixed_array_construction_expression *pace =
14070 static_cast<const Fixed_array_construction_expression*>(this);
14071 return !pace->is_constant_array();
14072 }
14073 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
14074 {
14075 const Open_array_construction_expression *pace =
14076 static_cast<const Open_array_construction_expression*>(this);
14077 return !pace->is_constant_array();
14078 }
14079 case EXPRESSION_MAP_CONSTRUCTION:
14080 return true;
14081 default:
14082 return false;
14083 }
14084}
14085
35a54f17 14086// Return true if this is a variable or temporary_variable.
14087
14088bool
14089Expression::is_variable() const
14090{
14091 switch (this->classification_)
14092 {
14093 case EXPRESSION_VAR_REFERENCE:
14094 case EXPRESSION_TEMPORARY_REFERENCE:
14095 case EXPRESSION_SET_AND_USE_TEMPORARY:
14096 return true;
14097 default:
14098 return false;
14099 }
14100}
14101
e440a328 14102// Return true if this is a reference to a local variable.
14103
14104bool
14105Expression::is_local_variable() const
14106{
14107 const Var_expression* ve = this->var_expression();
14108 if (ve == NULL)
14109 return false;
14110 const Named_object* no = ve->named_object();
14111 return (no->is_result_variable()
14112 || (no->is_variable() && !no->var_value()->is_global()));
14113}
14114
14115// Class Type_guard_expression.
14116
14117// Traversal.
14118
14119int
14120Type_guard_expression::do_traverse(Traverse* traverse)
14121{
14122 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14123 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14124 return TRAVERSE_EXIT;
14125 return TRAVERSE_CONTINUE;
14126}
14127
14128// Check types of a type guard expression. The expression must have
14129// an interface type, but the actual type conversion is checked at run
14130// time.
14131
14132void
14133Type_guard_expression::do_check_types(Gogo*)
14134{
e440a328 14135 Type* expr_type = this->expr_->type();
7e9da23f 14136 if (expr_type->interface_type() == NULL)
f725ade8 14137 {
5c13bd80 14138 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 14139 this->report_error(_("type assertion only valid for interface types"));
14140 this->set_is_error();
14141 }
e440a328 14142 else if (this->type_->interface_type() == NULL)
14143 {
14144 std::string reason;
14145 if (!expr_type->interface_type()->implements_interface(this->type_,
14146 &reason))
14147 {
5c13bd80 14148 if (!this->type_->is_error())
e440a328 14149 {
f725ade8 14150 if (reason.empty())
14151 this->report_error(_("impossible type assertion: "
14152 "type does not implement interface"));
14153 else
14154 error_at(this->location(),
14155 ("impossible type assertion: "
14156 "type does not implement interface (%s)"),
14157 reason.c_str());
e440a328 14158 }
f725ade8 14159 this->set_is_error();
e440a328 14160 }
14161 }
14162}
14163
14164// Return a tree for a type guard expression.
14165
14166tree
14167Type_guard_expression::do_get_tree(Translate_context* context)
14168{
e440a328 14169 tree expr_tree = this->expr_->get_tree(context);
14170 if (expr_tree == error_mark_node)
14171 return error_mark_node;
7e9da23f 14172 if (this->type_->interface_type() != NULL)
e440a328 14173 return Expression::convert_interface_to_interface(context, this->type_,
14174 this->expr_->type(),
14175 expr_tree, true,
14176 this->location());
14177 else
14178 return Expression::convert_for_assignment(context, this->type_,
14179 this->expr_->type(), expr_tree,
14180 this->location());
14181}
14182
d751bb78 14183// Dump ast representation for a type guard expression.
14184
14185void
14186Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14187 const
14188{
14189 this->expr_->dump_expression(ast_dump_context);
14190 ast_dump_context->ostream() << ".";
14191 ast_dump_context->dump_type(this->type_);
14192}
14193
e440a328 14194// Make a type guard expression.
14195
14196Expression*
14197Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 14198 Location location)
e440a328 14199{
14200 return new Type_guard_expression(expr, type, location);
14201}
14202
14203// Class Heap_composite_expression.
14204
14205// When you take the address of a composite literal, it is allocated
14206// on the heap. This class implements that.
14207
14208class Heap_composite_expression : public Expression
14209{
14210 public:
b13c66cd 14211 Heap_composite_expression(Expression* expr, Location location)
e440a328 14212 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
14213 expr_(expr)
14214 { }
14215
14216 protected:
14217 int
14218 do_traverse(Traverse* traverse)
14219 { return Expression::traverse(&this->expr_, traverse); }
14220
14221 Type*
14222 do_type()
14223 { return Type::make_pointer_type(this->expr_->type()); }
14224
14225 void
14226 do_determine_type(const Type_context*)
14227 { this->expr_->determine_type_no_context(); }
14228
14229 Expression*
14230 do_copy()
14231 {
14232 return Expression::make_heap_composite(this->expr_->copy(),
14233 this->location());
14234 }
14235
14236 tree
14237 do_get_tree(Translate_context*);
14238
14239 // We only export global objects, and the parser does not generate
14240 // this in global scope.
14241 void
14242 do_export(Export*) const
c3e6f413 14243 { go_unreachable(); }
e440a328 14244
d751bb78 14245 void
14246 do_dump_expression(Ast_dump_context*) const;
14247
e440a328 14248 private:
14249 // The composite literal which is being put on the heap.
14250 Expression* expr_;
14251};
14252
14253// Return a tree which allocates a composite literal on the heap.
14254
14255tree
14256Heap_composite_expression::do_get_tree(Translate_context* context)
14257{
14258 tree expr_tree = this->expr_->get_tree(context);
6d3ed74c 14259 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
e440a328 14260 return error_mark_node;
14261 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
c484d925 14262 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
e440a328 14263 tree space = context->gogo()->allocate_memory(this->expr_->type(),
14264 expr_size, this->location());
14265 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
14266 space = save_expr(space);
b13c66cd 14267 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
14268 space);
e440a328 14269 TREE_THIS_NOTRAP(ref) = 1;
14270 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
14271 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
14272 space);
b13c66cd 14273 SET_EXPR_LOCATION(ret, this->location().gcc_location());
e440a328 14274 return ret;
14275}
14276
d751bb78 14277// Dump ast representation for a heap composite expression.
14278
14279void
14280Heap_composite_expression::do_dump_expression(
14281 Ast_dump_context* ast_dump_context) const
14282{
14283 ast_dump_context->ostream() << "&(";
14284 ast_dump_context->dump_expression(this->expr_);
14285 ast_dump_context->ostream() << ")";
14286}
14287
e440a328 14288// Allocate a composite literal on the heap.
14289
14290Expression*
b13c66cd 14291Expression::make_heap_composite(Expression* expr, Location location)
e440a328 14292{
14293 return new Heap_composite_expression(expr, location);
14294}
14295
14296// Class Receive_expression.
14297
14298// Return the type of a receive expression.
14299
14300Type*
14301Receive_expression::do_type()
14302{
14303 Channel_type* channel_type = this->channel_->type()->channel_type();
14304 if (channel_type == NULL)
14305 return Type::make_error_type();
14306 return channel_type->element_type();
14307}
14308
14309// Check types for a receive expression.
14310
14311void
14312Receive_expression::do_check_types(Gogo*)
14313{
14314 Type* type = this->channel_->type();
5c13bd80 14315 if (type->is_error())
e440a328 14316 {
14317 this->set_is_error();
14318 return;
14319 }
14320 if (type->channel_type() == NULL)
14321 {
14322 this->report_error(_("expected channel"));
14323 return;
14324 }
14325 if (!type->channel_type()->may_receive())
14326 {
14327 this->report_error(_("invalid receive on send-only channel"));
14328 return;
14329 }
14330}
14331
14332// Get a tree for a receive expression.
14333
14334tree
14335Receive_expression::do_get_tree(Translate_context* context)
14336{
f24f10bb 14337 Location loc = this->location();
14338
e440a328 14339 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 14340 if (channel_type == NULL)
14341 {
c484d925 14342 go_assert(this->channel_->type()->is_error());
5b8368f4 14343 return error_mark_node;
14344 }
f24f10bb 14345
14346 Expression* td = Expression::make_type_descriptor(channel_type, loc);
14347 tree td_tree = td->get_tree(context);
14348
e440a328 14349 Type* element_type = channel_type->element_type();
9f0e0513 14350 Btype* element_type_btype = element_type->get_backend(context->gogo());
14351 tree element_type_tree = type_to_tree(element_type_btype);
e440a328 14352
14353 tree channel = this->channel_->get_tree(context);
14354 if (element_type_tree == error_mark_node || channel == error_mark_node)
14355 return error_mark_node;
14356
f24f10bb 14357 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
e440a328 14358}
14359
d751bb78 14360// Dump ast representation for a receive expression.
14361
14362void
14363Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14364{
14365 ast_dump_context->ostream() << " <- " ;
14366 ast_dump_context->dump_expression(channel_);
14367}
14368
e440a328 14369// Make a receive expression.
14370
14371Receive_expression*
b13c66cd 14372Expression::make_receive(Expression* channel, Location location)
e440a328 14373{
14374 return new Receive_expression(channel, location);
14375}
14376
e440a328 14377// An expression which evaluates to a pointer to the type descriptor
14378// of a type.
14379
14380class Type_descriptor_expression : public Expression
14381{
14382 public:
b13c66cd 14383 Type_descriptor_expression(Type* type, Location location)
e440a328 14384 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14385 type_(type)
14386 { }
14387
14388 protected:
14389 Type*
14390 do_type()
14391 { return Type::make_type_descriptor_ptr_type(); }
14392
14393 void
14394 do_determine_type(const Type_context*)
14395 { }
14396
14397 Expression*
14398 do_copy()
14399 { return this; }
14400
14401 tree
14402 do_get_tree(Translate_context* context)
a1d23b41 14403 {
175a4612 14404 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
14405 this->location());
14406 return expr_to_tree(ret);
a1d23b41 14407 }
e440a328 14408
d751bb78 14409 void
14410 do_dump_expression(Ast_dump_context*) const;
14411
e440a328 14412 private:
14413 // The type for which this is the descriptor.
14414 Type* type_;
14415};
14416
d751bb78 14417// Dump ast representation for a type descriptor expression.
14418
14419void
14420Type_descriptor_expression::do_dump_expression(
14421 Ast_dump_context* ast_dump_context) const
14422{
14423 ast_dump_context->dump_type(this->type_);
14424}
14425
e440a328 14426// Make a type descriptor expression.
14427
14428Expression*
b13c66cd 14429Expression::make_type_descriptor(Type* type, Location location)
e440a328 14430{
14431 return new Type_descriptor_expression(type, location);
14432}
14433
14434// An expression which evaluates to some characteristic of a type.
14435// This is only used to initialize fields of a type descriptor. Using
14436// a new expression class is slightly inefficient but gives us a good
14437// separation between the frontend and the middle-end with regard to
14438// how types are laid out.
14439
14440class Type_info_expression : public Expression
14441{
14442 public:
14443 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 14444 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 14445 type_(type), type_info_(type_info)
14446 { }
14447
14448 protected:
14449 Type*
14450 do_type();
14451
14452 void
14453 do_determine_type(const Type_context*)
14454 { }
14455
14456 Expression*
14457 do_copy()
14458 { return this; }
14459
14460 tree
14461 do_get_tree(Translate_context* context);
14462
d751bb78 14463 void
14464 do_dump_expression(Ast_dump_context*) const;
14465
e440a328 14466 private:
14467 // The type for which we are getting information.
14468 Type* type_;
14469 // What information we want.
14470 Type_info type_info_;
14471};
14472
14473// The type is chosen to match what the type descriptor struct
14474// expects.
14475
14476Type*
14477Type_info_expression::do_type()
14478{
14479 switch (this->type_info_)
14480 {
14481 case TYPE_INFO_SIZE:
14482 return Type::lookup_integer_type("uintptr");
14483 case TYPE_INFO_ALIGNMENT:
14484 case TYPE_INFO_FIELD_ALIGNMENT:
14485 return Type::lookup_integer_type("uint8");
14486 default:
c3e6f413 14487 go_unreachable();
e440a328 14488 }
14489}
14490
14491// Return type information in GENERIC.
14492
14493tree
14494Type_info_expression::do_get_tree(Translate_context* context)
14495{
927a01eb 14496 Btype* btype = this->type_->get_backend(context->gogo());
14497 Gogo* gogo = context->gogo();
14498 size_t val;
14499 switch (this->type_info_)
e440a328 14500 {
927a01eb 14501 case TYPE_INFO_SIZE:
14502 val = gogo->backend()->type_size(btype);
14503 break;
14504 case TYPE_INFO_ALIGNMENT:
14505 val = gogo->backend()->type_alignment(btype);
14506 break;
14507 case TYPE_INFO_FIELD_ALIGNMENT:
14508 val = gogo->backend()->type_field_alignment(btype);
14509 break;
14510 default:
14511 go_unreachable();
e440a328 14512 }
927a01eb 14513 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14514 go_assert(val_type_tree != error_mark_node);
14515 return build_int_cstu(val_type_tree, val);
e440a328 14516}
14517
d751bb78 14518// Dump ast representation for a type info expression.
14519
14520void
14521Type_info_expression::do_dump_expression(
14522 Ast_dump_context* ast_dump_context) const
14523{
14524 ast_dump_context->ostream() << "typeinfo(";
14525 ast_dump_context->dump_type(this->type_);
14526 ast_dump_context->ostream() << ",";
14527 ast_dump_context->ostream() <<
14528 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14529 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14530 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14531 : "unknown");
14532 ast_dump_context->ostream() << ")";
14533}
14534
e440a328 14535// Make a type info expression.
14536
14537Expression*
14538Expression::make_type_info(Type* type, Type_info type_info)
14539{
14540 return new Type_info_expression(type, type_info);
14541}
14542
35a54f17 14543// An expression that evaluates to some characteristic of a slice.
14544// This is used when indexing, bound-checking, or nil checking a slice.
14545
14546class Slice_info_expression : public Expression
14547{
14548 public:
14549 Slice_info_expression(Expression* slice, Slice_info slice_info,
14550 Location location)
14551 : Expression(EXPRESSION_SLICE_INFO, location),
14552 slice_(slice), slice_info_(slice_info)
14553 { }
14554
14555 protected:
14556 Type*
14557 do_type();
14558
14559 void
14560 do_determine_type(const Type_context*)
14561 { }
14562
14563 Expression*
14564 do_copy()
14565 {
14566 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14567 this->location());
14568 }
14569
14570 tree
14571 do_get_tree(Translate_context* context);
14572
14573 void
14574 do_dump_expression(Ast_dump_context*) const;
14575
14576 void
14577 do_issue_nil_check()
14578 { this->slice_->issue_nil_check(); }
14579
14580 private:
14581 // The slice for which we are getting information.
14582 Expression* slice_;
14583 // What information we want.
14584 Slice_info slice_info_;
14585};
14586
14587// Return the type of the slice info.
14588
14589Type*
14590Slice_info_expression::do_type()
14591{
14592 switch (this->slice_info_)
14593 {
14594 case SLICE_INFO_VALUE_POINTER:
14595 return Type::make_pointer_type(
14596 this->slice_->type()->array_type()->element_type());
14597 case SLICE_INFO_LENGTH:
14598 case SLICE_INFO_CAPACITY:
14599 return Type::lookup_integer_type("int");
14600 default:
14601 go_unreachable();
14602 }
14603}
14604
14605// Return slice information in GENERIC.
14606
14607tree
14608Slice_info_expression::do_get_tree(Translate_context* context)
14609{
14610 Gogo* gogo = context->gogo();
14611
14612 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14613 Bexpression* ret;
14614 switch (this->slice_info_)
14615 {
14616 case SLICE_INFO_VALUE_POINTER:
14617 case SLICE_INFO_LENGTH:
14618 case SLICE_INFO_CAPACITY:
14619 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14620 this->location());
14621 break;
14622 default:
14623 go_unreachable();
14624 }
14625 return expr_to_tree(ret);
14626}
14627
14628// Dump ast representation for a type info expression.
14629
14630void
14631Slice_info_expression::do_dump_expression(
14632 Ast_dump_context* ast_dump_context) const
14633{
14634 ast_dump_context->ostream() << "sliceinfo(";
14635 this->slice_->dump_expression(ast_dump_context);
14636 ast_dump_context->ostream() << ",";
14637 ast_dump_context->ostream() <<
14638 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14639 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14640 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14641 : "unknown");
14642 ast_dump_context->ostream() << ")";
14643}
14644
14645// Make a slice info expression.
14646
14647Expression*
14648Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14649 Location location)
14650{
14651 return new Slice_info_expression(slice, slice_info, location);
14652}
14653
2387f644 14654
14655// An expression that evaluates to some characteristic of a non-empty interface.
14656// This is used to access the method table or underlying object of an interface.
14657
14658class Interface_info_expression : public Expression
14659{
14660 public:
14661 Interface_info_expression(Expression* iface, Interface_info iface_info,
14662 Location location)
14663 : Expression(EXPRESSION_INTERFACE_INFO, location),
14664 iface_(iface), iface_info_(iface_info)
14665 { }
14666
14667 protected:
14668 Type*
14669 do_type();
14670
14671 void
14672 do_determine_type(const Type_context*)
14673 { }
14674
14675 Expression*
14676 do_copy()
14677 {
14678 return new Interface_info_expression(this->iface_->copy(),
14679 this->iface_info_, this->location());
14680 }
14681
14682 tree
14683 do_get_tree(Translate_context* context);
14684
14685 void
14686 do_dump_expression(Ast_dump_context*) const;
14687
14688 void
14689 do_issue_nil_check()
14690 { this->iface_->issue_nil_check(); }
14691
14692 private:
14693 // The interface for which we are getting information.
14694 Expression* iface_;
14695 // What information we want.
14696 Interface_info iface_info_;
14697};
14698
14699// Return the type of the interface info.
14700
14701Type*
14702Interface_info_expression::do_type()
14703{
14704 switch (this->iface_info_)
14705 {
14706 case INTERFACE_INFO_METHODS:
14707 {
14708 Location loc = this->location();
14709 Struct_field_list* sfl = new Struct_field_list();
14710 Type* pdt = Type::make_type_descriptor_ptr_type();
14711 sfl->push_back(
14712 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14713
14714 Interface_type* itype = this->iface_->type()->interface_type();
14715 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14716 p != itype->methods()->end();
14717 ++p)
14718 {
14719 Function_type* ft = p->type()->function_type();
14720 go_assert(ft->receiver() == NULL);
14721
14722 const Typed_identifier_list* params = ft->parameters();
14723 Typed_identifier_list* mparams = new Typed_identifier_list();
14724 if (params != NULL)
14725 mparams->reserve(params->size() + 1);
14726 Type* vt = Type::make_pointer_type(Type::make_void_type());
14727 mparams->push_back(Typed_identifier("", vt, ft->location()));
14728 if (params != NULL)
14729 {
14730 for (Typed_identifier_list::const_iterator pp = params->begin();
14731 pp != params->end();
14732 ++pp)
14733 mparams->push_back(*pp);
14734 }
14735
14736 Typed_identifier_list* mresults = (ft->results() == NULL
14737 ? NULL
14738 : ft->results()->copy());
14739 Backend_function_type* mft =
14740 Type::make_backend_function_type(NULL, mparams, mresults,
14741 ft->location());
14742
14743 std::string fname = Gogo::unpack_hidden_name(p->name());
14744 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14745 }
14746
14747 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14748 }
14749 case INTERFACE_INFO_OBJECT:
14750 return Type::make_pointer_type(Type::make_void_type());
14751 default:
14752 go_unreachable();
14753 }
14754}
14755
14756// Return interface information in GENERIC.
14757
14758tree
14759Interface_info_expression::do_get_tree(Translate_context* context)
14760{
14761 Gogo* gogo = context->gogo();
14762
14763 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14764 Bexpression* ret;
14765 switch (this->iface_info_)
14766 {
14767 case INTERFACE_INFO_METHODS:
14768 case INTERFACE_INFO_OBJECT:
14769 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14770 this->location());
14771 break;
14772 default:
14773 go_unreachable();
14774 }
14775 return expr_to_tree(ret);
14776}
14777
14778// Dump ast representation for an interface info expression.
14779
14780void
14781Interface_info_expression::do_dump_expression(
14782 Ast_dump_context* ast_dump_context) const
14783{
14784 ast_dump_context->ostream() << "interfaceinfo(";
14785 this->iface_->dump_expression(ast_dump_context);
14786 ast_dump_context->ostream() << ",";
14787 ast_dump_context->ostream() <<
14788 (this->iface_info_ == INTERFACE_INFO_METHODS ? "methods"
14789 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14790 : "unknown");
14791 ast_dump_context->ostream() << ")";
14792}
14793
14794// Make an interface info expression.
14795
14796Expression*
14797Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14798 Location location)
14799{
14800 return new Interface_info_expression(iface, iface_info, location);
14801}
14802
e440a328 14803// An expression which evaluates to the offset of a field within a
14804// struct. This, like Type_info_expression, q.v., is only used to
14805// initialize fields of a type descriptor.
14806
14807class Struct_field_offset_expression : public Expression
14808{
14809 public:
14810 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 14811 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14812 Linemap::predeclared_location()),
e440a328 14813 type_(type), field_(field)
14814 { }
14815
14816 protected:
14817 Type*
14818 do_type()
14819 { return Type::lookup_integer_type("uintptr"); }
14820
14821 void
14822 do_determine_type(const Type_context*)
14823 { }
14824
14825 Expression*
14826 do_copy()
14827 { return this; }
14828
14829 tree
14830 do_get_tree(Translate_context* context);
14831
d751bb78 14832 void
14833 do_dump_expression(Ast_dump_context*) const;
14834
e440a328 14835 private:
14836 // The type of the struct.
14837 Struct_type* type_;
14838 // The field.
14839 const Struct_field* field_;
14840};
14841
14842// Return a struct field offset in GENERIC.
14843
14844tree
14845Struct_field_offset_expression::do_get_tree(Translate_context* context)
14846{
9f0e0513 14847 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
e440a328 14848 if (type_tree == error_mark_node)
14849 return error_mark_node;
14850
9f0e0513 14851 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
c484d925 14852 go_assert(val_type_tree != error_mark_node);
e440a328 14853
14854 const Struct_field_list* fields = this->type_->fields();
14855 tree struct_field_tree = TYPE_FIELDS(type_tree);
14856 Struct_field_list::const_iterator p;
14857 for (p = fields->begin();
14858 p != fields->end();
14859 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14860 {
c484d925 14861 go_assert(struct_field_tree != NULL_TREE);
e440a328 14862 if (&*p == this->field_)
14863 break;
14864 }
c484d925 14865 go_assert(&*p == this->field_);
e440a328 14866
14867 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14868 byte_position(struct_field_tree));
14869}
14870
d751bb78 14871// Dump ast representation for a struct field offset expression.
14872
14873void
14874Struct_field_offset_expression::do_dump_expression(
14875 Ast_dump_context* ast_dump_context) const
14876{
14877 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 14878 ast_dump_context->dump_type(this->type_);
14879 ast_dump_context->ostream() << '.';
14880 ast_dump_context->ostream() <<
14881 Gogo::message_name(this->field_->field_name());
d751bb78 14882 ast_dump_context->ostream() << ")";
14883}
14884
e440a328 14885// Make an expression for a struct field offset.
14886
14887Expression*
14888Expression::make_struct_field_offset(Struct_type* type,
14889 const Struct_field* field)
14890{
14891 return new Struct_field_offset_expression(type, field);
14892}
14893
a9182619 14894// An expression which evaluates to a pointer to the map descriptor of
14895// a map type.
14896
14897class Map_descriptor_expression : public Expression
14898{
14899 public:
b13c66cd 14900 Map_descriptor_expression(Map_type* type, Location location)
a9182619 14901 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14902 type_(type)
14903 { }
14904
14905 protected:
14906 Type*
14907 do_type()
14908 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14909
14910 void
14911 do_determine_type(const Type_context*)
14912 { }
14913
14914 Expression*
14915 do_copy()
14916 { return this; }
14917
14918 tree
14919 do_get_tree(Translate_context* context)
14920 {
175a4612 14921 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14922 this->location());
14923 return expr_to_tree(ret);
a9182619 14924 }
14925
d751bb78 14926 void
14927 do_dump_expression(Ast_dump_context*) const;
14928
a9182619 14929 private:
14930 // The type for which this is the descriptor.
14931 Map_type* type_;
14932};
14933
d751bb78 14934// Dump ast representation for a map descriptor expression.
14935
14936void
14937Map_descriptor_expression::do_dump_expression(
14938 Ast_dump_context* ast_dump_context) const
14939{
14940 ast_dump_context->ostream() << "map_descriptor(";
14941 ast_dump_context->dump_type(this->type_);
14942 ast_dump_context->ostream() << ")";
14943}
14944
a9182619 14945// Make a map descriptor expression.
14946
14947Expression*
b13c66cd 14948Expression::make_map_descriptor(Map_type* type, Location location)
a9182619 14949{
14950 return new Map_descriptor_expression(type, location);
14951}
14952
e440a328 14953// An expression which evaluates to the address of an unnamed label.
14954
14955class Label_addr_expression : public Expression
14956{
14957 public:
b13c66cd 14958 Label_addr_expression(Label* label, Location location)
e440a328 14959 : Expression(EXPRESSION_LABEL_ADDR, location),
14960 label_(label)
14961 { }
14962
14963 protected:
14964 Type*
14965 do_type()
14966 { return Type::make_pointer_type(Type::make_void_type()); }
14967
14968 void
14969 do_determine_type(const Type_context*)
14970 { }
14971
14972 Expression*
14973 do_copy()
14974 { return new Label_addr_expression(this->label_, this->location()); }
14975
14976 tree
6e193e6f 14977 do_get_tree(Translate_context* context)
14978 {
e8816003 14979 return expr_to_tree(this->label_->get_addr(context, this->location()));
6e193e6f 14980 }
e440a328 14981
d751bb78 14982 void
14983 do_dump_expression(Ast_dump_context* ast_dump_context) const
14984 { ast_dump_context->ostream() << this->label_->name(); }
14985
e440a328 14986 private:
14987 // The label whose address we are taking.
14988 Label* label_;
14989};
14990
14991// Make an expression for the address of an unnamed label.
14992
14993Expression*
b13c66cd 14994Expression::make_label_addr(Label* label, Location location)
e440a328 14995{
14996 return new Label_addr_expression(label, location);
14997}
14998
14999// Import an expression. This comes at the end in order to see the
15000// various class definitions.
15001
15002Expression*
15003Expression::import_expression(Import* imp)
15004{
15005 int c = imp->peek_char();
15006 if (imp->match_c_string("- ")
15007 || imp->match_c_string("! ")
15008 || imp->match_c_string("^ "))
15009 return Unary_expression::do_import(imp);
15010 else if (c == '(')
15011 return Binary_expression::do_import(imp);
15012 else if (imp->match_c_string("true")
15013 || imp->match_c_string("false"))
15014 return Boolean_expression::do_import(imp);
15015 else if (c == '"')
15016 return String_expression::do_import(imp);
15017 else if (c == '-' || (c >= '0' && c <= '9'))
15018 {
15019 // This handles integers, floats and complex constants.
15020 return Integer_expression::do_import(imp);
15021 }
15022 else if (imp->match_c_string("nil"))
15023 return Nil_expression::do_import(imp);
15024 else if (imp->match_c_string("convert"))
15025 return Type_conversion_expression::do_import(imp);
15026 else
15027 {
15028 error_at(imp->location(), "import error: expected expression");
15029 return Expression::make_error(imp->location());
15030 }
15031}
15032
15033// Class Expression_list.
15034
15035// Traverse the list.
15036
15037int
15038Expression_list::traverse(Traverse* traverse)
15039{
15040 for (Expression_list::iterator p = this->begin();
15041 p != this->end();
15042 ++p)
15043 {
15044 if (*p != NULL)
15045 {
15046 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15047 return TRAVERSE_EXIT;
15048 }
15049 }
15050 return TRAVERSE_CONTINUE;
15051}
15052
15053// Copy the list.
15054
15055Expression_list*
15056Expression_list::copy()
15057{
15058 Expression_list* ret = new Expression_list();
15059 for (Expression_list::iterator p = this->begin();
15060 p != this->end();
15061 ++p)
15062 {
15063 if (*p == NULL)
15064 ret->push_back(NULL);
15065 else
15066 ret->push_back((*p)->copy());
15067 }
15068 return ret;
15069}
15070
15071// Return whether an expression list has an error expression.
15072
15073bool
15074Expression_list::contains_error() const
15075{
15076 for (Expression_list::const_iterator p = this->begin();
15077 p != this->end();
15078 ++p)
15079 if (*p != NULL && (*p)->is_error_expression())
15080 return true;
15081 return false;
15082}
0c77715b 15083
15084// Class Numeric_constant.
15085
15086// Destructor.
15087
15088Numeric_constant::~Numeric_constant()
15089{
15090 this->clear();
15091}
15092
15093// Copy constructor.
15094
15095Numeric_constant::Numeric_constant(const Numeric_constant& a)
15096 : classification_(a.classification_), type_(a.type_)
15097{
15098 switch (a.classification_)
15099 {
15100 case NC_INVALID:
15101 break;
15102 case NC_INT:
15103 case NC_RUNE:
15104 mpz_init_set(this->u_.int_val, a.u_.int_val);
15105 break;
15106 case NC_FLOAT:
15107 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15108 break;
15109 case NC_COMPLEX:
15110 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15111 GMP_RNDN);
15112 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15113 GMP_RNDN);
15114 break;
15115 default:
15116 go_unreachable();
15117 }
15118}
15119
15120// Assignment operator.
15121
15122Numeric_constant&
15123Numeric_constant::operator=(const Numeric_constant& a)
15124{
15125 this->clear();
15126 this->classification_ = a.classification_;
15127 this->type_ = a.type_;
15128 switch (a.classification_)
15129 {
15130 case NC_INVALID:
15131 break;
15132 case NC_INT:
15133 case NC_RUNE:
15134 mpz_init_set(this->u_.int_val, a.u_.int_val);
15135 break;
15136 case NC_FLOAT:
15137 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15138 break;
15139 case NC_COMPLEX:
15140 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15141 GMP_RNDN);
15142 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15143 GMP_RNDN);
15144 break;
15145 default:
15146 go_unreachable();
15147 }
15148 return *this;
15149}
15150
15151// Clear the contents.
15152
15153void
15154Numeric_constant::clear()
15155{
15156 switch (this->classification_)
15157 {
15158 case NC_INVALID:
15159 break;
15160 case NC_INT:
15161 case NC_RUNE:
15162 mpz_clear(this->u_.int_val);
15163 break;
15164 case NC_FLOAT:
15165 mpfr_clear(this->u_.float_val);
15166 break;
15167 case NC_COMPLEX:
15168 mpfr_clear(this->u_.complex_val.real);
15169 mpfr_clear(this->u_.complex_val.imag);
15170 break;
15171 default:
15172 go_unreachable();
15173 }
15174 this->classification_ = NC_INVALID;
15175}
15176
15177// Set to an unsigned long value.
15178
15179void
15180Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15181{
15182 this->clear();
15183 this->classification_ = NC_INT;
15184 this->type_ = type;
15185 mpz_init_set_ui(this->u_.int_val, val);
15186}
15187
15188// Set to an integer value.
15189
15190void
15191Numeric_constant::set_int(Type* type, const mpz_t val)
15192{
15193 this->clear();
15194 this->classification_ = NC_INT;
15195 this->type_ = type;
15196 mpz_init_set(this->u_.int_val, val);
15197}
15198
15199// Set to a rune value.
15200
15201void
15202Numeric_constant::set_rune(Type* type, const mpz_t val)
15203{
15204 this->clear();
15205 this->classification_ = NC_RUNE;
15206 this->type_ = type;
15207 mpz_init_set(this->u_.int_val, val);
15208}
15209
15210// Set to a floating point value.
15211
15212void
15213Numeric_constant::set_float(Type* type, const mpfr_t val)
15214{
15215 this->clear();
15216 this->classification_ = NC_FLOAT;
15217 this->type_ = type;
833b523c 15218 // Numeric constants do not have negative zero values, so remove
15219 // them here. They also don't have infinity or NaN values, but we
15220 // should never see them here.
15221 if (mpfr_zero_p(val))
15222 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15223 else
15224 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15225}
15226
15227// Set to a complex value.
15228
15229void
15230Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15231{
15232 this->clear();
15233 this->classification_ = NC_COMPLEX;
15234 this->type_ = type;
15235 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15236 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15237}
15238
15239// Get an int value.
15240
15241void
15242Numeric_constant::get_int(mpz_t* val) const
15243{
15244 go_assert(this->is_int());
15245 mpz_init_set(*val, this->u_.int_val);
15246}
15247
15248// Get a rune value.
15249
15250void
15251Numeric_constant::get_rune(mpz_t* val) const
15252{
15253 go_assert(this->is_rune());
15254 mpz_init_set(*val, this->u_.int_val);
15255}
15256
15257// Get a floating point value.
15258
15259void
15260Numeric_constant::get_float(mpfr_t* val) const
15261{
15262 go_assert(this->is_float());
15263 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15264}
15265
15266// Get a complex value.
15267
15268void
15269Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15270{
15271 go_assert(this->is_complex());
15272 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15273 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15274}
15275
15276// Express value as unsigned long if possible.
15277
15278Numeric_constant::To_unsigned_long
15279Numeric_constant::to_unsigned_long(unsigned long* val) const
15280{
15281 switch (this->classification_)
15282 {
15283 case NC_INT:
15284 case NC_RUNE:
15285 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15286 case NC_FLOAT:
15287 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15288 case NC_COMPLEX:
15289 if (!mpfr_zero_p(this->u_.complex_val.imag))
15290 return NC_UL_NOTINT;
15291 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15292 default:
15293 go_unreachable();
15294 }
15295}
15296
15297// Express integer value as unsigned long if possible.
15298
15299Numeric_constant::To_unsigned_long
15300Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15301 unsigned long *val) const
15302{
15303 if (mpz_sgn(ival) < 0)
15304 return NC_UL_NEGATIVE;
15305 unsigned long ui = mpz_get_ui(ival);
15306 if (mpz_cmp_ui(ival, ui) != 0)
15307 return NC_UL_BIG;
15308 *val = ui;
15309 return NC_UL_VALID;
15310}
15311
15312// Express floating point value as unsigned long if possible.
15313
15314Numeric_constant::To_unsigned_long
15315Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15316 unsigned long *val) const
15317{
15318 if (!mpfr_integer_p(fval))
15319 return NC_UL_NOTINT;
15320 mpz_t ival;
15321 mpz_init(ival);
15322 mpfr_get_z(ival, fval, GMP_RNDN);
15323 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15324 mpz_clear(ival);
15325 return ret;
15326}
15327
15328// Convert value to integer if possible.
15329
15330bool
15331Numeric_constant::to_int(mpz_t* val) const
15332{
15333 switch (this->classification_)
15334 {
15335 case NC_INT:
15336 case NC_RUNE:
15337 mpz_init_set(*val, this->u_.int_val);
15338 return true;
15339 case NC_FLOAT:
15340 if (!mpfr_integer_p(this->u_.float_val))
15341 return false;
15342 mpz_init(*val);
15343 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15344 return true;
15345 case NC_COMPLEX:
15346 if (!mpfr_zero_p(this->u_.complex_val.imag)
15347 || !mpfr_integer_p(this->u_.complex_val.real))
15348 return false;
15349 mpz_init(*val);
15350 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15351 return true;
15352 default:
15353 go_unreachable();
15354 }
15355}
15356
15357// Convert value to floating point if possible.
15358
15359bool
15360Numeric_constant::to_float(mpfr_t* val) const
15361{
15362 switch (this->classification_)
15363 {
15364 case NC_INT:
15365 case NC_RUNE:
15366 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15367 return true;
15368 case NC_FLOAT:
15369 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15370 return true;
15371 case NC_COMPLEX:
15372 if (!mpfr_zero_p(this->u_.complex_val.imag))
15373 return false;
15374 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15375 return true;
15376 default:
15377 go_unreachable();
15378 }
15379}
15380
15381// Convert value to complex.
15382
15383bool
15384Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15385{
15386 switch (this->classification_)
15387 {
15388 case NC_INT:
15389 case NC_RUNE:
15390 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15391 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15392 return true;
15393 case NC_FLOAT:
15394 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15395 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15396 return true;
15397 case NC_COMPLEX:
15398 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15399 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15400 return true;
15401 default:
15402 go_unreachable();
15403 }
15404}
15405
15406// Get the type.
15407
15408Type*
15409Numeric_constant::type() const
15410{
15411 if (this->type_ != NULL)
15412 return this->type_;
15413 switch (this->classification_)
15414 {
15415 case NC_INT:
15416 return Type::make_abstract_integer_type();
15417 case NC_RUNE:
15418 return Type::make_abstract_character_type();
15419 case NC_FLOAT:
15420 return Type::make_abstract_float_type();
15421 case NC_COMPLEX:
15422 return Type::make_abstract_complex_type();
15423 default:
15424 go_unreachable();
15425 }
15426}
15427
15428// If the constant can be expressed in TYPE, then set the type of the
15429// constant to TYPE and return true. Otherwise return false, and, if
15430// ISSUE_ERROR is true, report an appropriate error message.
15431
15432bool
15433Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15434{
15435 bool ret;
15436 if (type == NULL)
15437 ret = true;
15438 else if (type->integer_type() != NULL)
15439 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15440 else if (type->float_type() != NULL)
15441 ret = this->check_float_type(type->float_type(), issue_error, loc);
15442 else if (type->complex_type() != NULL)
15443 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15444 else
15445 go_unreachable();
15446 if (ret)
15447 this->type_ = type;
15448 return ret;
15449}
15450
15451// Check whether the constant can be expressed in an integer type.
15452
15453bool
15454Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15455 Location location) const
15456{
15457 mpz_t val;
15458 switch (this->classification_)
15459 {
15460 case NC_INT:
15461 case NC_RUNE:
15462 mpz_init_set(val, this->u_.int_val);
15463 break;
15464
15465 case NC_FLOAT:
15466 if (!mpfr_integer_p(this->u_.float_val))
15467 {
15468 if (issue_error)
15469 error_at(location, "floating point constant truncated to integer");
15470 return false;
15471 }
15472 mpz_init(val);
15473 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15474 break;
15475
15476 case NC_COMPLEX:
15477 if (!mpfr_integer_p(this->u_.complex_val.real)
15478 || !mpfr_zero_p(this->u_.complex_val.imag))
15479 {
15480 if (issue_error)
15481 error_at(location, "complex constant truncated to integer");
15482 return false;
15483 }
15484 mpz_init(val);
15485 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15486 break;
15487
15488 default:
15489 go_unreachable();
15490 }
15491
15492 bool ret;
15493 if (type->is_abstract())
15494 ret = true;
15495 else
15496 {
15497 int bits = mpz_sizeinbase(val, 2);
15498 if (type->is_unsigned())
15499 {
15500 // For an unsigned type we can only accept a nonnegative
15501 // number, and we must be able to represents at least BITS.
15502 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15503 }
15504 else
15505 {
15506 // For a signed type we need an extra bit to indicate the
15507 // sign. We have to handle the most negative integer
15508 // specially.
15509 ret = (bits + 1 <= type->bits()
15510 || (bits <= type->bits()
15511 && mpz_sgn(val) < 0
15512 && (mpz_scan1(val, 0)
15513 == static_cast<unsigned long>(type->bits() - 1))
15514 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15515 }
15516 }
15517
15518 if (!ret && issue_error)
15519 error_at(location, "integer constant overflow");
15520
15521 return ret;
15522}
15523
15524// Check whether the constant can be expressed in a floating point
15525// type.
15526
15527bool
15528Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15529 Location location)
0c77715b 15530{
15531 mpfr_t val;
15532 switch (this->classification_)
15533 {
15534 case NC_INT:
15535 case NC_RUNE:
15536 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15537 break;
15538
15539 case NC_FLOAT:
15540 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15541 break;
15542
15543 case NC_COMPLEX:
15544 if (!mpfr_zero_p(this->u_.complex_val.imag))
15545 {
15546 if (issue_error)
15547 error_at(location, "complex constant truncated to float");
15548 return false;
15549 }
15550 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15551 break;
15552
15553 default:
15554 go_unreachable();
15555 }
15556
15557 bool ret;
15558 if (type->is_abstract())
15559 ret = true;
15560 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15561 {
15562 // A NaN or Infinity always fits in the range of the type.
15563 ret = true;
15564 }
15565 else
15566 {
15567 mp_exp_t exp = mpfr_get_exp(val);
15568 mp_exp_t max_exp;
15569 switch (type->bits())
15570 {
15571 case 32:
15572 max_exp = 128;
15573 break;
15574 case 64:
15575 max_exp = 1024;
15576 break;
15577 default:
15578 go_unreachable();
15579 }
15580
15581 ret = exp <= max_exp;
d0bcce51 15582
15583 if (ret)
15584 {
15585 // Round the constant to the desired type.
15586 mpfr_t t;
15587 mpfr_init(t);
15588 switch (type->bits())
15589 {
15590 case 32:
15591 mpfr_set_prec(t, 24);
15592 break;
15593 case 64:
15594 mpfr_set_prec(t, 53);
15595 break;
15596 default:
15597 go_unreachable();
15598 }
15599 mpfr_set(t, val, GMP_RNDN);
15600 mpfr_set(val, t, GMP_RNDN);
15601 mpfr_clear(t);
15602
15603 this->set_float(type, val);
15604 }
0c77715b 15605 }
15606
15607 mpfr_clear(val);
15608
15609 if (!ret && issue_error)
15610 error_at(location, "floating point constant overflow");
15611
15612 return ret;
15613}
15614
15615// Check whether the constant can be expressed in a complex type.
15616
15617bool
15618Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 15619 Location location)
0c77715b 15620{
15621 if (type->is_abstract())
15622 return true;
15623
15624 mp_exp_t max_exp;
15625 switch (type->bits())
15626 {
15627 case 64:
15628 max_exp = 128;
15629 break;
15630 case 128:
15631 max_exp = 1024;
15632 break;
15633 default:
15634 go_unreachable();
15635 }
15636
15637 mpfr_t real;
d0bcce51 15638 mpfr_t imag;
0c77715b 15639 switch (this->classification_)
15640 {
15641 case NC_INT:
15642 case NC_RUNE:
15643 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
d0bcce51 15644 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15645 break;
15646
15647 case NC_FLOAT:
15648 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
d0bcce51 15649 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15650 break;
15651
15652 case NC_COMPLEX:
0c77715b 15653 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
d0bcce51 15654 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
0c77715b 15655 break;
15656
15657 default:
15658 go_unreachable();
15659 }
15660
d0bcce51 15661 bool ret = true;
15662 if (!mpfr_nan_p(real)
15663 && !mpfr_inf_p(real)
15664 && !mpfr_zero_p(real)
15665 && mpfr_get_exp(real) > max_exp)
15666 {
15667 if (issue_error)
15668 error_at(location, "complex real part overflow");
15669 ret = false;
15670 }
0c77715b 15671
d0bcce51 15672 if (!mpfr_nan_p(imag)
15673 && !mpfr_inf_p(imag)
15674 && !mpfr_zero_p(imag)
15675 && mpfr_get_exp(imag) > max_exp)
15676 {
15677 if (issue_error)
15678 error_at(location, "complex imaginary part overflow");
15679 ret = false;
15680 }
0c77715b 15681
d0bcce51 15682 if (ret)
15683 {
15684 // Round the constant to the desired type.
15685 mpfr_t t;
15686 mpfr_init(t);
15687 switch (type->bits())
15688 {
15689 case 64:
15690 mpfr_set_prec(t, 24);
15691 break;
15692 case 128:
15693 mpfr_set_prec(t, 53);
15694 break;
15695 default:
15696 go_unreachable();
15697 }
15698 mpfr_set(t, real, GMP_RNDN);
15699 mpfr_set(real, t, GMP_RNDN);
15700 mpfr_set(t, imag, GMP_RNDN);
15701 mpfr_set(imag, t, GMP_RNDN);
15702 mpfr_clear(t);
15703
15704 this->set_complex(type, real, imag);
15705 }
15706
15707 mpfr_clear(real);
15708 mpfr_clear(imag);
0c77715b 15709
15710 return ret;
15711}
15712
15713// Return an Expression for this value.
15714
15715Expression*
15716Numeric_constant::expression(Location loc) const
15717{
15718 switch (this->classification_)
15719 {
15720 case NC_INT:
15721 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15722 case NC_RUNE:
15723 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15724 case NC_FLOAT:
15725 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15726 case NC_COMPLEX:
15727 return Expression::make_complex(&this->u_.complex_val.real,
15728 &this->u_.complex_val.imag,
15729 this->type_, loc);
15730 default:
15731 go_unreachable();
15732 }
15733}