OSDN Git Service

39824bfcb6f8cac4dce6de4d29c595c44d901063
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / expressions.cc
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
9 #include <algorithm>
10
11 #include <gmp.h>
12
13 #ifndef ENABLE_BUILD_WITH_CXX
14 extern "C"
15 {
16 #endif
17
18 #include "toplev.h"
19 #include "intl.h"
20 #include "tree.h"
21 #include "gimple.h"
22 #include "tree-iterator.h"
23 #include "convert.h"
24 #include "real.h"
25 #include "realmpfr.h"
26
27 #ifndef ENABLE_BUILD_WITH_CXX
28 }
29 #endif
30
31 #include "go-c.h"
32 #include "gogo.h"
33 #include "types.h"
34 #include "export.h"
35 #include "import.h"
36 #include "statements.h"
37 #include "lex.h"
38 #include "runtime.h"
39 #include "backend.h"
40 #include "expressions.h"
41 #include "ast-dump.h"
42
43 // Class Expression.
44
45 Expression::Expression(Expression_classification classification,
46                        Location location)
47   : classification_(classification), location_(location)
48 {
49 }
50
51 Expression::~Expression()
52 {
53 }
54
55 // Traverse the expressions.
56
57 int
58 Expression::traverse(Expression** pexpr, Traverse* traverse)
59 {
60   Expression* expr = *pexpr;
61   if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
62     {
63       int t = traverse->expression(pexpr);
64       if (t == TRAVERSE_EXIT)
65         return TRAVERSE_EXIT;
66       else if (t == TRAVERSE_SKIP_COMPONENTS)
67         return TRAVERSE_CONTINUE;
68     }
69   return expr->do_traverse(traverse);
70 }
71
72 // Traverse subexpressions of this expression.
73
74 int
75 Expression::traverse_subexpressions(Traverse* traverse)
76 {
77   return this->do_traverse(traverse);
78 }
79
80 // Default implementation for do_traverse for child classes.
81
82 int
83 Expression::do_traverse(Traverse*)
84 {
85   return TRAVERSE_CONTINUE;
86 }
87
88 // This virtual function is called by the parser if the value of this
89 // expression is being discarded.  By default, we give an error.
90 // Expressions with side effects override.
91
92 void
93 Expression::do_discarding_value()
94 {
95   this->unused_value_error();
96 }
97
98 // This virtual function is called to export expressions.  This will
99 // only be used by expressions which may be constant.
100
101 void
102 Expression::do_export(Export*) const
103 {
104   go_unreachable();
105 }
106
107 // Give an error saying that the value of the expression is not used.
108
109 void
110 Expression::unused_value_error()
111 {
112   error_at(this->location(), "value computed is not used");
113 }
114
115 // Note that this expression is an error.  This is called by children
116 // when they discover an error.
117
118 void
119 Expression::set_is_error()
120 {
121   this->classification_ = EXPRESSION_ERROR;
122 }
123
124 // For children to call to report an error conveniently.
125
126 void
127 Expression::report_error(const char* msg)
128 {
129   error_at(this->location_, "%s", msg);
130   this->set_is_error();
131 }
132
133 // Set types of variables and constants.  This is implemented by the
134 // child class.
135
136 void
137 Expression::determine_type(const Type_context* context)
138 {
139   this->do_determine_type(context);
140 }
141
142 // Set types when there is no context.
143
144 void
145 Expression::determine_type_no_context()
146 {
147   Type_context context;
148   this->do_determine_type(&context);
149 }
150
151 // Return a tree handling any conversions which must be done during
152 // assignment.
153
154 tree
155 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
156                                    Type* rhs_type, tree rhs_tree,
157                                    Location location)
158 {
159   if (lhs_type->is_error() || rhs_type->is_error())
160     return error_mark_node;
161
162   if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
163     return error_mark_node;
164
165   Gogo* gogo = context->gogo();
166
167   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
168   if (lhs_type_tree == error_mark_node)
169     return error_mark_node;
170
171   if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
172     {
173       if (rhs_type->interface_type() == NULL)
174         return Expression::convert_type_to_interface(context, lhs_type,
175                                                      rhs_type, rhs_tree,
176                                                      location);
177       else
178         return Expression::convert_interface_to_interface(context, lhs_type,
179                                                           rhs_type, rhs_tree,
180                                                           false, location);
181     }
182   else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
183     return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
184                                                  rhs_tree, location);
185   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
186     {
187       // Assigning nil to an open array.
188       go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
189
190       VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
191
192       constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
193       tree field = TYPE_FIELDS(lhs_type_tree);
194       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
195                         "__values") == 0);
196       elt->index = field;
197       elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
198
199       elt = VEC_quick_push(constructor_elt, init, NULL);
200       field = DECL_CHAIN(field);
201       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
202                         "__count") == 0);
203       elt->index = field;
204       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
205
206       elt = VEC_quick_push(constructor_elt, init, NULL);
207       field = DECL_CHAIN(field);
208       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
209                         "__capacity") == 0);
210       elt->index = field;
211       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
212
213       tree val = build_constructor(lhs_type_tree, init);
214       TREE_CONSTANT(val) = 1;
215
216       return val;
217     }
218   else if (rhs_type->is_nil_type())
219     {
220       // The left hand side should be a pointer type at the tree
221       // level.
222       go_assert(POINTER_TYPE_P(lhs_type_tree));
223       return fold_convert(lhs_type_tree, null_pointer_node);
224     }
225   else if (lhs_type_tree == TREE_TYPE(rhs_tree))
226     {
227       // No conversion is needed.
228       return rhs_tree;
229     }
230   else if (POINTER_TYPE_P(lhs_type_tree)
231            || INTEGRAL_TYPE_P(lhs_type_tree)
232            || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
233            || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
234     return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
235   else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
236             && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
237            || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
238                && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
239     {
240       // Avoid confusion from zero sized variables which may be
241       // represented as non-zero-sized.
242       if (int_size_in_bytes(lhs_type_tree) == 0
243           || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
244         return rhs_tree;
245
246       // This conversion must be permitted by Go, or we wouldn't have
247       // gotten here.
248       go_assert(int_size_in_bytes(lhs_type_tree)
249                 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
250       return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
251                              lhs_type_tree, rhs_tree);
252     }
253   else
254     {
255       go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
256       return rhs_tree;
257     }
258 }
259
260 // Return a tree for a conversion from a non-interface type to an
261 // interface type.
262
263 tree
264 Expression::convert_type_to_interface(Translate_context* context,
265                                       Type* lhs_type, Type* rhs_type,
266                                       tree rhs_tree, Location location)
267 {
268   Gogo* gogo = context->gogo();
269   Interface_type* lhs_interface_type = lhs_type->interface_type();
270   bool lhs_is_empty = lhs_interface_type->is_empty();
271
272   // Since RHS_TYPE is a static type, we can create the interface
273   // method table at compile time.
274
275   // When setting an interface to nil, we just set both fields to
276   // NULL.
277   if (rhs_type->is_nil_type())
278     {
279       Btype* lhs_btype = lhs_type->get_backend(gogo);
280       return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
281     }
282
283   // This should have been checked already.
284   go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
285
286   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
287   if (lhs_type_tree == error_mark_node)
288     return error_mark_node;
289
290   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
291   // then the first field is the type descriptor for RHS_TYPE.
292   // Otherwise it is the interface method table for RHS_TYPE.
293   tree first_field_value;
294   if (lhs_is_empty)
295     first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
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();
302       bool is_pointer = false;
303       if (rhs_named_type == NULL)
304         {
305           rhs_named_type = rhs_type->deref()->named_type();
306           is_pointer = true;
307         }
308       tree method_table;
309       if (rhs_named_type == NULL)
310         method_table = null_pointer_node;
311       else
312         method_table =
313           rhs_named_type->interface_method_table(gogo, lhs_interface_type,
314                                                  is_pointer);
315       first_field_value = fold_convert_loc(location.gcc_location(),
316                                            const_ptr_type_node, method_table);
317     }
318   if (first_field_value == error_mark_node)
319     return error_mark_node;
320
321   // Start building a constructor for the value we will return.
322
323   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
324
325   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
326   tree field = TYPE_FIELDS(lhs_type_tree);
327   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
328                     (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
329   elt->index = field;
330   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
331                                 first_field_value);
332
333   elt = VEC_quick_push(constructor_elt, init, NULL);
334   field = DECL_CHAIN(field);
335   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
336   elt->index = field;
337
338   if (rhs_type->points_to() != NULL)
339     {
340       //  We are assigning a pointer to the interface; the interface
341       // holds the pointer itself.
342       elt->value = rhs_tree;
343       return build_constructor(lhs_type_tree, init);
344     }
345
346   // We are assigning a non-pointer value to the interface; the
347   // interface gets a copy of the value in the heap.
348
349   tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
350
351   tree space = gogo->allocate_memory(rhs_type, object_size, location);
352   space = fold_convert_loc(location.gcc_location(),
353                            build_pointer_type(TREE_TYPE(rhs_tree)), space);
354   space = save_expr(space);
355
356   tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
357   TREE_THIS_NOTRAP(ref) = 1;
358   tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
359                              void_type_node, ref, rhs_tree);
360
361   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
362                                 space);
363
364   return build2(COMPOUND_EXPR, lhs_type_tree, set,
365                 build_constructor(lhs_type_tree, init));
366 }
367
368 // Return a tree for the type descriptor of RHS_TREE, which has
369 // interface type RHS_TYPE.  If RHS_TREE is nil the result will be
370 // NULL.
371
372 tree
373 Expression::get_interface_type_descriptor(Translate_context*,
374                                           Type* rhs_type, tree rhs_tree,
375                                           Location location)
376 {
377   tree rhs_type_tree = TREE_TYPE(rhs_tree);
378   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
379   tree rhs_field = TYPE_FIELDS(rhs_type_tree);
380   tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
381                   NULL_TREE);
382   if (rhs_type->interface_type()->is_empty())
383     {
384       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
385                         "__type_descriptor") == 0);
386       return v;
387     }
388
389   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
390              == 0);
391   go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
392   v = save_expr(v);
393   tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
394   go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
395   tree f = TYPE_FIELDS(TREE_TYPE(v1));
396   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
397              == 0);
398   v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
399
400   tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
401                             v, fold_convert_loc(location.gcc_location(),
402                                                 TREE_TYPE(v),
403                                                 null_pointer_node));
404   tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
405                             null_pointer_node);
406   return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
407                          eq, n, v1);
408 }
409
410 // Return a tree for the conversion of an interface type to an
411 // interface type.
412
413 tree
414 Expression::convert_interface_to_interface(Translate_context* context,
415                                            Type *lhs_type, Type *rhs_type,
416                                            tree rhs_tree, bool for_type_guard,
417                                            Location location)
418 {
419   Gogo* gogo = context->gogo();
420   Interface_type* lhs_interface_type = lhs_type->interface_type();
421   bool lhs_is_empty = lhs_interface_type->is_empty();
422
423   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
424   if (lhs_type_tree == error_mark_node)
425     return error_mark_node;
426
427   // In the general case this requires runtime examination of the type
428   // method table to match it up with the interface methods.
429
430   // FIXME: If all of the methods in the right hand side interface
431   // also appear in the left hand side interface, then we don't need
432   // to do a runtime check, although we still need to build a new
433   // method table.
434
435   // Get the type descriptor for the right hand side.  This will be
436   // NULL for a nil interface.
437
438   if (!DECL_P(rhs_tree))
439     rhs_tree = save_expr(rhs_tree);
440
441   tree rhs_type_descriptor =
442     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
443                                               location);
444
445   // The result is going to be a two element constructor.
446
447   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
448
449   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
450   tree field = TYPE_FIELDS(lhs_type_tree);
451   elt->index = field;
452
453   if (for_type_guard)
454     {
455       // A type assertion fails when converting a nil interface.
456       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
457                                                                    location);
458       static tree assert_interface_decl;
459       tree call = Gogo::call_builtin(&assert_interface_decl,
460                                      location,
461                                      "__go_assert_interface",
462                                      2,
463                                      ptr_type_node,
464                                      TREE_TYPE(lhs_type_descriptor),
465                                      lhs_type_descriptor,
466                                      TREE_TYPE(rhs_type_descriptor),
467                                      rhs_type_descriptor);
468       if (call == error_mark_node)
469         return error_mark_node;
470       // This will panic if the interface conversion fails.
471       TREE_NOTHROW(assert_interface_decl) = 0;
472       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
473                                     call);
474     }
475   else if (lhs_is_empty)
476     {
477       // A convertion to an empty interface always succeeds, and the
478       // first field is just the type descriptor of the object.
479       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
480                         "__type_descriptor") == 0);
481       elt->value = fold_convert_loc(location.gcc_location(),
482                                     TREE_TYPE(field), rhs_type_descriptor);
483     }
484   else
485     {
486       // A conversion to a non-empty interface may fail, but unlike a
487       // type assertion converting nil will always succeed.
488       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
489                  == 0);
490       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
491                                                                    location);
492       static tree convert_interface_decl;
493       tree call = Gogo::call_builtin(&convert_interface_decl,
494                                      location,
495                                      "__go_convert_interface",
496                                      2,
497                                      ptr_type_node,
498                                      TREE_TYPE(lhs_type_descriptor),
499                                      lhs_type_descriptor,
500                                      TREE_TYPE(rhs_type_descriptor),
501                                      rhs_type_descriptor);
502       if (call == error_mark_node)
503         return error_mark_node;
504       // This will panic if the interface conversion fails.
505       TREE_NOTHROW(convert_interface_decl) = 0;
506       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
507                                     call);
508     }
509
510   // The second field is simply the object pointer.
511
512   elt = VEC_quick_push(constructor_elt, init, NULL);
513   field = DECL_CHAIN(field);
514   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
515   elt->index = field;
516
517   tree rhs_type_tree = TREE_TYPE(rhs_tree);
518   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
519   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
520   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
521   elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
522                       NULL_TREE);
523
524   return build_constructor(lhs_type_tree, init);
525 }
526
527 // Return a tree for the conversion of an interface type to a
528 // non-interface type.
529
530 tree
531 Expression::convert_interface_to_type(Translate_context* context,
532                                       Type *lhs_type, Type* rhs_type,
533                                       tree rhs_tree, Location location)
534 {
535   Gogo* gogo = context->gogo();
536   tree rhs_type_tree = TREE_TYPE(rhs_tree);
537
538   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
539   if (lhs_type_tree == error_mark_node)
540     return error_mark_node;
541
542   // Call a function to check that the type is valid.  The function
543   // will panic with an appropriate runtime type error if the type is
544   // not valid.
545
546   tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
547
548   if (!DECL_P(rhs_tree))
549     rhs_tree = save_expr(rhs_tree);
550
551   tree rhs_type_descriptor =
552     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
553                                               location);
554
555   tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
556                                                                 location);
557
558   static tree check_interface_type_decl;
559   tree call = Gogo::call_builtin(&check_interface_type_decl,
560                                  location,
561                                  "__go_check_interface_type",
562                                  3,
563                                  void_type_node,
564                                  TREE_TYPE(lhs_type_descriptor),
565                                  lhs_type_descriptor,
566                                  TREE_TYPE(rhs_type_descriptor),
567                                  rhs_type_descriptor,
568                                  TREE_TYPE(rhs_inter_descriptor),
569                                  rhs_inter_descriptor);
570   if (call == error_mark_node)
571     return error_mark_node;
572   // This call will panic if the conversion is invalid.
573   TREE_NOTHROW(check_interface_type_decl) = 0;
574
575   // If the call succeeds, pull out the value.
576   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
577   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
578   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
579   tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
580                     NULL_TREE);
581
582   // If the value is a pointer, then it is the value we want.
583   // Otherwise it points to the value.
584   if (lhs_type->points_to() == NULL)
585     {
586       val = fold_convert_loc(location.gcc_location(),
587                              build_pointer_type(lhs_type_tree), val);
588       val = build_fold_indirect_ref_loc(location.gcc_location(), val);
589     }
590
591   return build2(COMPOUND_EXPR, lhs_type_tree, call,
592                 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
593 }
594
595 // Convert an expression to a tree.  This is implemented by the child
596 // class.  Not that it is not in general safe to call this multiple
597 // times for a single expression, but that we don't catch such errors.
598
599 tree
600 Expression::get_tree(Translate_context* context)
601 {
602   // The child may have marked this expression as having an error.
603   if (this->classification_ == EXPRESSION_ERROR)
604     return error_mark_node;
605
606   return this->do_get_tree(context);
607 }
608
609 // Return a tree for VAL in TYPE.
610
611 tree
612 Expression::integer_constant_tree(mpz_t val, tree type)
613 {
614   if (type == error_mark_node)
615     return error_mark_node;
616   else if (TREE_CODE(type) == INTEGER_TYPE)
617     return double_int_to_tree(type,
618                               mpz_get_double_int(type, val, true));
619   else if (TREE_CODE(type) == REAL_TYPE)
620     {
621       mpfr_t fval;
622       mpfr_init_set_z(fval, val, GMP_RNDN);
623       tree ret = Expression::float_constant_tree(fval, type);
624       mpfr_clear(fval);
625       return ret;
626     }
627   else if (TREE_CODE(type) == COMPLEX_TYPE)
628     {
629       mpfr_t fval;
630       mpfr_init_set_z(fval, val, GMP_RNDN);
631       tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
632       mpfr_clear(fval);
633       tree imag = build_real_from_int_cst(TREE_TYPE(type),
634                                           integer_zero_node);
635       return build_complex(type, real, imag);
636     }
637   else
638     go_unreachable();
639 }
640
641 // Return a tree for VAL in TYPE.
642
643 tree
644 Expression::float_constant_tree(mpfr_t val, tree type)
645 {
646   if (type == error_mark_node)
647     return error_mark_node;
648   else if (TREE_CODE(type) == INTEGER_TYPE)
649     {
650       mpz_t ival;
651       mpz_init(ival);
652       mpfr_get_z(ival, val, GMP_RNDN);
653       tree ret = Expression::integer_constant_tree(ival, type);
654       mpz_clear(ival);
655       return ret;
656     }
657   else if (TREE_CODE(type) == REAL_TYPE)
658     {
659       REAL_VALUE_TYPE r1;
660       real_from_mpfr(&r1, val, type, GMP_RNDN);
661       REAL_VALUE_TYPE r2;
662       real_convert(&r2, TYPE_MODE(type), &r1);
663       return build_real(type, r2);
664     }
665   else if (TREE_CODE(type) == COMPLEX_TYPE)
666     {
667       REAL_VALUE_TYPE r1;
668       real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
669       REAL_VALUE_TYPE r2;
670       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
671       tree imag = build_real_from_int_cst(TREE_TYPE(type),
672                                           integer_zero_node);
673       return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
674     }
675   else
676     go_unreachable();
677 }
678
679 // Return a tree for REAL/IMAG in TYPE.
680
681 tree
682 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
683 {
684   if (type == error_mark_node)
685     return error_mark_node;
686   else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
687     return Expression::float_constant_tree(real, type);
688   else if (TREE_CODE(type) == COMPLEX_TYPE)
689     {
690       REAL_VALUE_TYPE r1;
691       real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
692       REAL_VALUE_TYPE r2;
693       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
694
695       REAL_VALUE_TYPE r3;
696       real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
697       REAL_VALUE_TYPE r4;
698       real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
699
700       return build_complex(type, build_real(TREE_TYPE(type), r2),
701                            build_real(TREE_TYPE(type), r4));
702     }
703   else
704     go_unreachable();
705 }
706
707 // Return a tree which evaluates to true if VAL, of arbitrary integer
708 // type, is negative or is more than the maximum value of BOUND_TYPE.
709 // If SOFAR is not NULL, it is or'red into the result.  The return
710 // value may be NULL if SOFAR is NULL.
711
712 tree
713 Expression::check_bounds(tree val, tree bound_type, tree sofar,
714                          Location loc)
715 {
716   tree val_type = TREE_TYPE(val);
717   tree ret = NULL_TREE;
718
719   if (!TYPE_UNSIGNED(val_type))
720     {
721       ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
722                             build_int_cst(val_type, 0));
723       if (ret == boolean_false_node)
724         ret = NULL_TREE;
725     }
726
727   HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
728   HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
729   go_assert(val_type_size != -1 && bound_type_size != -1);
730   if (val_type_size > bound_type_size
731       || (val_type_size == bound_type_size
732           && TYPE_UNSIGNED(val_type)
733           && !TYPE_UNSIGNED(bound_type)))
734     {
735       tree max = TYPE_MAX_VALUE(bound_type);
736       tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
737                                  val, fold_convert_loc(loc.gcc_location(),
738                                                        val_type, max));
739       if (big == boolean_false_node)
740         ;
741       else if (ret == NULL_TREE)
742         ret = big;
743       else
744         ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
745                               boolean_type_node, ret, big);
746     }
747
748   if (ret == NULL_TREE)
749     return sofar;
750   else if (sofar == NULL_TREE)
751     return ret;
752   else
753     return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
754                            sofar, ret);
755 }
756
757 void
758 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
759 {
760   this->do_dump_expression(ast_dump_context);
761 }
762
763 // Error expressions.  This are used to avoid cascading errors.
764
765 class Error_expression : public Expression
766 {
767  public:
768   Error_expression(Location location)
769     : Expression(EXPRESSION_ERROR, location)
770   { }
771
772  protected:
773   bool
774   do_is_constant() const
775   { return true; }
776
777   bool
778   do_numeric_constant_value(Numeric_constant* nc) const
779   {
780     nc->set_unsigned_long(NULL, 0);
781     return true;
782   }
783
784   void
785   do_discarding_value()
786   { }
787
788   Type*
789   do_type()
790   { return Type::make_error_type(); }
791
792   void
793   do_determine_type(const Type_context*)
794   { }
795
796   Expression*
797   do_copy()
798   { return this; }
799
800   bool
801   do_is_addressable() const
802   { return true; }
803
804   tree
805   do_get_tree(Translate_context*)
806   { return error_mark_node; }
807
808   void
809   do_dump_expression(Ast_dump_context*) const;
810 };
811
812 // Dump the ast representation for an error expression to a dump context.
813
814 void
815 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
816 {
817   ast_dump_context->ostream() << "_Error_" ;
818 }
819
820 Expression*
821 Expression::make_error(Location location)
822 {
823   return new Error_expression(location);
824 }
825
826 // An expression which is really a type.  This is used during parsing.
827 // It is an error if these survive after lowering.
828
829 class
830 Type_expression : public Expression
831 {
832  public:
833   Type_expression(Type* type, Location location)
834     : Expression(EXPRESSION_TYPE, location),
835       type_(type)
836   { }
837
838  protected:
839   int
840   do_traverse(Traverse* traverse)
841   { return Type::traverse(this->type_, traverse); }
842
843   Type*
844   do_type()
845   { return this->type_; }
846
847   void
848   do_determine_type(const Type_context*)
849   { }
850
851   void
852   do_check_types(Gogo*)
853   { this->report_error(_("invalid use of type")); }
854
855   Expression*
856   do_copy()
857   { return this; }
858
859   tree
860   do_get_tree(Translate_context*)
861   { go_unreachable(); }
862
863   void do_dump_expression(Ast_dump_context*) const;
864  
865  private:
866   // The type which we are representing as an expression.
867   Type* type_;
868 };
869
870 void
871 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
872 {
873   ast_dump_context->dump_type(this->type_);
874 }
875
876 Expression*
877 Expression::make_type(Type* type, Location location)
878 {
879   return new Type_expression(type, location);
880 }
881
882 // Class Parser_expression.
883
884 Type*
885 Parser_expression::do_type()
886 {
887   // We should never really ask for the type of a Parser_expression.
888   // However, it can happen, at least when we have an invalid const
889   // whose initializer refers to the const itself.  In that case we
890   // may ask for the type when lowering the const itself.
891   go_assert(saw_errors());
892   return Type::make_error_type();
893 }
894
895 // Class Var_expression.
896
897 // Lower a variable expression.  Here we just make sure that the
898 // initialization expression of the variable has been lowered.  This
899 // ensures that we will be able to determine the type of the variable
900 // if necessary.
901
902 Expression*
903 Var_expression::do_lower(Gogo* gogo, Named_object* function,
904                          Statement_inserter* inserter, int)
905 {
906   if (this->variable_->is_variable())
907     {
908       Variable* var = this->variable_->var_value();
909       // This is either a local variable or a global variable.  A
910       // reference to a variable which is local to an enclosing
911       // function will be a reference to a field in a closure.
912       if (var->is_global())
913         {
914           function = NULL;
915           inserter = NULL;
916         }
917       var->lower_init_expression(gogo, function, inserter);
918     }
919   return this;
920 }
921
922 // Return the type of a reference to a variable.
923
924 Type*
925 Var_expression::do_type()
926 {
927   if (this->variable_->is_variable())
928     return this->variable_->var_value()->type();
929   else if (this->variable_->is_result_variable())
930     return this->variable_->result_var_value()->type();
931   else
932     go_unreachable();
933 }
934
935 // Determine the type of a reference to a variable.
936
937 void
938 Var_expression::do_determine_type(const Type_context*)
939 {
940   if (this->variable_->is_variable())
941     this->variable_->var_value()->determine_type();
942 }
943
944 // Something takes the address of this variable.  This means that we
945 // may want to move the variable onto the heap.
946
947 void
948 Var_expression::do_address_taken(bool escapes)
949 {
950   if (!escapes)
951     {
952       if (this->variable_->is_variable())
953         this->variable_->var_value()->set_non_escaping_address_taken();
954       else if (this->variable_->is_result_variable())
955         this->variable_->result_var_value()->set_non_escaping_address_taken();
956       else
957         go_unreachable();
958     }
959   else
960     {
961       if (this->variable_->is_variable())
962         this->variable_->var_value()->set_address_taken();
963       else if (this->variable_->is_result_variable())
964         this->variable_->result_var_value()->set_address_taken();
965       else
966         go_unreachable();
967     }
968 }
969
970 // Get the tree for a reference to a variable.
971
972 tree
973 Var_expression::do_get_tree(Translate_context* context)
974 {
975   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
976                                                           context->function());
977   tree ret = var_to_tree(bvar);
978   if (ret == error_mark_node)
979     return error_mark_node;
980   bool is_in_heap;
981   if (this->variable_->is_variable())
982     is_in_heap = this->variable_->var_value()->is_in_heap();
983   else if (this->variable_->is_result_variable())
984     is_in_heap = this->variable_->result_var_value()->is_in_heap();
985   else
986     go_unreachable();
987   if (is_in_heap)
988     {
989       ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
990       TREE_THIS_NOTRAP(ret) = 1;
991     }
992   return ret;
993 }
994
995 // Ast dump for variable expression.
996
997 void
998 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
999 {
1000   ast_dump_context->ostream() << this->variable_->name() ;
1001 }
1002
1003 // Make a reference to a variable in an expression.
1004
1005 Expression*
1006 Expression::make_var_reference(Named_object* var, Location location)
1007 {
1008   if (var->is_sink())
1009     return Expression::make_sink(location);
1010
1011   // FIXME: Creating a new object for each reference to a variable is
1012   // wasteful.
1013   return new Var_expression(var, location);
1014 }
1015
1016 // Class Temporary_reference_expression.
1017
1018 // The type.
1019
1020 Type*
1021 Temporary_reference_expression::do_type()
1022 {
1023   return this->statement_->type();
1024 }
1025
1026 // Called if something takes the address of this temporary variable.
1027 // We never have to move temporary variables to the heap, but we do
1028 // need to know that they must live in the stack rather than in a
1029 // register.
1030
1031 void
1032 Temporary_reference_expression::do_address_taken(bool)
1033 {
1034   this->statement_->set_is_address_taken();
1035 }
1036
1037 // Get a tree referring to the variable.
1038
1039 tree
1040 Temporary_reference_expression::do_get_tree(Translate_context* context)
1041 {
1042   Bvariable* bvar = this->statement_->get_backend_variable(context);
1043
1044   // The gcc backend can't represent the same set of recursive types
1045   // that the Go frontend can.  In some cases this means that a
1046   // temporary variable won't have the right backend type.  Correct
1047   // that here by adding a type cast.  We need to use base() to push
1048   // the circularity down one level.
1049   tree ret = var_to_tree(bvar);
1050   if (!this->is_lvalue_
1051       && POINTER_TYPE_P(TREE_TYPE(ret))
1052       && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1053     {
1054       Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1055       tree type_tree = type_to_tree(type_btype);
1056       ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1057     }
1058   return ret;
1059 }
1060
1061 // Ast dump for temporary reference.
1062
1063 void
1064 Temporary_reference_expression::do_dump_expression(
1065                                 Ast_dump_context* ast_dump_context) const
1066 {
1067   ast_dump_context->dump_temp_variable_name(this->statement_);
1068 }
1069
1070 // Make a reference to a temporary variable.
1071
1072 Temporary_reference_expression*
1073 Expression::make_temporary_reference(Temporary_statement* statement,
1074                                      Location location)
1075 {
1076   return new Temporary_reference_expression(statement, location);
1077 }
1078
1079 // Class Set_and_use_temporary_expression.
1080
1081 // Return the type.
1082
1083 Type*
1084 Set_and_use_temporary_expression::do_type()
1085 {
1086   return this->statement_->type();
1087 }
1088
1089 // Take the address.
1090
1091 void
1092 Set_and_use_temporary_expression::do_address_taken(bool)
1093 {
1094   this->statement_->set_is_address_taken();
1095 }
1096
1097 // Return the backend representation.
1098
1099 tree
1100 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1101 {
1102   Bvariable* bvar = this->statement_->get_backend_variable(context);
1103   tree var_tree = var_to_tree(bvar);
1104   tree expr_tree = this->expr_->get_tree(context);
1105   if (var_tree == error_mark_node || expr_tree == error_mark_node)
1106     return error_mark_node;
1107   Location loc = this->location();
1108   return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1109                     build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1110                                var_tree, expr_tree),
1111                     var_tree);
1112 }
1113
1114 // Dump.
1115
1116 void
1117 Set_and_use_temporary_expression::do_dump_expression(
1118     Ast_dump_context* ast_dump_context) const
1119 {
1120   ast_dump_context->ostream() << '(';
1121   ast_dump_context->dump_temp_variable_name(this->statement_);
1122   ast_dump_context->ostream() << " = ";
1123   this->expr_->dump_expression(ast_dump_context);
1124   ast_dump_context->ostream() << ')';
1125 }
1126
1127 // Make a set-and-use temporary.
1128
1129 Set_and_use_temporary_expression*
1130 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1131                                        Expression* expr, Location location)
1132 {
1133   return new Set_and_use_temporary_expression(statement, expr, location);
1134 }
1135
1136 // A sink expression--a use of the blank identifier _.
1137
1138 class Sink_expression : public Expression
1139 {
1140  public:
1141   Sink_expression(Location location)
1142     : Expression(EXPRESSION_SINK, location),
1143       type_(NULL), var_(NULL_TREE)
1144   { }
1145
1146  protected:
1147   void
1148   do_discarding_value()
1149   { }
1150
1151   Type*
1152   do_type();
1153
1154   void
1155   do_determine_type(const Type_context*);
1156
1157   Expression*
1158   do_copy()
1159   { return new Sink_expression(this->location()); }
1160
1161   tree
1162   do_get_tree(Translate_context*);
1163
1164   void
1165   do_dump_expression(Ast_dump_context*) const;
1166
1167  private:
1168   // The type of this sink variable.
1169   Type* type_;
1170   // The temporary variable we generate.
1171   tree var_;
1172 };
1173
1174 // Return the type of a sink expression.
1175
1176 Type*
1177 Sink_expression::do_type()
1178 {
1179   if (this->type_ == NULL)
1180     return Type::make_sink_type();
1181   return this->type_;
1182 }
1183
1184 // Determine the type of a sink expression.
1185
1186 void
1187 Sink_expression::do_determine_type(const Type_context* context)
1188 {
1189   if (context->type != NULL)
1190     this->type_ = context->type;
1191 }
1192
1193 // Return a temporary variable for a sink expression.  This will
1194 // presumably be a write-only variable which the middle-end will drop.
1195
1196 tree
1197 Sink_expression::do_get_tree(Translate_context* context)
1198 {
1199   if (this->var_ == NULL_TREE)
1200     {
1201       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1202       Btype* bt = this->type_->get_backend(context->gogo());
1203       this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1204     }
1205   return this->var_;
1206 }
1207
1208 // Ast dump for sink expression.
1209
1210 void
1211 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1212 {
1213   ast_dump_context->ostream() << "_" ;
1214 }
1215
1216 // Make a sink expression.
1217
1218 Expression*
1219 Expression::make_sink(Location location)
1220 {
1221   return new Sink_expression(location);
1222 }
1223
1224 // Class Func_expression.
1225
1226 // FIXME: Can a function expression appear in a constant expression?
1227 // The value is unchanging.  Initializing a constant to the address of
1228 // a function seems like it could work, though there might be little
1229 // point to it.
1230
1231 // Traversal.
1232
1233 int
1234 Func_expression::do_traverse(Traverse* traverse)
1235 {
1236   return (this->closure_ == NULL
1237           ? TRAVERSE_CONTINUE
1238           : Expression::traverse(&this->closure_, traverse));
1239 }
1240
1241 // Return the type of a function expression.
1242
1243 Type*
1244 Func_expression::do_type()
1245 {
1246   if (this->function_->is_function())
1247     return this->function_->func_value()->type();
1248   else if (this->function_->is_function_declaration())
1249     return this->function_->func_declaration_value()->type();
1250   else
1251     go_unreachable();
1252 }
1253
1254 // Get the tree for a function expression without evaluating the
1255 // closure.
1256
1257 tree
1258 Func_expression::get_tree_without_closure(Gogo* gogo)
1259 {
1260   Function_type* fntype;
1261   if (this->function_->is_function())
1262     fntype = this->function_->func_value()->type();
1263   else if (this->function_->is_function_declaration())
1264     fntype = this->function_->func_declaration_value()->type();
1265   else
1266     go_unreachable();
1267
1268   // Builtin functions are handled specially by Call_expression.  We
1269   // can't take their address.
1270   if (fntype->is_builtin())
1271     {
1272       error_at(this->location(),
1273                "invalid use of special builtin function %qs; must be called",
1274                this->function_->name().c_str());
1275       return error_mark_node;
1276     }
1277
1278   Named_object* no = this->function_;
1279
1280   tree id = no->get_id(gogo);
1281   if (id == error_mark_node)
1282     return error_mark_node;
1283
1284   tree fndecl;
1285   if (no->is_function())
1286     fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1287   else if (no->is_function_declaration())
1288     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1289   else
1290     go_unreachable();
1291
1292   if (fndecl == error_mark_node)
1293     return error_mark_node;
1294
1295   return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1296 }
1297
1298 // Get the tree for a function expression.  This is used when we take
1299 // the address of a function rather than simply calling it.  If the
1300 // function has a closure, we must use a trampoline.
1301
1302 tree
1303 Func_expression::do_get_tree(Translate_context* context)
1304 {
1305   Gogo* gogo = context->gogo();
1306
1307   tree fnaddr = this->get_tree_without_closure(gogo);
1308   if (fnaddr == error_mark_node)
1309     return error_mark_node;
1310
1311   go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1312              && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1313   TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1314
1315   // For a normal non-nested function call, that is all we have to do.
1316   if (!this->function_->is_function()
1317       || this->function_->func_value()->enclosing() == NULL)
1318     {
1319       go_assert(this->closure_ == NULL);
1320       return fnaddr;
1321     }
1322
1323   // For a nested function call, we have to always allocate a
1324   // trampoline.  If we don't always allocate, then closures will not
1325   // be reliably distinct.
1326   Expression* closure = this->closure_;
1327   tree closure_tree;
1328   if (closure == NULL)
1329     closure_tree = null_pointer_node;
1330   else
1331     {
1332       // Get the value of the closure.  This will be a pointer to
1333       // space allocated on the heap.
1334       closure_tree = closure->get_tree(context);
1335       if (closure_tree == error_mark_node)
1336         return error_mark_node;
1337       go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1338     }
1339
1340   // Now we need to build some code on the heap.  This code will load
1341   // the static chain pointer with the closure and then jump to the
1342   // body of the function.  The normal gcc approach is to build the
1343   // code on the stack.  Unfortunately we can not do that, as Go
1344   // permits us to return the function pointer.
1345
1346   return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1347 }
1348
1349 // Ast dump for function.
1350
1351 void
1352 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1353 {
1354   ast_dump_context->ostream() << this->function_->name();
1355   if (this->closure_ != NULL)
1356     {
1357       ast_dump_context->ostream() << " {closure =  ";
1358       this->closure_->dump_expression(ast_dump_context);
1359       ast_dump_context->ostream() << "}";
1360     }
1361 }
1362
1363 // Make a reference to a function in an expression.
1364
1365 Expression*
1366 Expression::make_func_reference(Named_object* function, Expression* closure,
1367                                 Location location)
1368 {
1369   return new Func_expression(function, closure, location);
1370 }
1371
1372 // Class Unknown_expression.
1373
1374 // Return the name of an unknown expression.
1375
1376 const std::string&
1377 Unknown_expression::name() const
1378 {
1379   return this->named_object_->name();
1380 }
1381
1382 // Lower a reference to an unknown name.
1383
1384 Expression*
1385 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1386 {
1387   Location location = this->location();
1388   Named_object* no = this->named_object_;
1389   Named_object* real;
1390   if (!no->is_unknown())
1391     real = no;
1392   else
1393     {
1394       real = no->unknown_value()->real_named_object();
1395       if (real == NULL)
1396         {
1397           if (this->is_composite_literal_key_)
1398             return this;
1399           if (!this->no_error_message_)
1400             error_at(location, "reference to undefined name %qs",
1401                      this->named_object_->message_name().c_str());
1402           return Expression::make_error(location);
1403         }
1404     }
1405   switch (real->classification())
1406     {
1407     case Named_object::NAMED_OBJECT_CONST:
1408       return Expression::make_const_reference(real, location);
1409     case Named_object::NAMED_OBJECT_TYPE:
1410       return Expression::make_type(real->type_value(), location);
1411     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1412       if (this->is_composite_literal_key_)
1413         return this;
1414       if (!this->no_error_message_)
1415         error_at(location, "reference to undefined type %qs",
1416                  real->message_name().c_str());
1417       return Expression::make_error(location);
1418     case Named_object::NAMED_OBJECT_VAR:
1419       real->var_value()->set_is_used();
1420       return Expression::make_var_reference(real, location);
1421     case Named_object::NAMED_OBJECT_FUNC:
1422     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1423       return Expression::make_func_reference(real, NULL, location);
1424     case Named_object::NAMED_OBJECT_PACKAGE:
1425       if (this->is_composite_literal_key_)
1426         return this;
1427       if (!this->no_error_message_)
1428         error_at(location, "unexpected reference to package");
1429       return Expression::make_error(location);
1430     default:
1431       go_unreachable();
1432     }
1433 }
1434
1435 // Dump the ast representation for an unknown expression to a dump context.
1436
1437 void
1438 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1439 {
1440   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1441                               << ")";
1442 }
1443
1444 // Make a reference to an unknown name.
1445
1446 Unknown_expression*
1447 Expression::make_unknown_reference(Named_object* no, Location location)
1448 {
1449   return new Unknown_expression(no, location);
1450 }
1451
1452 // A boolean expression.
1453
1454 class Boolean_expression : public Expression
1455 {
1456  public:
1457   Boolean_expression(bool val, Location location)
1458     : Expression(EXPRESSION_BOOLEAN, location),
1459       val_(val), type_(NULL)
1460   { }
1461
1462   static Expression*
1463   do_import(Import*);
1464
1465  protected:
1466   bool
1467   do_is_constant() const
1468   { return true; }
1469
1470   Type*
1471   do_type();
1472
1473   void
1474   do_determine_type(const Type_context*);
1475
1476   Expression*
1477   do_copy()
1478   { return this; }
1479
1480   tree
1481   do_get_tree(Translate_context*)
1482   { return this->val_ ? boolean_true_node : boolean_false_node; }
1483
1484   void
1485   do_export(Export* exp) const
1486   { exp->write_c_string(this->val_ ? "true" : "false"); }
1487
1488   void
1489   do_dump_expression(Ast_dump_context* ast_dump_context) const
1490   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1491   
1492  private:
1493   // The constant.
1494   bool val_;
1495   // The type as determined by context.
1496   Type* type_;
1497 };
1498
1499 // Get the type.
1500
1501 Type*
1502 Boolean_expression::do_type()
1503 {
1504   if (this->type_ == NULL)
1505     this->type_ = Type::make_boolean_type();
1506   return this->type_;
1507 }
1508
1509 // Set the type from the context.
1510
1511 void
1512 Boolean_expression::do_determine_type(const Type_context* context)
1513 {
1514   if (this->type_ != NULL && !this->type_->is_abstract())
1515     ;
1516   else if (context->type != NULL && context->type->is_boolean_type())
1517     this->type_ = context->type;
1518   else if (!context->may_be_abstract)
1519     this->type_ = Type::lookup_bool_type();
1520 }
1521
1522 // Import a boolean constant.
1523
1524 Expression*
1525 Boolean_expression::do_import(Import* imp)
1526 {
1527   if (imp->peek_char() == 't')
1528     {
1529       imp->require_c_string("true");
1530       return Expression::make_boolean(true, imp->location());
1531     }
1532   else
1533     {
1534       imp->require_c_string("false");
1535       return Expression::make_boolean(false, imp->location());
1536     }
1537 }
1538
1539 // Make a boolean expression.
1540
1541 Expression*
1542 Expression::make_boolean(bool val, Location location)
1543 {
1544   return new Boolean_expression(val, location);
1545 }
1546
1547 // Class String_expression.
1548
1549 // Get the type.
1550
1551 Type*
1552 String_expression::do_type()
1553 {
1554   if (this->type_ == NULL)
1555     this->type_ = Type::make_string_type();
1556   return this->type_;
1557 }
1558
1559 // Set the type from the context.
1560
1561 void
1562 String_expression::do_determine_type(const Type_context* context)
1563 {
1564   if (this->type_ != NULL && !this->type_->is_abstract())
1565     ;
1566   else if (context->type != NULL && context->type->is_string_type())
1567     this->type_ = context->type;
1568   else if (!context->may_be_abstract)
1569     this->type_ = Type::lookup_string_type();
1570 }
1571
1572 // Build a string constant.
1573
1574 tree
1575 String_expression::do_get_tree(Translate_context* context)
1576 {
1577   return context->gogo()->go_string_constant_tree(this->val_);
1578 }
1579
1580  // Write string literal to string dump.
1581
1582 void
1583 String_expression::export_string(String_dump* exp,
1584                                  const String_expression* str)
1585 {
1586   std::string s;
1587   s.reserve(str->val_.length() * 4 + 2);
1588   s += '"';
1589   for (std::string::const_iterator p = str->val_.begin();
1590        p != str->val_.end();
1591        ++p)
1592     {
1593       if (*p == '\\' || *p == '"')
1594         {
1595           s += '\\';
1596           s += *p;
1597         }
1598       else if (*p >= 0x20 && *p < 0x7f)
1599         s += *p;
1600       else if (*p == '\n')
1601         s += "\\n";
1602       else if (*p == '\t')
1603         s += "\\t";
1604       else
1605         {
1606           s += "\\x";
1607           unsigned char c = *p;
1608           unsigned int dig = c >> 4;
1609           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1610           dig = c & 0xf;
1611           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1612         }
1613     }
1614   s += '"';
1615   exp->write_string(s);
1616 }
1617
1618 // Export a string expression.
1619
1620 void
1621 String_expression::do_export(Export* exp) const
1622 {
1623   String_expression::export_string(exp, this);
1624 }
1625
1626 // Import a string expression.
1627
1628 Expression*
1629 String_expression::do_import(Import* imp)
1630 {
1631   imp->require_c_string("\"");
1632   std::string val;
1633   while (true)
1634     {
1635       int c = imp->get_char();
1636       if (c == '"' || c == -1)
1637         break;
1638       if (c != '\\')
1639         val += static_cast<char>(c);
1640       else
1641         {
1642           c = imp->get_char();
1643           if (c == '\\' || c == '"')
1644             val += static_cast<char>(c);
1645           else if (c == 'n')
1646             val += '\n';
1647           else if (c == 't')
1648             val += '\t';
1649           else if (c == 'x')
1650             {
1651               c = imp->get_char();
1652               unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1653               c = imp->get_char();
1654               unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1655               char v = (vh << 4) | vl;
1656               val += v;
1657             }
1658           else
1659             {
1660               error_at(imp->location(), "bad string constant");
1661               return Expression::make_error(imp->location());
1662             }
1663         }
1664     }
1665   return Expression::make_string(val, imp->location());
1666 }
1667
1668 // Ast dump for string expression.
1669
1670 void
1671 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1672 {
1673   String_expression::export_string(ast_dump_context, this);
1674 }
1675
1676 // Make a string expression.
1677
1678 Expression*
1679 Expression::make_string(const std::string& val, Location location)
1680 {
1681   return new String_expression(val, location);
1682 }
1683
1684 // Make an integer expression.
1685
1686 class Integer_expression : public Expression
1687 {
1688  public:
1689   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1690                      Location location)
1691     : Expression(EXPRESSION_INTEGER, location),
1692       type_(type), is_character_constant_(is_character_constant)
1693   { mpz_init_set(this->val_, *val); }
1694
1695   static Expression*
1696   do_import(Import*);
1697
1698   // Write VAL to string dump.
1699   static void
1700   export_integer(String_dump* exp, const mpz_t val);
1701
1702   // Write VAL to dump context.
1703   static void
1704   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1705
1706  protected:
1707   bool
1708   do_is_constant() const
1709   { return true; }
1710
1711   bool
1712   do_numeric_constant_value(Numeric_constant* nc) const;
1713
1714   Type*
1715   do_type();
1716
1717   void
1718   do_determine_type(const Type_context* context);
1719
1720   void
1721   do_check_types(Gogo*);
1722
1723   tree
1724   do_get_tree(Translate_context*);
1725
1726   Expression*
1727   do_copy()
1728   {
1729     if (this->is_character_constant_)
1730       return Expression::make_character(&this->val_, this->type_,
1731                                         this->location());
1732     else
1733       return Expression::make_integer(&this->val_, this->type_,
1734                                       this->location());
1735   }
1736
1737   void
1738   do_export(Export*) const;
1739
1740   void
1741   do_dump_expression(Ast_dump_context*) const;
1742
1743  private:
1744   // The integer value.
1745   mpz_t val_;
1746   // The type so far.
1747   Type* type_;
1748   // Whether this is a character constant.
1749   bool is_character_constant_;
1750 };
1751
1752 // Return a numeric constant for this expression.  We have to mark
1753 // this as a character when appropriate.
1754
1755 bool
1756 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1757 {
1758   if (this->is_character_constant_)
1759     nc->set_rune(this->type_, this->val_);
1760   else
1761     nc->set_int(this->type_, this->val_);
1762   return true;
1763 }
1764
1765 // Return the current type.  If we haven't set the type yet, we return
1766 // an abstract integer type.
1767
1768 Type*
1769 Integer_expression::do_type()
1770 {
1771   if (this->type_ == NULL)
1772     {
1773       if (this->is_character_constant_)
1774         this->type_ = Type::make_abstract_character_type();
1775       else
1776         this->type_ = Type::make_abstract_integer_type();
1777     }
1778   return this->type_;
1779 }
1780
1781 // Set the type of the integer value.  Here we may switch from an
1782 // abstract type to a real type.
1783
1784 void
1785 Integer_expression::do_determine_type(const Type_context* context)
1786 {
1787   if (this->type_ != NULL && !this->type_->is_abstract())
1788     ;
1789   else if (context->type != NULL && context->type->is_numeric_type())
1790     this->type_ = context->type;
1791   else if (!context->may_be_abstract)
1792     {
1793       if (this->is_character_constant_)
1794         this->type_ = Type::lookup_integer_type("int32");
1795       else
1796         this->type_ = Type::lookup_integer_type("int");
1797     }
1798 }
1799
1800 // Check the type of an integer constant.
1801
1802 void
1803 Integer_expression::do_check_types(Gogo*)
1804 {
1805   Type* type = this->type_;
1806   if (type == NULL)
1807     return;
1808   Numeric_constant nc;
1809   if (this->is_character_constant_)
1810     nc.set_rune(NULL, this->val_);
1811   else
1812     nc.set_int(NULL, this->val_);
1813   if (!nc.set_type(type, true, this->location()))
1814     this->set_is_error();
1815 }
1816
1817 // Get a tree for an integer constant.
1818
1819 tree
1820 Integer_expression::do_get_tree(Translate_context* context)
1821 {
1822   Gogo* gogo = context->gogo();
1823   tree type;
1824   if (this->type_ != NULL && !this->type_->is_abstract())
1825     type = type_to_tree(this->type_->get_backend(gogo));
1826   else if (this->type_ != NULL && this->type_->float_type() != NULL)
1827     {
1828       // We are converting to an abstract floating point type.
1829       Type* ftype = Type::lookup_float_type("float64");
1830       type = type_to_tree(ftype->get_backend(gogo));
1831     }
1832   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1833     {
1834       // We are converting to an abstract complex type.
1835       Type* ctype = Type::lookup_complex_type("complex128");
1836       type = type_to_tree(ctype->get_backend(gogo));
1837     }
1838   else
1839     {
1840       // If we still have an abstract type here, then this is being
1841       // used in a constant expression which didn't get reduced for
1842       // some reason.  Use a type which will fit the value.  We use <,
1843       // not <=, because we need an extra bit for the sign bit.
1844       int bits = mpz_sizeinbase(this->val_, 2);
1845       if (bits < INT_TYPE_SIZE)
1846         {
1847           Type* t = Type::lookup_integer_type("int");
1848           type = type_to_tree(t->get_backend(gogo));
1849         }
1850       else if (bits < 64)
1851         {
1852           Type* t = Type::lookup_integer_type("int64");
1853           type = type_to_tree(t->get_backend(gogo));
1854         }
1855       else
1856         type = long_long_integer_type_node;
1857     }
1858   return Expression::integer_constant_tree(this->val_, type);
1859 }
1860
1861 // Write VAL to export data.
1862
1863 void
1864 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1865 {
1866   char* s = mpz_get_str(NULL, 10, val);
1867   exp->write_c_string(s);
1868   free(s);
1869 }
1870
1871 // Export an integer in a constant expression.
1872
1873 void
1874 Integer_expression::do_export(Export* exp) const
1875 {
1876   Integer_expression::export_integer(exp, this->val_);
1877   if (this->is_character_constant_)
1878     exp->write_c_string("'");
1879   // A trailing space lets us reliably identify the end of the number.
1880   exp->write_c_string(" ");
1881 }
1882
1883 // Import an integer, floating point, or complex value.  This handles
1884 // all these types because they all start with digits.
1885
1886 Expression*
1887 Integer_expression::do_import(Import* imp)
1888 {
1889   std::string num = imp->read_identifier();
1890   imp->require_c_string(" ");
1891   if (!num.empty() && num[num.length() - 1] == 'i')
1892     {
1893       mpfr_t real;
1894       size_t plus_pos = num.find('+', 1);
1895       size_t minus_pos = num.find('-', 1);
1896       size_t pos;
1897       if (plus_pos == std::string::npos)
1898         pos = minus_pos;
1899       else if (minus_pos == std::string::npos)
1900         pos = plus_pos;
1901       else
1902         {
1903           error_at(imp->location(), "bad number in import data: %qs",
1904                    num.c_str());
1905           return Expression::make_error(imp->location());
1906         }
1907       if (pos == std::string::npos)
1908         mpfr_set_ui(real, 0, GMP_RNDN);
1909       else
1910         {
1911           std::string real_str = num.substr(0, pos);
1912           if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1913             {
1914               error_at(imp->location(), "bad number in import data: %qs",
1915                        real_str.c_str());
1916               return Expression::make_error(imp->location());
1917             }
1918         }
1919
1920       std::string imag_str;
1921       if (pos == std::string::npos)
1922         imag_str = num;
1923       else
1924         imag_str = num.substr(pos);
1925       imag_str = imag_str.substr(0, imag_str.size() - 1);
1926       mpfr_t imag;
1927       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1928         {
1929           error_at(imp->location(), "bad number in import data: %qs",
1930                    imag_str.c_str());
1931           return Expression::make_error(imp->location());
1932         }
1933       Expression* ret = Expression::make_complex(&real, &imag, NULL,
1934                                                  imp->location());
1935       mpfr_clear(real);
1936       mpfr_clear(imag);
1937       return ret;
1938     }
1939   else if (num.find('.') == std::string::npos
1940            && num.find('E') == std::string::npos)
1941     {
1942       bool is_character_constant = (!num.empty()
1943                                     && num[num.length() - 1] == '\'');
1944       if (is_character_constant)
1945         num = num.substr(0, num.length() - 1);
1946       mpz_t val;
1947       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1948         {
1949           error_at(imp->location(), "bad number in import data: %qs",
1950                    num.c_str());
1951           return Expression::make_error(imp->location());
1952         }
1953       Expression* ret;
1954       if (is_character_constant)
1955         ret = Expression::make_character(&val, NULL, imp->location());
1956       else
1957         ret = Expression::make_integer(&val, NULL, imp->location());
1958       mpz_clear(val);
1959       return ret;
1960     }
1961   else
1962     {
1963       mpfr_t val;
1964       if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1965         {
1966           error_at(imp->location(), "bad number in import data: %qs",
1967                    num.c_str());
1968           return Expression::make_error(imp->location());
1969         }
1970       Expression* ret = Expression::make_float(&val, NULL, imp->location());
1971       mpfr_clear(val);
1972       return ret;
1973     }
1974 }
1975 // Ast dump for integer expression.
1976
1977 void
1978 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1979 {
1980   if (this->is_character_constant_)
1981     ast_dump_context->ostream() << '\'';
1982   Integer_expression::export_integer(ast_dump_context, this->val_);
1983   if (this->is_character_constant_)
1984     ast_dump_context->ostream() << '\'';
1985 }
1986
1987 // Build a new integer value.
1988
1989 Expression*
1990 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1991 {
1992   return new Integer_expression(val, type, false, location);
1993 }
1994
1995 // Build a new character constant value.
1996
1997 Expression*
1998 Expression::make_character(const mpz_t* val, Type* type, Location location)
1999 {
2000   return new Integer_expression(val, type, true, location);
2001 }
2002
2003 // Floats.
2004
2005 class Float_expression : public Expression
2006 {
2007  public:
2008   Float_expression(const mpfr_t* val, Type* type, Location location)
2009     : Expression(EXPRESSION_FLOAT, location),
2010       type_(type)
2011   {
2012     mpfr_init_set(this->val_, *val, GMP_RNDN);
2013   }
2014
2015   // Write VAL to export data.
2016   static void
2017   export_float(String_dump* exp, const mpfr_t val);
2018
2019   // Write VAL to dump file.
2020   static void
2021   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2022
2023  protected:
2024   bool
2025   do_is_constant() const
2026   { return true; }
2027
2028   bool
2029   do_numeric_constant_value(Numeric_constant* nc) const
2030   {
2031     nc->set_float(this->type_, this->val_);
2032     return true;
2033   }
2034
2035   Type*
2036   do_type();
2037
2038   void
2039   do_determine_type(const Type_context*);
2040
2041   void
2042   do_check_types(Gogo*);
2043
2044   Expression*
2045   do_copy()
2046   { return Expression::make_float(&this->val_, this->type_,
2047                                   this->location()); }
2048
2049   tree
2050   do_get_tree(Translate_context*);
2051
2052   void
2053   do_export(Export*) const;
2054
2055   void
2056   do_dump_expression(Ast_dump_context*) const;
2057
2058  private:
2059   // The floating point value.
2060   mpfr_t val_;
2061   // The type so far.
2062   Type* type_;
2063 };
2064
2065 // Return the current type.  If we haven't set the type yet, we return
2066 // an abstract float type.
2067
2068 Type*
2069 Float_expression::do_type()
2070 {
2071   if (this->type_ == NULL)
2072     this->type_ = Type::make_abstract_float_type();
2073   return this->type_;
2074 }
2075
2076 // Set the type of the float value.  Here we may switch from an
2077 // abstract type to a real type.
2078
2079 void
2080 Float_expression::do_determine_type(const Type_context* context)
2081 {
2082   if (this->type_ != NULL && !this->type_->is_abstract())
2083     ;
2084   else if (context->type != NULL
2085            && (context->type->integer_type() != NULL
2086                || context->type->float_type() != NULL
2087                || context->type->complex_type() != NULL))
2088     this->type_ = context->type;
2089   else if (!context->may_be_abstract)
2090     this->type_ = Type::lookup_float_type("float64");
2091 }
2092
2093 // Check the type of a float value.
2094
2095 void
2096 Float_expression::do_check_types(Gogo*)
2097 {
2098   Type* type = this->type_;
2099   if (type == NULL)
2100     return;
2101   Numeric_constant nc;
2102   nc.set_float(NULL, this->val_);
2103   if (!nc.set_type(this->type_, true, this->location()))
2104     this->set_is_error();
2105 }
2106
2107 // Get a tree for a float constant.
2108
2109 tree
2110 Float_expression::do_get_tree(Translate_context* context)
2111 {
2112   Gogo* gogo = context->gogo();
2113   tree type;
2114   if (this->type_ != NULL && !this->type_->is_abstract())
2115     type = type_to_tree(this->type_->get_backend(gogo));
2116   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2117     {
2118       // We have an abstract integer type.  We just hope for the best.
2119       type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2120     }
2121   else
2122     {
2123       // If we still have an abstract type here, then this is being
2124       // used in a constant expression which didn't get reduced.  We
2125       // just use float64 and hope for the best.
2126       Type* ft = Type::lookup_float_type("float64");
2127       type = type_to_tree(ft->get_backend(gogo));
2128     }
2129   return Expression::float_constant_tree(this->val_, type);
2130 }
2131
2132 // Write a floating point number to a string dump.
2133
2134 void
2135 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2136 {
2137   mp_exp_t exponent;
2138   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2139   if (*s == '-')
2140     exp->write_c_string("-");
2141   exp->write_c_string("0.");
2142   exp->write_c_string(*s == '-' ? s + 1 : s);
2143   mpfr_free_str(s);
2144   char buf[30];
2145   snprintf(buf, sizeof buf, "E%ld", exponent);
2146   exp->write_c_string(buf);
2147 }
2148
2149 // Export a floating point number in a constant expression.
2150
2151 void
2152 Float_expression::do_export(Export* exp) const
2153 {
2154   Float_expression::export_float(exp, this->val_);
2155   // A trailing space lets us reliably identify the end of the number.
2156   exp->write_c_string(" ");
2157 }
2158
2159 // Dump a floating point number to the dump file.
2160
2161 void
2162 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2163 {
2164   Float_expression::export_float(ast_dump_context, this->val_);
2165 }
2166
2167 // Make a float expression.
2168
2169 Expression*
2170 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2171 {
2172   return new Float_expression(val, type, location);
2173 }
2174
2175 // Complex numbers.
2176
2177 class Complex_expression : public Expression
2178 {
2179  public:
2180   Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2181                      Location location)
2182     : Expression(EXPRESSION_COMPLEX, location),
2183       type_(type)
2184   {
2185     mpfr_init_set(this->real_, *real, GMP_RNDN);
2186     mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2187   }
2188
2189   // Write REAL/IMAG to string dump.
2190   static void
2191   export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2192
2193   // Write REAL/IMAG to dump context.
2194   static void
2195   dump_complex(Ast_dump_context* ast_dump_context, 
2196                const mpfr_t real, const mpfr_t val);
2197   
2198  protected:
2199   bool
2200   do_is_constant() const
2201   { return true; }
2202
2203   bool
2204   do_numeric_constant_value(Numeric_constant* nc) const
2205   {
2206     nc->set_complex(this->type_, this->real_, this->imag_);
2207     return true;
2208   }
2209
2210   Type*
2211   do_type();
2212
2213   void
2214   do_determine_type(const Type_context*);
2215
2216   void
2217   do_check_types(Gogo*);
2218
2219   Expression*
2220   do_copy()
2221   {
2222     return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2223                                     this->location());
2224   }
2225
2226   tree
2227   do_get_tree(Translate_context*);
2228
2229   void
2230   do_export(Export*) const;
2231
2232   void
2233   do_dump_expression(Ast_dump_context*) const;
2234   
2235  private:
2236   // The real part.
2237   mpfr_t real_;
2238   // The imaginary part;
2239   mpfr_t imag_;
2240   // The type if known.
2241   Type* type_;
2242 };
2243
2244 // Return the current type.  If we haven't set the type yet, we return
2245 // an abstract complex type.
2246
2247 Type*
2248 Complex_expression::do_type()
2249 {
2250   if (this->type_ == NULL)
2251     this->type_ = Type::make_abstract_complex_type();
2252   return this->type_;
2253 }
2254
2255 // Set the type of the complex value.  Here we may switch from an
2256 // abstract type to a real type.
2257
2258 void
2259 Complex_expression::do_determine_type(const Type_context* context)
2260 {
2261   if (this->type_ != NULL && !this->type_->is_abstract())
2262     ;
2263   else if (context->type != NULL
2264            && context->type->complex_type() != NULL)
2265     this->type_ = context->type;
2266   else if (!context->may_be_abstract)
2267     this->type_ = Type::lookup_complex_type("complex128");
2268 }
2269
2270 // Check the type of a complex value.
2271
2272 void
2273 Complex_expression::do_check_types(Gogo*)
2274 {
2275   Type* type = this->type_;
2276   if (type == NULL)
2277     return;
2278   Numeric_constant nc;
2279   nc.set_complex(NULL, this->real_, this->imag_);
2280   if (!nc.set_type(this->type_, true, this->location()))
2281     this->set_is_error();
2282 }
2283
2284 // Get a tree for a complex constant.
2285
2286 tree
2287 Complex_expression::do_get_tree(Translate_context* context)
2288 {
2289   Gogo* gogo = context->gogo();
2290   tree type;
2291   if (this->type_ != NULL && !this->type_->is_abstract())
2292     type = type_to_tree(this->type_->get_backend(gogo));
2293   else
2294     {
2295       // If we still have an abstract type here, this this is being
2296       // used in a constant expression which didn't get reduced.  We
2297       // just use complex128 and hope for the best.
2298       Type* ct = Type::lookup_complex_type("complex128");
2299       type = type_to_tree(ct->get_backend(gogo));
2300     }
2301   return Expression::complex_constant_tree(this->real_, this->imag_, type);
2302 }
2303
2304 // Write REAL/IMAG to export data.
2305
2306 void
2307 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2308                                    const mpfr_t imag)
2309 {
2310   if (!mpfr_zero_p(real))
2311     {
2312       Float_expression::export_float(exp, real);
2313       if (mpfr_sgn(imag) > 0)
2314         exp->write_c_string("+");
2315     }
2316   Float_expression::export_float(exp, imag);
2317   exp->write_c_string("i");
2318 }
2319
2320 // Export a complex number in a constant expression.
2321
2322 void
2323 Complex_expression::do_export(Export* exp) const
2324 {
2325   Complex_expression::export_complex(exp, this->real_, this->imag_);
2326   // A trailing space lets us reliably identify the end of the number.
2327   exp->write_c_string(" ");
2328 }
2329
2330 // Dump a complex expression to the dump file.
2331
2332 void
2333 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2334 {
2335   Complex_expression::export_complex(ast_dump_context,
2336                                       this->real_,
2337                                       this->imag_);
2338 }
2339
2340 // Make a complex expression.
2341
2342 Expression*
2343 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2344                          Location location)
2345 {
2346   return new Complex_expression(real, imag, type, location);
2347 }
2348
2349 // Find a named object in an expression.
2350
2351 class Find_named_object : public Traverse
2352 {
2353  public:
2354   Find_named_object(Named_object* no)
2355     : Traverse(traverse_expressions),
2356       no_(no), found_(false)
2357   { }
2358
2359   // Whether we found the object.
2360   bool
2361   found() const
2362   { return this->found_; }
2363
2364  protected:
2365   int
2366   expression(Expression**);
2367
2368  private:
2369   // The object we are looking for.
2370   Named_object* no_;
2371   // Whether we found it.
2372   bool found_;
2373 };
2374
2375 // A reference to a const in an expression.
2376
2377 class Const_expression : public Expression
2378 {
2379  public:
2380   Const_expression(Named_object* constant, Location location)
2381     : Expression(EXPRESSION_CONST_REFERENCE, location),
2382       constant_(constant), type_(NULL), seen_(false)
2383   { }
2384
2385   Named_object*
2386   named_object()
2387   { return this->constant_; }
2388
2389   // Check that the initializer does not refer to the constant itself.
2390   void
2391   check_for_init_loop();
2392
2393  protected:
2394   int
2395   do_traverse(Traverse*);
2396
2397   Expression*
2398   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2399
2400   bool
2401   do_is_constant() const
2402   { return true; }
2403
2404   bool
2405   do_numeric_constant_value(Numeric_constant* nc) const;
2406
2407   bool
2408   do_string_constant_value(std::string* val) const;
2409
2410   Type*
2411   do_type();
2412
2413   // The type of a const is set by the declaration, not the use.
2414   void
2415   do_determine_type(const Type_context*);
2416
2417   void
2418   do_check_types(Gogo*);
2419
2420   Expression*
2421   do_copy()
2422   { return this; }
2423
2424   tree
2425   do_get_tree(Translate_context* context);
2426
2427   // When exporting a reference to a const as part of a const
2428   // expression, we export the value.  We ignore the fact that it has
2429   // a name.
2430   void
2431   do_export(Export* exp) const
2432   { this->constant_->const_value()->expr()->export_expression(exp); }
2433
2434   void
2435   do_dump_expression(Ast_dump_context*) const;
2436
2437  private:
2438   // The constant.
2439   Named_object* constant_;
2440   // The type of this reference.  This is used if the constant has an
2441   // abstract type.
2442   Type* type_;
2443   // Used to prevent infinite recursion when a constant incorrectly
2444   // refers to itself.
2445   mutable bool seen_;
2446 };
2447
2448 // Traversal.
2449
2450 int
2451 Const_expression::do_traverse(Traverse* traverse)
2452 {
2453   if (this->type_ != NULL)
2454     return Type::traverse(this->type_, traverse);
2455   return TRAVERSE_CONTINUE;
2456 }
2457
2458 // Lower a constant expression.  This is where we convert the
2459 // predeclared constant iota into an integer value.
2460
2461 Expression*
2462 Const_expression::do_lower(Gogo* gogo, Named_object*,
2463                            Statement_inserter*, int iota_value)
2464 {
2465   if (this->constant_->const_value()->expr()->classification()
2466       == EXPRESSION_IOTA)
2467     {
2468       if (iota_value == -1)
2469         {
2470           error_at(this->location(),
2471                    "iota is only defined in const declarations");
2472           iota_value = 0;
2473         }
2474       mpz_t val;
2475       mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2476       Expression* ret = Expression::make_integer(&val, NULL,
2477                                                  this->location());
2478       mpz_clear(val);
2479       return ret;
2480     }
2481
2482   // Make sure that the constant itself has been lowered.
2483   gogo->lower_constant(this->constant_);
2484
2485   return this;
2486 }
2487
2488 // Return a numeric constant value.
2489
2490 bool
2491 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2492 {
2493   if (this->seen_)
2494     return false;
2495
2496   Expression* e = this->constant_->const_value()->expr();
2497   
2498   this->seen_ = true;
2499
2500   bool r = e->numeric_constant_value(nc);
2501
2502   this->seen_ = false;
2503
2504   Type* ctype;
2505   if (this->type_ != NULL)
2506     ctype = this->type_;
2507   else
2508     ctype = this->constant_->const_value()->type();
2509   if (r && ctype != NULL)
2510     {
2511       if (!nc->set_type(ctype, false, this->location()))
2512         return false;
2513     }
2514
2515   return r;
2516 }
2517
2518 bool
2519 Const_expression::do_string_constant_value(std::string* val) const
2520 {
2521   if (this->seen_)
2522     return false;
2523
2524   Expression* e = this->constant_->const_value()->expr();
2525
2526   this->seen_ = true;
2527   bool ok = e->string_constant_value(val);
2528   this->seen_ = false;
2529
2530   return ok;
2531 }
2532
2533 // Return the type of the const reference.
2534
2535 Type*
2536 Const_expression::do_type()
2537 {
2538   if (this->type_ != NULL)
2539     return this->type_;
2540
2541   Named_constant* nc = this->constant_->const_value();
2542
2543   if (this->seen_ || nc->lowering())
2544     {
2545       this->report_error(_("constant refers to itself"));
2546       this->type_ = Type::make_error_type();
2547       return this->type_;
2548     }
2549
2550   this->seen_ = true;
2551
2552   Type* ret = nc->type();
2553
2554   if (ret != NULL)
2555     {
2556       this->seen_ = false;
2557       return ret;
2558     }
2559
2560   // During parsing, a named constant may have a NULL type, but we
2561   // must not return a NULL type here.
2562   ret = nc->expr()->type();
2563
2564   this->seen_ = false;
2565
2566   return ret;
2567 }
2568
2569 // Set the type of the const reference.
2570
2571 void
2572 Const_expression::do_determine_type(const Type_context* context)
2573 {
2574   Type* ctype = this->constant_->const_value()->type();
2575   Type* cetype = (ctype != NULL
2576                   ? ctype
2577                   : this->constant_->const_value()->expr()->type());
2578   if (ctype != NULL && !ctype->is_abstract())
2579     ;
2580   else if (context->type != NULL
2581            && context->type->is_numeric_type()
2582            && cetype->is_numeric_type())
2583     this->type_ = context->type;
2584   else if (context->type != NULL
2585            && context->type->is_string_type()
2586            && cetype->is_string_type())
2587     this->type_ = context->type;
2588   else if (context->type != NULL
2589            && context->type->is_boolean_type()
2590            && cetype->is_boolean_type())
2591     this->type_ = context->type;
2592   else if (!context->may_be_abstract)
2593     {
2594       if (cetype->is_abstract())
2595         cetype = cetype->make_non_abstract_type();
2596       this->type_ = cetype;
2597     }
2598 }
2599
2600 // Check for a loop in which the initializer of a constant refers to
2601 // the constant itself.
2602
2603 void
2604 Const_expression::check_for_init_loop()
2605 {
2606   if (this->type_ != NULL && this->type_->is_error())
2607     return;
2608
2609   if (this->seen_)
2610     {
2611       this->report_error(_("constant refers to itself"));
2612       this->type_ = Type::make_error_type();
2613       return;
2614     }
2615
2616   Expression* init = this->constant_->const_value()->expr();
2617   Find_named_object find_named_object(this->constant_);
2618
2619   this->seen_ = true;
2620   Expression::traverse(&init, &find_named_object);
2621   this->seen_ = false;
2622
2623   if (find_named_object.found())
2624     {
2625       if (this->type_ == NULL || !this->type_->is_error())
2626         {
2627           this->report_error(_("constant refers to itself"));
2628           this->type_ = Type::make_error_type();
2629         }
2630       return;
2631     }
2632 }
2633
2634 // Check types of a const reference.
2635
2636 void
2637 Const_expression::do_check_types(Gogo*)
2638 {
2639   if (this->type_ != NULL && this->type_->is_error())
2640     return;
2641
2642   this->check_for_init_loop();
2643
2644   // Check that numeric constant fits in type.
2645   if (this->type_ != NULL && this->type_->is_numeric_type())
2646     {
2647       Numeric_constant nc;
2648       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2649         {
2650           if (!nc.set_type(this->type_, true, this->location()))
2651             this->set_is_error();
2652         }
2653     }
2654 }
2655
2656 // Return a tree for the const reference.
2657
2658 tree
2659 Const_expression::do_get_tree(Translate_context* context)
2660 {
2661   Gogo* gogo = context->gogo();
2662   tree type_tree;
2663   if (this->type_ == NULL)
2664     type_tree = NULL_TREE;
2665   else
2666     {
2667       type_tree = type_to_tree(this->type_->get_backend(gogo));
2668       if (type_tree == error_mark_node)
2669         return error_mark_node;
2670     }
2671
2672   // If the type has been set for this expression, but the underlying
2673   // object is an abstract int or float, we try to get the abstract
2674   // value.  Otherwise we may lose something in the conversion.
2675   if (this->type_ != NULL
2676       && this->type_->is_numeric_type()
2677       && (this->constant_->const_value()->type() == NULL
2678           || this->constant_->const_value()->type()->is_abstract()))
2679     {
2680       Expression* expr = this->constant_->const_value()->expr();
2681       Numeric_constant nc;
2682       if (expr->numeric_constant_value(&nc)
2683           && nc.set_type(this->type_, false, this->location()))
2684         {
2685           Expression* e = nc.expression(this->location());
2686           return e->get_tree(context);
2687         }
2688     }
2689
2690   tree const_tree = this->constant_->get_tree(gogo, context->function());
2691   if (this->type_ == NULL
2692       || const_tree == error_mark_node
2693       || TREE_TYPE(const_tree) == error_mark_node)
2694     return const_tree;
2695
2696   tree ret;
2697   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2698     ret = fold_convert(type_tree, const_tree);
2699   else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2700     ret = fold(convert_to_integer(type_tree, const_tree));
2701   else if (TREE_CODE(type_tree) == REAL_TYPE)
2702     ret = fold(convert_to_real(type_tree, const_tree));
2703   else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2704     ret = fold(convert_to_complex(type_tree, const_tree));
2705   else
2706     go_unreachable();
2707   return ret;
2708 }
2709
2710 // Dump ast representation for constant expression.
2711
2712 void
2713 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2714 {
2715   ast_dump_context->ostream() << this->constant_->name();
2716 }
2717
2718 // Make a reference to a constant in an expression.
2719
2720 Expression*
2721 Expression::make_const_reference(Named_object* constant,
2722                                  Location location)
2723 {
2724   return new Const_expression(constant, location);
2725 }
2726
2727 // Find a named object in an expression.
2728
2729 int
2730 Find_named_object::expression(Expression** pexpr)
2731 {
2732   switch ((*pexpr)->classification())
2733     {
2734     case Expression::EXPRESSION_CONST_REFERENCE:
2735       {
2736         Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2737         if (ce->named_object() == this->no_)
2738           break;
2739
2740         // We need to check a constant initializer explicitly, as
2741         // loops here will not be caught by the loop checking for
2742         // variable initializers.
2743         ce->check_for_init_loop();
2744
2745         return TRAVERSE_CONTINUE;
2746       }
2747
2748     case Expression::EXPRESSION_VAR_REFERENCE:
2749       if ((*pexpr)->var_expression()->named_object() == this->no_)
2750         break;
2751       return TRAVERSE_CONTINUE;
2752     case Expression::EXPRESSION_FUNC_REFERENCE:
2753       if ((*pexpr)->func_expression()->named_object() == this->no_)
2754         break;
2755       return TRAVERSE_CONTINUE;
2756     default:
2757       return TRAVERSE_CONTINUE;
2758     }
2759   this->found_ = true;
2760   return TRAVERSE_EXIT;
2761 }
2762
2763 // The nil value.
2764
2765 class Nil_expression : public Expression
2766 {
2767  public:
2768   Nil_expression(Location location)
2769     : Expression(EXPRESSION_NIL, location)
2770   { }
2771
2772   static Expression*
2773   do_import(Import*);
2774
2775  protected:
2776   bool
2777   do_is_constant() const
2778   { return true; }
2779
2780   Type*
2781   do_type()
2782   { return Type::make_nil_type(); }
2783
2784   void
2785   do_determine_type(const Type_context*)
2786   { }
2787
2788   Expression*
2789   do_copy()
2790   { return this; }
2791
2792   tree
2793   do_get_tree(Translate_context*)
2794   { return null_pointer_node; }
2795
2796   void
2797   do_export(Export* exp) const
2798   { exp->write_c_string("nil"); }
2799
2800   void
2801   do_dump_expression(Ast_dump_context* ast_dump_context) const
2802   { ast_dump_context->ostream() << "nil"; }
2803 };
2804
2805 // Import a nil expression.
2806
2807 Expression*
2808 Nil_expression::do_import(Import* imp)
2809 {
2810   imp->require_c_string("nil");
2811   return Expression::make_nil(imp->location());
2812 }
2813
2814 // Make a nil expression.
2815
2816 Expression*
2817 Expression::make_nil(Location location)
2818 {
2819   return new Nil_expression(location);
2820 }
2821
2822 // The value of the predeclared constant iota.  This is little more
2823 // than a marker.  This will be lowered to an integer in
2824 // Const_expression::do_lower, which is where we know the value that
2825 // it should have.
2826
2827 class Iota_expression : public Parser_expression
2828 {
2829  public:
2830   Iota_expression(Location location)
2831     : Parser_expression(EXPRESSION_IOTA, location)
2832   { }
2833
2834  protected:
2835   Expression*
2836   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2837   { go_unreachable(); }
2838
2839   // There should only ever be one of these.
2840   Expression*
2841   do_copy()
2842   { go_unreachable(); }
2843   
2844   void
2845   do_dump_expression(Ast_dump_context* ast_dump_context) const
2846   { ast_dump_context->ostream() << "iota"; } 
2847 };
2848
2849 // Make an iota expression.  This is only called for one case: the
2850 // value of the predeclared constant iota.
2851
2852 Expression*
2853 Expression::make_iota()
2854 {
2855   static Iota_expression iota_expression(Linemap::unknown_location());
2856   return &iota_expression;
2857 }
2858
2859 // A type conversion expression.
2860
2861 class Type_conversion_expression : public Expression
2862 {
2863  public:
2864   Type_conversion_expression(Type* type, Expression* expr,
2865                              Location location)
2866     : Expression(EXPRESSION_CONVERSION, location),
2867       type_(type), expr_(expr), may_convert_function_types_(false)
2868   { }
2869
2870   // Return the type to which we are converting.
2871   Type*
2872   type() const
2873   { return this->type_; }
2874
2875   // Return the expression which we are converting.
2876   Expression*
2877   expr() const
2878   { return this->expr_; }
2879
2880   // Permit converting from one function type to another.  This is
2881   // used internally for method expressions.
2882   void
2883   set_may_convert_function_types()
2884   {
2885     this->may_convert_function_types_ = true;
2886   }
2887
2888   // Import a type conversion expression.
2889   static Expression*
2890   do_import(Import*);
2891
2892  protected:
2893   int
2894   do_traverse(Traverse* traverse);
2895
2896   Expression*
2897   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2898
2899   bool
2900   do_is_constant() const
2901   { return this->expr_->is_constant(); }
2902
2903   bool
2904   do_numeric_constant_value(Numeric_constant*) const;
2905
2906   bool
2907   do_string_constant_value(std::string*) const;
2908
2909   Type*
2910   do_type()
2911   { return this->type_; }
2912
2913   void
2914   do_determine_type(const Type_context*)
2915   {
2916     Type_context subcontext(this->type_, false);
2917     this->expr_->determine_type(&subcontext);
2918   }
2919
2920   void
2921   do_check_types(Gogo*);
2922
2923   Expression*
2924   do_copy()
2925   {
2926     return new Type_conversion_expression(this->type_, this->expr_->copy(),
2927                                           this->location());
2928   }
2929
2930   tree
2931   do_get_tree(Translate_context* context);
2932
2933   void
2934   do_export(Export*) const;
2935
2936   void
2937   do_dump_expression(Ast_dump_context*) const;
2938
2939  private:
2940   // The type to convert to.
2941   Type* type_;
2942   // The expression to convert.
2943   Expression* expr_;
2944   // True if this is permitted to convert function types.  This is
2945   // used internally for method expressions.
2946   bool may_convert_function_types_;
2947 };
2948
2949 // Traversal.
2950
2951 int
2952 Type_conversion_expression::do_traverse(Traverse* traverse)
2953 {
2954   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2955       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2956     return TRAVERSE_EXIT;
2957   return TRAVERSE_CONTINUE;
2958 }
2959
2960 // Convert to a constant at lowering time.
2961
2962 Expression*
2963 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2964                                      Statement_inserter*, int)
2965 {
2966   Type* type = this->type_;
2967   Expression* val = this->expr_;
2968   Location location = this->location();
2969
2970   if (type->is_numeric_type())
2971     {
2972       Numeric_constant nc;
2973       if (val->numeric_constant_value(&nc))
2974         {
2975           if (!nc.set_type(type, true, location))
2976             return Expression::make_error(location);
2977           return nc.expression(location);
2978         }
2979     }
2980
2981   if (type->is_slice_type())
2982     {
2983       Type* element_type = type->array_type()->element_type()->forwarded();
2984       bool is_byte = (element_type->integer_type() != NULL
2985                       && element_type->integer_type()->is_byte());
2986       bool is_rune = (element_type->integer_type() != NULL
2987                       && element_type->integer_type()->is_rune());
2988       if (is_byte || is_rune)
2989         {
2990           std::string s;
2991           if (val->string_constant_value(&s))
2992             {
2993               Expression_list* vals = new Expression_list();
2994               if (is_byte)
2995                 {
2996                   for (std::string::const_iterator p = s.begin();
2997                        p != s.end();
2998                        p++)
2999                     {
3000                       mpz_t val;
3001                       mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3002                       Expression* v = Expression::make_integer(&val,
3003                                                                element_type,
3004                                                                location);
3005                       vals->push_back(v);
3006                       mpz_clear(val);
3007                     }
3008                 }
3009               else
3010                 {
3011                   const char *p = s.data();
3012                   const char *pend = s.data() + s.length();
3013                   while (p < pend)
3014                     {
3015                       unsigned int c;
3016                       int adv = Lex::fetch_char(p, &c);
3017                       if (adv == 0)
3018                         {
3019                           warning_at(this->location(), 0,
3020                                      "invalid UTF-8 encoding");
3021                           adv = 1;
3022                         }
3023                       p += adv;
3024                       mpz_t val;
3025                       mpz_init_set_ui(val, c);
3026                       Expression* v = Expression::make_integer(&val,
3027                                                                element_type,
3028                                                                location);
3029                       vals->push_back(v);
3030                       mpz_clear(val);
3031                     }
3032                 }
3033
3034               return Expression::make_slice_composite_literal(type, vals,
3035                                                               location);
3036             }
3037         }
3038     }
3039
3040   return this;
3041 }
3042
3043 // Return the constant numeric value if there is one.
3044
3045 bool
3046 Type_conversion_expression::do_numeric_constant_value(
3047     Numeric_constant* nc) const
3048 {
3049   if (!this->type_->is_numeric_type())
3050     return false;
3051   if (!this->expr_->numeric_constant_value(nc))
3052     return false;
3053   return nc->set_type(this->type_, false, this->location());
3054 }
3055
3056 // Return the constant string value if there is one.
3057
3058 bool
3059 Type_conversion_expression::do_string_constant_value(std::string* val) const
3060 {
3061   if (this->type_->is_string_type()
3062       && this->expr_->type()->integer_type() != NULL)
3063     {
3064       Numeric_constant nc;
3065       if (this->expr_->numeric_constant_value(&nc))
3066         {
3067           unsigned long ival;
3068           if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3069             {
3070               val->clear();
3071               Lex::append_char(ival, true, val, this->location());
3072               return true;
3073             }
3074         }
3075     }
3076
3077   // FIXME: Could handle conversion from const []int here.
3078
3079   return false;
3080 }
3081
3082 // Check that types are convertible.
3083
3084 void
3085 Type_conversion_expression::do_check_types(Gogo*)
3086 {
3087   Type* type = this->type_;
3088   Type* expr_type = this->expr_->type();
3089   std::string reason;
3090
3091   if (type->is_error() || expr_type->is_error())
3092     {
3093       this->set_is_error();
3094       return;
3095     }
3096
3097   if (this->may_convert_function_types_
3098       && type->function_type() != NULL
3099       && expr_type->function_type() != NULL)
3100     return;
3101
3102   if (Type::are_convertible(type, expr_type, &reason))
3103     return;
3104
3105   error_at(this->location(), "%s", reason.c_str());
3106   this->set_is_error();
3107 }
3108
3109 // Get a tree for a type conversion.
3110
3111 tree
3112 Type_conversion_expression::do_get_tree(Translate_context* context)
3113 {
3114   Gogo* gogo = context->gogo();
3115   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3116   tree expr_tree = this->expr_->get_tree(context);
3117
3118   if (type_tree == error_mark_node
3119       || expr_tree == error_mark_node
3120       || TREE_TYPE(expr_tree) == error_mark_node)
3121     return error_mark_node;
3122
3123   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3124     return fold_convert(type_tree, expr_tree);
3125
3126   Type* type = this->type_;
3127   Type* expr_type = this->expr_->type();
3128   tree ret;
3129   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3130     ret = Expression::convert_for_assignment(context, type, expr_type,
3131                                              expr_tree, this->location());
3132   else if (type->integer_type() != NULL)
3133     {
3134       if (expr_type->integer_type() != NULL
3135           || expr_type->float_type() != NULL
3136           || expr_type->is_unsafe_pointer_type())
3137         ret = fold(convert_to_integer(type_tree, expr_tree));
3138       else
3139         go_unreachable();
3140     }
3141   else if (type->float_type() != NULL)
3142     {
3143       if (expr_type->integer_type() != NULL
3144           || expr_type->float_type() != NULL)
3145         ret = fold(convert_to_real(type_tree, expr_tree));
3146       else
3147         go_unreachable();
3148     }
3149   else if (type->complex_type() != NULL)
3150     {
3151       if (expr_type->complex_type() != NULL)
3152         ret = fold(convert_to_complex(type_tree, expr_tree));
3153       else
3154         go_unreachable();
3155     }
3156   else if (type->is_string_type()
3157            && expr_type->integer_type() != NULL)
3158     {
3159       expr_tree = fold_convert(integer_type_node, expr_tree);
3160       if (host_integerp(expr_tree, 0))
3161         {
3162           HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3163           std::string s;
3164           Lex::append_char(intval, true, &s, this->location());
3165           Expression* se = Expression::make_string(s, this->location());
3166           return se->get_tree(context);
3167         }
3168
3169       static tree int_to_string_fndecl;
3170       ret = Gogo::call_builtin(&int_to_string_fndecl,
3171                                this->location(),
3172                                "__go_int_to_string",
3173                                1,
3174                                type_tree,
3175                                integer_type_node,
3176                                fold_convert(integer_type_node, expr_tree));
3177     }
3178   else if (type->is_string_type() && expr_type->is_slice_type())
3179     {
3180       if (!DECL_P(expr_tree))
3181         expr_tree = save_expr(expr_tree);
3182       Array_type* a = expr_type->array_type();
3183       Type* e = a->element_type()->forwarded();
3184       go_assert(e->integer_type() != NULL);
3185       tree valptr = fold_convert(const_ptr_type_node,
3186                                  a->value_pointer_tree(gogo, expr_tree));
3187       tree len = a->length_tree(gogo, expr_tree);
3188       len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3189                              len);
3190       if (e->integer_type()->is_byte())
3191         {
3192           static tree byte_array_to_string_fndecl;
3193           ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3194                                    this->location(),
3195                                    "__go_byte_array_to_string",
3196                                    2,
3197                                    type_tree,
3198                                    const_ptr_type_node,
3199                                    valptr,
3200                                    integer_type_node,
3201                                    len);
3202         }
3203       else
3204         {
3205           go_assert(e->integer_type()->is_rune());
3206           static tree int_array_to_string_fndecl;
3207           ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3208                                    this->location(),
3209                                    "__go_int_array_to_string",
3210                                    2,
3211                                    type_tree,
3212                                    const_ptr_type_node,
3213                                    valptr,
3214                                    integer_type_node,
3215                                    len);
3216         }
3217     }
3218   else if (type->is_slice_type() && expr_type->is_string_type())
3219     {
3220       Type* e = type->array_type()->element_type()->forwarded();
3221       go_assert(e->integer_type() != NULL);
3222       if (e->integer_type()->is_byte())
3223         {
3224           tree string_to_byte_array_fndecl = NULL_TREE;
3225           ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3226                                    this->location(),
3227                                    "__go_string_to_byte_array",
3228                                    1,
3229                                    type_tree,
3230                                    TREE_TYPE(expr_tree),
3231                                    expr_tree);
3232         }
3233       else
3234         {
3235           go_assert(e->integer_type()->is_rune());
3236           tree string_to_int_array_fndecl = NULL_TREE;
3237           ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3238                                    this->location(),
3239                                    "__go_string_to_int_array",
3240                                    1,
3241                                    type_tree,
3242                                    TREE_TYPE(expr_tree),
3243                                    expr_tree);
3244         }
3245     }
3246   else if ((type->is_unsafe_pointer_type()
3247             && expr_type->points_to() != NULL)
3248            || (expr_type->is_unsafe_pointer_type()
3249                && type->points_to() != NULL))
3250     ret = fold_convert(type_tree, expr_tree);
3251   else if (type->is_unsafe_pointer_type()
3252            && expr_type->integer_type() != NULL)
3253     ret = convert_to_pointer(type_tree, expr_tree);
3254   else if (this->may_convert_function_types_
3255            && type->function_type() != NULL
3256            && expr_type->function_type() != NULL)
3257     ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3258                            expr_tree);
3259   else
3260     ret = Expression::convert_for_assignment(context, type, expr_type,
3261                                              expr_tree, this->location());
3262
3263   return ret;
3264 }
3265
3266 // Output a type conversion in a constant expression.
3267
3268 void
3269 Type_conversion_expression::do_export(Export* exp) const
3270 {
3271   exp->write_c_string("convert(");
3272   exp->write_type(this->type_);
3273   exp->write_c_string(", ");
3274   this->expr_->export_expression(exp);
3275   exp->write_c_string(")");
3276 }
3277
3278 // Import a type conversion or a struct construction.
3279
3280 Expression*
3281 Type_conversion_expression::do_import(Import* imp)
3282 {
3283   imp->require_c_string("convert(");
3284   Type* type = imp->read_type();
3285   imp->require_c_string(", ");
3286   Expression* val = Expression::import_expression(imp);
3287   imp->require_c_string(")");
3288   return Expression::make_cast(type, val, imp->location());
3289 }
3290
3291 // Dump ast representation for a type conversion expression.
3292
3293 void
3294 Type_conversion_expression::do_dump_expression(
3295     Ast_dump_context* ast_dump_context) const
3296 {
3297   ast_dump_context->dump_type(this->type_);
3298   ast_dump_context->ostream() << "(";
3299   ast_dump_context->dump_expression(this->expr_);
3300   ast_dump_context->ostream() << ") ";
3301 }
3302
3303 // Make a type cast expression.
3304
3305 Expression*
3306 Expression::make_cast(Type* type, Expression* val, Location location)
3307 {
3308   if (type->is_error_type() || val->is_error_expression())
3309     return Expression::make_error(location);
3310   return new Type_conversion_expression(type, val, location);
3311 }
3312
3313 // An unsafe type conversion, used to pass values to builtin functions.
3314
3315 class Unsafe_type_conversion_expression : public Expression
3316 {
3317  public:
3318   Unsafe_type_conversion_expression(Type* type, Expression* expr,
3319                                     Location location)
3320     : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3321       type_(type), expr_(expr)
3322   { }
3323
3324  protected:
3325   int
3326   do_traverse(Traverse* traverse);
3327
3328   Type*
3329   do_type()
3330   { return this->type_; }
3331
3332   void
3333   do_determine_type(const Type_context*)
3334   { this->expr_->determine_type_no_context(); }
3335
3336   Expression*
3337   do_copy()
3338   {
3339     return new Unsafe_type_conversion_expression(this->type_,
3340                                                  this->expr_->copy(),
3341                                                  this->location());
3342   }
3343
3344   tree
3345   do_get_tree(Translate_context*);
3346
3347   void
3348   do_dump_expression(Ast_dump_context*) const;
3349
3350  private:
3351   // The type to convert to.
3352   Type* type_;
3353   // The expression to convert.
3354   Expression* expr_;
3355 };
3356
3357 // Traversal.
3358
3359 int
3360 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3361 {
3362   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3363       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3364     return TRAVERSE_EXIT;
3365   return TRAVERSE_CONTINUE;
3366 }
3367
3368 // Convert to backend representation.
3369
3370 tree
3371 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3372 {
3373   // We are only called for a limited number of cases.
3374
3375   Type* t = this->type_;
3376   Type* et = this->expr_->type();
3377
3378   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3379   tree expr_tree = this->expr_->get_tree(context);
3380   if (type_tree == error_mark_node || expr_tree == error_mark_node)
3381     return error_mark_node;
3382
3383   Location loc = this->location();
3384
3385   bool use_view_convert = false;
3386   if (t->is_slice_type())
3387     {
3388       go_assert(et->is_slice_type());
3389       use_view_convert = true;
3390     }
3391   else if (t->map_type() != NULL)
3392     go_assert(et->map_type() != NULL);
3393   else if (t->channel_type() != NULL)
3394     go_assert(et->channel_type() != NULL);
3395   else if (t->points_to() != NULL)
3396     go_assert(et->points_to() != NULL || et->is_nil_type());
3397   else if (et->is_unsafe_pointer_type())
3398     go_assert(t->points_to() != NULL);
3399   else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3400     {
3401       go_assert(et->interface_type() != NULL
3402                  && !et->interface_type()->is_empty());
3403       use_view_convert = true;
3404     }
3405   else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3406     {
3407       go_assert(et->interface_type() != NULL
3408                  && et->interface_type()->is_empty());
3409       use_view_convert = true;
3410     }
3411   else if (t->integer_type() != NULL)
3412     {
3413       go_assert(et->is_boolean_type()
3414                  || et->integer_type() != NULL
3415                  || et->function_type() != NULL
3416                  || et->points_to() != NULL
3417                  || et->map_type() != NULL
3418                  || et->channel_type() != NULL);
3419       return convert_to_integer(type_tree, expr_tree);
3420     }
3421   else
3422     go_unreachable();
3423
3424   if (use_view_convert)
3425     return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3426                            expr_tree);
3427   else
3428     return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3429 }
3430
3431 // Dump ast representation for an unsafe type conversion expression.
3432
3433 void
3434 Unsafe_type_conversion_expression::do_dump_expression(
3435     Ast_dump_context* ast_dump_context) const
3436 {
3437   ast_dump_context->dump_type(this->type_);
3438   ast_dump_context->ostream() << "(";
3439   ast_dump_context->dump_expression(this->expr_);
3440   ast_dump_context->ostream() << ") ";
3441 }
3442
3443 // Make an unsafe type conversion expression.
3444
3445 Expression*
3446 Expression::make_unsafe_cast(Type* type, Expression* expr,
3447                              Location location)
3448 {
3449   return new Unsafe_type_conversion_expression(type, expr, location);
3450 }
3451
3452 // Unary expressions.
3453
3454 class Unary_expression : public Expression
3455 {
3456  public:
3457   Unary_expression(Operator op, Expression* expr, Location location)
3458     : Expression(EXPRESSION_UNARY, location),
3459       op_(op), escapes_(true), create_temp_(false), expr_(expr)
3460   { }
3461
3462   // Return the operator.
3463   Operator
3464   op() const
3465   { return this->op_; }
3466
3467   // Return the operand.
3468   Expression*
3469   operand() const
3470   { return this->expr_; }
3471
3472   // Record that an address expression does not escape.
3473   void
3474   set_does_not_escape()
3475   {
3476     go_assert(this->op_ == OPERATOR_AND);
3477     this->escapes_ = false;
3478   }
3479
3480   // Record that this is an address expression which should create a
3481   // temporary variable if necessary.  This is used for method calls.
3482   void
3483   set_create_temp()
3484   {
3485     go_assert(this->op_ == OPERATOR_AND);
3486     this->create_temp_ = true;
3487   }
3488
3489   // Apply unary opcode OP to UNC, setting NC.  Return true if this
3490   // could be done, false if not.  Issue errors for overflow.
3491   static bool
3492   eval_constant(Operator op, const Numeric_constant* unc,
3493                 Location, Numeric_constant* nc);
3494
3495   static Expression*
3496   do_import(Import*);
3497
3498  protected:
3499   int
3500   do_traverse(Traverse* traverse)
3501   { return Expression::traverse(&this->expr_, traverse); }
3502
3503   Expression*
3504   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3505
3506   bool
3507   do_is_constant() const;
3508
3509   bool
3510   do_numeric_constant_value(Numeric_constant*) const;
3511
3512   Type*
3513   do_type();
3514
3515   void
3516   do_determine_type(const Type_context*);
3517
3518   void
3519   do_check_types(Gogo*);
3520
3521   Expression*
3522   do_copy()
3523   {
3524     return Expression::make_unary(this->op_, this->expr_->copy(),
3525                                   this->location());
3526   }
3527
3528   bool
3529   do_must_eval_subexpressions_in_order(int*) const
3530   { return this->op_ == OPERATOR_MULT; }
3531
3532   bool
3533   do_is_addressable() const
3534   { return this->op_ == OPERATOR_MULT; }
3535
3536   tree
3537   do_get_tree(Translate_context*);
3538
3539   void
3540   do_export(Export*) const;
3541
3542   void
3543   do_dump_expression(Ast_dump_context*) const;
3544
3545  private:
3546   // The unary operator to apply.
3547   Operator op_;
3548   // Normally true.  False if this is an address expression which does
3549   // not escape the current function.
3550   bool escapes_;
3551   // True if this is an address expression which should create a
3552   // temporary variable if necessary.
3553   bool create_temp_;
3554   // The operand.
3555   Expression* expr_;
3556 };
3557
3558 // If we are taking the address of a composite literal, and the
3559 // contents are not constant, then we want to make a heap composite
3560 // instead.
3561
3562 Expression*
3563 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3564 {
3565   Location loc = this->location();
3566   Operator op = this->op_;
3567   Expression* expr = this->expr_;
3568
3569   if (op == OPERATOR_MULT && expr->is_type_expression())
3570     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3571
3572   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
3573   // moving x to the heap.  FIXME: Is it worth doing a real escape
3574   // analysis here?  This case is found in math/unsafe.go and is
3575   // therefore worth special casing.
3576   if (op == OPERATOR_MULT)
3577     {
3578       Expression* e = expr;
3579       while (e->classification() == EXPRESSION_CONVERSION)
3580         {
3581           Type_conversion_expression* te
3582             = static_cast<Type_conversion_expression*>(e);
3583           e = te->expr();
3584         }
3585
3586       if (e->classification() == EXPRESSION_UNARY)
3587         {
3588           Unary_expression* ue = static_cast<Unary_expression*>(e);
3589           if (ue->op_ == OPERATOR_AND)
3590             {
3591               if (e == expr)
3592                 {
3593                   // *&x == x.
3594                   return ue->expr_;
3595                 }
3596               ue->set_does_not_escape();
3597             }
3598         }
3599     }
3600
3601   // Catching an invalid indirection of unsafe.Pointer here avoid
3602   // having to deal with TYPE_VOID in other places.
3603   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3604     {
3605       error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3606       return Expression::make_error(this->location());
3607     }
3608
3609   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3610     {
3611       Numeric_constant nc;
3612       if (expr->numeric_constant_value(&nc))
3613         {
3614           Numeric_constant result;
3615           if (Unary_expression::eval_constant(op, &nc, loc, &result))
3616             return result.expression(loc);
3617         }
3618     }
3619
3620   return this;
3621 }
3622
3623 // Return whether a unary expression is a constant.
3624
3625 bool
3626 Unary_expression::do_is_constant() const
3627 {
3628   if (this->op_ == OPERATOR_MULT)
3629     {
3630       // Indirecting through a pointer is only constant if the object
3631       // to which the expression points is constant, but we currently
3632       // have no way to determine that.
3633       return false;
3634     }
3635   else if (this->op_ == OPERATOR_AND)
3636     {
3637       // Taking the address of a variable is constant if it is a
3638       // global variable, not constant otherwise.  In other cases
3639       // taking the address is probably not a constant.
3640       Var_expression* ve = this->expr_->var_expression();
3641       if (ve != NULL)
3642         {
3643           Named_object* no = ve->named_object();
3644           return no->is_variable() && no->var_value()->is_global();
3645         }
3646       return false;
3647     }
3648   else
3649     return this->expr_->is_constant();
3650 }
3651
3652 // Apply unary opcode OP to UNC, setting NC.  Return true if this
3653 // could be done, false if not.  Issue errors for overflow.
3654
3655 bool
3656 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3657                                 Location location, Numeric_constant* nc)
3658 {
3659   switch (op)
3660     {
3661     case OPERATOR_PLUS:
3662       *nc = *unc;
3663       return true;
3664
3665     case OPERATOR_MINUS:
3666       if (unc->is_int() || unc->is_rune())
3667         break;
3668       else if (unc->is_float())
3669         {
3670           mpfr_t uval;
3671           unc->get_float(&uval);
3672           mpfr_t val;
3673           mpfr_init(val);
3674           mpfr_neg(val, uval, GMP_RNDN);
3675           nc->set_float(unc->type(), val);
3676           mpfr_clear(uval);
3677           mpfr_clear(val);
3678           return true;
3679         }
3680       else if (unc->is_complex())
3681         {
3682           mpfr_t ureal, uimag;
3683           unc->get_complex(&ureal, &uimag);
3684           mpfr_t real, imag;
3685           mpfr_init(real);
3686           mpfr_init(imag);
3687           mpfr_neg(real, ureal, GMP_RNDN);
3688           mpfr_neg(imag, uimag, GMP_RNDN);
3689           nc->set_complex(unc->type(), real, imag);
3690           mpfr_clear(ureal);
3691           mpfr_clear(uimag);
3692           mpfr_clear(real);
3693           mpfr_clear(imag);
3694           return true;
3695         }
3696       else
3697         go_unreachable();
3698
3699     case OPERATOR_XOR:
3700       break;
3701
3702     case OPERATOR_NOT:
3703     case OPERATOR_AND:
3704     case OPERATOR_MULT:
3705       return false;
3706
3707     default:
3708       go_unreachable();
3709     }
3710
3711   if (!unc->is_int() && !unc->is_rune())
3712     return false;
3713
3714   mpz_t uval;
3715   unc->get_int(&uval);
3716   mpz_t val;
3717   mpz_init(val);
3718
3719   switch (op)
3720     {
3721     case OPERATOR_MINUS:
3722       mpz_neg(val, uval);
3723       break;
3724
3725     case OPERATOR_NOT:
3726       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3727       break;
3728
3729     case OPERATOR_XOR:
3730       {
3731         Type* utype = unc->type();
3732         if (utype->integer_type() == NULL
3733             || utype->integer_type()->is_abstract())
3734           mpz_com(val, uval);
3735         else
3736           {
3737             // The number of HOST_WIDE_INTs that it takes to represent
3738             // UVAL.
3739             size_t count = ((mpz_sizeinbase(uval, 2)
3740                              + HOST_BITS_PER_WIDE_INT
3741                              - 1)
3742                             / HOST_BITS_PER_WIDE_INT);
3743
3744             unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3745             memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3746
3747             size_t obits = utype->integer_type()->bits();
3748
3749             if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3750               {
3751                 mpz_t adj;
3752                 mpz_init_set_ui(adj, 1);
3753                 mpz_mul_2exp(adj, adj, obits);
3754                 mpz_add(uval, uval, adj);
3755                 mpz_clear(adj);
3756               }
3757
3758             size_t ecount;
3759             mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3760             go_assert(ecount <= count);
3761
3762             // Trim down to the number of words required by the type.
3763             size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3764                              / HOST_BITS_PER_WIDE_INT);
3765             go_assert(ocount <= count);
3766
3767             for (size_t i = 0; i < ocount; ++i)
3768               phwi[i] = ~phwi[i];
3769
3770             size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3771             if (clearbits != 0)
3772               phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3773                                    >> clearbits);
3774
3775             mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3776
3777             if (!utype->integer_type()->is_unsigned()
3778                 && mpz_tstbit(val, obits - 1))
3779               {
3780                 mpz_t adj;
3781                 mpz_init_set_ui(adj, 1);
3782                 mpz_mul_2exp(adj, adj, obits);
3783                 mpz_sub(val, val, adj);
3784                 mpz_clear(adj);
3785               }
3786
3787             delete[] phwi;
3788           }
3789       }
3790       break;
3791
3792     default:
3793       go_unreachable();
3794     }
3795
3796   if (unc->is_rune())
3797     nc->set_rune(NULL, val);
3798   else
3799     nc->set_int(NULL, val);
3800
3801   mpz_clear(uval);
3802   mpz_clear(val);
3803
3804   return nc->set_type(unc->type(), true, location);
3805 }
3806
3807 // Return the integral constant value of a unary expression, if it has one.
3808
3809 bool
3810 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3811 {
3812   Numeric_constant unc;
3813   if (!this->expr_->numeric_constant_value(&unc))
3814     return false;
3815   return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3816                                          nc);
3817 }
3818
3819 // Return the type of a unary expression.
3820
3821 Type*
3822 Unary_expression::do_type()
3823 {
3824   switch (this->op_)
3825     {
3826     case OPERATOR_PLUS:
3827     case OPERATOR_MINUS:
3828     case OPERATOR_NOT:
3829     case OPERATOR_XOR:
3830       return this->expr_->type();
3831
3832     case OPERATOR_AND:
3833       return Type::make_pointer_type(this->expr_->type());
3834
3835     case OPERATOR_MULT:
3836       {
3837         Type* subtype = this->expr_->type();
3838         Type* points_to = subtype->points_to();
3839         if (points_to == NULL)
3840           return Type::make_error_type();
3841         return points_to;
3842       }
3843
3844     default:
3845       go_unreachable();
3846     }
3847 }
3848
3849 // Determine abstract types for a unary expression.
3850
3851 void
3852 Unary_expression::do_determine_type(const Type_context* context)
3853 {
3854   switch (this->op_)
3855     {
3856     case OPERATOR_PLUS:
3857     case OPERATOR_MINUS:
3858     case OPERATOR_NOT:
3859     case OPERATOR_XOR:
3860       this->expr_->determine_type(context);
3861       break;
3862
3863     case OPERATOR_AND:
3864       // Taking the address of something.
3865       {
3866         Type* subtype = (context->type == NULL
3867                          ? NULL
3868                          : context->type->points_to());
3869         Type_context subcontext(subtype, false);
3870         this->expr_->determine_type(&subcontext);
3871       }
3872       break;
3873
3874     case OPERATOR_MULT:
3875       // Indirecting through a pointer.
3876       {
3877         Type* subtype = (context->type == NULL
3878                          ? NULL
3879                          : Type::make_pointer_type(context->type));
3880         Type_context subcontext(subtype, false);
3881         this->expr_->determine_type(&subcontext);
3882       }
3883       break;
3884
3885     default:
3886       go_unreachable();
3887     }
3888 }
3889
3890 // Check types for a unary expression.
3891
3892 void
3893 Unary_expression::do_check_types(Gogo*)
3894 {
3895   Type* type = this->expr_->type();
3896   if (type->is_error())
3897     {
3898       this->set_is_error();
3899       return;
3900     }
3901
3902   switch (this->op_)
3903     {
3904     case OPERATOR_PLUS:
3905     case OPERATOR_MINUS:
3906       if (type->integer_type() == NULL
3907           && type->float_type() == NULL
3908           && type->complex_type() == NULL)
3909         this->report_error(_("expected numeric type"));
3910       break;
3911
3912     case OPERATOR_NOT:
3913       if (!type->is_boolean_type())
3914         this->report_error(_("expected boolean type"));
3915       break;
3916
3917     case OPERATOR_XOR:
3918       if (type->integer_type() == NULL
3919           && !type->is_boolean_type())
3920         this->report_error(_("expected integer or boolean type"));
3921       break;
3922
3923     case OPERATOR_AND:
3924       if (!this->expr_->is_addressable())
3925         {
3926           if (!this->create_temp_)
3927             this->report_error(_("invalid operand for unary %<&%>"));
3928         }
3929       else
3930         this->expr_->address_taken(this->escapes_);
3931       break;
3932
3933     case OPERATOR_MULT:
3934       // Indirecting through a pointer.
3935       if (type->points_to() == NULL)
3936         this->report_error(_("expected pointer"));
3937       break;
3938
3939     default:
3940       go_unreachable();
3941     }
3942 }
3943
3944 // Get a tree for a unary expression.
3945
3946 tree
3947 Unary_expression::do_get_tree(Translate_context* context)
3948 {
3949   Location loc = this->location();
3950
3951   // Taking the address of a set-and-use-temporary expression requires
3952   // setting the temporary and then taking the address.
3953   if (this->op_ == OPERATOR_AND)
3954     {
3955       Set_and_use_temporary_expression* sut =
3956         this->expr_->set_and_use_temporary_expression();
3957       if (sut != NULL)
3958         {
3959           Temporary_statement* temp = sut->temporary();
3960           Bvariable* bvar = temp->get_backend_variable(context);
3961           tree var_tree = var_to_tree(bvar);
3962           Expression* val = sut->expression();
3963           tree val_tree = val->get_tree(context);
3964           if (var_tree == error_mark_node || val_tree == error_mark_node)
3965             return error_mark_node;
3966           tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3967                                                     var_tree);
3968           return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3969                             TREE_TYPE(addr_tree),
3970                             build2_loc(sut->location().gcc_location(),
3971                                        MODIFY_EXPR, void_type_node,
3972                                        var_tree, val_tree),
3973                             addr_tree);
3974         }
3975     }
3976
3977   tree expr = this->expr_->get_tree(context);
3978   if (expr == error_mark_node)
3979     return error_mark_node;
3980
3981   switch (this->op_)
3982     {
3983     case OPERATOR_PLUS:
3984       return expr;
3985
3986     case OPERATOR_MINUS:
3987       {
3988         tree type = TREE_TYPE(expr);
3989         tree compute_type = excess_precision_type(type);
3990         if (compute_type != NULL_TREE)
3991           expr = ::convert(compute_type, expr);
3992         tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3993                                    (compute_type != NULL_TREE
3994                                     ? compute_type
3995                                     : type),
3996                                    expr);
3997         if (compute_type != NULL_TREE)
3998           ret = ::convert(type, ret);
3999         return ret;
4000       }
4001
4002     case OPERATOR_NOT:
4003       if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
4004         return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4005                                TREE_TYPE(expr), expr);
4006       else
4007         return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4008                                expr, build_int_cst(TREE_TYPE(expr), 0));
4009
4010     case OPERATOR_XOR:
4011       return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4012                              expr);
4013
4014     case OPERATOR_AND:
4015       if (!this->create_temp_)
4016         {
4017           // We should not see a non-constant constructor here; cases
4018           // where we would see one should have been moved onto the
4019           // heap at parse time.  Taking the address of a nonconstant
4020           // constructor will not do what the programmer expects.
4021           go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4022           go_assert(TREE_CODE(expr) != ADDR_EXPR);
4023         }
4024
4025       // Build a decl for a constant constructor.
4026       if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4027         {
4028           tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4029                                  create_tmp_var_name("C"), TREE_TYPE(expr));
4030           DECL_EXTERNAL(decl) = 0;
4031           TREE_PUBLIC(decl) = 0;
4032           TREE_READONLY(decl) = 1;
4033           TREE_CONSTANT(decl) = 1;
4034           TREE_STATIC(decl) = 1;
4035           TREE_ADDRESSABLE(decl) = 1;
4036           DECL_ARTIFICIAL(decl) = 1;
4037           DECL_INITIAL(decl) = expr;
4038           rest_of_decl_compilation(decl, 1, 0);
4039           expr = decl;
4040         }
4041
4042       if (this->create_temp_
4043           && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4044           && !DECL_P(expr)
4045           && TREE_CODE(expr) != INDIRECT_REF
4046           && TREE_CODE(expr) != COMPONENT_REF)
4047         {
4048           tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4049           DECL_IGNORED_P(tmp) = 1;
4050           DECL_INITIAL(tmp) = expr;
4051           TREE_ADDRESSABLE(tmp) = 1;
4052           return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4053                             build_pointer_type(TREE_TYPE(expr)),
4054                             build1_loc(loc.gcc_location(), DECL_EXPR,
4055                                        void_type_node, tmp),
4056                             build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4057         }
4058
4059       return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4060
4061     case OPERATOR_MULT:
4062       {
4063         go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4064
4065         // If we are dereferencing the pointer to a large struct, we
4066         // need to check for nil.  We don't bother to check for small
4067         // structs because we expect the system to crash on a nil
4068         // pointer dereference.
4069         tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4070         if (!VOID_TYPE_P(target_type_tree))
4071           {
4072             HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4073             if (s == -1 || s >= 4096)
4074               {
4075                 if (!DECL_P(expr))
4076                   expr = save_expr(expr);
4077                 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4078                                                boolean_type_node,
4079                                                expr,
4080                                                fold_convert(TREE_TYPE(expr),
4081                                                             null_pointer_node));
4082                 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4083                                                  loc);
4084                 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4085                                        TREE_TYPE(expr), build3(COND_EXPR,
4086                                                                void_type_node,
4087                                                                compare, crash,
4088                                                                NULL_TREE),
4089                                        expr);
4090               }
4091           }
4092
4093         // If the type of EXPR is a recursive pointer type, then we
4094         // need to insert a cast before indirecting.
4095         if (VOID_TYPE_P(target_type_tree))
4096           {
4097             Type* pt = this->expr_->type()->points_to();
4098             tree ind = type_to_tree(pt->get_backend(context->gogo()));
4099             expr = fold_convert_loc(loc.gcc_location(),
4100                                     build_pointer_type(ind), expr);
4101           }
4102
4103         return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4104       }
4105
4106     default:
4107       go_unreachable();
4108     }
4109 }
4110
4111 // Export a unary expression.
4112
4113 void
4114 Unary_expression::do_export(Export* exp) const
4115 {
4116   switch (this->op_)
4117     {
4118     case OPERATOR_PLUS:
4119       exp->write_c_string("+ ");
4120       break;
4121     case OPERATOR_MINUS:
4122       exp->write_c_string("- ");
4123       break;
4124     case OPERATOR_NOT:
4125       exp->write_c_string("! ");
4126       break;
4127     case OPERATOR_XOR:
4128       exp->write_c_string("^ ");
4129       break;
4130     case OPERATOR_AND:
4131     case OPERATOR_MULT:
4132     default:
4133       go_unreachable();
4134     }
4135   this->expr_->export_expression(exp);
4136 }
4137
4138 // Import a unary expression.
4139
4140 Expression*
4141 Unary_expression::do_import(Import* imp)
4142 {
4143   Operator op;
4144   switch (imp->get_char())
4145     {
4146     case '+':
4147       op = OPERATOR_PLUS;
4148       break;
4149     case '-':
4150       op = OPERATOR_MINUS;
4151       break;
4152     case '!':
4153       op = OPERATOR_NOT;
4154       break;
4155     case '^':
4156       op = OPERATOR_XOR;
4157       break;
4158     default:
4159       go_unreachable();
4160     }
4161   imp->require_c_string(" ");
4162   Expression* expr = Expression::import_expression(imp);
4163   return Expression::make_unary(op, expr, imp->location());
4164 }
4165
4166 // Dump ast representation of an unary expression.
4167
4168 void
4169 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4170 {
4171   ast_dump_context->dump_operator(this->op_);
4172   ast_dump_context->ostream() << "(";
4173   ast_dump_context->dump_expression(this->expr_);
4174   ast_dump_context->ostream() << ") ";
4175 }
4176
4177 // Make a unary expression.
4178
4179 Expression*
4180 Expression::make_unary(Operator op, Expression* expr, Location location)
4181 {
4182   return new Unary_expression(op, expr, location);
4183 }
4184
4185 // If this is an indirection through a pointer, return the expression
4186 // being pointed through.  Otherwise return this.
4187
4188 Expression*
4189 Expression::deref()
4190 {
4191   if (this->classification_ == EXPRESSION_UNARY)
4192     {
4193       Unary_expression* ue = static_cast<Unary_expression*>(this);
4194       if (ue->op() == OPERATOR_MULT)
4195         return ue->operand();
4196     }
4197   return this;
4198 }
4199
4200 // Class Binary_expression.
4201
4202 // Traversal.
4203
4204 int
4205 Binary_expression::do_traverse(Traverse* traverse)
4206 {
4207   int t = Expression::traverse(&this->left_, traverse);
4208   if (t == TRAVERSE_EXIT)
4209     return TRAVERSE_EXIT;
4210   return Expression::traverse(&this->right_, traverse);
4211 }
4212
4213 // Return the type to use for a binary operation on operands of
4214 // LEFT_TYPE and RIGHT_TYPE.  These are the types of constants and as
4215 // such may be NULL or abstract.
4216
4217 bool
4218 Binary_expression::operation_type(Operator op, Type* left_type,
4219                                   Type* right_type, Type** result_type)
4220 {
4221   if (left_type != right_type
4222       && !left_type->is_abstract()
4223       && !right_type->is_abstract()
4224       && left_type->base() != right_type->base()
4225       && op != OPERATOR_LSHIFT
4226       && op != OPERATOR_RSHIFT)
4227     {
4228       // May be a type error--let it be diagnosed elsewhere.
4229       return false;
4230     }
4231
4232   if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4233     {
4234       if (left_type->integer_type() != NULL)
4235         *result_type = left_type;
4236       else
4237         *result_type = Type::make_abstract_integer_type();
4238     }
4239   else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4240     *result_type = left_type;
4241   else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4242     *result_type = right_type;
4243   else if (!left_type->is_abstract())
4244     *result_type = left_type;
4245   else if (!right_type->is_abstract())
4246     *result_type = right_type;
4247   else if (left_type->complex_type() != NULL)
4248     *result_type = left_type;
4249   else if (right_type->complex_type() != NULL)
4250     *result_type = right_type;
4251   else if (left_type->float_type() != NULL)
4252     *result_type = left_type;
4253   else if (right_type->float_type() != NULL)
4254     *result_type = right_type;
4255   else if (left_type->integer_type() != NULL
4256            && left_type->integer_type()->is_rune())
4257     *result_type = left_type;
4258   else if (right_type->integer_type() != NULL
4259            && right_type->integer_type()->is_rune())
4260     *result_type = right_type;
4261   else
4262     *result_type = left_type;
4263
4264   return true;
4265 }
4266
4267 // Convert an integer comparison code and an operator to a boolean
4268 // value.
4269
4270 bool
4271 Binary_expression::cmp_to_bool(Operator op, int cmp)
4272 {
4273   switch (op)
4274     {
4275     case OPERATOR_EQEQ:
4276       return cmp == 0;
4277       break;
4278     case OPERATOR_NOTEQ:
4279       return cmp != 0;
4280       break;
4281     case OPERATOR_LT:
4282       return cmp < 0;
4283       break;
4284     case OPERATOR_LE:
4285       return cmp <= 0;
4286     case OPERATOR_GT:
4287       return cmp > 0;
4288     case OPERATOR_GE:
4289       return cmp >= 0;
4290     default:
4291       go_unreachable();
4292     }
4293 }
4294
4295 // Compare constants according to OP.
4296
4297 bool
4298 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4299                                     Numeric_constant* right_nc,
4300                                     Location location, bool* result)
4301 {
4302   Type* left_type = left_nc->type();
4303   Type* right_type = right_nc->type();
4304
4305   Type* type;
4306   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4307     return false;
4308
4309   // When comparing an untyped operand to a typed operand, we are
4310   // effectively coercing the untyped operand to the other operand's
4311   // type, so make sure that is valid.
4312   if (!left_nc->set_type(type, true, location)
4313       || !right_nc->set_type(type, true, location))
4314     return false;
4315
4316   bool ret;
4317   int cmp;
4318   if (type->complex_type() != NULL)
4319     {
4320       if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4321         return false;
4322       ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4323     }
4324   else if (type->float_type() != NULL)
4325     ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4326   else
4327     ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4328
4329   if (ret)
4330     *result = Binary_expression::cmp_to_bool(op, cmp);
4331
4332   return ret;
4333 }
4334
4335 // Compare integer constants.
4336
4337 bool
4338 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4339                                    const Numeric_constant* right_nc,
4340                                    int* cmp)
4341 {
4342   mpz_t left_val;
4343   if (!left_nc->to_int(&left_val))
4344     return false;
4345   mpz_t right_val;
4346   if (!right_nc->to_int(&right_val))
4347     {
4348       mpz_clear(left_val);
4349       return false;
4350     }
4351
4352   *cmp = mpz_cmp(left_val, right_val);
4353
4354   mpz_clear(left_val);
4355   mpz_clear(right_val);
4356
4357   return true;
4358 }
4359
4360 // Compare floating point constants.
4361
4362 bool
4363 Binary_expression::compare_float(const Numeric_constant* left_nc,
4364                                  const Numeric_constant* right_nc,
4365                                  int* cmp)
4366 {
4367   mpfr_t left_val;
4368   if (!left_nc->to_float(&left_val))
4369     return false;
4370   mpfr_t right_val;
4371   if (!right_nc->to_float(&right_val))
4372     {
4373       mpfr_clear(left_val);
4374       return false;
4375     }
4376
4377   // We already coerced both operands to the same type.  If that type
4378   // is not an abstract type, we need to round the values accordingly.
4379   Type* type = left_nc->type();
4380   if (!type->is_abstract() && type->float_type() != NULL)
4381     {
4382       int bits = type->float_type()->bits();
4383       mpfr_prec_round(left_val, bits, GMP_RNDN);
4384       mpfr_prec_round(right_val, bits, GMP_RNDN);
4385     }
4386
4387   *cmp = mpfr_cmp(left_val, right_val);
4388
4389   mpfr_clear(left_val);
4390   mpfr_clear(right_val);
4391
4392   return true;
4393 }
4394
4395 // Compare complex constants.  Complex numbers may only be compared
4396 // for equality.
4397
4398 bool
4399 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4400                                    const Numeric_constant* right_nc,
4401                                    int* cmp)
4402 {
4403   mpfr_t left_real, left_imag;
4404   if (!left_nc->to_complex(&left_real, &left_imag))
4405     return false;
4406   mpfr_t right_real, right_imag;
4407   if (!right_nc->to_complex(&right_real, &right_imag))
4408     {
4409       mpfr_clear(left_real);
4410       mpfr_clear(left_imag);
4411       return false;
4412     }
4413
4414   // We already coerced both operands to the same type.  If that type
4415   // is not an abstract type, we need to round the values accordingly.
4416   Type* type = left_nc->type();
4417   if (!type->is_abstract() && type->complex_type() != NULL)
4418     {
4419       int bits = type->complex_type()->bits();
4420       mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4421       mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4422       mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4423       mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4424     }
4425
4426   *cmp = (mpfr_cmp(left_real, right_real) != 0
4427           || mpfr_cmp(left_imag, right_imag) != 0);
4428
4429   mpfr_clear(left_real);
4430   mpfr_clear(left_imag);
4431   mpfr_clear(right_real);
4432   mpfr_clear(right_imag);
4433
4434   return true;
4435 }
4436
4437 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC.  Return
4438 // true if this could be done, false if not.  Issue errors at LOCATION
4439 // as appropriate.
4440
4441 bool
4442 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4443                                  Numeric_constant* right_nc,
4444                                  Location location, Numeric_constant* nc)
4445 {
4446   switch (op)
4447     {
4448     case OPERATOR_OROR:
4449     case OPERATOR_ANDAND:
4450     case OPERATOR_EQEQ:
4451     case OPERATOR_NOTEQ:
4452     case OPERATOR_LT:
4453     case OPERATOR_LE:
4454     case OPERATOR_GT:
4455     case OPERATOR_GE:
4456       // These return boolean values and as such must be handled
4457       // elsewhere.
4458       go_unreachable();
4459     default:
4460       break;
4461     }
4462
4463   Type* left_type = left_nc->type();
4464   Type* right_type = right_nc->type();
4465
4466   Type* type;
4467   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4468     return false;
4469
4470   bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4471
4472   // When combining an untyped operand with a typed operand, we are
4473   // effectively coercing the untyped operand to the other operand's
4474   // type, so make sure that is valid.
4475   if (!left_nc->set_type(type, true, location))
4476     return false;
4477   if (!is_shift && !right_nc->set_type(type, true, location))
4478     return false;
4479
4480   bool r;
4481   if (type->complex_type() != NULL)
4482     r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4483   else if (type->float_type() != NULL)
4484     r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4485   else
4486     r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4487
4488   if (r)
4489     r = nc->set_type(type, true, location);
4490
4491   return r;
4492 }
4493
4494 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4495 // integer operations.  Return true if this could be done, false if
4496 // not.
4497
4498 bool
4499 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4500                                 const Numeric_constant* right_nc,
4501                                 Location location, Numeric_constant* nc)
4502 {
4503   mpz_t left_val;
4504   if (!left_nc->to_int(&left_val))
4505     return false;
4506   mpz_t right_val;
4507   if (!right_nc->to_int(&right_val))
4508     {
4509       mpz_clear(left_val);
4510       return false;
4511     }
4512
4513   mpz_t val;
4514   mpz_init(val);
4515
4516   switch (op)
4517     {
4518     case OPERATOR_PLUS:
4519       mpz_add(val, left_val, right_val);
4520       break;
4521     case OPERATOR_MINUS:
4522       mpz_sub(val, left_val, right_val);
4523       break;
4524     case OPERATOR_OR:
4525       mpz_ior(val, left_val, right_val);
4526       break;
4527     case OPERATOR_XOR:
4528       mpz_xor(val, left_val, right_val);
4529       break;
4530     case OPERATOR_MULT:
4531       mpz_mul(val, left_val, right_val);
4532       break;
4533     case OPERATOR_DIV:
4534       if (mpz_sgn(right_val) != 0)
4535         mpz_tdiv_q(val, left_val, right_val);
4536       else
4537         {
4538           error_at(location, "division by zero");
4539           mpz_set_ui(val, 0);
4540         }
4541       break;
4542     case OPERATOR_MOD:
4543       if (mpz_sgn(right_val) != 0)
4544         mpz_tdiv_r(val, left_val, right_val);
4545       else
4546         {
4547           error_at(location, "division by zero");
4548           mpz_set_ui(val, 0);
4549         }
4550       break;
4551     case OPERATOR_LSHIFT:
4552       {
4553         unsigned long shift = mpz_get_ui(right_val);
4554         if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4555           mpz_mul_2exp(val, left_val, shift);
4556         else
4557           {
4558             error_at(location, "shift count overflow");
4559             mpz_set_ui(val, 0);
4560           }
4561         break;
4562       }
4563       break;
4564     case OPERATOR_RSHIFT:
4565       {
4566         unsigned long shift = mpz_get_ui(right_val);
4567         if (mpz_cmp_ui(right_val, shift) != 0)
4568           {
4569             error_at(location, "shift count overflow");
4570             mpz_set_ui(val, 0);
4571           }
4572         else
4573           {
4574             if (mpz_cmp_ui(left_val, 0) >= 0)
4575               mpz_tdiv_q_2exp(val, left_val, shift);
4576             else
4577               mpz_fdiv_q_2exp(val, left_val, shift);
4578           }
4579         break;
4580       }
4581       break;
4582     case OPERATOR_AND:
4583       mpz_and(val, left_val, right_val);
4584       break;
4585     case OPERATOR_BITCLEAR:
4586       {
4587         mpz_t tval;
4588         mpz_init(tval);
4589         mpz_com(tval, right_val);
4590         mpz_and(val, left_val, tval);
4591         mpz_clear(tval);
4592       }
4593       break;
4594     default:
4595       go_unreachable();
4596     }
4597
4598   mpz_clear(left_val);
4599   mpz_clear(right_val);
4600
4601   if (left_nc->is_rune()
4602       || (op != OPERATOR_LSHIFT
4603           && op != OPERATOR_RSHIFT
4604           && right_nc->is_rune()))
4605     nc->set_rune(NULL, val);
4606   else
4607     nc->set_int(NULL, val);
4608
4609   mpz_clear(val);
4610
4611   return true;
4612 }
4613
4614 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4615 // floating point operations.  Return true if this could be done,
4616 // false if not.
4617
4618 bool
4619 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4620                               const Numeric_constant* right_nc,
4621                               Location location, Numeric_constant* nc)
4622 {
4623   mpfr_t left_val;
4624   if (!left_nc->to_float(&left_val))
4625     return false;
4626   mpfr_t right_val;
4627   if (!right_nc->to_float(&right_val))
4628     {
4629       mpfr_clear(left_val);
4630       return false;
4631     }
4632
4633   mpfr_t val;
4634   mpfr_init(val);
4635
4636   bool ret = true;
4637   switch (op)
4638     {
4639     case OPERATOR_PLUS:
4640       mpfr_add(val, left_val, right_val, GMP_RNDN);
4641       break;
4642     case OPERATOR_MINUS:
4643       mpfr_sub(val, left_val, right_val, GMP_RNDN);
4644       break;
4645     case OPERATOR_OR:
4646     case OPERATOR_XOR:
4647     case OPERATOR_AND:
4648     case OPERATOR_BITCLEAR:
4649     case OPERATOR_MOD:
4650     case OPERATOR_LSHIFT:
4651     case OPERATOR_RSHIFT:
4652       mpfr_set_ui(val, 0, GMP_RNDN);
4653       ret = false;
4654       break;
4655     case OPERATOR_MULT:
4656       mpfr_mul(val, left_val, right_val, GMP_RNDN);
4657       break;
4658     case OPERATOR_DIV:
4659       if (!mpfr_zero_p(right_val))
4660         mpfr_div(val, left_val, right_val, GMP_RNDN);
4661       else
4662         {
4663           error_at(location, "division by zero");
4664           mpfr_set_ui(val, 0, GMP_RNDN);
4665         }
4666       break;
4667     default:
4668       go_unreachable();
4669     }
4670
4671   mpfr_clear(left_val);
4672   mpfr_clear(right_val);
4673
4674   nc->set_float(NULL, val);
4675   mpfr_clear(val);
4676
4677   return ret;
4678 }
4679
4680 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4681 // complex operations.  Return true if this could be done, false if
4682 // not.
4683
4684 bool
4685 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4686                                 const Numeric_constant* right_nc,
4687                                 Location location, Numeric_constant* nc)
4688 {
4689   mpfr_t left_real, left_imag;
4690   if (!left_nc->to_complex(&left_real, &left_imag))
4691     return false;
4692   mpfr_t right_real, right_imag;
4693   if (!right_nc->to_complex(&right_real, &right_imag))
4694     {
4695       mpfr_clear(left_real);
4696       mpfr_clear(left_imag);
4697       return false;
4698     }
4699
4700   mpfr_t real, imag;
4701   mpfr_init(real);
4702   mpfr_init(imag);
4703
4704   bool ret = true;
4705   switch (op)
4706     {
4707     case OPERATOR_PLUS:
4708       mpfr_add(real, left_real, right_real, GMP_RNDN);
4709       mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4710       break;
4711     case OPERATOR_MINUS:
4712       mpfr_sub(real, left_real, right_real, GMP_RNDN);
4713       mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4714       break;
4715     case OPERATOR_OR:
4716     case OPERATOR_XOR:
4717     case OPERATOR_AND:
4718     case OPERATOR_BITCLEAR:
4719     case OPERATOR_MOD:
4720     case OPERATOR_LSHIFT:
4721     case OPERATOR_RSHIFT:
4722       mpfr_set_ui(real, 0, GMP_RNDN);
4723       mpfr_set_ui(imag, 0, GMP_RNDN);
4724       ret = false;
4725       break;
4726     case OPERATOR_MULT:
4727       {
4728         // You might think that multiplying two complex numbers would
4729         // be simple, and you would be right, until you start to think
4730         // about getting the right answer for infinity.  If one
4731         // operand here is infinity and the other is anything other
4732         // than zero or NaN, then we are going to wind up subtracting
4733         // two infinity values.  That will give us a NaN, but the
4734         // correct answer is infinity.
4735
4736         mpfr_t lrrr;
4737         mpfr_init(lrrr);
4738         mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4739
4740         mpfr_t lrri;
4741         mpfr_init(lrri);
4742         mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4743
4744         mpfr_t lirr;
4745         mpfr_init(lirr);
4746         mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4747
4748         mpfr_t liri;
4749         mpfr_init(liri);
4750         mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4751
4752         mpfr_sub(real, lrrr, liri, GMP_RNDN);
4753         mpfr_add(imag, lrri, lirr, GMP_RNDN);
4754
4755         // If we get NaN on both sides, check whether it should really
4756         // be infinity.  The rule is that if either side of the
4757         // complex number is infinity, then the whole value is
4758         // infinity, even if the other side is NaN.  So the only case
4759         // we have to fix is the one in which both sides are NaN.
4760         if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4761             && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4762             && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4763           {
4764             bool is_infinity = false;
4765
4766             mpfr_t lr;
4767             mpfr_t li;
4768             mpfr_init_set(lr, left_real, GMP_RNDN);
4769             mpfr_init_set(li, left_imag, GMP_RNDN);
4770
4771             mpfr_t rr;
4772             mpfr_t ri;
4773             mpfr_init_set(rr, right_real, GMP_RNDN);
4774             mpfr_init_set(ri, right_imag, GMP_RNDN);
4775
4776             // If the left side is infinity, then the result is
4777             // infinity.
4778             if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4779               {
4780                 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4781                 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4782                 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4783                 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4784                 if (mpfr_nan_p(rr))
4785                   {
4786                     mpfr_set_ui(rr, 0, GMP_RNDN);
4787                     mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4788                   }
4789                 if (mpfr_nan_p(ri))
4790                   {
4791                     mpfr_set_ui(ri, 0, GMP_RNDN);
4792                     mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4793                   }
4794                 is_infinity = true;
4795               }
4796
4797             // If the right side is infinity, then the result is
4798             // infinity.
4799             if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4800               {
4801                 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4802                 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4803                 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4804                 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4805                 if (mpfr_nan_p(lr))
4806                   {
4807                     mpfr_set_ui(lr, 0, GMP_RNDN);
4808                     mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4809                   }
4810                 if (mpfr_nan_p(li))
4811                   {
4812                     mpfr_set_ui(li, 0, GMP_RNDN);
4813                     mpfr_copysign(li, li, left_imag, GMP_RNDN);
4814                   }
4815                 is_infinity = true;
4816               }
4817
4818             // If we got an overflow in the intermediate computations,
4819             // then the result is infinity.
4820             if (!is_infinity
4821                 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4822                     || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4823               {
4824                 if (mpfr_nan_p(lr))
4825                   {
4826                     mpfr_set_ui(lr, 0, GMP_RNDN);
4827                     mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4828                   }
4829                 if (mpfr_nan_p(li))
4830                   {
4831                     mpfr_set_ui(li, 0, GMP_RNDN);
4832                     mpfr_copysign(li, li, left_imag, GMP_RNDN);
4833                   }
4834                 if (mpfr_nan_p(rr))
4835                   {
4836                     mpfr_set_ui(rr, 0, GMP_RNDN);
4837                     mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4838                   }
4839                 if (mpfr_nan_p(ri))
4840                   {
4841                     mpfr_set_ui(ri, 0, GMP_RNDN);
4842                     mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4843                   }
4844                 is_infinity = true;
4845               }
4846
4847             if (is_infinity)
4848               {
4849                 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4850                 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4851                 mpfr_mul(lirr, li, rr, GMP_RNDN);
4852                 mpfr_mul(liri, li, ri, GMP_RNDN);
4853                 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4854                 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4855                 mpfr_set_inf(real, mpfr_sgn(real));
4856                 mpfr_set_inf(imag, mpfr_sgn(imag));
4857               }
4858
4859             mpfr_clear(lr);
4860             mpfr_clear(li);
4861             mpfr_clear(rr);
4862             mpfr_clear(ri);
4863           }
4864
4865         mpfr_clear(lrrr);
4866         mpfr_clear(lrri);
4867         mpfr_clear(lirr);
4868         mpfr_clear(liri);                                 
4869       }
4870       break;
4871     case OPERATOR_DIV:
4872       {
4873         // For complex division we want to avoid having an
4874         // intermediate overflow turn the whole result in a NaN.  We
4875         // scale the values to try to avoid this.
4876
4877         if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4878           {
4879             error_at(location, "division by zero");
4880             mpfr_set_ui(real, 0, GMP_RNDN);
4881             mpfr_set_ui(imag, 0, GMP_RNDN);
4882             break;
4883           }
4884
4885         mpfr_t rra;
4886         mpfr_t ria;
4887         mpfr_init(rra);
4888         mpfr_init(ria);
4889         mpfr_abs(rra, right_real, GMP_RNDN);
4890         mpfr_abs(ria, right_imag, GMP_RNDN);
4891         mpfr_t t;
4892         mpfr_init(t);
4893         mpfr_max(t, rra, ria, GMP_RNDN);
4894
4895         mpfr_t rr;
4896         mpfr_t ri;
4897         mpfr_init_set(rr, right_real, GMP_RNDN);
4898         mpfr_init_set(ri, right_imag, GMP_RNDN);
4899         long ilogbw = 0;
4900         if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4901           {
4902             ilogbw = mpfr_get_exp(t);
4903             mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4904             mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4905           }
4906
4907         mpfr_t denom;
4908         mpfr_init(denom);
4909         mpfr_mul(denom, rr, rr, GMP_RNDN);
4910         mpfr_mul(t, ri, ri, GMP_RNDN);
4911         mpfr_add(denom, denom, t, GMP_RNDN);
4912
4913         mpfr_mul(real, left_real, rr, GMP_RNDN);
4914         mpfr_mul(t, left_imag, ri, GMP_RNDN);
4915         mpfr_add(real, real, t, GMP_RNDN);
4916         mpfr_div(real, real, denom, GMP_RNDN);
4917         mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4918
4919         mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4920         mpfr_mul(t, left_real, ri, GMP_RNDN);
4921         mpfr_sub(imag, imag, t, GMP_RNDN);
4922         mpfr_div(imag, imag, denom, GMP_RNDN);
4923         mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4924
4925         // If we wind up with NaN on both sides, check whether we
4926         // should really have infinity.  The rule is that if either
4927         // side of the complex number is infinity, then the whole
4928         // value is infinity, even if the other side is NaN.  So the
4929         // only case we have to fix is the one in which both sides are
4930         // NaN.
4931         if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4932             && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4933             && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4934           {
4935             if (mpfr_zero_p(denom))
4936               {
4937                 mpfr_set_inf(real, mpfr_sgn(rr));
4938                 mpfr_mul(real, real, left_real, GMP_RNDN);
4939                 mpfr_set_inf(imag, mpfr_sgn(rr));
4940                 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4941               }
4942             else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4943                      && mpfr_number_p(rr) && mpfr_number_p(ri))
4944               {
4945                 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4946                 mpfr_copysign(t, t, left_real, GMP_RNDN);
4947
4948                 mpfr_t t2;
4949                 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4950                 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4951
4952                 mpfr_t t3;
4953                 mpfr_init(t3);
4954                 mpfr_mul(t3, t, rr, GMP_RNDN);
4955
4956                 mpfr_t t4;
4957                 mpfr_init(t4);
4958                 mpfr_mul(t4, t2, ri, GMP_RNDN);
4959
4960                 mpfr_add(t3, t3, t4, GMP_RNDN);
4961                 mpfr_set_inf(real, mpfr_sgn(t3));
4962
4963                 mpfr_mul(t3, t2, rr, GMP_RNDN);
4964                 mpfr_mul(t4, t, ri, GMP_RNDN);
4965                 mpfr_sub(t3, t3, t4, GMP_RNDN);
4966                 mpfr_set_inf(imag, mpfr_sgn(t3));
4967
4968                 mpfr_clear(t2);
4969                 mpfr_clear(t3);
4970                 mpfr_clear(t4);
4971               }
4972             else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
4973                      && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
4974               {
4975                 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4976                 mpfr_copysign(t, t, rr, GMP_RNDN);
4977
4978                 mpfr_t t2;
4979                 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4980                 mpfr_copysign(t2, t2, ri, GMP_RNDN);
4981
4982                 mpfr_t t3;
4983                 mpfr_init(t3);
4984                 mpfr_mul(t3, left_real, t, GMP_RNDN);
4985
4986                 mpfr_t t4;
4987                 mpfr_init(t4);
4988                 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
4989
4990                 mpfr_add(t3, t3, t4, GMP_RNDN);
4991                 mpfr_set_ui(real, 0, GMP_RNDN);
4992                 mpfr_mul(real, real, t3, GMP_RNDN);
4993
4994                 mpfr_mul(t3, left_imag, t, GMP_RNDN);
4995                 mpfr_mul(t4, left_real, t2, GMP_RNDN);
4996                 mpfr_sub(t3, t3, t4, GMP_RNDN);
4997                 mpfr_set_ui(imag, 0, GMP_RNDN);
4998                 mpfr_mul(imag, imag, t3, GMP_RNDN);
4999
5000                 mpfr_clear(t2);
5001                 mpfr_clear(t3);
5002                 mpfr_clear(t4);
5003               }
5004           }
5005
5006         mpfr_clear(denom);
5007         mpfr_clear(rr);
5008         mpfr_clear(ri);
5009         mpfr_clear(t);
5010         mpfr_clear(rra);
5011         mpfr_clear(ria);
5012       }
5013       break;
5014     default:
5015       go_unreachable();
5016     }
5017
5018   mpfr_clear(left_real);
5019   mpfr_clear(left_imag);
5020   mpfr_clear(right_real);
5021   mpfr_clear(right_imag);
5022
5023   nc->set_complex(NULL, real, imag);
5024   mpfr_clear(real);
5025   mpfr_clear(imag);
5026
5027   return ret;
5028 }
5029
5030 // Lower a binary expression.  We have to evaluate constant
5031 // expressions now, in order to implement Go's unlimited precision
5032 // constants.
5033
5034 Expression*
5035 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5036                             Statement_inserter* inserter, int)
5037 {
5038   Location location = this->location();
5039   Operator op = this->op_;
5040   Expression* left = this->left_;
5041   Expression* right = this->right_;
5042
5043   const bool is_comparison = (op == OPERATOR_EQEQ
5044                               || op == OPERATOR_NOTEQ
5045                               || op == OPERATOR_LT
5046                               || op == OPERATOR_LE
5047                               || op == OPERATOR_GT
5048                               || op == OPERATOR_GE);
5049
5050   // Numeric constant expressions.
5051   {
5052     Numeric_constant left_nc;
5053     Numeric_constant right_nc;
5054     if (left->numeric_constant_value(&left_nc)
5055         && right->numeric_constant_value(&right_nc))
5056       {
5057         if (is_comparison)
5058           {
5059             bool result;
5060             if (!Binary_expression::compare_constant(op, &left_nc,
5061                                                      &right_nc, location,
5062                                                      &result))
5063               return this;
5064             return Expression::make_cast(Type::lookup_bool_type(),
5065                                          Expression::make_boolean(result,
5066                                                                   location),
5067                                          location);
5068           }
5069         else
5070           {
5071             Numeric_constant nc;
5072             if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5073                                                   location, &nc))
5074               return this;
5075             return nc.expression(location);
5076           }
5077       }
5078   }
5079
5080   // String constant expressions.
5081   if (left->type()->is_string_type() && right->type()->is_string_type())
5082     {
5083       std::string left_string;
5084       std::string right_string;
5085       if (left->string_constant_value(&left_string)
5086           && right->string_constant_value(&right_string))
5087         {
5088           if (op == OPERATOR_PLUS)
5089             return Expression::make_string(left_string + right_string,
5090                                            location);
5091           else if (is_comparison)
5092             {
5093               int cmp = left_string.compare(right_string);
5094               bool r = Binary_expression::cmp_to_bool(op, cmp);
5095               return Expression::make_cast(Type::lookup_bool_type(),
5096                                            Expression::make_boolean(r,
5097                                                                     location),
5098                                            location);
5099             }
5100         }
5101     }
5102
5103   // Lower struct and array comparisons.
5104   if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5105     {
5106       if (left->type()->struct_type() != NULL)
5107         return this->lower_struct_comparison(gogo, inserter);
5108       else if (left->type()->array_type() != NULL
5109                && !left->type()->is_slice_type())
5110         return this->lower_array_comparison(gogo, inserter);
5111     }
5112
5113   return this;
5114 }
5115
5116 // Lower a struct comparison.
5117
5118 Expression*
5119 Binary_expression::lower_struct_comparison(Gogo* gogo,
5120                                            Statement_inserter* inserter)
5121 {
5122   Struct_type* st = this->left_->type()->struct_type();
5123   Struct_type* st2 = this->right_->type()->struct_type();
5124   if (st2 == NULL)
5125     return this;
5126   if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5127     return this;
5128   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5129                                            this->right_->type(), NULL))
5130     return this;
5131
5132   // See if we can compare using memcmp.  As a heuristic, we use
5133   // memcmp rather than field references and comparisons if there are
5134   // more than two fields.
5135   if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5136     return this->lower_compare_to_memcmp(gogo, inserter);
5137
5138   Location loc = this->location();
5139
5140   Expression* left = this->left_;
5141   Temporary_statement* left_temp = NULL;
5142   if (left->var_expression() == NULL
5143       && left->temporary_reference_expression() == NULL)
5144     {
5145       left_temp = Statement::make_temporary(left->type(), NULL, loc);
5146       inserter->insert(left_temp);
5147       left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5148     }
5149
5150   Expression* right = this->right_;
5151   Temporary_statement* right_temp = NULL;
5152   if (right->var_expression() == NULL
5153       && right->temporary_reference_expression() == NULL)
5154     {
5155       right_temp = Statement::make_temporary(right->type(), NULL, loc);
5156       inserter->insert(right_temp);
5157       right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5158     }
5159
5160   Expression* ret = Expression::make_boolean(true, loc);
5161   const Struct_field_list* fields = st->fields();
5162   unsigned int field_index = 0;
5163   for (Struct_field_list::const_iterator pf = fields->begin();
5164        pf != fields->end();
5165        ++pf, ++field_index)
5166     {
5167       if (field_index > 0)
5168         {
5169           if (left_temp == NULL)
5170             left = left->copy();
5171           else
5172             left = Expression::make_temporary_reference(left_temp, loc);
5173           if (right_temp == NULL)
5174             right = right->copy();
5175           else
5176             right = Expression::make_temporary_reference(right_temp, loc);
5177         }
5178       Expression* f1 = Expression::make_field_reference(left, field_index,
5179                                                         loc);
5180       Expression* f2 = Expression::make_field_reference(right, field_index,
5181                                                         loc);
5182       Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5183       ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5184     }
5185
5186   if (this->op_ == OPERATOR_NOTEQ)
5187     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5188
5189   return ret;
5190 }
5191
5192 // Lower an array comparison.
5193
5194 Expression*
5195 Binary_expression::lower_array_comparison(Gogo* gogo,
5196                                           Statement_inserter* inserter)
5197 {
5198   Array_type* at = this->left_->type()->array_type();
5199   Array_type* at2 = this->right_->type()->array_type();
5200   if (at2 == NULL)
5201     return this;
5202   if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5203     return this;
5204   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5205                                            this->right_->type(), NULL))
5206     return this;
5207
5208   // Call memcmp directly if possible.  This may let the middle-end
5209   // optimize the call.
5210   if (at->compare_is_identity(gogo))
5211     return this->lower_compare_to_memcmp(gogo, inserter);
5212
5213   // Call the array comparison function.
5214   Named_object* hash_fn;
5215   Named_object* equal_fn;
5216   at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5217                      &hash_fn, &equal_fn);
5218
5219   Location loc = this->location();
5220
5221   Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5222
5223   Expression_list* args = new Expression_list();
5224   args->push_back(this->operand_address(inserter, this->left_));
5225   args->push_back(this->operand_address(inserter, this->right_));
5226   args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5227
5228   Expression* ret = Expression::make_call(func, args, false, loc);
5229
5230   if (this->op_ == OPERATOR_NOTEQ)
5231     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5232
5233   return ret;
5234 }
5235
5236 // Lower a struct or array comparison to a call to memcmp.
5237
5238 Expression*
5239 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5240 {
5241   Location loc = this->location();
5242
5243   Expression* a1 = this->operand_address(inserter, this->left_);
5244   Expression* a2 = this->operand_address(inserter, this->right_);
5245   Expression* len = Expression::make_type_info(this->left_->type(),
5246                                                TYPE_INFO_SIZE);
5247
5248   Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5249
5250   mpz_t zval;
5251   mpz_init_set_ui(zval, 0);
5252   Expression* zero = Expression::make_integer(&zval, NULL, loc);
5253   mpz_clear(zval);
5254
5255   return Expression::make_binary(this->op_, call, zero, loc);
5256 }
5257
5258 // Return the address of EXPR, cast to unsafe.Pointer.
5259
5260 Expression*
5261 Binary_expression::operand_address(Statement_inserter* inserter,
5262                                    Expression* expr)
5263 {
5264   Location loc = this->location();
5265
5266   if (!expr->is_addressable())
5267     {
5268       Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5269                                                             loc);
5270       inserter->insert(temp);
5271       expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5272     }
5273   expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5274   static_cast<Unary_expression*>(expr)->set_does_not_escape();
5275   Type* void_type = Type::make_void_type();
5276   Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5277   return Expression::make_cast(unsafe_pointer_type, expr, loc);
5278 }
5279
5280 // Return the numeric constant value, if it has one.
5281
5282 bool
5283 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5284 {
5285   Operator op = this->op_;
5286
5287   if (op == OPERATOR_EQEQ
5288       || op == OPERATOR_NOTEQ
5289       || op == OPERATOR_LT
5290       || op == OPERATOR_LE
5291       || op == OPERATOR_GT
5292       || op == OPERATOR_GE)
5293     return false;
5294
5295   Numeric_constant left_nc;
5296   if (!this->left_->numeric_constant_value(&left_nc))
5297     return false;
5298   Numeric_constant right_nc;
5299   if (!this->right_->numeric_constant_value(&right_nc))
5300     return false;
5301
5302   return Binary_expression::eval_constant(op, &left_nc, &right_nc,
5303                                           this->location(), nc);
5304 }
5305
5306 // Note that the value is being discarded.
5307
5308 void
5309 Binary_expression::do_discarding_value()
5310 {
5311   if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5312     this->right_->discarding_value();
5313   else
5314     this->unused_value_error();
5315 }
5316
5317 // Get type.
5318
5319 Type*
5320 Binary_expression::do_type()
5321 {
5322   if (this->classification() == EXPRESSION_ERROR)
5323     return Type::make_error_type();
5324
5325   switch (this->op_)
5326     {
5327     case OPERATOR_OROR:
5328     case OPERATOR_ANDAND:
5329     case OPERATOR_EQEQ:
5330     case OPERATOR_NOTEQ:
5331     case OPERATOR_LT:
5332     case OPERATOR_LE:
5333     case OPERATOR_GT:
5334     case OPERATOR_GE:
5335       return Type::lookup_bool_type();
5336
5337     case OPERATOR_PLUS:
5338     case OPERATOR_MINUS:
5339     case OPERATOR_OR:
5340     case OPERATOR_XOR:
5341     case OPERATOR_MULT:
5342     case OPERATOR_DIV:
5343     case OPERATOR_MOD:
5344     case OPERATOR_AND:
5345     case OPERATOR_BITCLEAR:
5346       {
5347         Type* type;
5348         if (!Binary_expression::operation_type(this->op_,
5349                                                this->left_->type(),
5350                                                this->right_->type(),
5351                                                &type))
5352           return Type::make_error_type();
5353         return type;
5354       }
5355
5356     case OPERATOR_LSHIFT:
5357     case OPERATOR_RSHIFT:
5358       return this->left_->type();
5359
5360     default:
5361       go_unreachable();
5362     }
5363 }
5364
5365 // Set type for a binary expression.
5366
5367 void
5368 Binary_expression::do_determine_type(const Type_context* context)
5369 {
5370   Type* tleft = this->left_->type();
5371   Type* tright = this->right_->type();
5372
5373   // Both sides should have the same type, except for the shift
5374   // operations.  For a comparison, we should ignore the incoming
5375   // type.
5376
5377   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5378                       || this->op_ == OPERATOR_RSHIFT);
5379
5380   bool is_comparison = (this->op_ == OPERATOR_EQEQ
5381                         || this->op_ == OPERATOR_NOTEQ
5382                         || this->op_ == OPERATOR_LT
5383                         || this->op_ == OPERATOR_LE
5384                         || this->op_ == OPERATOR_GT
5385                         || this->op_ == OPERATOR_GE);
5386
5387   Type_context subcontext(*context);
5388
5389   if (is_comparison)
5390     {
5391       // In a comparison, the context does not determine the types of
5392       // the operands.
5393       subcontext.type = NULL;
5394     }
5395
5396   // Set the context for the left hand operand.
5397   if (is_shift_op)
5398     {
5399       // The right hand operand of a shift plays no role in
5400       // determining the type of the left hand operand.
5401     }
5402   else if (!tleft->is_abstract())
5403     subcontext.type = tleft;
5404   else if (!tright->is_abstract())
5405     subcontext.type = tright;
5406   else if (subcontext.type == NULL)
5407     {
5408       if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5409           || (tleft->float_type() != NULL && tright->float_type() != NULL)
5410           || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5411         {
5412           // Both sides have an abstract integer, abstract float, or
5413           // abstract complex type.  Just let CONTEXT determine
5414           // whether they may remain abstract or not.
5415         }
5416       else if (tleft->complex_type() != NULL)
5417         subcontext.type = tleft;
5418       else if (tright->complex_type() != NULL)
5419         subcontext.type = tright;
5420       else if (tleft->float_type() != NULL)
5421         subcontext.type = tleft;
5422       else if (tright->float_type() != NULL)
5423         subcontext.type = tright;
5424       else
5425         subcontext.type = tleft;
5426
5427       if (subcontext.type != NULL && !context->may_be_abstract)
5428         subcontext.type = subcontext.type->make_non_abstract_type();
5429     }
5430
5431   this->left_->determine_type(&subcontext);
5432
5433   if (is_shift_op)
5434     {
5435       // We may have inherited an unusable type for the shift operand.
5436       // Give a useful error if that happened.
5437       if (tleft->is_abstract()
5438           && subcontext.type != NULL
5439           && (this->left_->type()->integer_type() == NULL
5440               || (subcontext.type->integer_type() == NULL
5441                   && subcontext.type->float_type() == NULL
5442                   && subcontext.type->complex_type() == NULL)))
5443         this->report_error(("invalid context-determined non-integer type "
5444                             "for shift operand"));
5445
5446       // The context for the right hand operand is the same as for the
5447       // left hand operand, except for a shift operator.
5448       subcontext.type = Type::lookup_integer_type("uint");
5449       subcontext.may_be_abstract = false;
5450     }
5451
5452   this->right_->determine_type(&subcontext);
5453 }
5454
5455 // Report an error if the binary operator OP does not support TYPE.
5456 // OTYPE is the type of the other operand.  Return whether the
5457 // operation is OK.  This should not be used for shift.
5458
5459 bool
5460 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5461                                        Location location)
5462 {
5463   switch (op)
5464     {
5465     case OPERATOR_OROR:
5466     case OPERATOR_ANDAND:
5467       if (!type->is_boolean_type())
5468         {
5469           error_at(location, "expected boolean type");
5470           return false;
5471         }
5472       break;
5473
5474     case OPERATOR_EQEQ:
5475     case OPERATOR_NOTEQ:
5476       {
5477         std::string reason;
5478         if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5479           {
5480             error_at(location, "%s", reason.c_str());
5481             return false;
5482           }
5483       }
5484       break;
5485
5486     case OPERATOR_LT:
5487     case OPERATOR_LE:
5488     case OPERATOR_GT:
5489     case OPERATOR_GE:
5490       {
5491         std::string reason;
5492         if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5493           {
5494             error_at(location, "%s", reason.c_str());
5495             return false;
5496           }
5497       }
5498       break;
5499
5500     case OPERATOR_PLUS:
5501     case OPERATOR_PLUSEQ:
5502       if (type->integer_type() == NULL
5503           && type->float_type() == NULL
5504           && type->complex_type() == NULL
5505           && !type->is_string_type())
5506         {
5507           error_at(location,
5508                    "expected integer, floating, complex, or string type");
5509           return false;
5510         }
5511       break;
5512
5513     case OPERATOR_MINUS:
5514     case OPERATOR_MINUSEQ:
5515     case OPERATOR_MULT:
5516     case OPERATOR_MULTEQ:
5517     case OPERATOR_DIV:
5518     case OPERATOR_DIVEQ:
5519       if (type->integer_type() == NULL
5520           && type->float_type() == NULL
5521           && type->complex_type() == NULL)
5522         {
5523           error_at(location, "expected integer, floating, or complex type");
5524           return false;
5525         }
5526       break;
5527
5528     case OPERATOR_MOD:
5529     case OPERATOR_MODEQ:
5530     case OPERATOR_OR:
5531     case OPERATOR_OREQ:
5532     case OPERATOR_AND:
5533     case OPERATOR_ANDEQ:
5534     case OPERATOR_XOR:
5535     case OPERATOR_XOREQ:
5536     case OPERATOR_BITCLEAR:
5537     case OPERATOR_BITCLEAREQ:
5538       if (type->integer_type() == NULL)
5539         {
5540           error_at(location, "expected integer type");
5541           return false;
5542         }
5543       break;
5544
5545     default:
5546       go_unreachable();
5547     }
5548
5549   return true;
5550 }
5551
5552 // Check types.
5553
5554 void
5555 Binary_expression::do_check_types(Gogo*)
5556 {
5557   if (this->classification() == EXPRESSION_ERROR)
5558     return;
5559
5560   Type* left_type = this->left_->type();
5561   Type* right_type = this->right_->type();
5562   if (left_type->is_error() || right_type->is_error())
5563     {
5564       this->set_is_error();
5565       return;
5566     }
5567
5568   if (this->op_ == OPERATOR_EQEQ
5569       || this->op_ == OPERATOR_NOTEQ
5570       || this->op_ == OPERATOR_LT
5571       || this->op_ == OPERATOR_LE
5572       || this->op_ == OPERATOR_GT
5573       || this->op_ == OPERATOR_GE)
5574     {
5575       if (!Type::are_assignable(left_type, right_type, NULL)
5576           && !Type::are_assignable(right_type, left_type, NULL))
5577         {
5578           this->report_error(_("incompatible types in binary expression"));
5579           return;
5580         }
5581       if (!Binary_expression::check_operator_type(this->op_, left_type,
5582                                                   right_type,
5583                                                   this->location())
5584           || !Binary_expression::check_operator_type(this->op_, right_type,
5585                                                      left_type,
5586                                                      this->location()))
5587         {
5588           this->set_is_error();
5589           return;
5590         }
5591     }
5592   else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5593     {
5594       if (!Type::are_compatible_for_binop(left_type, right_type))
5595         {
5596           this->report_error(_("incompatible types in binary expression"));
5597           return;
5598         }
5599       if (!Binary_expression::check_operator_type(this->op_, left_type,
5600                                                   right_type,
5601                                                   this->location()))
5602         {
5603           this->set_is_error();
5604           return;
5605         }
5606     }
5607   else
5608     {
5609       if (left_type->integer_type() == NULL)
5610         this->report_error(_("shift of non-integer operand"));
5611
5612       if (!right_type->is_abstract()
5613           && (right_type->integer_type() == NULL
5614               || !right_type->integer_type()->is_unsigned()))
5615         this->report_error(_("shift count not unsigned integer"));
5616       else
5617         {
5618           Numeric_constant nc;
5619           if (this->right_->numeric_constant_value(&nc))
5620             {
5621               mpz_t val;
5622               if (!nc.to_int(&val))
5623                 this->report_error(_("shift count not unsigned integer"));
5624               else
5625                 {
5626                   if (mpz_sgn(val) < 0)
5627                     {
5628                       this->report_error(_("negative shift count"));
5629                       mpz_set_ui(val, 0);
5630                       Location rloc = this->right_->location();
5631                       this->right_ = Expression::make_integer(&val, right_type,
5632                                                               rloc);
5633                     }
5634                   mpz_clear(val);
5635                 }
5636             }
5637         }
5638     }
5639 }
5640
5641 // Get a tree for a binary expression.
5642
5643 tree
5644 Binary_expression::do_get_tree(Translate_context* context)
5645 {
5646   tree left = this->left_->get_tree(context);
5647   tree right = this->right_->get_tree(context);
5648
5649   if (left == error_mark_node || right == error_mark_node)
5650     return error_mark_node;
5651
5652   enum tree_code code;
5653   bool use_left_type = true;
5654   bool is_shift_op = false;
5655   bool is_idiv_op = false;
5656   switch (this->op_)
5657     {
5658     case OPERATOR_EQEQ:
5659     case OPERATOR_NOTEQ:
5660     case OPERATOR_LT:
5661     case OPERATOR_LE:
5662     case OPERATOR_GT:
5663     case OPERATOR_GE:
5664       return Expression::comparison_tree(context, this->op_,
5665                                          this->left_->type(), left,
5666                                          this->right_->type(), right,
5667                                          this->location());
5668
5669     case OPERATOR_OROR:
5670       code = TRUTH_ORIF_EXPR;
5671       use_left_type = false;
5672       break;
5673     case OPERATOR_ANDAND:
5674       code = TRUTH_ANDIF_EXPR;
5675       use_left_type = false;
5676       break;
5677     case OPERATOR_PLUS:
5678       code = PLUS_EXPR;
5679       break;
5680     case OPERATOR_MINUS:
5681       code = MINUS_EXPR;
5682       break;
5683     case OPERATOR_OR:
5684       code = BIT_IOR_EXPR;
5685       break;
5686     case OPERATOR_XOR:
5687       code = BIT_XOR_EXPR;
5688       break;
5689     case OPERATOR_MULT:
5690       code = MULT_EXPR;
5691       break;
5692     case OPERATOR_DIV:
5693       {
5694         Type *t = this->left_->type();
5695         if (t->float_type() != NULL || t->complex_type() != NULL)
5696           code = RDIV_EXPR;
5697         else
5698           {
5699             code = TRUNC_DIV_EXPR;
5700             is_idiv_op = true;
5701           }
5702       }
5703       break;
5704     case OPERATOR_MOD:
5705       code = TRUNC_MOD_EXPR;
5706       is_idiv_op = true;
5707       break;
5708     case OPERATOR_LSHIFT:
5709       code = LSHIFT_EXPR;
5710       is_shift_op = true;
5711       break;
5712     case OPERATOR_RSHIFT:
5713       code = RSHIFT_EXPR;
5714       is_shift_op = true;
5715       break;
5716     case OPERATOR_AND:
5717       code = BIT_AND_EXPR;
5718       break;
5719     case OPERATOR_BITCLEAR:
5720       right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5721       code = BIT_AND_EXPR;
5722       break;
5723     default:
5724       go_unreachable();
5725     }
5726
5727   location_t gccloc = this->location().gcc_location();
5728   tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5729
5730   if (this->left_->type()->is_string_type())
5731     {
5732       go_assert(this->op_ == OPERATOR_PLUS);
5733       Type* st = Type::make_string_type();
5734       tree string_type = type_to_tree(st->get_backend(context->gogo()));
5735       static tree string_plus_decl;
5736       return Gogo::call_builtin(&string_plus_decl,
5737                                 this->location(),
5738                                 "__go_string_plus",
5739                                 2,
5740                                 string_type,
5741                                 string_type,
5742                                 left,
5743                                 string_type,
5744                                 right);
5745     }
5746
5747   tree compute_type = excess_precision_type(type);
5748   if (compute_type != NULL_TREE)
5749     {
5750       left = ::convert(compute_type, left);
5751       right = ::convert(compute_type, right);
5752     }
5753
5754   tree eval_saved = NULL_TREE;
5755   if (is_shift_op
5756       || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5757     {
5758       // Make sure the values are evaluated.
5759       if (!DECL_P(left))
5760         {
5761           left = save_expr(left);
5762           eval_saved = left;
5763         }
5764       if (!DECL_P(right))
5765         {
5766           right = save_expr(right);
5767           if (eval_saved == NULL_TREE)
5768             eval_saved = right;
5769           else
5770             eval_saved = fold_build2_loc(gccloc, COMPOUND_EXPR,
5771                                          void_type_node, eval_saved, right);
5772         }
5773     }
5774
5775   tree ret = fold_build2_loc(gccloc, code,
5776                              compute_type != NULL_TREE ? compute_type : type,
5777                              left, right);
5778
5779   if (compute_type != NULL_TREE)
5780     ret = ::convert(type, ret);
5781
5782   // In Go, a shift larger than the size of the type is well-defined.
5783   // This is not true in GENERIC, so we need to insert a conditional.
5784   if (is_shift_op)
5785     {
5786       go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5787       go_assert(this->left_->type()->integer_type() != NULL);
5788       int bits = TYPE_PRECISION(TREE_TYPE(left));
5789
5790       tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5791                                  build_int_cst_type(TREE_TYPE(right), bits));
5792
5793       tree overflow_result = fold_convert_loc(gccloc, TREE_TYPE(left),
5794                                               integer_zero_node);
5795       if (this->op_ == OPERATOR_RSHIFT
5796           && !this->left_->type()->integer_type()->is_unsigned())
5797         {
5798           tree neg =
5799             fold_build2_loc(gccloc, LT_EXPR, boolean_type_node,
5800                             left,
5801                             fold_convert_loc(gccloc, TREE_TYPE(left),
5802                                              integer_zero_node));
5803           tree neg_one =
5804             fold_build2_loc(gccloc, MINUS_EXPR, TREE_TYPE(left),
5805                             fold_convert_loc(gccloc, TREE_TYPE(left),
5806                                              integer_zero_node),
5807                             fold_convert_loc(gccloc, TREE_TYPE(left),
5808                                              integer_one_node));
5809           overflow_result =
5810             fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5811                             neg, neg_one, overflow_result);
5812         }
5813
5814       ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5815                             compare, ret, overflow_result);
5816
5817       if (eval_saved != NULL_TREE)
5818         ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5819                               eval_saved, ret);
5820     }
5821
5822   // Add checks for division by zero and division overflow as needed.
5823   if (is_idiv_op)
5824     {
5825       if (go_check_divide_zero)
5826         {
5827           // right == 0
5828           tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5829                                        right,
5830                                        fold_convert_loc(gccloc,
5831                                                         TREE_TYPE(right),
5832                                                         integer_zero_node));
5833
5834           // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO), 0
5835           int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5836           tree panic = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5837                                        Gogo::runtime_error(errcode,
5838                                                            this->location()),
5839                                        fold_convert_loc(gccloc, TREE_TYPE(ret),
5840                                                         integer_zero_node));
5841
5842           // right == 0 ? (__go_runtime_error(...), 0) : ret
5843           ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5844                                 check, panic, ret);
5845         }
5846
5847       if (go_check_divide_overflow)
5848         {
5849           // right == -1
5850           // FIXME: It would be nice to say that this test is expected
5851           // to return false.
5852           tree m1 = integer_minus_one_node;
5853           tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5854                                        right,
5855                                        fold_convert_loc(gccloc,
5856                                                         TREE_TYPE(right),
5857                                                         m1));
5858
5859           tree overflow;
5860           if (TYPE_UNSIGNED(TREE_TYPE(ret)))
5861             {
5862               // An unsigned -1 is the largest possible number, so
5863               // dividing is always 1 or 0.
5864               tree cmp = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5865                                          left, right);
5866               if (this->op_ == OPERATOR_DIV)
5867                 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5868                                            cmp,
5869                                            fold_convert_loc(gccloc,
5870                                                             TREE_TYPE(ret),
5871                                                             integer_one_node),
5872                                            fold_convert_loc(gccloc,
5873                                                             TREE_TYPE(ret),
5874                                                             integer_zero_node));
5875               else
5876                 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5877                                            cmp,
5878                                            fold_convert_loc(gccloc,
5879                                                             TREE_TYPE(ret),
5880                                                             integer_zero_node),
5881                                            left);
5882             }
5883           else
5884             {
5885               // Computing left / -1 is the same as computing - left,
5886               // which does not overflow since Go sets -fwrapv.
5887               if (this->op_ == OPERATOR_DIV)
5888                 overflow = fold_build1_loc(gccloc, NEGATE_EXPR, TREE_TYPE(left),
5889                                            left);
5890               else
5891                 overflow = integer_zero_node;
5892             }
5893           overflow = fold_convert_loc(gccloc, TREE_TYPE(ret), overflow);
5894
5895           // right == -1 ? - left : ret
5896           ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5897                                 check, overflow, ret);
5898         }
5899
5900       if (eval_saved != NULL_TREE)
5901         ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5902                               eval_saved, ret);
5903     }
5904
5905   return ret;
5906 }
5907
5908 // Export a binary expression.
5909
5910 void
5911 Binary_expression::do_export(Export* exp) const
5912 {
5913   exp->write_c_string("(");
5914   this->left_->export_expression(exp);
5915   switch (this->op_)
5916     {
5917     case OPERATOR_OROR:
5918       exp->write_c_string(" || ");
5919       break;
5920     case OPERATOR_ANDAND:
5921       exp->write_c_string(" && ");
5922       break;
5923     case OPERATOR_EQEQ:
5924       exp->write_c_string(" == ");
5925       break;
5926     case OPERATOR_NOTEQ:
5927       exp->write_c_string(" != ");
5928       break;
5929     case OPERATOR_LT:
5930       exp->write_c_string(" < ");
5931       break;
5932     case OPERATOR_LE:
5933       exp->write_c_string(" <= ");
5934       break;
5935     case OPERATOR_GT:
5936       exp->write_c_string(" > ");
5937       break;
5938     case OPERATOR_GE:
5939       exp->write_c_string(" >= ");
5940       break;
5941     case OPERATOR_PLUS:
5942       exp->write_c_string(" + ");
5943       break;
5944     case OPERATOR_MINUS:
5945       exp->write_c_string(" - ");
5946       break;
5947     case OPERATOR_OR:
5948       exp->write_c_string(" | ");
5949       break;
5950     case OPERATOR_XOR:
5951       exp->write_c_string(" ^ ");
5952       break;
5953     case OPERATOR_MULT:
5954       exp->write_c_string(" * ");
5955       break;
5956     case OPERATOR_DIV:
5957       exp->write_c_string(" / ");
5958       break;
5959     case OPERATOR_MOD:
5960       exp->write_c_string(" % ");
5961       break;
5962     case OPERATOR_LSHIFT:
5963       exp->write_c_string(" << ");
5964       break;
5965     case OPERATOR_RSHIFT:
5966       exp->write_c_string(" >> ");
5967       break;
5968     case OPERATOR_AND:
5969       exp->write_c_string(" & ");
5970       break;
5971     case OPERATOR_BITCLEAR:
5972       exp->write_c_string(" &^ ");
5973       break;
5974     default:
5975       go_unreachable();
5976     }
5977   this->right_->export_expression(exp);
5978   exp->write_c_string(")");
5979 }
5980
5981 // Import a binary expression.
5982
5983 Expression*
5984 Binary_expression::do_import(Import* imp)
5985 {
5986   imp->require_c_string("(");
5987
5988   Expression* left = Expression::import_expression(imp);
5989
5990   Operator op;
5991   if (imp->match_c_string(" || "))
5992     {
5993       op = OPERATOR_OROR;
5994       imp->advance(4);
5995     }
5996   else if (imp->match_c_string(" && "))
5997     {
5998       op = OPERATOR_ANDAND;
5999       imp->advance(4);
6000     }
6001   else if (imp->match_c_string(" == "))
6002     {
6003       op = OPERATOR_EQEQ;
6004       imp->advance(4);
6005     }
6006   else if (imp->match_c_string(" != "))
6007     {
6008       op = OPERATOR_NOTEQ;
6009       imp->advance(4);
6010     }
6011   else if (imp->match_c_string(" < "))
6012     {
6013       op = OPERATOR_LT;
6014       imp->advance(3);
6015     }
6016   else if (imp->match_c_string(" <= "))
6017     {
6018       op = OPERATOR_LE;
6019       imp->advance(4);
6020     }
6021   else if (imp->match_c_string(" > "))
6022     {
6023       op = OPERATOR_GT;
6024       imp->advance(3);
6025     }
6026   else if (imp->match_c_string(" >= "))
6027     {
6028       op = OPERATOR_GE;
6029       imp->advance(4);
6030     }
6031   else if (imp->match_c_string(" + "))
6032     {
6033       op = OPERATOR_PLUS;
6034       imp->advance(3);
6035     }
6036   else if (imp->match_c_string(" - "))
6037     {
6038       op = OPERATOR_MINUS;
6039       imp->advance(3);
6040     }
6041   else if (imp->match_c_string(" | "))
6042     {
6043       op = OPERATOR_OR;
6044       imp->advance(3);
6045     }
6046   else if (imp->match_c_string(" ^ "))
6047     {
6048       op = OPERATOR_XOR;
6049       imp->advance(3);
6050     }
6051   else if (imp->match_c_string(" * "))
6052     {
6053       op = OPERATOR_MULT;
6054       imp->advance(3);
6055     }
6056   else if (imp->match_c_string(" / "))
6057     {
6058       op = OPERATOR_DIV;
6059       imp->advance(3);
6060     }
6061   else if (imp->match_c_string(" % "))
6062     {
6063       op = OPERATOR_MOD;
6064       imp->advance(3);
6065     }
6066   else if (imp->match_c_string(" << "))
6067     {
6068       op = OPERATOR_LSHIFT;
6069       imp->advance(4);
6070     }
6071   else if (imp->match_c_string(" >> "))
6072     {
6073       op = OPERATOR_RSHIFT;
6074       imp->advance(4);
6075     }
6076   else if (imp->match_c_string(" & "))
6077     {
6078       op = OPERATOR_AND;
6079       imp->advance(3);
6080     }
6081   else if (imp->match_c_string(" &^ "))
6082     {
6083       op = OPERATOR_BITCLEAR;
6084       imp->advance(4);
6085     }
6086   else
6087     {
6088       error_at(imp->location(), "unrecognized binary operator");
6089       return Expression::make_error(imp->location());
6090     }
6091
6092   Expression* right = Expression::import_expression(imp);
6093
6094   imp->require_c_string(")");
6095
6096   return Expression::make_binary(op, left, right, imp->location());
6097 }
6098
6099 // Dump ast representation of a binary expression.
6100
6101 void
6102 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6103 {
6104   ast_dump_context->ostream() << "(";
6105   ast_dump_context->dump_expression(this->left_);
6106   ast_dump_context->ostream() << " ";
6107   ast_dump_context->dump_operator(this->op_);
6108   ast_dump_context->ostream() << " ";
6109   ast_dump_context->dump_expression(this->right_);
6110   ast_dump_context->ostream() << ") ";
6111 }
6112
6113 // Make a binary expression.
6114
6115 Expression*
6116 Expression::make_binary(Operator op, Expression* left, Expression* right,
6117                         Location location)
6118 {
6119   return new Binary_expression(op, left, right, location);
6120 }
6121
6122 // Implement a comparison.
6123
6124 tree
6125 Expression::comparison_tree(Translate_context* context, Operator op,
6126                             Type* left_type, tree left_tree,
6127                             Type* right_type, tree right_tree,
6128                             Location location)
6129 {
6130   enum tree_code code;
6131   switch (op)
6132     {
6133     case OPERATOR_EQEQ:
6134       code = EQ_EXPR;
6135       break;
6136     case OPERATOR_NOTEQ:
6137       code = NE_EXPR;
6138       break;
6139     case OPERATOR_LT:
6140       code = LT_EXPR;
6141       break;
6142     case OPERATOR_LE:
6143       code = LE_EXPR;
6144       break;
6145     case OPERATOR_GT:
6146       code = GT_EXPR;
6147       break;
6148     case OPERATOR_GE:
6149       code = GE_EXPR;
6150       break;
6151     default:
6152       go_unreachable();
6153     }
6154
6155   if (left_type->is_string_type() && right_type->is_string_type())
6156     {
6157       Type* st = Type::make_string_type();
6158       tree string_type = type_to_tree(st->get_backend(context->gogo()));
6159       static tree string_compare_decl;
6160       left_tree = Gogo::call_builtin(&string_compare_decl,
6161                                      location,
6162                                      "__go_strcmp",
6163                                      2,
6164                                      integer_type_node,
6165                                      string_type,
6166                                      left_tree,
6167                                      string_type,
6168                                      right_tree);
6169       right_tree = build_int_cst_type(integer_type_node, 0);
6170     }
6171   else if ((left_type->interface_type() != NULL
6172             && right_type->interface_type() == NULL
6173             && !right_type->is_nil_type())
6174            || (left_type->interface_type() == NULL
6175                && !left_type->is_nil_type()
6176                && right_type->interface_type() != NULL))
6177     {
6178       // Comparing an interface value to a non-interface value.
6179       if (left_type->interface_type() == NULL)
6180         {
6181           std::swap(left_type, right_type);
6182           std::swap(left_tree, right_tree);
6183         }
6184
6185       // The right operand is not an interface.  We need to take its
6186       // address if it is not a pointer.
6187       tree make_tmp;
6188       tree arg;
6189       if (right_type->points_to() != NULL)
6190         {
6191           make_tmp = NULL_TREE;
6192           arg = right_tree;
6193         }
6194       else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree))
6195         {
6196           make_tmp = NULL_TREE;
6197           arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6198           if (DECL_P(right_tree))
6199             TREE_ADDRESSABLE(right_tree) = 1;
6200         }
6201       else
6202         {
6203           tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6204                                     get_name(right_tree));
6205           DECL_IGNORED_P(tmp) = 0;
6206           DECL_INITIAL(tmp) = right_tree;
6207           TREE_ADDRESSABLE(tmp) = 1;
6208           make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6209           SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6210           arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6211         }
6212       arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6213
6214       tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6215                                                             location);
6216
6217       if (left_type->interface_type()->is_empty())
6218         {
6219           static tree empty_interface_value_compare_decl;
6220           left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6221                                          location,
6222                                          "__go_empty_interface_value_compare",
6223                                          3,
6224                                          integer_type_node,
6225                                          TREE_TYPE(left_tree),
6226                                          left_tree,
6227                                          TREE_TYPE(descriptor),
6228                                          descriptor,
6229                                          ptr_type_node,
6230                                          arg);
6231           if (left_tree == error_mark_node)
6232             return error_mark_node;
6233           // This can panic if the type is not comparable.
6234           TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6235         }
6236       else
6237         {
6238           static tree interface_value_compare_decl;
6239           left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6240                                          location,
6241                                          "__go_interface_value_compare",
6242                                          3,
6243                                          integer_type_node,
6244                                          TREE_TYPE(left_tree),
6245                                          left_tree,
6246                                          TREE_TYPE(descriptor),
6247                                          descriptor,
6248                                          ptr_type_node,
6249                                          arg);
6250           if (left_tree == error_mark_node)
6251             return error_mark_node;
6252           // This can panic if the type is not comparable.
6253           TREE_NOTHROW(interface_value_compare_decl) = 0;
6254         }
6255       right_tree = build_int_cst_type(integer_type_node, 0);
6256
6257       if (make_tmp != NULL_TREE)
6258         left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6259                            left_tree);
6260     }
6261   else if (left_type->interface_type() != NULL
6262            && right_type->interface_type() != NULL)
6263     {
6264       if (left_type->interface_type()->is_empty()
6265           && right_type->interface_type()->is_empty())
6266         {
6267           static tree empty_interface_compare_decl;
6268           left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6269                                          location,
6270                                          "__go_empty_interface_compare",
6271                                          2,
6272                                          integer_type_node,
6273                                          TREE_TYPE(left_tree),
6274                                          left_tree,
6275                                          TREE_TYPE(right_tree),
6276                                          right_tree);
6277           if (left_tree == error_mark_node)
6278             return error_mark_node;
6279           // This can panic if the type is uncomparable.
6280           TREE_NOTHROW(empty_interface_compare_decl) = 0;
6281         }
6282       else if (!left_type->interface_type()->is_empty()
6283                && !right_type->interface_type()->is_empty())
6284         {
6285           static tree interface_compare_decl;
6286           left_tree = Gogo::call_builtin(&interface_compare_decl,
6287                                          location,
6288                                          "__go_interface_compare",
6289                                          2,
6290                                          integer_type_node,
6291                                          TREE_TYPE(left_tree),
6292                                          left_tree,
6293                                          TREE_TYPE(right_tree),
6294                                          right_tree);
6295           if (left_tree == error_mark_node)
6296             return error_mark_node;
6297           // This can panic if the type is uncomparable.
6298           TREE_NOTHROW(interface_compare_decl) = 0;
6299         }
6300       else
6301         {
6302           if (left_type->interface_type()->is_empty())
6303             {
6304               go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6305               std::swap(left_type, right_type);
6306               std::swap(left_tree, right_tree);
6307             }
6308           go_assert(!left_type->interface_type()->is_empty());
6309           go_assert(right_type->interface_type()->is_empty());
6310           static tree interface_empty_compare_decl;
6311           left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6312                                          location,
6313                                          "__go_interface_empty_compare",
6314                                          2,
6315                                          integer_type_node,
6316                                          TREE_TYPE(left_tree),
6317                                          left_tree,
6318                                          TREE_TYPE(right_tree),
6319                                          right_tree);
6320           if (left_tree == error_mark_node)
6321             return error_mark_node;
6322           // This can panic if the type is uncomparable.
6323           TREE_NOTHROW(interface_empty_compare_decl) = 0;
6324         }
6325
6326       right_tree = build_int_cst_type(integer_type_node, 0);
6327     }
6328
6329   if (left_type->is_nil_type()
6330       && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6331     {
6332       std::swap(left_type, right_type);
6333       std::swap(left_tree, right_tree);
6334     }
6335
6336   if (right_type->is_nil_type())
6337     {
6338       if (left_type->array_type() != NULL
6339           && left_type->array_type()->length() == NULL)
6340         {
6341           Array_type* at = left_type->array_type();
6342           left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6343           right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6344         }
6345       else if (left_type->interface_type() != NULL)
6346         {
6347           // An interface is nil if the first field is nil.
6348           tree left_type_tree = TREE_TYPE(left_tree);
6349           go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6350           tree field = TYPE_FIELDS(left_type_tree);
6351           left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6352                              field, NULL_TREE);
6353           right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6354         }
6355       else
6356         {
6357           go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6358           right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6359         }
6360     }
6361
6362   if (left_tree == error_mark_node || right_tree == error_mark_node)
6363     return error_mark_node;
6364
6365   tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
6366   if (CAN_HAVE_LOCATION_P(ret))
6367     SET_EXPR_LOCATION(ret, location.gcc_location());
6368   return ret;
6369 }
6370
6371 // Class Bound_method_expression.
6372
6373 // Traversal.
6374
6375 int
6376 Bound_method_expression::do_traverse(Traverse* traverse)
6377 {
6378   return Expression::traverse(&this->expr_, traverse);
6379 }
6380
6381 // Return the type of a bound method expression.  The type of this
6382 // object is really the type of the method with no receiver.  We
6383 // should be able to get away with just returning the type of the
6384 // method.
6385
6386 Type*
6387 Bound_method_expression::do_type()
6388 {
6389   if (this->method_->is_function())
6390     return this->method_->func_value()->type();
6391   else if (this->method_->is_function_declaration())
6392     return this->method_->func_declaration_value()->type();
6393   else
6394     return Type::make_error_type();
6395 }
6396
6397 // Determine the types of a method expression.
6398
6399 void
6400 Bound_method_expression::do_determine_type(const Type_context*)
6401 {
6402   Function_type* fntype = this->type()->function_type();
6403   if (fntype == NULL || !fntype->is_method())
6404     this->expr_->determine_type_no_context();
6405   else
6406     {
6407       Type_context subcontext(fntype->receiver()->type(), false);
6408       this->expr_->determine_type(&subcontext);
6409     }
6410 }
6411
6412 // Check the types of a method expression.
6413
6414 void
6415 Bound_method_expression::do_check_types(Gogo*)
6416 {
6417   if (!this->method_->is_function()
6418       && !this->method_->is_function_declaration())
6419     this->report_error(_("object is not a method"));
6420   else
6421     {
6422       Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6423       Type* etype = (this->expr_type_ != NULL
6424                      ? this->expr_type_
6425                      : this->expr_->type());
6426       etype = etype->deref();
6427       if (!Type::are_identical(rtype, etype, true, NULL))
6428         this->report_error(_("method type does not match object type"));
6429     }
6430 }
6431
6432 // Get the tree for a method expression.  There is no standard tree
6433 // representation for this.  The only places it may currently be used
6434 // are in a Call_expression or a Go_statement, which will take it
6435 // apart directly.  So this has nothing to do at present.
6436
6437 tree
6438 Bound_method_expression::do_get_tree(Translate_context*)
6439 {
6440   error_at(this->location(), "reference to method other than calling it");
6441   return error_mark_node;
6442 }
6443
6444 // Dump ast representation of a bound method expression.
6445
6446 void
6447 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6448     const
6449 {
6450   if (this->expr_type_ != NULL)
6451     ast_dump_context->ostream() << "(";
6452   ast_dump_context->dump_expression(this->expr_); 
6453   if (this->expr_type_ != NULL) 
6454     {
6455       ast_dump_context->ostream() << ":";
6456       ast_dump_context->dump_type(this->expr_type_);
6457       ast_dump_context->ostream() << ")";
6458     }
6459     
6460   ast_dump_context->ostream() << "." << this->method_->name();
6461 }
6462
6463 // Make a method expression.
6464
6465 Bound_method_expression*
6466 Expression::make_bound_method(Expression* expr, Named_object* method,
6467                               Location location)
6468 {
6469   return new Bound_method_expression(expr, method, location);
6470 }
6471
6472 // Class Builtin_call_expression.  This is used for a call to a
6473 // builtin function.
6474
6475 class Builtin_call_expression : public Call_expression
6476 {
6477  public:
6478   Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6479                           bool is_varargs, Location location);
6480
6481  protected:
6482   // This overrides Call_expression::do_lower.
6483   Expression*
6484   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6485
6486   bool
6487   do_is_constant() const;
6488
6489   bool
6490   do_numeric_constant_value(Numeric_constant*) const;
6491
6492   void
6493   do_discarding_value();
6494
6495   Type*
6496   do_type();
6497
6498   void
6499   do_determine_type(const Type_context*);
6500
6501   void
6502   do_check_types(Gogo*);
6503
6504   Expression*
6505   do_copy()
6506   {
6507     return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6508                                        this->args()->copy(),
6509                                        this->is_varargs(),
6510                                        this->location());
6511   }
6512
6513   tree
6514   do_get_tree(Translate_context*);
6515
6516   void
6517   do_export(Export*) const;
6518
6519   virtual bool
6520   do_is_recover_call() const;
6521
6522   virtual void
6523   do_set_recover_arg(Expression*);
6524
6525  private:
6526   // The builtin functions.
6527   enum Builtin_function_code
6528     {
6529       BUILTIN_INVALID,
6530
6531       // Predeclared builtin functions.
6532       BUILTIN_APPEND,
6533       BUILTIN_CAP,
6534       BUILTIN_CLOSE,
6535       BUILTIN_COMPLEX,
6536       BUILTIN_COPY,
6537       BUILTIN_DELETE,
6538       BUILTIN_IMAG,
6539       BUILTIN_LEN,
6540       BUILTIN_MAKE,
6541       BUILTIN_NEW,
6542       BUILTIN_PANIC,
6543       BUILTIN_PRINT,
6544       BUILTIN_PRINTLN,
6545       BUILTIN_REAL,
6546       BUILTIN_RECOVER,
6547
6548       // Builtin functions from the unsafe package.
6549       BUILTIN_ALIGNOF,
6550       BUILTIN_OFFSETOF,
6551       BUILTIN_SIZEOF
6552     };
6553
6554   Expression*
6555   one_arg() const;
6556
6557   bool
6558   check_one_arg();
6559
6560   static Type*
6561   real_imag_type(Type*);
6562
6563   static Type*
6564   complex_type(Type*);
6565
6566   Expression*
6567   lower_make();
6568
6569   bool
6570   check_int_value(Expression*);
6571
6572   // A pointer back to the general IR structure.  This avoids a global
6573   // variable, or passing it around everywhere.
6574   Gogo* gogo_;
6575   // The builtin function being called.
6576   Builtin_function_code code_;
6577   // Used to stop endless loops when the length of an array uses len
6578   // or cap of the array itself.
6579   mutable bool seen_;
6580 };
6581
6582 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6583                                                  Expression* fn,
6584                                                  Expression_list* args,
6585                                                  bool is_varargs,
6586                                                  Location location)
6587   : Call_expression(fn, args, is_varargs, location),
6588     gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6589 {
6590   Func_expression* fnexp = this->fn()->func_expression();
6591   go_assert(fnexp != NULL);
6592   const std::string& name(fnexp->named_object()->name());
6593   if (name == "append")
6594     this->code_ = BUILTIN_APPEND;
6595   else if (name == "cap")
6596     this->code_ = BUILTIN_CAP;
6597   else if (name == "close")
6598     this->code_ = BUILTIN_CLOSE;
6599   else if (name == "complex")
6600     this->code_ = BUILTIN_COMPLEX;
6601   else if (name == "copy")
6602     this->code_ = BUILTIN_COPY;
6603   else if (name == "delete")
6604     this->code_ = BUILTIN_DELETE;
6605   else if (name == "imag")
6606     this->code_ = BUILTIN_IMAG;
6607   else if (name == "len")
6608     this->code_ = BUILTIN_LEN;
6609   else if (name == "make")
6610     this->code_ = BUILTIN_MAKE;
6611   else if (name == "new")
6612     this->code_ = BUILTIN_NEW;
6613   else if (name == "panic")
6614     this->code_ = BUILTIN_PANIC;
6615   else if (name == "print")
6616     this->code_ = BUILTIN_PRINT;
6617   else if (name == "println")
6618     this->code_ = BUILTIN_PRINTLN;
6619   else if (name == "real")
6620     this->code_ = BUILTIN_REAL;
6621   else if (name == "recover")
6622     this->code_ = BUILTIN_RECOVER;
6623   else if (name == "Alignof")
6624     this->code_ = BUILTIN_ALIGNOF;
6625   else if (name == "Offsetof")
6626     this->code_ = BUILTIN_OFFSETOF;
6627   else if (name == "Sizeof")
6628     this->code_ = BUILTIN_SIZEOF;
6629   else
6630     go_unreachable();
6631 }
6632
6633 // Return whether this is a call to recover.  This is a virtual
6634 // function called from the parent class.
6635
6636 bool
6637 Builtin_call_expression::do_is_recover_call() const
6638 {
6639   if (this->classification() == EXPRESSION_ERROR)
6640     return false;
6641   return this->code_ == BUILTIN_RECOVER;
6642 }
6643
6644 // Set the argument for a call to recover.
6645
6646 void
6647 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6648 {
6649   const Expression_list* args = this->args();
6650   go_assert(args == NULL || args->empty());
6651   Expression_list* new_args = new Expression_list();
6652   new_args->push_back(arg);
6653   this->set_args(new_args);
6654 }
6655
6656 // A traversal class which looks for a call expression.
6657
6658 class Find_call_expression : public Traverse
6659 {
6660  public:
6661   Find_call_expression()
6662     : Traverse(traverse_expressions),
6663       found_(false)
6664   { }
6665
6666   int
6667   expression(Expression**);
6668
6669   bool
6670   found()
6671   { return this->found_; }
6672
6673  private:
6674   bool found_;
6675 };
6676
6677 int
6678 Find_call_expression::expression(Expression** pexpr)
6679 {
6680   if ((*pexpr)->call_expression() != NULL)
6681     {
6682       this->found_ = true;
6683       return TRAVERSE_EXIT;
6684     }
6685   return TRAVERSE_CONTINUE;
6686 }
6687
6688 // Lower a builtin call expression.  This turns new and make into
6689 // specific expressions.  We also convert to a constant if we can.
6690
6691 Expression*
6692 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6693                                   Statement_inserter* inserter, int)
6694 {
6695   if (this->classification() == EXPRESSION_ERROR)
6696     return this;
6697
6698   Location loc = this->location();
6699
6700   if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6701     {
6702       this->report_error(_("invalid use of %<...%> with builtin function"));
6703       return Expression::make_error(loc);
6704     }
6705
6706   if (this->is_constant())
6707     {
6708       // We can only lower len and cap if there are no function calls
6709       // in the arguments.  Otherwise we have to make the call.
6710       if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
6711         {
6712           Expression* arg = this->one_arg();
6713           if (arg != NULL && !arg->is_constant())
6714             {
6715               Find_call_expression find_call;
6716               Expression::traverse(&arg, &find_call);
6717               if (find_call.found())
6718                 return this;
6719             }
6720         }
6721
6722       Numeric_constant nc;
6723       if (this->numeric_constant_value(&nc))
6724         return nc.expression(loc);
6725     }
6726
6727   switch (this->code_)
6728     {
6729     default:
6730       break;
6731
6732     case BUILTIN_NEW:
6733       {
6734         const Expression_list* args = this->args();
6735         if (args == NULL || args->size() < 1)
6736           this->report_error(_("not enough arguments"));
6737         else if (args->size() > 1)
6738           this->report_error(_("too many arguments"));
6739         else
6740           {
6741             Expression* arg = args->front();
6742             if (!arg->is_type_expression())
6743               {
6744                 error_at(arg->location(), "expected type");
6745                 this->set_is_error();
6746               }
6747             else
6748               return Expression::make_allocation(arg->type(), loc);
6749           }
6750       }
6751       break;
6752
6753     case BUILTIN_MAKE:
6754       return this->lower_make();
6755
6756     case BUILTIN_RECOVER:
6757       if (function != NULL)
6758         function->func_value()->set_calls_recover();
6759       else
6760         {
6761           // Calling recover outside of a function always returns the
6762           // nil empty interface.
6763           Type* eface = Type::make_empty_interface_type(loc);
6764           return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6765         }
6766       break;
6767
6768     case BUILTIN_APPEND:
6769       {
6770         // Lower the varargs.
6771         const Expression_list* args = this->args();
6772         if (args == NULL || args->empty())
6773           return this;
6774         Type* slice_type = args->front()->type();
6775         if (!slice_type->is_slice_type())
6776           {
6777             error_at(args->front()->location(), "argument 1 must be a slice");
6778             this->set_is_error();
6779             return this;
6780           }
6781         Type* element_type = slice_type->array_type()->element_type();
6782         this->lower_varargs(gogo, function, inserter,
6783                             Type::make_array_type(element_type, NULL),
6784                             2);
6785       }
6786       break;
6787
6788     case BUILTIN_DELETE:
6789       {
6790         // Lower to a runtime function call.
6791         const Expression_list* args = this->args();
6792         if (args == NULL || args->size() < 2)
6793           this->report_error(_("not enough arguments"));
6794         else if (args->size() > 2)
6795           this->report_error(_("too many arguments"));
6796         else if (args->front()->type()->map_type() == NULL)
6797           this->report_error(_("argument 1 must be a map"));
6798         else
6799           {
6800             // Since this function returns no value it must appear in
6801             // a statement by itself, so we don't have to worry about
6802             // order of evaluation of values around it.  Evaluate the
6803             // map first to get order of evaluation right.
6804             Map_type* mt = args->front()->type()->map_type();
6805             Temporary_statement* map_temp =
6806               Statement::make_temporary(mt, args->front(), loc);
6807             inserter->insert(map_temp);
6808
6809             Temporary_statement* key_temp =
6810               Statement::make_temporary(mt->key_type(), args->back(), loc);
6811             inserter->insert(key_temp);
6812
6813             Expression* e1 = Expression::make_temporary_reference(map_temp,
6814                                                                   loc);
6815             Expression* e2 = Expression::make_temporary_reference(key_temp,
6816                                                                   loc);
6817             e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6818             return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6819                                       2, e1, e2);
6820           }
6821       }
6822       break;
6823     }
6824
6825   return this;
6826 }
6827
6828 // Lower a make expression.
6829
6830 Expression*
6831 Builtin_call_expression::lower_make()
6832 {
6833   Location loc = this->location();
6834
6835   const Expression_list* args = this->args();
6836   if (args == NULL || args->size() < 1)
6837     {
6838       this->report_error(_("not enough arguments"));
6839       return Expression::make_error(this->location());
6840     }
6841
6842   Expression_list::const_iterator parg = args->begin();
6843
6844   Expression* first_arg = *parg;
6845   if (!first_arg->is_type_expression())
6846     {
6847       error_at(first_arg->location(), "expected type");
6848       this->set_is_error();
6849       return Expression::make_error(this->location());
6850     }
6851   Type* type = first_arg->type();
6852
6853   bool is_slice = false;
6854   bool is_map = false;
6855   bool is_chan = false;
6856   if (type->is_slice_type())
6857     is_slice = true;
6858   else if (type->map_type() != NULL)
6859     is_map = true;
6860   else if (type->channel_type() != NULL)
6861     is_chan = true;
6862   else
6863     {
6864       this->report_error(_("invalid type for make function"));
6865       return Expression::make_error(this->location());
6866     }
6867
6868   bool have_big_args = false;
6869   Type* uintptr_type = Type::lookup_integer_type("uintptr");
6870   int uintptr_bits = uintptr_type->integer_type()->bits();
6871
6872   ++parg;
6873   Expression* len_arg;
6874   if (parg == args->end())
6875     {
6876       if (is_slice)
6877         {
6878           this->report_error(_("length required when allocating a slice"));
6879           return Expression::make_error(this->location());
6880         }
6881
6882       mpz_t zval;
6883       mpz_init_set_ui(zval, 0);
6884       len_arg = Expression::make_integer(&zval, NULL, loc);
6885       mpz_clear(zval);
6886     }
6887   else
6888     {
6889       len_arg = *parg;
6890       if (!this->check_int_value(len_arg))
6891         {
6892           this->report_error(_("bad size for make"));
6893           return Expression::make_error(this->location());
6894         }
6895       if (len_arg->type()->integer_type() != NULL
6896           && len_arg->type()->integer_type()->bits() > uintptr_bits)
6897         have_big_args = true;
6898       ++parg;
6899     }
6900
6901   Expression* cap_arg = NULL;
6902   if (is_slice && parg != args->end())
6903     {
6904       cap_arg = *parg;
6905       if (!this->check_int_value(cap_arg))
6906         {
6907           this->report_error(_("bad capacity when making slice"));
6908           return Expression::make_error(this->location());
6909         }
6910       if (cap_arg->type()->integer_type() != NULL
6911           && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6912         have_big_args = true;
6913       ++parg;
6914     }
6915
6916   if (parg != args->end())
6917     {
6918       this->report_error(_("too many arguments to make"));
6919       return Expression::make_error(this->location());
6920     }
6921
6922   Location type_loc = first_arg->location();
6923   Expression* type_arg;
6924   if (is_slice || is_chan)
6925     type_arg = Expression::make_type_descriptor(type, type_loc);
6926   else if (is_map)
6927     type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6928   else
6929     go_unreachable();
6930
6931   Expression* call;
6932   if (is_slice)
6933     {
6934       if (cap_arg == NULL)
6935         call = Runtime::make_call((have_big_args
6936                                    ? Runtime::MAKESLICE1BIG
6937                                    : Runtime::MAKESLICE1),
6938                                   loc, 2, type_arg, len_arg);
6939       else
6940         call = Runtime::make_call((have_big_args
6941                                    ? Runtime::MAKESLICE2BIG
6942                                    : Runtime::MAKESLICE2),
6943                                   loc, 3, type_arg, len_arg, cap_arg);
6944     }
6945   else if (is_map)
6946     call = Runtime::make_call((have_big_args
6947                                ? Runtime::MAKEMAPBIG
6948                                : Runtime::MAKEMAP),
6949                               loc, 2, type_arg, len_arg);
6950   else if (is_chan)
6951     call = Runtime::make_call((have_big_args
6952                                ? Runtime::MAKECHANBIG
6953                                : Runtime::MAKECHAN),
6954                               loc, 2, type_arg, len_arg);
6955   else
6956     go_unreachable();
6957
6958   return Expression::make_unsafe_cast(type, call, loc);
6959 }
6960
6961 // Return whether an expression has an integer value.  Report an error
6962 // if not.  This is used when handling calls to the predeclared make
6963 // function.
6964
6965 bool
6966 Builtin_call_expression::check_int_value(Expression* e)
6967 {
6968   if (e->type()->integer_type() != NULL)
6969     return true;
6970
6971   // Check for a floating point constant with integer value.
6972   Numeric_constant nc;
6973   mpz_t ival;
6974   if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6975     {
6976       mpz_clear(ival);
6977       return true;
6978     }
6979
6980   return false;
6981 }
6982
6983 // Return the type of the real or imag functions, given the type of
6984 // the argument.  We need to map complex to float, complex64 to
6985 // float32, and complex128 to float64, so it has to be done by name.
6986 // This returns NULL if it can't figure out the type.
6987
6988 Type*
6989 Builtin_call_expression::real_imag_type(Type* arg_type)
6990 {
6991   if (arg_type == NULL || arg_type->is_abstract())
6992     return NULL;
6993   Named_type* nt = arg_type->named_type();
6994   if (nt == NULL)
6995     return NULL;
6996   while (nt->real_type()->named_type() != NULL)
6997     nt = nt->real_type()->named_type();
6998   if (nt->name() == "complex64")
6999     return Type::lookup_float_type("float32");
7000   else if (nt->name() == "complex128")
7001     return Type::lookup_float_type("float64");
7002   else
7003     return NULL;
7004 }
7005
7006 // Return the type of the complex function, given the type of one of the
7007 // argments.  Like real_imag_type, we have to map by name.
7008
7009 Type*
7010 Builtin_call_expression::complex_type(Type* arg_type)
7011 {
7012   if (arg_type == NULL || arg_type->is_abstract())
7013     return NULL;
7014   Named_type* nt = arg_type->named_type();
7015   if (nt == NULL)
7016     return NULL;
7017   while (nt->real_type()->named_type() != NULL)
7018     nt = nt->real_type()->named_type();
7019   if (nt->name() == "float32")
7020     return Type::lookup_complex_type("complex64");
7021   else if (nt->name() == "float64")
7022     return Type::lookup_complex_type("complex128");
7023   else
7024     return NULL;
7025 }
7026
7027 // Return a single argument, or NULL if there isn't one.
7028
7029 Expression*
7030 Builtin_call_expression::one_arg() const
7031 {
7032   const Expression_list* args = this->args();
7033   if (args == NULL || args->size() != 1)
7034     return NULL;
7035   return args->front();
7036 }
7037
7038 // Return whether this is constant: len of a string, or len or cap of
7039 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
7040
7041 bool
7042 Builtin_call_expression::do_is_constant() const
7043 {
7044   switch (this->code_)
7045     {
7046     case BUILTIN_LEN:
7047     case BUILTIN_CAP:
7048       {
7049         if (this->seen_)
7050           return false;
7051
7052         Expression* arg = this->one_arg();
7053         if (arg == NULL)
7054           return false;
7055         Type* arg_type = arg->type();
7056
7057         if (arg_type->points_to() != NULL
7058             && arg_type->points_to()->array_type() != NULL
7059             && !arg_type->points_to()->is_slice_type())
7060           arg_type = arg_type->points_to();
7061
7062         if (arg_type->array_type() != NULL
7063             && arg_type->array_type()->length() != NULL)
7064           return true;
7065
7066         if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7067           {
7068             this->seen_ = true;
7069             bool ret = arg->is_constant();
7070             this->seen_ = false;
7071             return ret;
7072           }
7073       }
7074       break;
7075
7076     case BUILTIN_SIZEOF:
7077     case BUILTIN_ALIGNOF:
7078       return this->one_arg() != NULL;
7079
7080     case BUILTIN_OFFSETOF:
7081       {
7082         Expression* arg = this->one_arg();
7083         if (arg == NULL)
7084           return false;
7085         return arg->field_reference_expression() != NULL;
7086       }
7087
7088     case BUILTIN_COMPLEX:
7089       {
7090         const Expression_list* args = this->args();
7091         if (args != NULL && args->size() == 2)
7092           return args->front()->is_constant() && args->back()->is_constant();
7093       }
7094       break;
7095
7096     case BUILTIN_REAL:
7097     case BUILTIN_IMAG:
7098       {
7099         Expression* arg = this->one_arg();
7100         return arg != NULL && arg->is_constant();
7101       }
7102
7103     default:
7104       break;
7105     }
7106
7107   return false;
7108 }
7109
7110 // Return a numeric constant if possible.
7111
7112 bool
7113 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7114 {
7115   if (this->code_ == BUILTIN_LEN
7116       || this->code_ == BUILTIN_CAP)
7117     {
7118       Expression* arg = this->one_arg();
7119       if (arg == NULL)
7120         return false;
7121       Type* arg_type = arg->type();
7122
7123       if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7124         {
7125           std::string sval;
7126           if (arg->string_constant_value(&sval))
7127             {
7128               nc->set_unsigned_long(Type::lookup_integer_type("int"),
7129                                     sval.length());
7130               return true;
7131             }
7132         }
7133
7134       if (arg_type->points_to() != NULL
7135           && arg_type->points_to()->array_type() != NULL
7136           && !arg_type->points_to()->is_slice_type())
7137         arg_type = arg_type->points_to();
7138
7139       if (arg_type->array_type() != NULL
7140           && arg_type->array_type()->length() != NULL)
7141         {
7142           if (this->seen_)
7143             return false;
7144           Expression* e = arg_type->array_type()->length();
7145           this->seen_ = true;
7146           bool r = e->numeric_constant_value(nc);
7147           this->seen_ = false;
7148           if (r)
7149             {
7150               if (!nc->set_type(Type::lookup_integer_type("int"), false,
7151                                 this->location()))
7152                 r = false;
7153             }
7154           return r;
7155         }
7156     }
7157   else if (this->code_ == BUILTIN_SIZEOF
7158            || this->code_ == BUILTIN_ALIGNOF)
7159     {
7160       Expression* arg = this->one_arg();
7161       if (arg == NULL)
7162         return false;
7163       Type* arg_type = arg->type();
7164       if (arg_type->is_error())
7165         return false;
7166       if (arg_type->is_abstract())
7167         return false;
7168       if (arg_type->named_type() != NULL)
7169         arg_type->named_type()->convert(this->gogo_);
7170
7171       unsigned int ret;
7172       if (this->code_ == BUILTIN_SIZEOF)
7173         {
7174           if (!arg_type->backend_type_size(this->gogo_, &ret))
7175             return false;
7176         }
7177       else if (this->code_ == BUILTIN_ALIGNOF)
7178         {
7179           if (arg->field_reference_expression() == NULL)
7180             {
7181               if (!arg_type->backend_type_align(this->gogo_, &ret))
7182                 return false;
7183             }
7184           else
7185             {
7186               // Calling unsafe.Alignof(s.f) returns the alignment of
7187               // the type of f when it is used as a field in a struct.
7188               if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7189                 return false;
7190             }
7191         }
7192       else
7193         go_unreachable();
7194
7195       nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7196                             static_cast<unsigned long>(ret));
7197       return true;
7198     }
7199   else if (this->code_ == BUILTIN_OFFSETOF)
7200     {
7201       Expression* arg = this->one_arg();
7202       if (arg == NULL)
7203         return false;
7204       Field_reference_expression* farg = arg->field_reference_expression();
7205       if (farg == NULL)
7206         return false;
7207       Expression* struct_expr = farg->expr();
7208       Type* st = struct_expr->type();
7209       if (st->struct_type() == NULL)
7210         return false;
7211       if (st->named_type() != NULL)
7212         st->named_type()->convert(this->gogo_);
7213       unsigned int offset;
7214       if (!st->struct_type()->backend_field_offset(this->gogo_,
7215                                                    farg->field_index(),
7216                                                    &offset))
7217         return false;
7218       nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7219                             static_cast<unsigned long>(offset));
7220       return true;
7221     }
7222   else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7223     {
7224       Expression* arg = this->one_arg();
7225       if (arg == NULL)
7226         return false;
7227
7228       Numeric_constant argnc;
7229       if (!arg->numeric_constant_value(&argnc))
7230         return false;
7231
7232       mpfr_t real;
7233       mpfr_t imag;
7234       if (!argnc.to_complex(&real, &imag))
7235         return false;
7236
7237       Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7238       if (this->code_ == BUILTIN_REAL)
7239         nc->set_float(type, real);
7240       else
7241         nc->set_float(type, imag);
7242       return true;
7243     }
7244   else if (this->code_ == BUILTIN_COMPLEX)
7245     {
7246       const Expression_list* args = this->args();
7247       if (args == NULL || args->size() != 2)
7248         return false;
7249
7250       Numeric_constant rnc;
7251       if (!args->front()->numeric_constant_value(&rnc))
7252         return false;
7253       Numeric_constant inc;
7254       if (!args->back()->numeric_constant_value(&inc))
7255         return false;
7256
7257       if (rnc.type() != NULL
7258           && !rnc.type()->is_abstract()
7259           && inc.type() != NULL
7260           && !inc.type()->is_abstract()
7261           && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7262         return false;
7263
7264       mpfr_t r;
7265       if (!rnc.to_float(&r))
7266         return false;
7267       mpfr_t i;
7268       if (!inc.to_float(&i))
7269         {
7270           mpfr_clear(r);
7271           return false;
7272         }
7273
7274       Type* arg_type = rnc.type();
7275       if (arg_type == NULL || arg_type->is_abstract())
7276         arg_type = inc.type();
7277
7278       Type* type = Builtin_call_expression::complex_type(arg_type);
7279       nc->set_complex(type, r, i);
7280
7281       mpfr_clear(r);
7282       mpfr_clear(i);
7283
7284       return true;
7285     }
7286
7287   return false;
7288 }
7289
7290 // Give an error if we are discarding the value of an expression which
7291 // should not normally be discarded.  We don't give an error for
7292 // discarding the value of an ordinary function call, but we do for
7293 // builtin functions, purely for consistency with the gc compiler.
7294
7295 void
7296 Builtin_call_expression::do_discarding_value()
7297 {
7298   switch (this->code_)
7299     {
7300     case BUILTIN_INVALID:
7301     default:
7302       go_unreachable();
7303
7304     case BUILTIN_APPEND:
7305     case BUILTIN_CAP:
7306     case BUILTIN_COMPLEX:
7307     case BUILTIN_IMAG:
7308     case BUILTIN_LEN:
7309     case BUILTIN_MAKE:
7310     case BUILTIN_NEW:
7311     case BUILTIN_REAL:
7312     case BUILTIN_ALIGNOF:
7313     case BUILTIN_OFFSETOF:
7314     case BUILTIN_SIZEOF:
7315       this->unused_value_error();
7316       break;
7317
7318     case BUILTIN_CLOSE:
7319     case BUILTIN_COPY:
7320     case BUILTIN_DELETE:
7321     case BUILTIN_PANIC:
7322     case BUILTIN_PRINT:
7323     case BUILTIN_PRINTLN:
7324     case BUILTIN_RECOVER:
7325       break;
7326     }
7327 }
7328
7329 // Return the type.
7330
7331 Type*
7332 Builtin_call_expression::do_type()
7333 {
7334   switch (this->code_)
7335     {
7336     case BUILTIN_INVALID:
7337     default:
7338       go_unreachable();
7339
7340     case BUILTIN_NEW:
7341     case BUILTIN_MAKE:
7342       {
7343         const Expression_list* args = this->args();
7344         if (args == NULL || args->empty())
7345           return Type::make_error_type();
7346         return Type::make_pointer_type(args->front()->type());
7347       }
7348
7349     case BUILTIN_CAP:
7350     case BUILTIN_COPY:
7351     case BUILTIN_LEN:
7352       return Type::lookup_integer_type("int");
7353
7354     case BUILTIN_ALIGNOF:
7355     case BUILTIN_OFFSETOF:
7356     case BUILTIN_SIZEOF:
7357       return Type::lookup_integer_type("uintptr");
7358
7359     case BUILTIN_CLOSE:
7360     case BUILTIN_DELETE:
7361     case BUILTIN_PANIC:
7362     case BUILTIN_PRINT:
7363     case BUILTIN_PRINTLN:
7364       return Type::make_void_type();
7365
7366     case BUILTIN_RECOVER:
7367       return Type::make_empty_interface_type(Linemap::predeclared_location());
7368
7369     case BUILTIN_APPEND:
7370       {
7371         const Expression_list* args = this->args();
7372         if (args == NULL || args->empty())
7373           return Type::make_error_type();
7374         return args->front()->type();
7375       }
7376
7377     case BUILTIN_REAL:
7378     case BUILTIN_IMAG:
7379       {
7380         Expression* arg = this->one_arg();
7381         if (arg == NULL)
7382           return Type::make_error_type();
7383         Type* t = arg->type();
7384         if (t->is_abstract())
7385           t = t->make_non_abstract_type();
7386         t = Builtin_call_expression::real_imag_type(t);
7387         if (t == NULL)
7388           t = Type::make_error_type();
7389         return t;
7390       }
7391
7392     case BUILTIN_COMPLEX:
7393       {
7394         const Expression_list* args = this->args();
7395         if (args == NULL || args->size() != 2)
7396           return Type::make_error_type();
7397         Type* t = args->front()->type();
7398         if (t->is_abstract())
7399           {
7400             t = args->back()->type();
7401             if (t->is_abstract())
7402               t = t->make_non_abstract_type();
7403           }
7404         t = Builtin_call_expression::complex_type(t);
7405         if (t == NULL)
7406           t = Type::make_error_type();
7407         return t;
7408       }
7409     }
7410 }
7411
7412 // Determine the type.
7413
7414 void
7415 Builtin_call_expression::do_determine_type(const Type_context* context)
7416 {
7417   if (!this->determining_types())
7418     return;
7419
7420   this->fn()->determine_type_no_context();
7421
7422   const Expression_list* args = this->args();
7423
7424   bool is_print;
7425   Type* arg_type = NULL;
7426   switch (this->code_)
7427     {
7428     case BUILTIN_PRINT:
7429     case BUILTIN_PRINTLN:
7430       // Do not force a large integer constant to "int".
7431       is_print = true;
7432       break;
7433
7434     case BUILTIN_REAL:
7435     case BUILTIN_IMAG:
7436       arg_type = Builtin_call_expression::complex_type(context->type);
7437       is_print = false;
7438       break;
7439
7440     case BUILTIN_COMPLEX:
7441       {
7442         // For the complex function the type of one operand can
7443         // determine the type of the other, as in a binary expression.
7444         arg_type = Builtin_call_expression::real_imag_type(context->type);
7445         if (args != NULL && args->size() == 2)
7446           {
7447             Type* t1 = args->front()->type();
7448             Type* t2 = args->front()->type();
7449             if (!t1->is_abstract())
7450               arg_type = t1;
7451             else if (!t2->is_abstract())
7452               arg_type = t2;
7453           }
7454         is_print = false;
7455       }
7456       break;
7457
7458     default:
7459       is_print = false;
7460       break;
7461     }
7462
7463   if (args != NULL)
7464     {
7465       for (Expression_list::const_iterator pa = args->begin();
7466            pa != args->end();
7467            ++pa)
7468         {
7469           Type_context subcontext;
7470           subcontext.type = arg_type;
7471
7472           if (is_print)
7473             {
7474               // We want to print large constants, we so can't just
7475               // use the appropriate nonabstract type.  Use uint64 for
7476               // an integer if we know it is nonnegative, otherwise
7477               // use int64 for a integer, otherwise use float64 for a
7478               // float or complex128 for a complex.
7479               Type* want_type = NULL;
7480               Type* atype = (*pa)->type();
7481               if (atype->is_abstract())
7482                 {
7483                   if (atype->integer_type() != NULL)
7484                     {
7485                       Numeric_constant nc;
7486                       if (this->numeric_constant_value(&nc))
7487                         {
7488                           mpz_t val;
7489                           if (nc.to_int(&val))
7490                             {
7491                               if (mpz_sgn(val) >= 0)
7492                                 want_type = Type::lookup_integer_type("uint64");
7493                               mpz_clear(val);
7494                             }
7495                         }
7496                       if (want_type == NULL)
7497                         want_type = Type::lookup_integer_type("int64");
7498                     }
7499                   else if (atype->float_type() != NULL)
7500                     want_type = Type::lookup_float_type("float64");
7501                   else if (atype->complex_type() != NULL)
7502                     want_type = Type::lookup_complex_type("complex128");
7503                   else if (atype->is_abstract_string_type())
7504                     want_type = Type::lookup_string_type();
7505                   else if (atype->is_abstract_boolean_type())
7506                     want_type = Type::lookup_bool_type();
7507                   else
7508                     go_unreachable();
7509                   subcontext.type = want_type;
7510                 }
7511             }
7512
7513           (*pa)->determine_type(&subcontext);
7514         }
7515     }
7516 }
7517
7518 // If there is exactly one argument, return true.  Otherwise give an
7519 // error message and return false.
7520
7521 bool
7522 Builtin_call_expression::check_one_arg()
7523 {
7524   const Expression_list* args = this->args();
7525   if (args == NULL || args->size() < 1)
7526     {
7527       this->report_error(_("not enough arguments"));
7528       return false;
7529     }
7530   else if (args->size() > 1)
7531     {
7532       this->report_error(_("too many arguments"));
7533       return false;
7534     }
7535   if (args->front()->is_error_expression()
7536       || args->front()->type()->is_error())
7537     {
7538       this->set_is_error();
7539       return false;
7540     }
7541   return true;
7542 }
7543
7544 // Check argument types for a builtin function.
7545
7546 void
7547 Builtin_call_expression::do_check_types(Gogo*)
7548 {
7549   if (this->is_error_expression())
7550     return;
7551   switch (this->code_)
7552     {
7553     case BUILTIN_INVALID:
7554     case BUILTIN_NEW:
7555     case BUILTIN_MAKE:
7556     case BUILTIN_DELETE:
7557       return;
7558
7559     case BUILTIN_LEN:
7560     case BUILTIN_CAP:
7561       {
7562         // The single argument may be either a string or an array or a
7563         // map or a channel, or a pointer to a closed array.
7564         if (this->check_one_arg())
7565           {
7566             Type* arg_type = this->one_arg()->type();
7567             if (arg_type->points_to() != NULL
7568                 && arg_type->points_to()->array_type() != NULL
7569                 && !arg_type->points_to()->is_slice_type())
7570               arg_type = arg_type->points_to();
7571             if (this->code_ == BUILTIN_CAP)
7572               {
7573                 if (!arg_type->is_error()
7574                     && arg_type->array_type() == NULL
7575                     && arg_type->channel_type() == NULL)
7576                   this->report_error(_("argument must be array or slice "
7577                                        "or channel"));
7578               }
7579             else
7580               {
7581                 if (!arg_type->is_error()
7582                     && !arg_type->is_string_type()
7583                     && arg_type->array_type() == NULL
7584                     && arg_type->map_type() == NULL
7585                     && arg_type->channel_type() == NULL)
7586                   this->report_error(_("argument must be string or "
7587                                        "array or slice or map or channel"));
7588               }
7589           }
7590       }
7591       break;
7592
7593     case BUILTIN_PRINT:
7594     case BUILTIN_PRINTLN:
7595       {
7596         const Expression_list* args = this->args();
7597         if (args == NULL)
7598           {
7599             if (this->code_ == BUILTIN_PRINT)
7600               warning_at(this->location(), 0,
7601                          "no arguments for builtin function %<%s%>",
7602                          (this->code_ == BUILTIN_PRINT
7603                           ? "print"
7604                           : "println"));
7605           }
7606         else
7607           {
7608             for (Expression_list::const_iterator p = args->begin();
7609                  p != args->end();
7610                  ++p)
7611               {
7612                 Type* type = (*p)->type();
7613                 if (type->is_error()
7614                     || type->is_string_type()
7615                     || type->integer_type() != NULL
7616                     || type->float_type() != NULL
7617                     || type->complex_type() != NULL
7618                     || type->is_boolean_type()
7619                     || type->points_to() != NULL
7620                     || type->interface_type() != NULL
7621                     || type->channel_type() != NULL
7622                     || type->map_type() != NULL
7623                     || type->function_type() != NULL
7624                     || type->is_slice_type())
7625                   ;
7626                 else if ((*p)->is_type_expression())
7627                   {
7628                     // If this is a type expression it's going to give
7629                     // an error anyhow, so we don't need one here.
7630                   }
7631                 else
7632                   this->report_error(_("unsupported argument type to "
7633                                        "builtin function"));
7634               }
7635           }
7636       }
7637       break;
7638
7639     case BUILTIN_CLOSE:
7640       if (this->check_one_arg())
7641         {
7642           if (this->one_arg()->type()->channel_type() == NULL)
7643             this->report_error(_("argument must be channel"));
7644           else if (!this->one_arg()->type()->channel_type()->may_send())
7645             this->report_error(_("cannot close receive-only channel"));
7646         }
7647       break;
7648
7649     case BUILTIN_PANIC:
7650     case BUILTIN_SIZEOF:
7651     case BUILTIN_ALIGNOF:
7652       this->check_one_arg();
7653       break;
7654
7655     case BUILTIN_RECOVER:
7656       if (this->args() != NULL && !this->args()->empty())
7657         this->report_error(_("too many arguments"));
7658       break;
7659
7660     case BUILTIN_OFFSETOF:
7661       if (this->check_one_arg())
7662         {
7663           Expression* arg = this->one_arg();
7664           if (arg->field_reference_expression() == NULL)
7665             this->report_error(_("argument must be a field reference"));
7666         }
7667       break;
7668
7669     case BUILTIN_COPY:
7670       {
7671         const Expression_list* args = this->args();
7672         if (args == NULL || args->size() < 2)
7673           {
7674             this->report_error(_("not enough arguments"));
7675             break;
7676           }
7677         else if (args->size() > 2)
7678           {
7679             this->report_error(_("too many arguments"));
7680             break;
7681           }
7682         Type* arg1_type = args->front()->type();
7683         Type* arg2_type = args->back()->type();
7684         if (arg1_type->is_error() || arg2_type->is_error())
7685           break;
7686
7687         Type* e1;
7688         if (arg1_type->is_slice_type())
7689           e1 = arg1_type->array_type()->element_type();
7690         else
7691           {
7692             this->report_error(_("left argument must be a slice"));
7693             break;
7694           }
7695
7696         if (arg2_type->is_slice_type())
7697           {
7698             Type* e2 = arg2_type->array_type()->element_type();
7699             if (!Type::are_identical(e1, e2, true, NULL))
7700               this->report_error(_("element types must be the same"));
7701           }
7702         else if (arg2_type->is_string_type())
7703           {
7704             if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7705               this->report_error(_("first argument must be []byte"));
7706           }
7707         else
7708             this->report_error(_("second argument must be slice or string"));
7709       }
7710       break;
7711
7712     case BUILTIN_APPEND:
7713       {
7714         const Expression_list* args = this->args();
7715         if (args == NULL || args->size() < 2)
7716           {
7717             this->report_error(_("not enough arguments"));
7718             break;
7719           }
7720         if (args->size() > 2)
7721           {
7722             this->report_error(_("too many arguments"));
7723             break;
7724           }
7725         if (args->front()->type()->is_error()
7726             || args->back()->type()->is_error())
7727           break;
7728
7729         Array_type* at = args->front()->type()->array_type();
7730         Type* e = at->element_type();
7731
7732         // The language permits appending a string to a []byte, as a
7733         // special case.
7734         if (args->back()->type()->is_string_type())
7735           {
7736             if (e->integer_type() != NULL && e->integer_type()->is_byte())
7737               break;
7738           }
7739
7740         // The language says that the second argument must be
7741         // assignable to a slice of the element type of the first
7742         // argument.  We already know the first argument is a slice
7743         // type.
7744         Type* arg2_type = Type::make_array_type(e, NULL);
7745         std::string reason;
7746         if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7747           {
7748             if (reason.empty())
7749               this->report_error(_("argument 2 has invalid type"));
7750             else
7751               {
7752                 error_at(this->location(), "argument 2 has invalid type (%s)",
7753                          reason.c_str());
7754                 this->set_is_error();
7755               }
7756           }
7757         break;
7758       }
7759
7760     case BUILTIN_REAL:
7761     case BUILTIN_IMAG:
7762       if (this->check_one_arg())
7763         {
7764           if (this->one_arg()->type()->complex_type() == NULL)
7765             this->report_error(_("argument must have complex type"));
7766         }
7767       break;
7768
7769     case BUILTIN_COMPLEX:
7770       {
7771         const Expression_list* args = this->args();
7772         if (args == NULL || args->size() < 2)
7773           this->report_error(_("not enough arguments"));
7774         else if (args->size() > 2)
7775           this->report_error(_("too many arguments"));
7776         else if (args->front()->is_error_expression()
7777                  || args->front()->type()->is_error()
7778                  || args->back()->is_error_expression()
7779                  || args->back()->type()->is_error())
7780           this->set_is_error();
7781         else if (!Type::are_identical(args->front()->type(),
7782                                       args->back()->type(), true, NULL))
7783           this->report_error(_("complex arguments must have identical types"));
7784         else if (args->front()->type()->float_type() == NULL)
7785           this->report_error(_("complex arguments must have "
7786                                "floating-point type"));
7787       }
7788       break;
7789
7790     default:
7791       go_unreachable();
7792     }
7793 }
7794
7795 // Return the tree for a builtin function.
7796
7797 tree
7798 Builtin_call_expression::do_get_tree(Translate_context* context)
7799 {
7800   Gogo* gogo = context->gogo();
7801   Location location = this->location();
7802   switch (this->code_)
7803     {
7804     case BUILTIN_INVALID:
7805     case BUILTIN_NEW:
7806     case BUILTIN_MAKE:
7807       go_unreachable();
7808
7809     case BUILTIN_LEN:
7810     case BUILTIN_CAP:
7811       {
7812         const Expression_list* args = this->args();
7813         go_assert(args != NULL && args->size() == 1);
7814         Expression* arg = *args->begin();
7815         Type* arg_type = arg->type();
7816
7817         if (this->seen_)
7818           {
7819             go_assert(saw_errors());
7820             return error_mark_node;
7821           }
7822         this->seen_ = true;
7823
7824         tree arg_tree = arg->get_tree(context);
7825
7826         this->seen_ = false;
7827
7828         if (arg_tree == error_mark_node)
7829           return error_mark_node;
7830
7831         if (arg_type->points_to() != NULL)
7832           {
7833             arg_type = arg_type->points_to();
7834             go_assert(arg_type->array_type() != NULL
7835                        && !arg_type->is_slice_type());
7836             go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7837             arg_tree = build_fold_indirect_ref(arg_tree);
7838           }
7839
7840         tree val_tree;
7841         if (this->code_ == BUILTIN_LEN)
7842           {
7843             if (arg_type->is_string_type())
7844               val_tree = String_type::length_tree(gogo, arg_tree);
7845             else if (arg_type->array_type() != NULL)
7846               {
7847                 if (this->seen_)
7848                   {
7849                     go_assert(saw_errors());
7850                     return error_mark_node;
7851                   }
7852                 this->seen_ = true;
7853                 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7854                 this->seen_ = false;
7855               }
7856             else if (arg_type->map_type() != NULL)
7857               {
7858                 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7859                 static tree map_len_fndecl;
7860                 val_tree = Gogo::call_builtin(&map_len_fndecl,
7861                                               location,
7862                                               "__go_map_len",
7863                                               1,
7864                                               integer_type_node,
7865                                               arg_type_tree,
7866                                               arg_tree);
7867               }
7868             else if (arg_type->channel_type() != NULL)
7869               {
7870                 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7871                 static tree chan_len_fndecl;
7872                 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7873                                               location,
7874                                               "__go_chan_len",
7875                                               1,
7876                                               integer_type_node,
7877                                               arg_type_tree,
7878                                               arg_tree);
7879               }
7880             else
7881               go_unreachable();
7882           }
7883         else
7884           {
7885             if (arg_type->array_type() != NULL)
7886               {
7887                 if (this->seen_)
7888                   {
7889                     go_assert(saw_errors());
7890                     return error_mark_node;
7891                   }
7892                 this->seen_ = true;
7893                 val_tree = arg_type->array_type()->capacity_tree(gogo,
7894                                                                  arg_tree);
7895                 this->seen_ = false;
7896               }
7897             else if (arg_type->channel_type() != NULL)
7898               {
7899                 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7900                 static tree chan_cap_fndecl;
7901                 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7902                                               location,
7903                                               "__go_chan_cap",
7904                                               1,
7905                                               integer_type_node,
7906                                               arg_type_tree,
7907                                               arg_tree);
7908               }
7909             else
7910               go_unreachable();
7911           }
7912
7913         if (val_tree == error_mark_node)
7914           return error_mark_node;
7915
7916         Type* int_type = Type::lookup_integer_type("int");
7917         tree type_tree = type_to_tree(int_type->get_backend(gogo));
7918         if (type_tree == TREE_TYPE(val_tree))
7919           return val_tree;
7920         else
7921           return fold(convert_to_integer(type_tree, val_tree));
7922       }
7923
7924     case BUILTIN_PRINT:
7925     case BUILTIN_PRINTLN:
7926       {
7927         const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7928         tree stmt_list = NULL_TREE;
7929
7930         const Expression_list* call_args = this->args();
7931         if (call_args != NULL)
7932           {
7933             for (Expression_list::const_iterator p = call_args->begin();
7934                  p != call_args->end();
7935                  ++p)
7936               {
7937                 if (is_ln && p != call_args->begin())
7938                   {
7939                     static tree print_space_fndecl;
7940                     tree call = Gogo::call_builtin(&print_space_fndecl,
7941                                                    location,
7942                                                    "__go_print_space",
7943                                                    0,
7944                                                    void_type_node);
7945                     if (call == error_mark_node)
7946                       return error_mark_node;
7947                     append_to_statement_list(call, &stmt_list);
7948                   }
7949
7950                 Type* type = (*p)->type();
7951
7952                 tree arg = (*p)->get_tree(context);
7953                 if (arg == error_mark_node)
7954                   return error_mark_node;
7955
7956                 tree* pfndecl;
7957                 const char* fnname;
7958                 if (type->is_string_type())
7959                   {
7960                     static tree print_string_fndecl;
7961                     pfndecl = &print_string_fndecl;
7962                     fnname = "__go_print_string";
7963                   }
7964                 else if (type->integer_type() != NULL
7965                          && type->integer_type()->is_unsigned())
7966                   {
7967                     static tree print_uint64_fndecl;
7968                     pfndecl = &print_uint64_fndecl;
7969                     fnname = "__go_print_uint64";
7970                     Type* itype = Type::lookup_integer_type("uint64");
7971                     Btype* bitype = itype->get_backend(gogo);
7972                     arg = fold_convert_loc(location.gcc_location(),
7973                                            type_to_tree(bitype), arg);
7974                   }
7975                 else if (type->integer_type() != NULL)
7976                   {
7977                     static tree print_int64_fndecl;
7978                     pfndecl = &print_int64_fndecl;
7979                     fnname = "__go_print_int64";
7980                     Type* itype = Type::lookup_integer_type("int64");
7981                     Btype* bitype = itype->get_backend(gogo);
7982                     arg = fold_convert_loc(location.gcc_location(),
7983                                            type_to_tree(bitype), arg);
7984                   }
7985                 else if (type->float_type() != NULL)
7986                   {
7987                     static tree print_double_fndecl;
7988                     pfndecl = &print_double_fndecl;
7989                     fnname = "__go_print_double";
7990                     arg = fold_convert_loc(location.gcc_location(),
7991                                            double_type_node, arg);
7992                   }
7993                 else if (type->complex_type() != NULL)
7994                   {
7995                     static tree print_complex_fndecl;
7996                     pfndecl = &print_complex_fndecl;
7997                     fnname = "__go_print_complex";
7998                     arg = fold_convert_loc(location.gcc_location(),
7999                                            complex_double_type_node, arg);
8000                   }
8001                 else if (type->is_boolean_type())
8002                   {
8003                     static tree print_bool_fndecl;
8004                     pfndecl = &print_bool_fndecl;
8005                     fnname = "__go_print_bool";
8006                   }
8007                 else if (type->points_to() != NULL
8008                          || type->channel_type() != NULL
8009                          || type->map_type() != NULL
8010                          || type->function_type() != NULL)
8011                   {
8012                     static tree print_pointer_fndecl;
8013                     pfndecl = &print_pointer_fndecl;
8014                     fnname = "__go_print_pointer";
8015                     arg = fold_convert_loc(location.gcc_location(),
8016                                            ptr_type_node, arg);
8017                   }
8018                 else if (type->interface_type() != NULL)
8019                   {
8020                     if (type->interface_type()->is_empty())
8021                       {
8022                         static tree print_empty_interface_fndecl;
8023                         pfndecl = &print_empty_interface_fndecl;
8024                         fnname = "__go_print_empty_interface";
8025                       }
8026                     else
8027                       {
8028                         static tree print_interface_fndecl;
8029                         pfndecl = &print_interface_fndecl;
8030                         fnname = "__go_print_interface";
8031                       }
8032                   }
8033                 else if (type->is_slice_type())
8034                   {
8035                     static tree print_slice_fndecl;
8036                     pfndecl = &print_slice_fndecl;
8037                     fnname = "__go_print_slice";
8038                   }
8039                 else
8040                   {
8041                     go_assert(saw_errors());
8042                     return error_mark_node;
8043                   }
8044
8045                 tree call = Gogo::call_builtin(pfndecl,
8046                                                location,
8047                                                fnname,
8048                                                1,
8049                                                void_type_node,
8050                                                TREE_TYPE(arg),
8051                                                arg);
8052                 if (call == error_mark_node)
8053                   return error_mark_node;
8054                 append_to_statement_list(call, &stmt_list);
8055               }
8056           }
8057
8058         if (is_ln)
8059           {
8060             static tree print_nl_fndecl;
8061             tree call = Gogo::call_builtin(&print_nl_fndecl,
8062                                            location,
8063                                            "__go_print_nl",
8064                                            0,
8065                                            void_type_node);
8066             if (call == error_mark_node)
8067               return error_mark_node;
8068             append_to_statement_list(call, &stmt_list);
8069           }
8070
8071         return stmt_list;
8072       }
8073
8074     case BUILTIN_PANIC:
8075       {
8076         const Expression_list* args = this->args();
8077         go_assert(args != NULL && args->size() == 1);
8078         Expression* arg = args->front();
8079         tree arg_tree = arg->get_tree(context);
8080         if (arg_tree == error_mark_node)
8081           return error_mark_node;
8082         Type *empty =
8083           Type::make_empty_interface_type(Linemap::predeclared_location());
8084         arg_tree = Expression::convert_for_assignment(context, empty,
8085                                                       arg->type(),
8086                                                       arg_tree, location);
8087         static tree panic_fndecl;
8088         tree call = Gogo::call_builtin(&panic_fndecl,
8089                                        location,
8090                                        "__go_panic",
8091                                        1,
8092                                        void_type_node,
8093                                        TREE_TYPE(arg_tree),
8094                                        arg_tree);
8095         if (call == error_mark_node)
8096           return error_mark_node;
8097         // This function will throw an exception.
8098         TREE_NOTHROW(panic_fndecl) = 0;
8099         // This function will not return.
8100         TREE_THIS_VOLATILE(panic_fndecl) = 1;
8101         return call;
8102       }
8103
8104     case BUILTIN_RECOVER:
8105       {
8106         // The argument is set when building recover thunks.  It's a
8107         // boolean value which is true if we can recover a value now.
8108         const Expression_list* args = this->args();
8109         go_assert(args != NULL && args->size() == 1);
8110         Expression* arg = args->front();
8111         tree arg_tree = arg->get_tree(context);
8112         if (arg_tree == error_mark_node)
8113           return error_mark_node;
8114
8115         Type *empty =
8116           Type::make_empty_interface_type(Linemap::predeclared_location());
8117         tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8118
8119         Type* nil_type = Type::make_nil_type();
8120         Expression* nil = Expression::make_nil(location);
8121         tree nil_tree = nil->get_tree(context);
8122         tree empty_nil_tree = Expression::convert_for_assignment(context,
8123                                                                  empty,
8124                                                                  nil_type,
8125                                                                  nil_tree,
8126                                                                  location);
8127
8128         // We need to handle a deferred call to recover specially,
8129         // because it changes whether it can recover a panic or not.
8130         // See test7 in test/recover1.go.
8131         tree call;
8132         if (this->is_deferred())
8133           {
8134             static tree deferred_recover_fndecl;
8135             call = Gogo::call_builtin(&deferred_recover_fndecl,
8136                                       location,
8137                                       "__go_deferred_recover",
8138                                       0,
8139                                       empty_tree);
8140           }
8141         else
8142           {
8143             static tree recover_fndecl;
8144             call = Gogo::call_builtin(&recover_fndecl,
8145                                       location,
8146                                       "__go_recover",
8147                                       0,
8148                                       empty_tree);
8149           }
8150         if (call == error_mark_node)
8151           return error_mark_node;
8152         return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8153                                arg_tree, call, empty_nil_tree);
8154       }
8155
8156     case BUILTIN_CLOSE:
8157       {
8158         const Expression_list* args = this->args();
8159         go_assert(args != NULL && args->size() == 1);
8160         Expression* arg = args->front();
8161         tree arg_tree = arg->get_tree(context);
8162         if (arg_tree == error_mark_node)
8163           return error_mark_node;
8164         static tree close_fndecl;
8165         return Gogo::call_builtin(&close_fndecl,
8166                                   location,
8167                                   "__go_builtin_close",
8168                                   1,
8169                                   void_type_node,
8170                                   TREE_TYPE(arg_tree),
8171                                   arg_tree);
8172       }
8173
8174     case BUILTIN_SIZEOF:
8175     case BUILTIN_OFFSETOF:
8176     case BUILTIN_ALIGNOF:
8177       {
8178         Numeric_constant nc;
8179         unsigned long val;
8180         if (!this->numeric_constant_value(&nc)
8181             || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8182           {
8183             go_assert(saw_errors());
8184             return error_mark_node;
8185           }
8186         Type* uintptr_type = Type::lookup_integer_type("uintptr");
8187         tree type = type_to_tree(uintptr_type->get_backend(gogo));
8188         return build_int_cst(type, val);
8189       }
8190
8191     case BUILTIN_COPY:
8192       {
8193         const Expression_list* args = this->args();
8194         go_assert(args != NULL && args->size() == 2);
8195         Expression* arg1 = args->front();
8196         Expression* arg2 = args->back();
8197
8198         tree arg1_tree = arg1->get_tree(context);
8199         tree arg2_tree = arg2->get_tree(context);
8200         if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8201           return error_mark_node;
8202
8203         Type* arg1_type = arg1->type();
8204         Array_type* at = arg1_type->array_type();
8205         arg1_tree = save_expr(arg1_tree);
8206         tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8207         tree arg1_len = at->length_tree(gogo, arg1_tree);
8208         if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8209           return error_mark_node;
8210
8211         Type* arg2_type = arg2->type();
8212         tree arg2_val;
8213         tree arg2_len;
8214         if (arg2_type->is_slice_type())
8215           {
8216             at = arg2_type->array_type();
8217             arg2_tree = save_expr(arg2_tree);
8218             arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8219             arg2_len = at->length_tree(gogo, arg2_tree);
8220           }
8221         else
8222           {
8223             arg2_tree = save_expr(arg2_tree);
8224             arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8225             arg2_len = String_type::length_tree(gogo, arg2_tree);
8226           }
8227         if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8228           return error_mark_node;
8229
8230         arg1_len = save_expr(arg1_len);
8231         arg2_len = save_expr(arg2_len);
8232         tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8233                                    TREE_TYPE(arg1_len),
8234                                    fold_build2_loc(location.gcc_location(),
8235                                                    LT_EXPR, boolean_type_node,
8236                                                    arg1_len, arg2_len),
8237                                    arg1_len, arg2_len);
8238         len = save_expr(len);
8239
8240         Type* element_type = at->element_type();
8241         Btype* element_btype = element_type->get_backend(gogo);
8242         tree element_type_tree = type_to_tree(element_btype);
8243         if (element_type_tree == error_mark_node)
8244           return error_mark_node;
8245         tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8246         tree bytecount = fold_convert_loc(location.gcc_location(),
8247                                           TREE_TYPE(element_size), len);
8248         bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8249                                     TREE_TYPE(element_size),
8250                                     bytecount, element_size);
8251         bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8252                                      bytecount);
8253
8254         arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8255                                     arg1_val);
8256         arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8257                                     arg2_val);
8258
8259         static tree copy_fndecl;
8260         tree call = Gogo::call_builtin(&copy_fndecl,
8261                                        location,
8262                                        "__go_copy",
8263                                        3,
8264                                        void_type_node,
8265                                        ptr_type_node,
8266                                        arg1_val,
8267                                        ptr_type_node,
8268                                        arg2_val,
8269                                        size_type_node,
8270                                        bytecount);
8271         if (call == error_mark_node)
8272           return error_mark_node;
8273
8274         return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8275                                TREE_TYPE(len), call, len);
8276       }
8277
8278     case BUILTIN_APPEND:
8279       {
8280         const Expression_list* args = this->args();
8281         go_assert(args != NULL && args->size() == 2);
8282         Expression* arg1 = args->front();
8283         Expression* arg2 = args->back();
8284
8285         tree arg1_tree = arg1->get_tree(context);
8286         tree arg2_tree = arg2->get_tree(context);
8287         if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8288           return error_mark_node;
8289
8290         Array_type* at = arg1->type()->array_type();
8291         Type* element_type = at->element_type()->forwarded();
8292
8293         tree arg2_val;
8294         tree arg2_len;
8295         tree element_size;
8296         if (arg2->type()->is_string_type()
8297             && element_type->integer_type() != NULL
8298             && element_type->integer_type()->is_byte())
8299           {
8300             arg2_tree = save_expr(arg2_tree);
8301             arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8302             arg2_len = String_type::length_tree(gogo, arg2_tree);
8303             element_size = size_int(1);
8304           }
8305         else
8306           {
8307             arg2_tree = Expression::convert_for_assignment(context, at,
8308                                                            arg2->type(),
8309                                                            arg2_tree,
8310                                                            location);
8311             if (arg2_tree == error_mark_node)
8312               return error_mark_node;
8313
8314             arg2_tree = save_expr(arg2_tree);
8315
8316              arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8317              arg2_len = at->length_tree(gogo, arg2_tree);
8318
8319              Btype* element_btype = element_type->get_backend(gogo);
8320              tree element_type_tree = type_to_tree(element_btype);
8321              if (element_type_tree == error_mark_node)
8322                return error_mark_node;
8323              element_size = TYPE_SIZE_UNIT(element_type_tree);
8324           }
8325
8326         arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8327                                     arg2_val);
8328         arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8329                                     arg2_len);
8330         element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8331                                         element_size);
8332
8333         if (arg2_val == error_mark_node
8334             || arg2_len == error_mark_node
8335             || element_size == error_mark_node)
8336           return error_mark_node;
8337
8338         // We rebuild the decl each time since the slice types may
8339         // change.
8340         tree append_fndecl = NULL_TREE;
8341         return Gogo::call_builtin(&append_fndecl,
8342                                   location,
8343                                   "__go_append",
8344                                   4,
8345                                   TREE_TYPE(arg1_tree),
8346                                   TREE_TYPE(arg1_tree),
8347                                   arg1_tree,
8348                                   ptr_type_node,
8349                                   arg2_val,
8350                                   size_type_node,
8351                                   arg2_len,
8352                                   size_type_node,
8353                                   element_size);
8354       }
8355
8356     case BUILTIN_REAL:
8357     case BUILTIN_IMAG:
8358       {
8359         const Expression_list* args = this->args();
8360         go_assert(args != NULL && args->size() == 1);
8361         Expression* arg = args->front();
8362         tree arg_tree = arg->get_tree(context);
8363         if (arg_tree == error_mark_node)
8364           return error_mark_node;
8365         go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8366         if (this->code_ == BUILTIN_REAL)
8367           return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8368                                  TREE_TYPE(TREE_TYPE(arg_tree)),
8369                                  arg_tree);
8370         else
8371           return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8372                                  TREE_TYPE(TREE_TYPE(arg_tree)),
8373                                  arg_tree);
8374       }
8375
8376     case BUILTIN_COMPLEX:
8377       {
8378         const Expression_list* args = this->args();
8379         go_assert(args != NULL && args->size() == 2);
8380         tree r = args->front()->get_tree(context);
8381         tree i = args->back()->get_tree(context);
8382         if (r == error_mark_node || i == error_mark_node)
8383           return error_mark_node;
8384         go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8385                    == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8386         go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8387         return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8388                                build_complex_type(TREE_TYPE(r)),
8389                                r, i);
8390       }
8391
8392     default:
8393       go_unreachable();
8394     }
8395 }
8396
8397 // We have to support exporting a builtin call expression, because
8398 // code can set a constant to the result of a builtin expression.
8399
8400 void
8401 Builtin_call_expression::do_export(Export* exp) const
8402 {
8403   Numeric_constant nc;
8404   if (!this->numeric_constant_value(&nc))
8405     {
8406       error_at(this->location(), "value is not constant");
8407       return;
8408     }
8409
8410   if (nc.is_int())
8411     {
8412       mpz_t val;
8413       nc.get_int(&val);
8414       Integer_expression::export_integer(exp, val);
8415       mpz_clear(val);
8416     }
8417   else if (nc.is_float())
8418     {
8419       mpfr_t fval;
8420       nc.get_float(&fval);
8421       Float_expression::export_float(exp, fval);
8422       mpfr_clear(fval);
8423     }
8424   else if (nc.is_complex())
8425     {
8426       mpfr_t real;
8427       mpfr_t imag;
8428       Complex_expression::export_complex(exp, real, imag);
8429       mpfr_clear(real);
8430       mpfr_clear(imag);
8431     }
8432   else
8433     go_unreachable();
8434
8435   // A trailing space lets us reliably identify the end of the number.
8436   exp->write_c_string(" ");
8437 }
8438
8439 // Class Call_expression.
8440
8441 // Traversal.
8442
8443 int
8444 Call_expression::do_traverse(Traverse* traverse)
8445 {
8446   if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8447     return TRAVERSE_EXIT;
8448   if (this->args_ != NULL)
8449     {
8450       if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8451         return TRAVERSE_EXIT;
8452     }
8453   return TRAVERSE_CONTINUE;
8454 }
8455
8456 // Lower a call statement.
8457
8458 Expression*
8459 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8460                           Statement_inserter* inserter, int)
8461 {
8462   Location loc = this->location();
8463
8464   // A type cast can look like a function call.
8465   if (this->fn_->is_type_expression()
8466       && this->args_ != NULL
8467       && this->args_->size() == 1)
8468     return Expression::make_cast(this->fn_->type(), this->args_->front(),
8469                                  loc);
8470
8471   // Recognize a call to a builtin function.
8472   Func_expression* fne = this->fn_->func_expression();
8473   if (fne != NULL
8474       && fne->named_object()->is_function_declaration()
8475       && fne->named_object()->func_declaration_value()->type()->is_builtin())
8476     return new Builtin_call_expression(gogo, this->fn_, this->args_,
8477                                        this->is_varargs_, loc);
8478
8479   // Handle an argument which is a call to a function which returns
8480   // multiple results.
8481   if (this->args_ != NULL
8482       && this->args_->size() == 1
8483       && this->args_->front()->call_expression() != NULL
8484       && this->fn_->type()->function_type() != NULL)
8485     {
8486       Function_type* fntype = this->fn_->type()->function_type();
8487       size_t rc = this->args_->front()->call_expression()->result_count();
8488       if (rc > 1
8489           && fntype->parameters() != NULL
8490           && (fntype->parameters()->size() == rc
8491               || (fntype->is_varargs()
8492                   && fntype->parameters()->size() - 1 <= rc)))
8493         {
8494           Call_expression* call = this->args_->front()->call_expression();
8495           Expression_list* args = new Expression_list;
8496           for (size_t i = 0; i < rc; ++i)
8497             args->push_back(Expression::make_call_result(call, i));
8498           // We can't return a new call expression here, because this
8499           // one may be referenced by Call_result expressions.  We
8500           // also can't delete the old arguments, because we may still
8501           // traverse them somewhere up the call stack.  FIXME.
8502           this->args_ = args;
8503         }
8504     }
8505
8506   // If this call returns multiple results, create a temporary
8507   // variable for each result.
8508   size_t rc = this->result_count();
8509   if (rc > 1 && this->results_ == NULL)
8510     {
8511       std::vector<Temporary_statement*>* temps =
8512         new std::vector<Temporary_statement*>;
8513       temps->reserve(rc);
8514       const Typed_identifier_list* results =
8515         this->fn_->type()->function_type()->results();
8516       for (Typed_identifier_list::const_iterator p = results->begin();
8517            p != results->end();
8518            ++p)
8519         {
8520           Temporary_statement* temp = Statement::make_temporary(p->type(),
8521                                                                 NULL, loc);
8522           inserter->insert(temp);
8523           temps->push_back(temp);
8524         }
8525       this->results_ = temps;
8526     }
8527
8528   // Handle a call to a varargs function by packaging up the extra
8529   // parameters.
8530   if (this->fn_->type()->function_type() != NULL
8531       && this->fn_->type()->function_type()->is_varargs())
8532     {
8533       Function_type* fntype = this->fn_->type()->function_type();
8534       const Typed_identifier_list* parameters = fntype->parameters();
8535       go_assert(parameters != NULL && !parameters->empty());
8536       Type* varargs_type = parameters->back().type();
8537       this->lower_varargs(gogo, function, inserter, varargs_type,
8538                           parameters->size());
8539     }
8540
8541   // If this is call to a method, call the method directly passing the
8542   // object as the first parameter.
8543   Bound_method_expression* bme = this->fn_->bound_method_expression();
8544   if (bme != NULL)
8545     {
8546       Named_object* method = bme->method();
8547       Expression* first_arg = bme->first_argument();
8548
8549       // We always pass a pointer when calling a method.
8550       if (first_arg->type()->points_to() == NULL
8551           && !first_arg->type()->is_error())
8552         {
8553           first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8554           // We may need to create a temporary variable so that we can
8555           // take the address.  We can't do that here because it will
8556           // mess up the order of evaluation.
8557           Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8558           ue->set_create_temp();
8559         }
8560
8561       // If we are calling a method which was inherited from an
8562       // embedded struct, and the method did not get a stub, then the
8563       // first type may be wrong.
8564       Type* fatype = bme->first_argument_type();
8565       if (fatype != NULL)
8566         {
8567           if (fatype->points_to() == NULL)
8568             fatype = Type::make_pointer_type(fatype);
8569           first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8570         }
8571
8572       Expression_list* new_args = new Expression_list();
8573       new_args->push_back(first_arg);
8574       if (this->args_ != NULL)
8575         {
8576           for (Expression_list::const_iterator p = this->args_->begin();
8577                p != this->args_->end();
8578                ++p)
8579             new_args->push_back(*p);
8580         }
8581
8582       // We have to change in place because this structure may be
8583       // referenced by Call_result_expressions.  We can't delete the
8584       // old arguments, because we may be traversing them up in some
8585       // caller.  FIXME.
8586       this->args_ = new_args;
8587       this->fn_ = Expression::make_func_reference(method, NULL,
8588                                                   bme->location());
8589     }
8590
8591   return this;
8592 }
8593
8594 // Lower a call to a varargs function.  FUNCTION is the function in
8595 // which the call occurs--it's not the function we are calling.
8596 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8597 // PARAM_COUNT is the number of parameters of the function we are
8598 // calling; the last of these parameters will be the varargs
8599 // parameter.
8600
8601 void
8602 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8603                                Statement_inserter* inserter,
8604                                Type* varargs_type, size_t param_count)
8605 {
8606   if (this->varargs_are_lowered_)
8607     return;
8608
8609   Location loc = this->location();
8610
8611   go_assert(param_count > 0);
8612   go_assert(varargs_type->is_slice_type());
8613
8614   size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8615   if (arg_count < param_count - 1)
8616     {
8617       // Not enough arguments; will be caught in check_types.
8618       return;
8619     }
8620
8621   Expression_list* old_args = this->args_;
8622   Expression_list* new_args = new Expression_list();
8623   bool push_empty_arg = false;
8624   if (old_args == NULL || old_args->empty())
8625     {
8626       go_assert(param_count == 1);
8627       push_empty_arg = true;
8628     }
8629   else
8630     {
8631       Expression_list::const_iterator pa;
8632       int i = 1;
8633       for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8634         {
8635           if (static_cast<size_t>(i) == param_count)
8636             break;
8637           new_args->push_back(*pa);
8638         }
8639
8640       // We have reached the varargs parameter.
8641
8642       bool issued_error = false;
8643       if (pa == old_args->end())
8644         push_empty_arg = true;
8645       else if (pa + 1 == old_args->end() && this->is_varargs_)
8646         new_args->push_back(*pa);
8647       else if (this->is_varargs_)
8648         {
8649           if ((*pa)->type()->is_slice_type())
8650             this->report_error(_("too many arguments"));
8651           else
8652             {
8653               error_at(this->location(),
8654                        _("invalid use of %<...%> with non-slice"));
8655               this->set_is_error();
8656             }
8657           return;
8658         }
8659       else
8660         {
8661           Type* element_type = varargs_type->array_type()->element_type();
8662           Expression_list* vals = new Expression_list;
8663           for (; pa != old_args->end(); ++pa, ++i)
8664             {
8665               // Check types here so that we get a better message.
8666               Type* patype = (*pa)->type();
8667               Location paloc = (*pa)->location();
8668               if (!this->check_argument_type(i, element_type, patype,
8669                                              paloc, issued_error))
8670                 continue;
8671               vals->push_back(*pa);
8672             }
8673           Expression* val =
8674             Expression::make_slice_composite_literal(varargs_type, vals, loc);
8675           gogo->lower_expression(function, inserter, &val);
8676           new_args->push_back(val);
8677         }
8678     }
8679
8680   if (push_empty_arg)
8681     new_args->push_back(Expression::make_nil(loc));
8682
8683   // We can't return a new call expression here, because this one may
8684   // be referenced by Call_result expressions.  FIXME.  We can't
8685   // delete OLD_ARGS because we may have both a Call_expression and a
8686   // Builtin_call_expression which refer to them.  FIXME.
8687   this->args_ = new_args;
8688   this->varargs_are_lowered_ = true;
8689 }
8690
8691 // Get the function type.  This can return NULL in error cases.
8692
8693 Function_type*
8694 Call_expression::get_function_type() const
8695 {
8696   return this->fn_->type()->function_type();
8697 }
8698
8699 // Return the number of values which this call will return.
8700
8701 size_t
8702 Call_expression::result_count() const
8703 {
8704   const Function_type* fntype = this->get_function_type();
8705   if (fntype == NULL)
8706     return 0;
8707   if (fntype->results() == NULL)
8708     return 0;
8709   return fntype->results()->size();
8710 }
8711
8712 // Return the temporary which holds a result.
8713
8714 Temporary_statement*
8715 Call_expression::result(size_t i) const
8716 {
8717   if (this->results_ == NULL || this->results_->size() <= i)
8718     {
8719       go_assert(saw_errors());
8720       return NULL;
8721     }
8722   return (*this->results_)[i];
8723 }
8724
8725 // Return whether this is a call to the predeclared function recover.
8726
8727 bool
8728 Call_expression::is_recover_call() const
8729 {
8730   return this->do_is_recover_call();
8731 }
8732
8733 // Set the argument to the recover function.
8734
8735 void
8736 Call_expression::set_recover_arg(Expression* arg)
8737 {
8738   this->do_set_recover_arg(arg);
8739 }
8740
8741 // Virtual functions also implemented by Builtin_call_expression.
8742
8743 bool
8744 Call_expression::do_is_recover_call() const
8745 {
8746   return false;
8747 }
8748
8749 void
8750 Call_expression::do_set_recover_arg(Expression*)
8751 {
8752   go_unreachable();
8753 }
8754
8755 // We have found an error with this call expression; return true if
8756 // we should report it.
8757
8758 bool
8759 Call_expression::issue_error()
8760 {
8761   if (this->issued_error_)
8762     return false;
8763   else
8764     {
8765       this->issued_error_ = true;
8766       return true;
8767     }
8768 }
8769
8770 // Get the type.
8771
8772 Type*
8773 Call_expression::do_type()
8774 {
8775   if (this->type_ != NULL)
8776     return this->type_;
8777
8778   Type* ret;
8779   Function_type* fntype = this->get_function_type();
8780   if (fntype == NULL)
8781     return Type::make_error_type();
8782
8783   const Typed_identifier_list* results = fntype->results();
8784   if (results == NULL)
8785     ret = Type::make_void_type();
8786   else if (results->size() == 1)
8787     ret = results->begin()->type();
8788   else
8789     ret = Type::make_call_multiple_result_type(this);
8790
8791   this->type_ = ret;
8792
8793   return this->type_;
8794 }
8795
8796 // Determine types for a call expression.  We can use the function
8797 // parameter types to set the types of the arguments.
8798
8799 void
8800 Call_expression::do_determine_type(const Type_context*)
8801 {
8802   if (!this->determining_types())
8803     return;
8804
8805   this->fn_->determine_type_no_context();
8806   Function_type* fntype = this->get_function_type();
8807   const Typed_identifier_list* parameters = NULL;
8808   if (fntype != NULL)
8809     parameters = fntype->parameters();
8810   if (this->args_ != NULL)
8811     {
8812       Typed_identifier_list::const_iterator pt;
8813       if (parameters != NULL)
8814         pt = parameters->begin();
8815       bool first = true;
8816       for (Expression_list::const_iterator pa = this->args_->begin();
8817            pa != this->args_->end();
8818            ++pa)
8819         {
8820           if (first)
8821             {
8822               first = false;
8823               // If this is a method, the first argument is the
8824               // receiver.
8825               if (fntype != NULL && fntype->is_method())
8826                 {
8827                   Type* rtype = fntype->receiver()->type();
8828                   // The receiver is always passed as a pointer.
8829                   if (rtype->points_to() == NULL)
8830                     rtype = Type::make_pointer_type(rtype);
8831                   Type_context subcontext(rtype, false);
8832                   (*pa)->determine_type(&subcontext);
8833                   continue;
8834                 }
8835             }
8836
8837           if (parameters != NULL && pt != parameters->end())
8838             {
8839               Type_context subcontext(pt->type(), false);
8840               (*pa)->determine_type(&subcontext);
8841               ++pt;
8842             }
8843           else
8844             (*pa)->determine_type_no_context();
8845         }
8846     }
8847 }
8848
8849 // Called when determining types for a Call_expression.  Return true
8850 // if we should go ahead, false if they have already been determined.
8851
8852 bool
8853 Call_expression::determining_types()
8854 {
8855   if (this->types_are_determined_)
8856     return false;
8857   else
8858     {
8859       this->types_are_determined_ = true;
8860       return true;
8861     }
8862 }
8863
8864 // Check types for parameter I.
8865
8866 bool
8867 Call_expression::check_argument_type(int i, const Type* parameter_type,
8868                                      const Type* argument_type,
8869                                      Location argument_location,
8870                                      bool issued_error)
8871 {
8872   std::string reason;
8873   bool ok;
8874   if (this->are_hidden_fields_ok_)
8875     ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8876                                         &reason);
8877   else
8878     ok = Type::are_assignable(parameter_type, argument_type, &reason);
8879   if (!ok)
8880     {
8881       if (!issued_error)
8882         {
8883           if (reason.empty())
8884             error_at(argument_location, "argument %d has incompatible type", i);
8885           else
8886             error_at(argument_location,
8887                      "argument %d has incompatible type (%s)",
8888                      i, reason.c_str());
8889         }
8890       this->set_is_error();
8891       return false;
8892     }
8893   return true;
8894 }
8895
8896 // Check types.
8897
8898 void
8899 Call_expression::do_check_types(Gogo*)
8900 {
8901   if (this->classification() == EXPRESSION_ERROR)
8902     return;
8903
8904   Function_type* fntype = this->get_function_type();
8905   if (fntype == NULL)
8906     {
8907       if (!this->fn_->type()->is_error())
8908         this->report_error(_("expected function"));
8909       return;
8910     }
8911
8912   bool is_method = fntype->is_method();
8913   if (is_method)
8914     {
8915       go_assert(this->args_ != NULL && !this->args_->empty());
8916       Type* rtype = fntype->receiver()->type();
8917       Expression* first_arg = this->args_->front();
8918       // The language permits copying hidden fields for a method
8919       // receiver.  We dereference the values since receivers are
8920       // always passed as pointers.
8921       std::string reason;
8922       if (!Type::are_assignable_hidden_ok(rtype->deref(),
8923                                           first_arg->type()->deref(),
8924                                           &reason))
8925         {
8926           if (reason.empty())
8927             this->report_error(_("incompatible type for receiver"));
8928           else
8929             {
8930               error_at(this->location(),
8931                        "incompatible type for receiver (%s)",
8932                        reason.c_str());
8933               this->set_is_error();
8934             }
8935         }
8936     }
8937
8938   // Note that varargs was handled by the lower_varargs() method, so
8939   // we don't have to worry about it here unless something is wrong.
8940   if (this->is_varargs_ && !this->varargs_are_lowered_)
8941     {
8942       if (!fntype->is_varargs())
8943         {
8944           error_at(this->location(),
8945                    _("invalid use of %<...%> calling non-variadic function"));
8946           this->set_is_error();
8947           return;
8948         }
8949     }
8950
8951   const Typed_identifier_list* parameters = fntype->parameters();
8952   if (this->args_ == NULL)
8953     {
8954       if (parameters != NULL && !parameters->empty())
8955         this->report_error(_("not enough arguments"));
8956     }
8957   else if (parameters == NULL)
8958     {
8959       if (!is_method || this->args_->size() > 1)
8960         this->report_error(_("too many arguments"));
8961     }
8962   else
8963     {
8964       int i = 0;
8965       Expression_list::const_iterator pa = this->args_->begin();
8966       if (is_method)
8967         ++pa;
8968       for (Typed_identifier_list::const_iterator pt = parameters->begin();
8969            pt != parameters->end();
8970            ++pt, ++pa, ++i)
8971         {
8972           if (pa == this->args_->end())
8973             {
8974               this->report_error(_("not enough arguments"));
8975               return;
8976             }
8977           this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
8978                                     (*pa)->location(), false);
8979         }
8980       if (pa != this->args_->end())
8981         this->report_error(_("too many arguments"));
8982     }
8983 }
8984
8985 // Return whether we have to use a temporary variable to ensure that
8986 // we evaluate this call expression in order.  If the call returns no
8987 // results then it will inevitably be executed last.
8988
8989 bool
8990 Call_expression::do_must_eval_in_order() const
8991 {
8992   return this->result_count() > 0;
8993 }
8994
8995 // Get the function and the first argument to use when calling an
8996 // interface method.
8997
8998 tree
8999 Call_expression::interface_method_function(
9000     Translate_context* context,
9001     Interface_field_reference_expression* interface_method,
9002     tree* first_arg_ptr)
9003 {
9004   tree expr = interface_method->expr()->get_tree(context);
9005   if (expr == error_mark_node)
9006     return error_mark_node;
9007   expr = save_expr(expr);
9008   tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9009   if (first_arg == error_mark_node)
9010     return error_mark_node;
9011   *first_arg_ptr = first_arg;
9012   return interface_method->get_function_tree(context, expr);
9013 }
9014
9015 // Build the call expression.
9016
9017 tree
9018 Call_expression::do_get_tree(Translate_context* context)
9019 {
9020   if (this->tree_ != NULL_TREE)
9021     return this->tree_;
9022
9023   Function_type* fntype = this->get_function_type();
9024   if (fntype == NULL)
9025     return error_mark_node;
9026
9027   if (this->fn_->is_error_expression())
9028     return error_mark_node;
9029
9030   Gogo* gogo = context->gogo();
9031   Location location = this->location();
9032
9033   Func_expression* func = this->fn_->func_expression();
9034   Interface_field_reference_expression* interface_method =
9035     this->fn_->interface_field_reference_expression();
9036   const bool has_closure = func != NULL && func->closure() != NULL;
9037   const bool is_interface_method = interface_method != NULL;
9038
9039   int nargs;
9040   tree* args;
9041   if (this->args_ == NULL || this->args_->empty())
9042     {
9043       nargs = is_interface_method ? 1 : 0;
9044       args = nargs == 0 ? NULL : new tree[nargs];
9045     }
9046   else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9047     {
9048       // Passing a receiver parameter.
9049       go_assert(!is_interface_method
9050                 && fntype->is_method()
9051                 && this->args_->size() == 1);
9052       nargs = 1;
9053       args = new tree[nargs];
9054       args[0] = this->args_->front()->get_tree(context);
9055     }
9056   else
9057     {
9058       const Typed_identifier_list* params = fntype->parameters();
9059
9060       nargs = this->args_->size();
9061       int i = is_interface_method ? 1 : 0;
9062       nargs += i;
9063       args = new tree[nargs];
9064
9065       Typed_identifier_list::const_iterator pp = params->begin();
9066       Expression_list::const_iterator pe = this->args_->begin();
9067       if (!is_interface_method && fntype->is_method())
9068         {
9069           args[i] = (*pe)->get_tree(context);
9070           ++pe;
9071           ++i;
9072         }
9073       for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9074         {
9075           go_assert(pp != params->end());
9076           tree arg_val = (*pe)->get_tree(context);
9077           args[i] = Expression::convert_for_assignment(context,
9078                                                        pp->type(),
9079                                                        (*pe)->type(),
9080                                                        arg_val,
9081                                                        location);
9082           if (args[i] == error_mark_node)
9083             {
9084               delete[] args;
9085               return error_mark_node;
9086             }
9087         }
9088       go_assert(pp == params->end());
9089       go_assert(i == nargs);
9090     }
9091
9092   tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
9093   if (rettype == error_mark_node)
9094     {
9095       delete[] args;
9096       return error_mark_node;
9097     }
9098
9099   tree fn;
9100   if (has_closure)
9101     fn = func->get_tree_without_closure(gogo);
9102   else if (!is_interface_method)
9103     fn = this->fn_->get_tree(context);
9104   else
9105     fn = this->interface_method_function(context, interface_method, &args[0]);
9106
9107   if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9108     {
9109       delete[] args;
9110       return error_mark_node;
9111     }
9112
9113   tree fndecl = fn;
9114   if (TREE_CODE(fndecl) == ADDR_EXPR)
9115     fndecl = TREE_OPERAND(fndecl, 0);
9116
9117   // Add a type cast in case the type of the function is a recursive
9118   // type which refers to itself.
9119   if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
9120     {
9121       tree fnt = type_to_tree(fntype->get_backend(gogo));
9122       if (fnt == error_mark_node)
9123         return error_mark_node;
9124       fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9125     }
9126
9127   // This is to support builtin math functions when using 80387 math.
9128   tree excess_type = NULL_TREE;
9129   if (optimize
9130       && TREE_CODE(fndecl) == FUNCTION_DECL
9131       && DECL_IS_BUILTIN(fndecl)
9132       && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9133       && nargs > 0
9134       && ((SCALAR_FLOAT_TYPE_P(rettype)
9135            && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9136           || (COMPLEX_FLOAT_TYPE_P(rettype)
9137               && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9138     {
9139       excess_type = excess_precision_type(TREE_TYPE(args[0]));
9140       if (excess_type != NULL_TREE)
9141         {
9142           tree excess_fndecl = mathfn_built_in(excess_type,
9143                                                DECL_FUNCTION_CODE(fndecl));
9144           if (excess_fndecl == NULL_TREE)
9145             excess_type = NULL_TREE;
9146           else
9147             {
9148               fn = build_fold_addr_expr_loc(location.gcc_location(),
9149                                             excess_fndecl);
9150               for (int i = 0; i < nargs; ++i)
9151                 {
9152                   if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9153                       || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9154                     args[i] = ::convert(excess_type, args[i]);
9155                 }
9156             }
9157         }
9158     }
9159
9160   tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9161                               fn, nargs, args);
9162   delete[] args;
9163
9164   SET_EXPR_LOCATION(ret, location.gcc_location());
9165
9166   if (has_closure)
9167     {
9168       tree closure_tree = func->closure()->get_tree(context);
9169       if (closure_tree != error_mark_node)
9170         CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9171     }
9172
9173   // If this is a recursive function type which returns itself, as in
9174   //   type F func() F
9175   // we have used ptr_type_node for the return type.  Add a cast here
9176   // to the correct type.
9177   if (TREE_TYPE(ret) == ptr_type_node)
9178     {
9179       tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9180       ret = fold_convert_loc(location.gcc_location(), t, ret);
9181     }
9182
9183   if (excess_type != NULL_TREE)
9184     {
9185       // Calling convert here can undo our excess precision change.
9186       // That may or may not be a bug in convert_to_real.
9187       ret = build1(NOP_EXPR, rettype, ret);
9188     }
9189
9190   if (this->results_ != NULL)
9191     ret = this->set_results(context, ret);
9192
9193   this->tree_ = ret;
9194
9195   return ret;
9196 }
9197
9198 // Set the result variables if this call returns multiple results.
9199
9200 tree
9201 Call_expression::set_results(Translate_context* context, tree call_tree)
9202 {
9203   tree stmt_list = NULL_TREE;
9204
9205   call_tree = save_expr(call_tree);
9206
9207   if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9208     {
9209       go_assert(saw_errors());
9210       return call_tree;
9211     }
9212
9213   Location loc = this->location();
9214   tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9215   size_t rc = this->result_count();
9216   for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9217     {
9218       go_assert(field != NULL_TREE);
9219
9220       Temporary_statement* temp = this->result(i);
9221       if (temp == NULL)
9222         {
9223           go_assert(saw_errors());
9224           return error_mark_node;
9225         }
9226       Temporary_reference_expression* ref =
9227         Expression::make_temporary_reference(temp, loc);
9228       ref->set_is_lvalue();
9229       tree temp_tree = ref->get_tree(context);
9230       if (temp_tree == error_mark_node)
9231         return error_mark_node;
9232
9233       tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9234                                  TREE_TYPE(field), call_tree, field, NULL_TREE);
9235       tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9236                                  void_type_node, temp_tree, val_tree);
9237
9238       append_to_statement_list(set_tree, &stmt_list);
9239     }
9240   go_assert(field == NULL_TREE);
9241
9242   return save_expr(stmt_list);
9243 }
9244
9245 // Dump ast representation for a call expressin.
9246
9247 void
9248 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9249 {
9250   this->fn_->dump_expression(ast_dump_context);
9251   ast_dump_context->ostream() << "(";
9252   if (args_ != NULL)
9253     ast_dump_context->dump_expression_list(this->args_);
9254
9255   ast_dump_context->ostream() << ") ";
9256 }
9257
9258 // Make a call expression.
9259
9260 Call_expression*
9261 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9262                       Location location)
9263 {
9264   return new Call_expression(fn, args, is_varargs, location);
9265 }
9266
9267 // A single result from a call which returns multiple results.
9268
9269 class Call_result_expression : public Expression
9270 {
9271  public:
9272   Call_result_expression(Call_expression* call, unsigned int index)
9273     : Expression(EXPRESSION_CALL_RESULT, call->location()),
9274       call_(call), index_(index)
9275   { }
9276
9277  protected:
9278   int
9279   do_traverse(Traverse*);
9280
9281   Type*
9282   do_type();
9283
9284   void
9285   do_determine_type(const Type_context*);
9286
9287   void
9288   do_check_types(Gogo*);
9289
9290   Expression*
9291   do_copy()
9292   {
9293     return new Call_result_expression(this->call_->call_expression(),
9294                                       this->index_);
9295   }
9296
9297   bool
9298   do_must_eval_in_order() const
9299   { return true; }
9300
9301   tree
9302   do_get_tree(Translate_context*);
9303
9304   void
9305   do_dump_expression(Ast_dump_context*) const;
9306
9307  private:
9308   // The underlying call expression.
9309   Expression* call_;
9310   // Which result we want.
9311   unsigned int index_;
9312 };
9313
9314 // Traverse a call result.
9315
9316 int
9317 Call_result_expression::do_traverse(Traverse* traverse)
9318 {
9319   if (traverse->remember_expression(this->call_))
9320     {
9321       // We have already traversed the call expression.
9322       return TRAVERSE_CONTINUE;
9323     }
9324   return Expression::traverse(&this->call_, traverse);
9325 }
9326
9327 // Get the type.
9328
9329 Type*
9330 Call_result_expression::do_type()
9331 {
9332   if (this->classification() == EXPRESSION_ERROR)
9333     return Type::make_error_type();
9334
9335   // THIS->CALL_ can be replaced with a temporary reference due to
9336   // Call_expression::do_must_eval_in_order when there is an error.
9337   Call_expression* ce = this->call_->call_expression();
9338   if (ce == NULL)
9339     {
9340       this->set_is_error();
9341       return Type::make_error_type();
9342     }
9343   Function_type* fntype = ce->get_function_type();
9344   if (fntype == NULL)
9345     {
9346       if (ce->issue_error())
9347         {
9348           if (!ce->fn()->type()->is_error())
9349             this->report_error(_("expected function"));
9350         }
9351       this->set_is_error();
9352       return Type::make_error_type();
9353     }
9354   const Typed_identifier_list* results = fntype->results();
9355   if (results == NULL || results->size() < 2)
9356     {
9357       if (ce->issue_error())
9358         this->report_error(_("number of results does not match "
9359                              "number of values"));
9360       return Type::make_error_type();
9361     }
9362   Typed_identifier_list::const_iterator pr = results->begin();
9363   for (unsigned int i = 0; i < this->index_; ++i)
9364     {
9365       if (pr == results->end())
9366         break;
9367       ++pr;
9368     }
9369   if (pr == results->end())
9370     {
9371       if (ce->issue_error())
9372         this->report_error(_("number of results does not match "
9373                              "number of values"));
9374       return Type::make_error_type();
9375     }
9376   return pr->type();
9377 }
9378
9379 // Check the type.  Just make sure that we trigger the warning in
9380 // do_type.
9381
9382 void
9383 Call_result_expression::do_check_types(Gogo*)
9384 {
9385   this->type();
9386 }
9387
9388 // Determine the type.  We have nothing to do here, but the 0 result
9389 // needs to pass down to the caller.
9390
9391 void
9392 Call_result_expression::do_determine_type(const Type_context*)
9393 {
9394   this->call_->determine_type_no_context();
9395 }
9396
9397 // Return the tree.  We just refer to the temporary set by the call
9398 // expression.  We don't do this at lowering time because it makes it
9399 // hard to evaluate the call at the right time.
9400
9401 tree
9402 Call_result_expression::do_get_tree(Translate_context* context)
9403 {
9404   Call_expression* ce = this->call_->call_expression();
9405   if (ce == NULL)
9406     {
9407       go_assert(this->call_->is_error_expression());
9408       return error_mark_node;
9409     }
9410   Temporary_statement* ts = ce->result(this->index_);
9411   if (ts == NULL)
9412     {
9413       go_assert(saw_errors());
9414       return error_mark_node;
9415     }
9416   Expression* ref = Expression::make_temporary_reference(ts, this->location());
9417   return ref->get_tree(context);
9418 }
9419
9420 // Dump ast representation for a call result expression.
9421
9422 void
9423 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9424     const
9425 {
9426   // FIXME: Wouldn't it be better if the call is assigned to a temporary 
9427   // (struct) and the fields are referenced instead.
9428   ast_dump_context->ostream() << this->index_ << "@(";
9429   ast_dump_context->dump_expression(this->call_);
9430   ast_dump_context->ostream() << ")";
9431 }
9432
9433 // Make a reference to a single result of a call which returns
9434 // multiple results.
9435
9436 Expression*
9437 Expression::make_call_result(Call_expression* call, unsigned int index)
9438 {
9439   return new Call_result_expression(call, index);
9440 }
9441
9442 // Class Index_expression.
9443
9444 // Traversal.
9445
9446 int
9447 Index_expression::do_traverse(Traverse* traverse)
9448 {
9449   if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9450       || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9451       || (this->end_ != NULL
9452           && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9453     return TRAVERSE_EXIT;
9454   return TRAVERSE_CONTINUE;
9455 }
9456
9457 // Lower an index expression.  This converts the generic index
9458 // expression into an array index, a string index, or a map index.
9459
9460 Expression*
9461 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9462 {
9463   Location location = this->location();
9464   Expression* left = this->left_;
9465   Expression* start = this->start_;
9466   Expression* end = this->end_;
9467
9468   Type* type = left->type();
9469   if (type->is_error())
9470     return Expression::make_error(location);
9471   else if (left->is_type_expression())
9472     {
9473       error_at(location, "attempt to index type expression");
9474       return Expression::make_error(location);
9475     }
9476   else if (type->array_type() != NULL)
9477     return Expression::make_array_index(left, start, end, location);
9478   else if (type->points_to() != NULL
9479            && type->points_to()->array_type() != NULL
9480            && !type->points_to()->is_slice_type())
9481     {
9482       Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9483                                                  location);
9484       return Expression::make_array_index(deref, start, end, location);
9485     }
9486   else if (type->is_string_type())
9487     return Expression::make_string_index(left, start, end, location);
9488   else if (type->map_type() != NULL)
9489     {
9490       if (end != NULL)
9491         {
9492           error_at(location, "invalid slice of map");
9493           return Expression::make_error(location);
9494         }
9495       Map_index_expression* ret = Expression::make_map_index(left, start,
9496                                                              location);
9497       if (this->is_lvalue_)
9498         ret->set_is_lvalue();
9499       return ret;
9500     }
9501   else
9502     {
9503       error_at(location,
9504                "attempt to index object which is not array, string, or map");
9505       return Expression::make_error(location);
9506     }
9507 }
9508
9509 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9510 // dump context
9511
9512 void
9513 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context, 
9514                                         const Expression* expr, 
9515                                         const Expression* start,
9516                                         const Expression* end)
9517 {
9518   expr->dump_expression(ast_dump_context);
9519   ast_dump_context->ostream() << "[";
9520   start->dump_expression(ast_dump_context);
9521   if (end != NULL)
9522     {
9523       ast_dump_context->ostream() << ":";
9524       end->dump_expression(ast_dump_context);
9525     }
9526   ast_dump_context->ostream() << "]";
9527 }
9528
9529 // Dump ast representation for an index expression.
9530
9531 void
9532 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
9533     const
9534 {
9535   Index_expression::dump_index_expression(ast_dump_context, this->left_, 
9536                                           this->start_, this->end_);
9537 }
9538
9539 // Make an index expression.
9540
9541 Expression*
9542 Expression::make_index(Expression* left, Expression* start, Expression* end,
9543                        Location location)
9544 {
9545   return new Index_expression(left, start, end, location);
9546 }
9547
9548 // An array index.  This is used for both indexing and slicing.
9549
9550 class Array_index_expression : public Expression
9551 {
9552  public:
9553   Array_index_expression(Expression* array, Expression* start,
9554                          Expression* end, Location location)
9555     : Expression(EXPRESSION_ARRAY_INDEX, location),
9556       array_(array), start_(start), end_(end), type_(NULL)
9557   { }
9558
9559  protected:
9560   int
9561   do_traverse(Traverse*);
9562
9563   Type*
9564   do_type();
9565
9566   void
9567   do_determine_type(const Type_context*);
9568
9569   void
9570   do_check_types(Gogo*);
9571
9572   Expression*
9573   do_copy()
9574   {
9575     return Expression::make_array_index(this->array_->copy(),
9576                                         this->start_->copy(),
9577                                         (this->end_ == NULL
9578                                          ? NULL
9579                                          : this->end_->copy()),
9580                                         this->location());
9581   }
9582
9583   bool
9584   do_must_eval_subexpressions_in_order(int* skip) const
9585   {
9586     *skip = 1;
9587     return true;
9588   }
9589
9590   bool
9591   do_is_addressable() const;
9592
9593   void
9594   do_address_taken(bool escapes)
9595   { this->array_->address_taken(escapes); }
9596
9597   tree
9598   do_get_tree(Translate_context*);
9599
9600   void
9601   do_dump_expression(Ast_dump_context*) const;
9602   
9603  private:
9604   // The array we are getting a value from.
9605   Expression* array_;
9606   // The start or only index.
9607   Expression* start_;
9608   // The end index of a slice.  This may be NULL for a simple array
9609   // index, or it may be a nil expression for the length of the array.
9610   Expression* end_;
9611   // The type of the expression.
9612   Type* type_;
9613 };
9614
9615 // Array index traversal.
9616
9617 int
9618 Array_index_expression::do_traverse(Traverse* traverse)
9619 {
9620   if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9621     return TRAVERSE_EXIT;
9622   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9623     return TRAVERSE_EXIT;
9624   if (this->end_ != NULL)
9625     {
9626       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9627         return TRAVERSE_EXIT;
9628     }
9629   return TRAVERSE_CONTINUE;
9630 }
9631
9632 // Return the type of an array index.
9633
9634 Type*
9635 Array_index_expression::do_type()
9636 {
9637   if (this->type_ == NULL)
9638     {
9639      Array_type* type = this->array_->type()->array_type();
9640       if (type == NULL)
9641         this->type_ = Type::make_error_type();
9642       else if (this->end_ == NULL)
9643         this->type_ = type->element_type();
9644       else if (type->is_slice_type())
9645         {
9646           // A slice of a slice has the same type as the original
9647           // slice.
9648           this->type_ = this->array_->type()->deref();
9649         }
9650       else
9651         {
9652           // A slice of an array is a slice.
9653           this->type_ = Type::make_array_type(type->element_type(), NULL);
9654         }
9655     }
9656   return this->type_;
9657 }
9658
9659 // Set the type of an array index.
9660
9661 void
9662 Array_index_expression::do_determine_type(const Type_context*)
9663 {
9664   this->array_->determine_type_no_context();
9665   this->start_->determine_type_no_context();
9666   if (this->end_ != NULL)
9667     this->end_->determine_type_no_context();
9668 }
9669
9670 // Check types of an array index.
9671
9672 void
9673 Array_index_expression::do_check_types(Gogo*)
9674 {
9675   if (this->start_->type()->integer_type() == NULL)
9676     this->report_error(_("index must be integer"));
9677   if (this->end_ != NULL
9678       && this->end_->type()->integer_type() == NULL
9679       && !this->end_->type()->is_error()
9680       && !this->end_->is_nil_expression()
9681       && !this->end_->is_error_expression())
9682     this->report_error(_("slice end must be integer"));
9683
9684   Array_type* array_type = this->array_->type()->array_type();
9685   if (array_type == NULL)
9686     {
9687       go_assert(this->array_->type()->is_error());
9688       return;
9689     }
9690
9691   unsigned int int_bits =
9692     Type::lookup_integer_type("int")->integer_type()->bits();
9693
9694   Numeric_constant lvalnc;
9695   mpz_t lval;
9696   bool lval_valid = (array_type->length() != NULL
9697                      && array_type->length()->numeric_constant_value(&lvalnc)
9698                      && lvalnc.to_int(&lval));
9699   Numeric_constant inc;
9700   mpz_t ival;
9701   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9702     {
9703       if (mpz_sgn(ival) < 0
9704           || mpz_sizeinbase(ival, 2) >= int_bits
9705           || (lval_valid
9706               && (this->end_ == NULL
9707                   ? mpz_cmp(ival, lval) >= 0
9708                   : mpz_cmp(ival, lval) > 0)))
9709         {
9710           error_at(this->start_->location(), "array index out of bounds");
9711           this->set_is_error();
9712         }
9713       mpz_clear(ival);
9714     }
9715   if (this->end_ != NULL && !this->end_->is_nil_expression())
9716     {
9717       Numeric_constant enc;
9718       mpz_t eval;
9719       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9720         {
9721           if (mpz_sgn(eval) < 0
9722               || mpz_sizeinbase(eval, 2) >= int_bits
9723               || (lval_valid && mpz_cmp(eval, lval) > 0))
9724             {
9725               error_at(this->end_->location(), "array index out of bounds");
9726               this->set_is_error();
9727             }
9728           mpz_clear(eval);
9729         }
9730     }
9731   if (lval_valid)
9732     mpz_clear(lval);
9733
9734   // A slice of an array requires an addressable array.  A slice of a
9735   // slice is always possible.
9736   if (this->end_ != NULL && !array_type->is_slice_type())
9737     {
9738       if (!this->array_->is_addressable())
9739         this->report_error(_("slice of unaddressable value"));
9740       else
9741         this->array_->address_taken(true);
9742     }
9743 }
9744
9745 // Return whether this expression is addressable.
9746
9747 bool
9748 Array_index_expression::do_is_addressable() const
9749 {
9750   // A slice expression is not addressable.
9751   if (this->end_ != NULL)
9752     return false;
9753
9754   // An index into a slice is addressable.
9755   if (this->array_->type()->is_slice_type())
9756     return true;
9757
9758   // An index into an array is addressable if the array is
9759   // addressable.
9760   return this->array_->is_addressable();
9761 }
9762
9763 // Get a tree for an array index.
9764
9765 tree
9766 Array_index_expression::do_get_tree(Translate_context* context)
9767 {
9768   Gogo* gogo = context->gogo();
9769   Location loc = this->location();
9770
9771   Array_type* array_type = this->array_->type()->array_type();
9772   if (array_type == NULL)
9773     {
9774       go_assert(this->array_->type()->is_error());
9775       return error_mark_node;
9776     }
9777
9778   tree type_tree = type_to_tree(array_type->get_backend(gogo));
9779   if (type_tree == error_mark_node)
9780     return error_mark_node;
9781
9782   tree array_tree = this->array_->get_tree(context);
9783   if (array_tree == error_mark_node)
9784     return error_mark_node;
9785
9786   if (array_type->length() == NULL && !DECL_P(array_tree))
9787     array_tree = save_expr(array_tree);
9788
9789   tree length_tree = NULL_TREE;
9790   if (this->end_ == NULL || this->end_->is_nil_expression())
9791     {
9792       length_tree = array_type->length_tree(gogo, array_tree);
9793       if (length_tree == error_mark_node)
9794         return error_mark_node;
9795       length_tree = save_expr(length_tree);
9796     }
9797
9798   tree capacity_tree = NULL_TREE;
9799   if (this->end_ != NULL)
9800     {
9801       capacity_tree = array_type->capacity_tree(gogo, array_tree);
9802       if (capacity_tree == error_mark_node)
9803         return error_mark_node;
9804       capacity_tree = save_expr(capacity_tree);
9805     }
9806
9807   tree length_type = (length_tree != NULL_TREE
9808                       ? TREE_TYPE(length_tree)
9809                       : TREE_TYPE(capacity_tree));
9810
9811   tree bad_index = boolean_false_node;
9812
9813   tree start_tree = this->start_->get_tree(context);
9814   if (start_tree == error_mark_node)
9815     return error_mark_node;
9816   if (!DECL_P(start_tree))
9817     start_tree = save_expr(start_tree);
9818   if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9819     start_tree = convert_to_integer(length_type, start_tree);
9820
9821   bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9822                                        loc);
9823
9824   start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9825   bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9826                               boolean_type_node, bad_index,
9827                               fold_build2_loc(loc.gcc_location(),
9828                                               (this->end_ == NULL
9829                                                ? GE_EXPR
9830                                                : GT_EXPR),
9831                                               boolean_type_node, start_tree,
9832                                               (this->end_ == NULL
9833                                                ? length_tree
9834                                                : capacity_tree)));
9835
9836   int code = (array_type->length() != NULL
9837               ? (this->end_ == NULL
9838                  ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9839                  : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9840               : (this->end_ == NULL
9841                  ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9842                  : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9843   tree crash = Gogo::runtime_error(code, loc);
9844
9845   if (this->end_ == NULL)
9846     {
9847       // Simple array indexing.  This has to return an l-value, so
9848       // wrap the index check into START_TREE.
9849       start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9850                           build3(COND_EXPR, void_type_node,
9851                                  bad_index, crash, NULL_TREE),
9852                           start_tree);
9853       start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9854
9855       if (array_type->length() != NULL)
9856         {
9857           // Fixed array.
9858           return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9859                         start_tree, NULL_TREE, NULL_TREE);
9860         }
9861       else
9862         {
9863           // Open array.
9864           tree values = array_type->value_pointer_tree(gogo, array_tree);
9865           Type* element_type = array_type->element_type();
9866           Btype* belement_type = element_type->get_backend(gogo);
9867           tree element_type_tree = type_to_tree(belement_type);
9868           if (element_type_tree == error_mark_node)
9869             return error_mark_node;
9870           tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9871           tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9872                                         start_tree, element_size);
9873           tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9874                                      TREE_TYPE(values), values, offset);
9875           return build_fold_indirect_ref(ptr);
9876         }
9877     }
9878
9879   // Array slice.
9880
9881   tree end_tree;
9882   if (this->end_->is_nil_expression())
9883     end_tree = length_tree;
9884   else
9885     {
9886       end_tree = this->end_->get_tree(context);
9887       if (end_tree == error_mark_node)
9888         return error_mark_node;
9889       if (!DECL_P(end_tree))
9890         end_tree = save_expr(end_tree);
9891       if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9892         end_tree = convert_to_integer(length_type, end_tree);
9893
9894       bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9895                                            loc);
9896
9897       end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9898
9899       tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9900                                      boolean_type_node,
9901                                      fold_build2_loc(loc.gcc_location(),
9902                                                      LT_EXPR, boolean_type_node,
9903                                                      end_tree, start_tree),
9904                                      fold_build2_loc(loc.gcc_location(),
9905                                                      GT_EXPR, boolean_type_node,
9906                                                      end_tree, capacity_tree));
9907       bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9908                                   boolean_type_node, bad_index, bad_end);
9909     }
9910
9911   Type* element_type = array_type->element_type();
9912   tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9913   if (element_type_tree == error_mark_node)
9914     return error_mark_node;
9915   tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9916
9917   tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9918                                 fold_convert_loc(loc.gcc_location(), sizetype,
9919                                                  start_tree),
9920                                 element_size);
9921
9922   tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9923   if (value_pointer == error_mark_node)
9924     return error_mark_node;
9925
9926   value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9927                                   TREE_TYPE(value_pointer),
9928                                   value_pointer, offset);
9929
9930   tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9931                                             length_type, end_tree, start_tree);
9932
9933   tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9934                                               length_type, capacity_tree,
9935                                               start_tree);
9936
9937   tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
9938   go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
9939
9940   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
9941
9942   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
9943   tree field = TYPE_FIELDS(struct_tree);
9944   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
9945   elt->index = field;
9946   elt->value = value_pointer;
9947
9948   elt = VEC_quick_push(constructor_elt, init, NULL);
9949   field = DECL_CHAIN(field);
9950   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
9951   elt->index = field;
9952   elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9953                                 result_length_tree);
9954
9955   elt = VEC_quick_push(constructor_elt, init, NULL);
9956   field = DECL_CHAIN(field);
9957   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
9958   elt->index = field;
9959   elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9960                                 result_capacity_tree);
9961
9962   tree constructor = build_constructor(struct_tree, init);
9963
9964   if (TREE_CONSTANT(value_pointer)
9965       && TREE_CONSTANT(result_length_tree)
9966       && TREE_CONSTANT(result_capacity_tree))
9967     TREE_CONSTANT(constructor) = 1;
9968
9969   return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
9970                          TREE_TYPE(constructor),
9971                          build3(COND_EXPR, void_type_node,
9972                                 bad_index, crash, NULL_TREE),
9973                          constructor);
9974 }
9975
9976 // Dump ast representation for an array index expression.
9977
9978 void
9979 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
9980     const
9981 {
9982   Index_expression::dump_index_expression(ast_dump_context, this->array_, 
9983                                           this->start_, this->end_);
9984 }
9985
9986 // Make an array index expression.  END may be NULL.
9987
9988 Expression*
9989 Expression::make_array_index(Expression* array, Expression* start,
9990                              Expression* end, Location location)
9991 {
9992   return new Array_index_expression(array, start, end, location);
9993 }
9994
9995 // A string index.  This is used for both indexing and slicing.
9996
9997 class String_index_expression : public Expression
9998 {
9999  public:
10000   String_index_expression(Expression* string, Expression* start,
10001                           Expression* end, Location location)
10002     : Expression(EXPRESSION_STRING_INDEX, location),
10003       string_(string), start_(start), end_(end)
10004   { }
10005
10006  protected:
10007   int
10008   do_traverse(Traverse*);
10009
10010   Type*
10011   do_type();
10012
10013   void
10014   do_determine_type(const Type_context*);
10015
10016   void
10017   do_check_types(Gogo*);
10018
10019   Expression*
10020   do_copy()
10021   {
10022     return Expression::make_string_index(this->string_->copy(),
10023                                          this->start_->copy(),
10024                                          (this->end_ == NULL
10025                                           ? NULL
10026                                           : this->end_->copy()),
10027                                          this->location());
10028   }
10029
10030   bool
10031   do_must_eval_subexpressions_in_order(int* skip) const
10032   {
10033     *skip = 1;
10034     return true;
10035   }
10036
10037   tree
10038   do_get_tree(Translate_context*);
10039
10040   void
10041   do_dump_expression(Ast_dump_context*) const;
10042
10043  private:
10044   // The string we are getting a value from.
10045   Expression* string_;
10046   // The start or only index.
10047   Expression* start_;
10048   // The end index of a slice.  This may be NULL for a single index,
10049   // or it may be a nil expression for the length of the string.
10050   Expression* end_;
10051 };
10052
10053 // String index traversal.
10054
10055 int
10056 String_index_expression::do_traverse(Traverse* traverse)
10057 {
10058   if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10059     return TRAVERSE_EXIT;
10060   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10061     return TRAVERSE_EXIT;
10062   if (this->end_ != NULL)
10063     {
10064       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10065         return TRAVERSE_EXIT;
10066     }
10067   return TRAVERSE_CONTINUE;
10068 }
10069
10070 // Return the type of a string index.
10071
10072 Type*
10073 String_index_expression::do_type()
10074 {
10075   if (this->end_ == NULL)
10076     return Type::lookup_integer_type("uint8");
10077   else
10078     return this->string_->type();
10079 }
10080
10081 // Determine the type of a string index.
10082
10083 void
10084 String_index_expression::do_determine_type(const Type_context*)
10085 {
10086   this->string_->determine_type_no_context();
10087   this->start_->determine_type_no_context();
10088   if (this->end_ != NULL)
10089     this->end_->determine_type_no_context();
10090 }
10091
10092 // Check types of a string index.
10093
10094 void
10095 String_index_expression::do_check_types(Gogo*)
10096 {
10097   if (this->start_->type()->integer_type() == NULL)
10098     this->report_error(_("index must be integer"));
10099   if (this->end_ != NULL
10100       && this->end_->type()->integer_type() == NULL
10101       && !this->end_->is_nil_expression())
10102     this->report_error(_("slice end must be integer"));
10103
10104   std::string sval;
10105   bool sval_valid = this->string_->string_constant_value(&sval);
10106
10107   Numeric_constant inc;
10108   mpz_t ival;
10109   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10110     {
10111       if (mpz_sgn(ival) < 0
10112           || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10113         {
10114           error_at(this->start_->location(), "string index out of bounds");
10115           this->set_is_error();
10116         }
10117       mpz_clear(ival);
10118     }
10119   if (this->end_ != NULL && !this->end_->is_nil_expression())
10120     {
10121       Numeric_constant enc;
10122       mpz_t eval;
10123       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10124         {
10125           if (mpz_sgn(eval) < 0
10126               || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10127             {
10128               error_at(this->end_->location(), "string index out of bounds");
10129               this->set_is_error();
10130             }
10131           mpz_clear(eval);
10132         }
10133     }
10134 }
10135
10136 // Get a tree for a string index.
10137
10138 tree
10139 String_index_expression::do_get_tree(Translate_context* context)
10140 {
10141   Location loc = this->location();
10142
10143   tree string_tree = this->string_->get_tree(context);
10144   if (string_tree == error_mark_node)
10145     return error_mark_node;
10146
10147   if (this->string_->type()->points_to() != NULL)
10148     string_tree = build_fold_indirect_ref(string_tree);
10149   if (!DECL_P(string_tree))
10150     string_tree = save_expr(string_tree);
10151   tree string_type = TREE_TYPE(string_tree);
10152
10153   tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10154   length_tree = save_expr(length_tree);
10155   tree length_type = TREE_TYPE(length_tree);
10156
10157   tree bad_index = boolean_false_node;
10158
10159   tree start_tree = this->start_->get_tree(context);
10160   if (start_tree == error_mark_node)
10161     return error_mark_node;
10162   if (!DECL_P(start_tree))
10163     start_tree = save_expr(start_tree);
10164   if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10165     start_tree = convert_to_integer(length_type, start_tree);
10166
10167   bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10168                                        loc);
10169
10170   start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10171
10172   int code = (this->end_ == NULL
10173               ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10174               : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10175   tree crash = Gogo::runtime_error(code, loc);
10176
10177   if (this->end_ == NULL)
10178     {
10179       bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10180                                   boolean_type_node, bad_index,
10181                                   fold_build2_loc(loc.gcc_location(), GE_EXPR,
10182                                                   boolean_type_node,
10183                                                   start_tree, length_tree));
10184
10185       tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10186       tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10187                                  TREE_TYPE(bytes_tree),
10188                                  bytes_tree,
10189                                  fold_convert_loc(loc.gcc_location(), sizetype,
10190                                                   start_tree));
10191       tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10192
10193       return build2(COMPOUND_EXPR, TREE_TYPE(index),
10194                     build3(COND_EXPR, void_type_node,
10195                            bad_index, crash, NULL_TREE),
10196                     index);
10197     }
10198   else
10199     {
10200       tree end_tree;
10201       if (this->end_->is_nil_expression())
10202         end_tree = build_int_cst(length_type, -1);
10203       else
10204         {
10205           end_tree = this->end_->get_tree(context);
10206           if (end_tree == error_mark_node)
10207             return error_mark_node;
10208           if (!DECL_P(end_tree))
10209             end_tree = save_expr(end_tree);
10210           if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10211             end_tree = convert_to_integer(length_type, end_tree);
10212
10213           bad_index = Expression::check_bounds(end_tree, length_type,
10214                                                bad_index, loc);
10215
10216           end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10217                                       end_tree);
10218         }
10219
10220       static tree strslice_fndecl;
10221       tree ret = Gogo::call_builtin(&strslice_fndecl,
10222                                     loc,
10223                                     "__go_string_slice",
10224                                     3,
10225                                     string_type,
10226                                     string_type,
10227                                     string_tree,
10228                                     length_type,
10229                                     start_tree,
10230                                     length_type,
10231                                     end_tree);
10232       if (ret == error_mark_node)
10233         return error_mark_node;
10234       // This will panic if the bounds are out of range for the
10235       // string.
10236       TREE_NOTHROW(strslice_fndecl) = 0;
10237
10238       if (bad_index == boolean_false_node)
10239         return ret;
10240       else
10241         return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10242                       build3(COND_EXPR, void_type_node,
10243                              bad_index, crash, NULL_TREE),
10244                       ret);
10245     }
10246 }
10247
10248 // Dump ast representation for a string index expression.
10249
10250 void
10251 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10252     const
10253 {
10254   Index_expression::dump_index_expression(ast_dump_context, this->string_, 
10255                                           this->start_, this->end_);
10256 }
10257
10258 // Make a string index expression.  END may be NULL.
10259
10260 Expression*
10261 Expression::make_string_index(Expression* string, Expression* start,
10262                               Expression* end, Location location)
10263 {
10264   return new String_index_expression(string, start, end, location);
10265 }
10266
10267 // Class Map_index.
10268
10269 // Get the type of the map.
10270
10271 Map_type*
10272 Map_index_expression::get_map_type() const
10273 {
10274   Map_type* mt = this->map_->type()->deref()->map_type();
10275   if (mt == NULL)
10276     go_assert(saw_errors());
10277   return mt;
10278 }
10279
10280 // Map index traversal.
10281
10282 int
10283 Map_index_expression::do_traverse(Traverse* traverse)
10284 {
10285   if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10286     return TRAVERSE_EXIT;
10287   return Expression::traverse(&this->index_, traverse);
10288 }
10289
10290 // Return the type of a map index.
10291
10292 Type*
10293 Map_index_expression::do_type()
10294 {
10295   Map_type* mt = this->get_map_type();
10296   if (mt == NULL)
10297     return Type::make_error_type();
10298   Type* type = mt->val_type();
10299   // If this map index is in a tuple assignment, we actually return a
10300   // pointer to the value type.  Tuple_map_assignment_statement is
10301   // responsible for handling this correctly.  We need to get the type
10302   // right in case this gets assigned to a temporary variable.
10303   if (this->is_in_tuple_assignment_)
10304     type = Type::make_pointer_type(type);
10305   return type;
10306 }
10307
10308 // Fix the type of a map index.
10309
10310 void
10311 Map_index_expression::do_determine_type(const Type_context*)
10312 {
10313   this->map_->determine_type_no_context();
10314   Map_type* mt = this->get_map_type();
10315   Type* key_type = mt == NULL ? NULL : mt->key_type();
10316   Type_context subcontext(key_type, false);
10317   this->index_->determine_type(&subcontext);
10318 }
10319
10320 // Check types of a map index.
10321
10322 void
10323 Map_index_expression::do_check_types(Gogo*)
10324 {
10325   std::string reason;
10326   Map_type* mt = this->get_map_type();
10327   if (mt == NULL)
10328     return;
10329   if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10330     {
10331       if (reason.empty())
10332         this->report_error(_("incompatible type for map index"));
10333       else
10334         {
10335           error_at(this->location(), "incompatible type for map index (%s)",
10336                    reason.c_str());
10337           this->set_is_error();
10338         }
10339     }
10340 }
10341
10342 // Get a tree for a map index.
10343
10344 tree
10345 Map_index_expression::do_get_tree(Translate_context* context)
10346 {
10347   Map_type* type = this->get_map_type();
10348   if (type == NULL)
10349     return error_mark_node;
10350
10351   tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10352   if (valptr == error_mark_node)
10353     return error_mark_node;
10354   valptr = save_expr(valptr);
10355
10356   tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10357
10358   if (this->is_lvalue_)
10359     return build_fold_indirect_ref(valptr);
10360   else if (this->is_in_tuple_assignment_)
10361     {
10362       // Tuple_map_assignment_statement is responsible for using this
10363       // appropriately.
10364       return valptr;
10365     }
10366   else
10367     {
10368       Gogo* gogo = context->gogo();
10369       Btype* val_btype = type->val_type()->get_backend(gogo);
10370       Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10371       return fold_build3(COND_EXPR, val_type_tree,
10372                          fold_build2(EQ_EXPR, boolean_type_node, valptr,
10373                                      fold_convert(TREE_TYPE(valptr),
10374                                                   null_pointer_node)),
10375                          expr_to_tree(val_zero),
10376                          build_fold_indirect_ref(valptr));
10377     }
10378 }
10379
10380 // Get a tree for the map index.  This returns a tree which evaluates
10381 // to a pointer to a value.  The pointer will be NULL if the key is
10382 // not in the map.
10383
10384 tree
10385 Map_index_expression::get_value_pointer(Translate_context* context,
10386                                         bool insert)
10387 {
10388   Map_type* type = this->get_map_type();
10389   if (type == NULL)
10390     return error_mark_node;
10391
10392   tree map_tree = this->map_->get_tree(context);
10393   tree index_tree = this->index_->get_tree(context);
10394   index_tree = Expression::convert_for_assignment(context, type->key_type(),
10395                                                   this->index_->type(),
10396                                                   index_tree,
10397                                                   this->location());
10398   if (map_tree == error_mark_node || index_tree == error_mark_node)
10399     return error_mark_node;
10400
10401   if (this->map_->type()->points_to() != NULL)
10402     map_tree = build_fold_indirect_ref(map_tree);
10403
10404   // We need to pass in a pointer to the key, so stuff it into a
10405   // variable.
10406   tree tmp;
10407   tree make_tmp;
10408   if (current_function_decl != NULL)
10409     {
10410       tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10411       DECL_IGNORED_P(tmp) = 0;
10412       DECL_INITIAL(tmp) = index_tree;
10413       make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10414       TREE_ADDRESSABLE(tmp) = 1;
10415     }
10416   else
10417     {
10418       tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10419                        create_tmp_var_name("M"),
10420                        TREE_TYPE(index_tree));
10421       DECL_EXTERNAL(tmp) = 0;
10422       TREE_PUBLIC(tmp) = 0;
10423       TREE_STATIC(tmp) = 1;
10424       DECL_ARTIFICIAL(tmp) = 1;
10425       if (!TREE_CONSTANT(index_tree))
10426         make_tmp = fold_build2_loc(this->location().gcc_location(),
10427                                    INIT_EXPR, void_type_node,
10428                                    tmp, index_tree);
10429       else
10430         {
10431           TREE_READONLY(tmp) = 1;
10432           TREE_CONSTANT(tmp) = 1;
10433           DECL_INITIAL(tmp) = index_tree;
10434           make_tmp = NULL_TREE;
10435         }
10436       rest_of_decl_compilation(tmp, 1, 0);
10437     }
10438   tree tmpref =
10439     fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10440                      build_fold_addr_expr_loc(this->location().gcc_location(),
10441                                               tmp));
10442
10443   static tree map_index_fndecl;
10444   tree call = Gogo::call_builtin(&map_index_fndecl,
10445                                  this->location(),
10446                                  "__go_map_index",
10447                                  3,
10448                                  const_ptr_type_node,
10449                                  TREE_TYPE(map_tree),
10450                                  map_tree,
10451                                  const_ptr_type_node,
10452                                  tmpref,
10453                                  boolean_type_node,
10454                                  (insert
10455                                   ? boolean_true_node
10456                                   : boolean_false_node));
10457   if (call == error_mark_node)
10458     return error_mark_node;
10459   // This can panic on a map of interface type if the interface holds
10460   // an uncomparable or unhashable type.
10461   TREE_NOTHROW(map_index_fndecl) = 0;
10462
10463   Type* val_type = type->val_type();
10464   tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10465   if (val_type_tree == error_mark_node)
10466     return error_mark_node;
10467   tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10468
10469   tree ret = fold_convert_loc(this->location().gcc_location(),
10470                               ptr_val_type_tree, call);
10471   if (make_tmp != NULL_TREE)
10472     ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10473   return ret;
10474 }
10475
10476 // Dump ast representation for a map index expression
10477
10478 void
10479 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
10480     const
10481 {
10482   Index_expression::dump_index_expression(ast_dump_context, 
10483                                           this->map_, this->index_, NULL);
10484 }
10485
10486 // Make a map index expression.
10487
10488 Map_index_expression*
10489 Expression::make_map_index(Expression* map, Expression* index,
10490                            Location location)
10491 {
10492   return new Map_index_expression(map, index, location);
10493 }
10494
10495 // Class Field_reference_expression.
10496
10497 // Return the type of a field reference.
10498
10499 Type*
10500 Field_reference_expression::do_type()
10501 {
10502   Type* type = this->expr_->type();
10503   if (type->is_error())
10504     return type;
10505   Struct_type* struct_type = type->struct_type();
10506   go_assert(struct_type != NULL);
10507   return struct_type->field(this->field_index_)->type();
10508 }
10509
10510 // Check the types for a field reference.
10511
10512 void
10513 Field_reference_expression::do_check_types(Gogo*)
10514 {
10515   Type* type = this->expr_->type();
10516   if (type->is_error())
10517     return;
10518   Struct_type* struct_type = type->struct_type();
10519   go_assert(struct_type != NULL);
10520   go_assert(struct_type->field(this->field_index_) != NULL);
10521 }
10522
10523 // Get a tree for a field reference.
10524
10525 tree
10526 Field_reference_expression::do_get_tree(Translate_context* context)
10527 {
10528   tree struct_tree = this->expr_->get_tree(context);
10529   if (struct_tree == error_mark_node
10530       || TREE_TYPE(struct_tree) == error_mark_node)
10531     return error_mark_node;
10532   go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10533   tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10534   if (field == NULL_TREE)
10535     {
10536       // This can happen for a type which refers to itself indirectly
10537       // and then turns out to be erroneous.
10538       go_assert(saw_errors());
10539       return error_mark_node;
10540     }
10541   for (unsigned int i = this->field_index_; i > 0; --i)
10542     {
10543       field = DECL_CHAIN(field);
10544       go_assert(field != NULL_TREE);
10545     }
10546   if (TREE_TYPE(field) == error_mark_node)
10547     return error_mark_node;
10548   return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10549                 NULL_TREE);
10550 }
10551
10552 // Dump ast representation for a field reference expression.
10553
10554 void
10555 Field_reference_expression::do_dump_expression(
10556     Ast_dump_context* ast_dump_context) const
10557 {
10558   this->expr_->dump_expression(ast_dump_context);
10559   ast_dump_context->ostream() << "." <<  this->field_index_;
10560 }
10561
10562 // Make a reference to a qualified identifier in an expression.
10563
10564 Field_reference_expression*
10565 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10566                                  Location location)
10567 {
10568   return new Field_reference_expression(expr, field_index, location);
10569 }
10570
10571 // Class Interface_field_reference_expression.
10572
10573 // Return a tree for the pointer to the function to call.
10574
10575 tree
10576 Interface_field_reference_expression::get_function_tree(Translate_context*,
10577                                                         tree expr)
10578 {
10579   if (this->expr_->type()->points_to() != NULL)
10580     expr = build_fold_indirect_ref(expr);
10581
10582   tree expr_type = TREE_TYPE(expr);
10583   go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10584
10585   tree field = TYPE_FIELDS(expr_type);
10586   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10587
10588   tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10589   go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10590
10591   table = build_fold_indirect_ref(table);
10592   go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10593
10594   std::string name = Gogo::unpack_hidden_name(this->name_);
10595   for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10596        field != NULL_TREE;
10597        field = DECL_CHAIN(field))
10598     {
10599       if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10600         break;
10601     }
10602   go_assert(field != NULL_TREE);
10603
10604   return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10605 }
10606
10607 // Return a tree for the first argument to pass to the interface
10608 // function.
10609
10610 tree
10611 Interface_field_reference_expression::get_underlying_object_tree(
10612     Translate_context*,
10613     tree expr)
10614 {
10615   if (this->expr_->type()->points_to() != NULL)
10616     expr = build_fold_indirect_ref(expr);
10617
10618   tree expr_type = TREE_TYPE(expr);
10619   go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10620
10621   tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10622   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10623
10624   return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10625 }
10626
10627 // Traversal.
10628
10629 int
10630 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10631 {
10632   return Expression::traverse(&this->expr_, traverse);
10633 }
10634
10635 // Return the type of an interface field reference.
10636
10637 Type*
10638 Interface_field_reference_expression::do_type()
10639 {
10640   Type* expr_type = this->expr_->type();
10641
10642   Type* points_to = expr_type->points_to();
10643   if (points_to != NULL)
10644     expr_type = points_to;
10645
10646   Interface_type* interface_type = expr_type->interface_type();
10647   if (interface_type == NULL)
10648     return Type::make_error_type();
10649
10650   const Typed_identifier* method = interface_type->find_method(this->name_);
10651   if (method == NULL)
10652     return Type::make_error_type();
10653
10654   return method->type();
10655 }
10656
10657 // Determine types.
10658
10659 void
10660 Interface_field_reference_expression::do_determine_type(const Type_context*)
10661 {
10662   this->expr_->determine_type_no_context();
10663 }
10664
10665 // Check the types for an interface field reference.
10666
10667 void
10668 Interface_field_reference_expression::do_check_types(Gogo*)
10669 {
10670   Type* type = this->expr_->type();
10671
10672   Type* points_to = type->points_to();
10673   if (points_to != NULL)
10674     type = points_to;
10675
10676   Interface_type* interface_type = type->interface_type();
10677   if (interface_type == NULL)
10678     {
10679       if (!type->is_error_type())
10680         this->report_error(_("expected interface or pointer to interface"));
10681     }
10682   else
10683     {
10684       const Typed_identifier* method =
10685         interface_type->find_method(this->name_);
10686       if (method == NULL)
10687         {
10688           error_at(this->location(), "method %qs not in interface",
10689                    Gogo::message_name(this->name_).c_str());
10690           this->set_is_error();
10691         }
10692     }
10693 }
10694
10695 // Get a tree for a reference to a field in an interface.  There is no
10696 // standard tree type representation for this: it's a function
10697 // attached to its first argument, like a Bound_method_expression.
10698 // The only places it may currently be used are in a Call_expression
10699 // or a Go_statement, which will take it apart directly.  So this has
10700 // nothing to do at present.
10701
10702 tree
10703 Interface_field_reference_expression::do_get_tree(Translate_context*)
10704 {
10705   error_at(this->location(), "reference to method other than calling it");
10706   return error_mark_node;
10707 }
10708
10709 // Dump ast representation for an interface field reference.
10710
10711 void
10712 Interface_field_reference_expression::do_dump_expression(
10713     Ast_dump_context* ast_dump_context) const
10714 {
10715   this->expr_->dump_expression(ast_dump_context);
10716   ast_dump_context->ostream() << "." << this->name_;
10717 }
10718
10719 // Make a reference to a field in an interface.
10720
10721 Expression*
10722 Expression::make_interface_field_reference(Expression* expr,
10723                                            const std::string& field,
10724                                            Location location)
10725 {
10726   return new Interface_field_reference_expression(expr, field, location);
10727 }
10728
10729 // A general selector.  This is a Parser_expression for LEFT.NAME.  It
10730 // is lowered after we know the type of the left hand side.
10731
10732 class Selector_expression : public Parser_expression
10733 {
10734  public:
10735   Selector_expression(Expression* left, const std::string& name,
10736                       Location location)
10737     : Parser_expression(EXPRESSION_SELECTOR, location),
10738       left_(left), name_(name)
10739   { }
10740
10741  protected:
10742   int
10743   do_traverse(Traverse* traverse)
10744   { return Expression::traverse(&this->left_, traverse); }
10745
10746   Expression*
10747   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10748
10749   Expression*
10750   do_copy()
10751   {
10752     return new Selector_expression(this->left_->copy(), this->name_,
10753                                    this->location());
10754   }
10755
10756   void
10757   do_dump_expression(Ast_dump_context* ast_dump_context) const;
10758
10759  private:
10760   Expression*
10761   lower_method_expression(Gogo*);
10762
10763   // The expression on the left hand side.
10764   Expression* left_;
10765   // The name on the right hand side.
10766   std::string name_;
10767 };
10768
10769 // Lower a selector expression once we know the real type of the left
10770 // hand side.
10771
10772 Expression*
10773 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10774                               int)
10775 {
10776   Expression* left = this->left_;
10777   if (left->is_type_expression())
10778     return this->lower_method_expression(gogo);
10779   return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10780                                     this->location());
10781 }
10782
10783 // Lower a method expression T.M or (*T).M.  We turn this into a
10784 // function literal.
10785
10786 Expression*
10787 Selector_expression::lower_method_expression(Gogo* gogo)
10788 {
10789   Location location = this->location();
10790   Type* type = this->left_->type();
10791   const std::string& name(this->name_);
10792
10793   bool is_pointer;
10794   if (type->points_to() == NULL)
10795     is_pointer = false;
10796   else
10797     {
10798       is_pointer = true;
10799       type = type->points_to();
10800     }
10801   Named_type* nt = type->named_type();
10802   if (nt == NULL)
10803     {
10804       error_at(location,
10805                ("method expression requires named type or "
10806                 "pointer to named type"));
10807       return Expression::make_error(location);
10808     }
10809
10810   bool is_ambiguous;
10811   Method* method = nt->method_function(name, &is_ambiguous);
10812   const Typed_identifier* imethod = NULL;
10813   if (method == NULL && !is_pointer)
10814     {
10815       Interface_type* it = nt->interface_type();
10816       if (it != NULL)
10817         imethod = it->find_method(name);
10818     }
10819
10820   if (method == NULL && imethod == NULL)
10821     {
10822       if (!is_ambiguous)
10823         error_at(location, "type %<%s%s%> has no method %<%s%>",
10824                  is_pointer ? "*" : "",
10825                  nt->message_name().c_str(),
10826                  Gogo::message_name(name).c_str());
10827       else
10828         error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10829                  Gogo::message_name(name).c_str(),
10830                  is_pointer ? "*" : "",
10831                  nt->message_name().c_str());
10832       return Expression::make_error(location);
10833     }
10834
10835   if (method != NULL && !is_pointer && !method->is_value_method())
10836     {
10837       error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10838                nt->message_name().c_str(),
10839                Gogo::message_name(name).c_str());
10840       return Expression::make_error(location);
10841     }
10842
10843   // Build a new function type in which the receiver becomes the first
10844   // argument.
10845   Function_type* method_type;
10846   if (method != NULL)
10847     {
10848       method_type = method->type();
10849       go_assert(method_type->is_method());
10850     }
10851   else
10852     {
10853       method_type = imethod->type()->function_type();
10854       go_assert(method_type != NULL && !method_type->is_method());
10855     }
10856
10857   const char* const receiver_name = "$this";
10858   Typed_identifier_list* parameters = new Typed_identifier_list();
10859   parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10860                                          location));
10861
10862   const Typed_identifier_list* method_parameters = method_type->parameters();
10863   if (method_parameters != NULL)
10864     {
10865       int i = 0;
10866       for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10867            p != method_parameters->end();
10868            ++p, ++i)
10869         {
10870           if (!p->name().empty())
10871             parameters->push_back(*p);
10872           else
10873             {
10874               char buf[20];
10875               snprintf(buf, sizeof buf, "$param%d", i);
10876               parameters->push_back(Typed_identifier(buf, p->type(),
10877                                                      p->location()));
10878             }
10879         }
10880     }
10881
10882   const Typed_identifier_list* method_results = method_type->results();
10883   Typed_identifier_list* results;
10884   if (method_results == NULL)
10885     results = NULL;
10886   else
10887     {
10888       results = new Typed_identifier_list();
10889       for (Typed_identifier_list::const_iterator p = method_results->begin();
10890            p != method_results->end();
10891            ++p)
10892         results->push_back(*p);
10893     }
10894   
10895   Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10896                                                    location);
10897   if (method_type->is_varargs())
10898     fntype->set_is_varargs();
10899
10900   // We generate methods which always takes a pointer to the receiver
10901   // as their first argument.  If this is for a pointer type, we can
10902   // simply reuse the existing function.  We use an internal hack to
10903   // get the right type.
10904
10905   if (method != NULL && is_pointer)
10906     {
10907       Named_object* mno = (method->needs_stub_method()
10908                            ? method->stub_object()
10909                            : method->named_object());
10910       Expression* f = Expression::make_func_reference(mno, NULL, location);
10911       f = Expression::make_cast(fntype, f, location);
10912       Type_conversion_expression* tce =
10913         static_cast<Type_conversion_expression*>(f);
10914       tce->set_may_convert_function_types();
10915       return f;
10916     }
10917
10918   Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10919                                           location);
10920
10921   Named_object* vno = gogo->lookup(receiver_name, NULL);
10922   go_assert(vno != NULL);
10923   Expression* ve = Expression::make_var_reference(vno, location);
10924   Expression* bm;
10925   if (method != NULL)
10926     bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
10927   else
10928     bm = Expression::make_interface_field_reference(ve, name, location);
10929
10930   // Even though we found the method above, if it has an error type we
10931   // may see an error here.
10932   if (bm->is_error_expression())
10933     {
10934       gogo->finish_function(location);
10935       return bm;
10936     }
10937
10938   Expression_list* args;
10939   if (parameters->size() <= 1)
10940     args = NULL;
10941   else
10942     {
10943       args = new Expression_list();
10944       Typed_identifier_list::const_iterator p = parameters->begin();
10945       ++p;
10946       for (; p != parameters->end(); ++p)
10947         {
10948           vno = gogo->lookup(p->name(), NULL);
10949           go_assert(vno != NULL);
10950           args->push_back(Expression::make_var_reference(vno, location));
10951         }
10952     }
10953
10954   gogo->start_block(location);
10955
10956   Call_expression* call = Expression::make_call(bm, args,
10957                                                 method_type->is_varargs(),
10958                                                 location);
10959
10960   size_t count = call->result_count();
10961   Statement* s;
10962   if (count == 0)
10963     s = Statement::make_statement(call, true);
10964   else
10965     {
10966       Expression_list* retvals = new Expression_list();
10967       if (count <= 1)
10968         retvals->push_back(call);
10969       else
10970         {
10971           for (size_t i = 0; i < count; ++i)
10972             retvals->push_back(Expression::make_call_result(call, i));
10973         }
10974       s = Statement::make_return_statement(retvals, location);
10975     }
10976   gogo->add_statement(s);
10977
10978   Block* b = gogo->finish_block(location);
10979
10980   gogo->add_block(b, location);
10981
10982   // Lower the call in case there are multiple results.
10983   gogo->lower_block(no, b);
10984
10985   gogo->finish_function(location);
10986
10987   return Expression::make_func_reference(no, NULL, location);
10988 }
10989
10990 // Dump the ast for a selector expression.
10991
10992 void
10993 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
10994     const
10995 {
10996   ast_dump_context->dump_expression(this->left_);
10997   ast_dump_context->ostream() << ".";
10998   ast_dump_context->ostream() << this->name_;
10999 }
11000                       
11001 // Make a selector expression.
11002
11003 Expression*
11004 Expression::make_selector(Expression* left, const std::string& name,
11005                           Location location)
11006 {
11007   return new Selector_expression(left, name, location);
11008 }
11009
11010 // Implement the builtin function new.
11011
11012 class Allocation_expression : public Expression
11013 {
11014  public:
11015   Allocation_expression(Type* type, Location location)
11016     : Expression(EXPRESSION_ALLOCATION, location),
11017       type_(type)
11018   { }
11019
11020  protected:
11021   int
11022   do_traverse(Traverse* traverse)
11023   { return Type::traverse(this->type_, traverse); }
11024
11025   Type*
11026   do_type()
11027   { return Type::make_pointer_type(this->type_); }
11028
11029   void
11030   do_determine_type(const Type_context*)
11031   { }
11032
11033   Expression*
11034   do_copy()
11035   { return new Allocation_expression(this->type_, this->location()); }
11036
11037   tree
11038   do_get_tree(Translate_context*);
11039
11040   void
11041   do_dump_expression(Ast_dump_context*) const;
11042   
11043  private:
11044   // The type we are allocating.
11045   Type* type_;
11046 };
11047
11048 // Return a tree for an allocation expression.
11049
11050 tree
11051 Allocation_expression::do_get_tree(Translate_context* context)
11052 {
11053   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
11054   if (type_tree == error_mark_node)
11055     return error_mark_node;
11056   tree size_tree = TYPE_SIZE_UNIT(type_tree);
11057   tree space = context->gogo()->allocate_memory(this->type_, size_tree,
11058                                                 this->location());
11059   if (space == error_mark_node)
11060     return error_mark_node;
11061   return fold_convert(build_pointer_type(type_tree), space);
11062 }
11063
11064 // Dump ast representation for an allocation expression.
11065
11066 void
11067 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
11068     const
11069 {
11070   ast_dump_context->ostream() << "new(";
11071   ast_dump_context->dump_type(this->type_);
11072   ast_dump_context->ostream() << ")";
11073 }
11074
11075 // Make an allocation expression.
11076
11077 Expression*
11078 Expression::make_allocation(Type* type, Location location)
11079 {
11080   return new Allocation_expression(type, location);
11081 }
11082
11083 // Construct a struct.
11084
11085 class Struct_construction_expression : public Expression
11086 {
11087  public:
11088   Struct_construction_expression(Type* type, Expression_list* vals,
11089                                  Location location)
11090     : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11091       type_(type), vals_(vals), traverse_order_(NULL)
11092   { }
11093
11094   // Set the traversal order, used to ensure that we implement the
11095   // order of evaluation rules.  Takes ownership of the argument.
11096   void
11097   set_traverse_order(std::vector<int>* traverse_order)
11098   { this->traverse_order_ = traverse_order; }
11099
11100   // Return whether this is a constant initializer.
11101   bool
11102   is_constant_struct() const;
11103
11104  protected:
11105   int
11106   do_traverse(Traverse* traverse);
11107
11108   Type*
11109   do_type()
11110   { return this->type_; }
11111
11112   void
11113   do_determine_type(const Type_context*);
11114
11115   void
11116   do_check_types(Gogo*);
11117
11118   Expression*
11119   do_copy()
11120   {
11121     Struct_construction_expression* ret =
11122       new Struct_construction_expression(this->type_, this->vals_->copy(),
11123                                          this->location());
11124     if (this->traverse_order_ != NULL)
11125       ret->set_traverse_order(this->traverse_order_);
11126     return ret;
11127   }
11128
11129   tree
11130   do_get_tree(Translate_context*);
11131
11132   void
11133   do_export(Export*) const;
11134
11135   void
11136   do_dump_expression(Ast_dump_context*) const;
11137
11138  private:
11139   // The type of the struct to construct.
11140   Type* type_;
11141   // The list of values, in order of the fields in the struct.  A NULL
11142   // entry means that the field should be zero-initialized.
11143   Expression_list* vals_;
11144   // If not NULL, the order in which to traverse vals_.  This is used
11145   // so that we implement the order of evaluation rules correctly.
11146   std::vector<int>* traverse_order_;
11147 };
11148
11149 // Traversal.
11150
11151 int
11152 Struct_construction_expression::do_traverse(Traverse* traverse)
11153 {
11154   if (this->vals_ != NULL)
11155     {
11156       if (this->traverse_order_ == NULL)
11157         {
11158           if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11159             return TRAVERSE_EXIT;
11160         }
11161       else
11162         {
11163           for (std::vector<int>::const_iterator p =
11164                  this->traverse_order_->begin();
11165                p != this->traverse_order_->end();
11166                ++p)
11167             {
11168               if (Expression::traverse(&this->vals_->at(*p), traverse)
11169                   == TRAVERSE_EXIT)
11170                 return TRAVERSE_EXIT;
11171             }
11172         }
11173     }
11174   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11175     return TRAVERSE_EXIT;
11176   return TRAVERSE_CONTINUE;
11177 }
11178
11179 // Return whether this is a constant initializer.
11180
11181 bool
11182 Struct_construction_expression::is_constant_struct() const
11183 {
11184   if (this->vals_ == NULL)
11185     return true;
11186   for (Expression_list::const_iterator pv = this->vals_->begin();
11187        pv != this->vals_->end();
11188        ++pv)
11189     {
11190       if (*pv != NULL
11191           && !(*pv)->is_constant()
11192           && (!(*pv)->is_composite_literal()
11193               || (*pv)->is_nonconstant_composite_literal()))
11194         return false;
11195     }
11196
11197   const Struct_field_list* fields = this->type_->struct_type()->fields();
11198   for (Struct_field_list::const_iterator pf = fields->begin();
11199        pf != fields->end();
11200        ++pf)
11201     {
11202       // There are no constant constructors for interfaces.
11203       if (pf->type()->interface_type() != NULL)
11204         return false;
11205     }
11206
11207   return true;
11208 }
11209
11210 // Final type determination.
11211
11212 void
11213 Struct_construction_expression::do_determine_type(const Type_context*)
11214 {
11215   if (this->vals_ == NULL)
11216     return;
11217   const Struct_field_list* fields = this->type_->struct_type()->fields();
11218   Expression_list::const_iterator pv = this->vals_->begin();
11219   for (Struct_field_list::const_iterator pf = fields->begin();
11220        pf != fields->end();
11221        ++pf, ++pv)
11222     {
11223       if (pv == this->vals_->end())
11224         return;
11225       if (*pv != NULL)
11226         {
11227           Type_context subcontext(pf->type(), false);
11228           (*pv)->determine_type(&subcontext);
11229         }
11230     }
11231   // Extra values are an error we will report elsewhere; we still want
11232   // to determine the type to avoid knockon errors.
11233   for (; pv != this->vals_->end(); ++pv)
11234     (*pv)->determine_type_no_context();
11235 }
11236
11237 // Check types.
11238
11239 void
11240 Struct_construction_expression::do_check_types(Gogo*)
11241 {
11242   if (this->vals_ == NULL)
11243     return;
11244
11245   Struct_type* st = this->type_->struct_type();
11246   if (this->vals_->size() > st->field_count())
11247     {
11248       this->report_error(_("too many expressions for struct"));
11249       return;
11250     }
11251
11252   const Struct_field_list* fields = st->fields();
11253   Expression_list::const_iterator pv = this->vals_->begin();
11254   int i = 0;
11255   for (Struct_field_list::const_iterator pf = fields->begin();
11256        pf != fields->end();
11257        ++pf, ++pv, ++i)
11258     {
11259       if (pv == this->vals_->end())
11260         {
11261           this->report_error(_("too few expressions for struct"));
11262           break;
11263         }
11264
11265       if (*pv == NULL)
11266         continue;
11267
11268       std::string reason;
11269       if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11270         {
11271           if (reason.empty())
11272             error_at((*pv)->location(),
11273                      "incompatible type for field %d in struct construction",
11274                      i + 1);
11275           else
11276             error_at((*pv)->location(),
11277                      ("incompatible type for field %d in "
11278                       "struct construction (%s)"),
11279                      i + 1, reason.c_str());
11280           this->set_is_error();
11281         }
11282     }
11283   go_assert(pv == this->vals_->end());
11284 }
11285
11286 // Return a tree for constructing a struct.
11287
11288 tree
11289 Struct_construction_expression::do_get_tree(Translate_context* context)
11290 {
11291   Gogo* gogo = context->gogo();
11292
11293   if (this->vals_ == NULL)
11294     {
11295       Btype* btype = this->type_->get_backend(gogo);
11296       return expr_to_tree(gogo->backend()->zero_expression(btype));
11297     }
11298
11299   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11300   if (type_tree == error_mark_node)
11301     return error_mark_node;
11302   go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11303
11304   bool is_constant = true;
11305   const Struct_field_list* fields = this->type_->struct_type()->fields();
11306   VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11307                                             fields->size());
11308   Struct_field_list::const_iterator pf = fields->begin();
11309   Expression_list::const_iterator pv = this->vals_->begin();
11310   for (tree field = TYPE_FIELDS(type_tree);
11311        field != NULL_TREE;
11312        field = DECL_CHAIN(field), ++pf)
11313     {
11314       go_assert(pf != fields->end());
11315
11316       Btype* fbtype = pf->type()->get_backend(gogo);
11317
11318       tree val;
11319       if (pv == this->vals_->end())
11320         val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11321       else if (*pv == NULL)
11322         {
11323           val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11324           ++pv;
11325         }
11326       else
11327         {
11328           val = Expression::convert_for_assignment(context, pf->type(),
11329                                                    (*pv)->type(),
11330                                                    (*pv)->get_tree(context),
11331                                                    this->location());
11332           ++pv;
11333         }
11334
11335       if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11336         return error_mark_node;
11337
11338       constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11339       elt->index = field;
11340       elt->value = val;
11341       if (!TREE_CONSTANT(val))
11342         is_constant = false;
11343     }
11344   go_assert(pf == fields->end());
11345
11346   tree ret = build_constructor(type_tree, elts);
11347   if (is_constant)
11348     TREE_CONSTANT(ret) = 1;
11349   return ret;
11350 }
11351
11352 // Export a struct construction.
11353
11354 void
11355 Struct_construction_expression::do_export(Export* exp) const
11356 {
11357   exp->write_c_string("convert(");
11358   exp->write_type(this->type_);
11359   for (Expression_list::const_iterator pv = this->vals_->begin();
11360        pv != this->vals_->end();
11361        ++pv)
11362     {
11363       exp->write_c_string(", ");
11364       if (*pv != NULL)
11365         (*pv)->export_expression(exp);
11366     }
11367   exp->write_c_string(")");
11368 }
11369
11370 // Dump ast representation of a struct construction expression.
11371
11372 void
11373 Struct_construction_expression::do_dump_expression(
11374     Ast_dump_context* ast_dump_context) const
11375 {
11376   ast_dump_context->dump_type(this->type_);
11377   ast_dump_context->ostream() << "{";
11378   ast_dump_context->dump_expression_list(this->vals_);
11379   ast_dump_context->ostream() << "}";
11380 }
11381
11382 // Make a struct composite literal.  This used by the thunk code.
11383
11384 Expression*
11385 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11386                                           Location location)
11387 {
11388   go_assert(type->struct_type() != NULL);
11389   return new Struct_construction_expression(type, vals, location);
11390 }
11391
11392 // Construct an array.  This class is not used directly; instead we
11393 // use the child classes, Fixed_array_construction_expression and
11394 // Open_array_construction_expression.
11395
11396 class Array_construction_expression : public Expression
11397 {
11398  protected:
11399   Array_construction_expression(Expression_classification classification,
11400                                 Type* type,
11401                                 const std::vector<unsigned long>* indexes,
11402                                 Expression_list* vals, Location location)
11403     : Expression(classification, location),
11404       type_(type), indexes_(indexes), vals_(vals)
11405   { go_assert(indexes == NULL || indexes->size() == vals->size()); }
11406
11407  public:
11408   // Return whether this is a constant initializer.
11409   bool
11410   is_constant_array() const;
11411
11412   // Return the number of elements.
11413   size_t
11414   element_count() const
11415   { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11416
11417 protected:
11418   int
11419   do_traverse(Traverse* traverse);
11420
11421   Type*
11422   do_type()
11423   { return this->type_; }
11424
11425   void
11426   do_determine_type(const Type_context*);
11427
11428   void
11429   do_check_types(Gogo*);
11430
11431   void
11432   do_export(Export*) const;
11433
11434   // The indexes.
11435   const std::vector<unsigned long>*
11436   indexes()
11437   { return this->indexes_; }
11438
11439   // The list of values.
11440   Expression_list*
11441   vals()
11442   { return this->vals_; }
11443
11444   // Get a constructor tree for the array values.
11445   tree
11446   get_constructor_tree(Translate_context* context, tree type_tree);
11447
11448   void
11449   do_dump_expression(Ast_dump_context*) const;
11450
11451  private:
11452   // The type of the array to construct.
11453   Type* type_;
11454   // The list of indexes into the array, one for each value.  This may
11455   // be NULL, in which case the indexes start at zero and increment.
11456   const std::vector<unsigned long>* indexes_;
11457   // The list of values.  This may be NULL if there are no values.
11458   Expression_list* vals_;
11459 };
11460
11461 // Traversal.
11462
11463 int
11464 Array_construction_expression::do_traverse(Traverse* traverse)
11465 {
11466   if (this->vals_ != NULL
11467       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11468     return TRAVERSE_EXIT;
11469   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11470     return TRAVERSE_EXIT;
11471   return TRAVERSE_CONTINUE;
11472 }
11473
11474 // Return whether this is a constant initializer.
11475
11476 bool
11477 Array_construction_expression::is_constant_array() const
11478 {
11479   if (this->vals_ == NULL)
11480     return true;
11481
11482   // There are no constant constructors for interfaces.
11483   if (this->type_->array_type()->element_type()->interface_type() != NULL)
11484     return false;
11485
11486   for (Expression_list::const_iterator pv = this->vals_->begin();
11487        pv != this->vals_->end();
11488        ++pv)
11489     {
11490       if (*pv != NULL
11491           && !(*pv)->is_constant()
11492           && (!(*pv)->is_composite_literal()
11493               || (*pv)->is_nonconstant_composite_literal()))
11494         return false;
11495     }
11496   return true;
11497 }
11498
11499 // Final type determination.
11500
11501 void
11502 Array_construction_expression::do_determine_type(const Type_context*)
11503 {
11504   if (this->vals_ == NULL)
11505     return;
11506   Type_context subcontext(this->type_->array_type()->element_type(), false);
11507   for (Expression_list::const_iterator pv = this->vals_->begin();
11508        pv != this->vals_->end();
11509        ++pv)
11510     {
11511       if (*pv != NULL)
11512         (*pv)->determine_type(&subcontext);
11513     }
11514 }
11515
11516 // Check types.
11517
11518 void
11519 Array_construction_expression::do_check_types(Gogo*)
11520 {
11521   if (this->vals_ == NULL)
11522     return;
11523
11524   Array_type* at = this->type_->array_type();
11525   int i = 0;
11526   Type* element_type = at->element_type();
11527   for (Expression_list::const_iterator pv = this->vals_->begin();
11528        pv != this->vals_->end();
11529        ++pv, ++i)
11530     {
11531       if (*pv != NULL
11532           && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11533         {
11534           error_at((*pv)->location(),
11535                    "incompatible type for element %d in composite literal",
11536                    i + 1);
11537           this->set_is_error();
11538         }
11539     }
11540 }
11541
11542 // Get a constructor tree for the array values.
11543
11544 tree
11545 Array_construction_expression::get_constructor_tree(Translate_context* context,
11546                                                     tree type_tree)
11547 {
11548   VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11549                                               (this->vals_ == NULL
11550                                                ? 0
11551                                                : this->vals_->size()));
11552   Type* element_type = this->type_->array_type()->element_type();
11553   bool is_constant = true;
11554   if (this->vals_ != NULL)
11555     {
11556       size_t i = 0;
11557       std::vector<unsigned long>::const_iterator pi;
11558       if (this->indexes_ != NULL)
11559         pi = this->indexes_->begin();
11560       for (Expression_list::const_iterator pv = this->vals_->begin();
11561            pv != this->vals_->end();
11562            ++pv, ++i)
11563         {
11564           if (this->indexes_ != NULL)
11565             go_assert(pi != this->indexes_->end());
11566           constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11567
11568           if (this->indexes_ == NULL)
11569             elt->index = size_int(i);
11570           else
11571             elt->index = size_int(*pi);
11572
11573           if (*pv == NULL)
11574             {
11575               Gogo* gogo = context->gogo();
11576               Btype* ebtype = element_type->get_backend(gogo);
11577               Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11578               elt->value = expr_to_tree(zv);
11579             }
11580           else
11581             {
11582               tree value_tree = (*pv)->get_tree(context);
11583               elt->value = Expression::convert_for_assignment(context,
11584                                                               element_type,
11585                                                               (*pv)->type(),
11586                                                               value_tree,
11587                                                               this->location());
11588             }
11589           if (elt->value == error_mark_node)
11590             return error_mark_node;
11591           if (!TREE_CONSTANT(elt->value))
11592             is_constant = false;
11593           if (this->indexes_ != NULL)
11594             ++pi;
11595         }
11596       if (this->indexes_ != NULL)
11597         go_assert(pi == this->indexes_->end());
11598     }
11599
11600   tree ret = build_constructor(type_tree, values);
11601   if (is_constant)
11602     TREE_CONSTANT(ret) = 1;
11603   return ret;
11604 }
11605
11606 // Export an array construction.
11607
11608 void
11609 Array_construction_expression::do_export(Export* exp) const
11610 {
11611   exp->write_c_string("convert(");
11612   exp->write_type(this->type_);
11613   if (this->vals_ != NULL)
11614     {
11615       std::vector<unsigned long>::const_iterator pi;
11616       if (this->indexes_ != NULL)
11617         pi = this->indexes_->begin();
11618       for (Expression_list::const_iterator pv = this->vals_->begin();
11619            pv != this->vals_->end();
11620            ++pv)
11621         {
11622           exp->write_c_string(", ");
11623
11624           if (this->indexes_ != NULL)
11625             {
11626               char buf[100];
11627               snprintf(buf, sizeof buf, "%lu", *pi);
11628               exp->write_c_string(buf);
11629               exp->write_c_string(":");
11630             }
11631
11632           if (*pv != NULL)
11633             (*pv)->export_expression(exp);
11634
11635           if (this->indexes_ != NULL)
11636             ++pi;
11637         }
11638     }
11639   exp->write_c_string(")");
11640 }
11641
11642 // Dump ast representation of an array construction expressin.
11643
11644 void
11645 Array_construction_expression::do_dump_expression(
11646     Ast_dump_context* ast_dump_context) const
11647 {
11648   Expression* length = this->type_->array_type()->length();
11649
11650   ast_dump_context->ostream() << "[" ;
11651   if (length != NULL)
11652     {
11653       ast_dump_context->dump_expression(length);
11654     }
11655   ast_dump_context->ostream() << "]" ;
11656   ast_dump_context->dump_type(this->type_);
11657   ast_dump_context->ostream() << "{" ;
11658   if (this->indexes_ == NULL)
11659     ast_dump_context->dump_expression_list(this->vals_);
11660   else
11661     {
11662       Expression_list::const_iterator pv = this->vals_->begin();
11663       for (std::vector<unsigned long>::const_iterator pi =
11664              this->indexes_->begin();
11665            pi != this->indexes_->end();
11666            ++pi, ++pv)
11667         {
11668           if (pi != this->indexes_->begin())
11669             ast_dump_context->ostream() << ", ";
11670           ast_dump_context->ostream() << *pi << ':';
11671           ast_dump_context->dump_expression(*pv);
11672         }
11673     }
11674   ast_dump_context->ostream() << "}" ;
11675
11676 }
11677
11678 // Construct a fixed array.
11679
11680 class Fixed_array_construction_expression :
11681   public Array_construction_expression
11682 {
11683  public:
11684   Fixed_array_construction_expression(Type* type,
11685                                       const std::vector<unsigned long>* indexes,
11686                                       Expression_list* vals, Location location)
11687     : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11688                                     type, indexes, vals, location)
11689   { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
11690
11691  protected:
11692   Expression*
11693   do_copy()
11694   {
11695     return new Fixed_array_construction_expression(this->type(),
11696                                                    this->indexes(),
11697                                                    (this->vals() == NULL
11698                                                     ? NULL
11699                                                     : this->vals()->copy()),
11700                                                    this->location());
11701   }
11702
11703   tree
11704   do_get_tree(Translate_context*);
11705 };
11706
11707 // Return a tree for constructing a fixed array.
11708
11709 tree
11710 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11711 {
11712   Type* type = this->type();
11713   Btype* btype = type->get_backend(context->gogo());
11714   return this->get_constructor_tree(context, type_to_tree(btype));
11715 }
11716
11717 // Construct an open array.
11718
11719 class Open_array_construction_expression : public Array_construction_expression
11720 {
11721  public:
11722   Open_array_construction_expression(Type* type,
11723                                      const std::vector<unsigned long>* indexes,
11724                                      Expression_list* vals, Location location)
11725     : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11726                                     type, indexes, vals, location)
11727   { go_assert(type->is_slice_type()); }
11728
11729  protected:
11730   // Note that taking the address of an open array literal is invalid.
11731
11732   Expression*
11733   do_copy()
11734   {
11735     return new Open_array_construction_expression(this->type(),
11736                                                   this->indexes(),
11737                                                   (this->vals() == NULL
11738                                                    ? NULL
11739                                                    : this->vals()->copy()),
11740                                                   this->location());
11741   }
11742
11743   tree
11744   do_get_tree(Translate_context*);
11745 };
11746
11747 // Return a tree for constructing an open array.
11748
11749 tree
11750 Open_array_construction_expression::do_get_tree(Translate_context* context)
11751 {
11752   Array_type* array_type = this->type()->array_type();
11753   if (array_type == NULL)
11754     {
11755       go_assert(this->type()->is_error());
11756       return error_mark_node;
11757     }
11758
11759   Type* element_type = array_type->element_type();
11760   Btype* belement_type = element_type->get_backend(context->gogo());
11761   tree element_type_tree = type_to_tree(belement_type);
11762   if (element_type_tree == error_mark_node)
11763     return error_mark_node;
11764
11765   tree values;
11766   tree length_tree;
11767   if (this->vals() == NULL || this->vals()->empty())
11768     {
11769       // We need to create a unique value.
11770       tree max = size_int(0);
11771       tree constructor_type = build_array_type(element_type_tree,
11772                                                build_index_type(max));
11773       if (constructor_type == error_mark_node)
11774         return error_mark_node;
11775       VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11776       constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11777       elt->index = size_int(0);
11778       Gogo* gogo = context->gogo();
11779       Btype* btype = element_type->get_backend(gogo);
11780       elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11781       values = build_constructor(constructor_type, vec);
11782       if (TREE_CONSTANT(elt->value))
11783         TREE_CONSTANT(values) = 1;
11784       length_tree = size_int(0);
11785     }
11786   else
11787     {
11788       unsigned long max_index;
11789       if (this->indexes() == NULL)
11790         max_index = this->vals()->size() - 1;
11791       else
11792         max_index = *std::max_element(this->indexes()->begin(),
11793                                       this->indexes()->end());
11794       tree max_tree = size_int(max_index);
11795       tree constructor_type = build_array_type(element_type_tree,
11796                                                build_index_type(max_tree));
11797       if (constructor_type == error_mark_node)
11798         return error_mark_node;
11799       values = this->get_constructor_tree(context, constructor_type);
11800       length_tree = size_int(max_index + 1);
11801     }
11802
11803   if (values == error_mark_node)
11804     return error_mark_node;
11805
11806   bool is_constant_initializer = TREE_CONSTANT(values);
11807
11808   // We have to copy the initial values into heap memory if we are in
11809   // a function or if the values are not constants.  We also have to
11810   // copy them if they may contain pointers in a non-constant context,
11811   // as otherwise the garbage collector won't see them.
11812   bool copy_to_heap = (context->function() != NULL
11813                        || !is_constant_initializer
11814                        || (element_type->has_pointer()
11815                            && !context->is_const()));
11816
11817   if (is_constant_initializer)
11818     {
11819       tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11820                             create_tmp_var_name("C"), TREE_TYPE(values));
11821       DECL_EXTERNAL(tmp) = 0;
11822       TREE_PUBLIC(tmp) = 0;
11823       TREE_STATIC(tmp) = 1;
11824       DECL_ARTIFICIAL(tmp) = 1;
11825       if (copy_to_heap)
11826         {
11827           // If we are not copying the value to the heap, we will only
11828           // initialize the value once, so we can use this directly
11829           // rather than copying it.  In that case we can't make it
11830           // read-only, because the program is permitted to change it.
11831           TREE_READONLY(tmp) = 1;
11832           TREE_CONSTANT(tmp) = 1;
11833         }
11834       DECL_INITIAL(tmp) = values;
11835       rest_of_decl_compilation(tmp, 1, 0);
11836       values = tmp;
11837     }
11838
11839   tree space;
11840   tree set;
11841   if (!copy_to_heap)
11842     {
11843       // the initializer will only run once.
11844       space = build_fold_addr_expr(values);
11845       set = NULL_TREE;
11846     }
11847   else
11848     {
11849       tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11850       space = context->gogo()->allocate_memory(element_type, memsize,
11851                                                this->location());
11852       space = save_expr(space);
11853
11854       tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11855       tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11856                                              s);
11857       TREE_THIS_NOTRAP(ref) = 1;
11858       set = build2(MODIFY_EXPR, void_type_node, ref, values);
11859     }
11860
11861   // Build a constructor for the open array.
11862
11863   tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11864   if (type_tree == error_mark_node)
11865     return error_mark_node;
11866   go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11867
11868   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11869
11870   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11871   tree field = TYPE_FIELDS(type_tree);
11872   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11873   elt->index = field;
11874   elt->value = fold_convert(TREE_TYPE(field), space);
11875
11876   elt = VEC_quick_push(constructor_elt, init, NULL);
11877   field = DECL_CHAIN(field);
11878   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11879   elt->index = field;
11880   elt->value = fold_convert(TREE_TYPE(field), length_tree);
11881
11882   elt = VEC_quick_push(constructor_elt, init, NULL);
11883   field = DECL_CHAIN(field);
11884   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11885   elt->index = field;
11886   elt->value = fold_convert(TREE_TYPE(field), length_tree);
11887
11888   tree constructor = build_constructor(type_tree, init);
11889   if (constructor == error_mark_node)
11890     return error_mark_node;
11891   if (!copy_to_heap)
11892     TREE_CONSTANT(constructor) = 1;
11893
11894   if (set == NULL_TREE)
11895     return constructor;
11896   else
11897     return build2(COMPOUND_EXPR, type_tree, set, constructor);
11898 }
11899
11900 // Make a slice composite literal.  This is used by the type
11901 // descriptor code.
11902
11903 Expression*
11904 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11905                                          Location location)
11906 {
11907   go_assert(type->is_slice_type());
11908   return new Open_array_construction_expression(type, NULL, vals, location);
11909 }
11910
11911 // Construct a map.
11912
11913 class Map_construction_expression : public Expression
11914 {
11915  public:
11916   Map_construction_expression(Type* type, Expression_list* vals,
11917                               Location location)
11918     : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11919       type_(type), vals_(vals)
11920   { go_assert(vals == NULL || vals->size() % 2 == 0); }
11921
11922  protected:
11923   int
11924   do_traverse(Traverse* traverse);
11925
11926   Type*
11927   do_type()
11928   { return this->type_; }
11929
11930   void
11931   do_determine_type(const Type_context*);
11932
11933   void
11934   do_check_types(Gogo*);
11935
11936   Expression*
11937   do_copy()
11938   {
11939     return new Map_construction_expression(this->type_, this->vals_->copy(),
11940                                            this->location());
11941   }
11942
11943   tree
11944   do_get_tree(Translate_context*);
11945
11946   void
11947   do_export(Export*) const;
11948
11949   void
11950   do_dump_expression(Ast_dump_context*) const;
11951   
11952  private:
11953   // The type of the map to construct.
11954   Type* type_;
11955   // The list of values.
11956   Expression_list* vals_;
11957 };
11958
11959 // Traversal.
11960
11961 int
11962 Map_construction_expression::do_traverse(Traverse* traverse)
11963 {
11964   if (this->vals_ != NULL
11965       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11966     return TRAVERSE_EXIT;
11967   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11968     return TRAVERSE_EXIT;
11969   return TRAVERSE_CONTINUE;
11970 }
11971
11972 // Final type determination.
11973
11974 void
11975 Map_construction_expression::do_determine_type(const Type_context*)
11976 {
11977   if (this->vals_ == NULL)
11978     return;
11979
11980   Map_type* mt = this->type_->map_type();
11981   Type_context key_context(mt->key_type(), false);
11982   Type_context val_context(mt->val_type(), false);
11983   for (Expression_list::const_iterator pv = this->vals_->begin();
11984        pv != this->vals_->end();
11985        ++pv)
11986     {
11987       (*pv)->determine_type(&key_context);
11988       ++pv;
11989       (*pv)->determine_type(&val_context);
11990     }
11991 }
11992
11993 // Check types.
11994
11995 void
11996 Map_construction_expression::do_check_types(Gogo*)
11997 {
11998   if (this->vals_ == NULL)
11999     return;
12000
12001   Map_type* mt = this->type_->map_type();
12002   int i = 0;
12003   Type* key_type = mt->key_type();
12004   Type* val_type = mt->val_type();
12005   for (Expression_list::const_iterator pv = this->vals_->begin();
12006        pv != this->vals_->end();
12007        ++pv, ++i)
12008     {
12009       if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12010         {
12011           error_at((*pv)->location(),
12012                    "incompatible type for element %d key in map construction",
12013                    i + 1);
12014           this->set_is_error();
12015         }
12016       ++pv;
12017       if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12018         {
12019           error_at((*pv)->location(),
12020                    ("incompatible type for element %d value "
12021                     "in map construction"),
12022                    i + 1);
12023           this->set_is_error();
12024         }
12025     }
12026 }
12027
12028 // Return a tree for constructing a map.
12029
12030 tree
12031 Map_construction_expression::do_get_tree(Translate_context* context)
12032 {
12033   Gogo* gogo = context->gogo();
12034   Location loc = this->location();
12035
12036   Map_type* mt = this->type_->map_type();
12037
12038   // Build a struct to hold the key and value.
12039   tree struct_type = make_node(RECORD_TYPE);
12040
12041   Type* key_type = mt->key_type();
12042   tree id = get_identifier("__key");
12043   tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12044   if (key_type_tree == error_mark_node)
12045     return error_mark_node;
12046   tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12047                               key_type_tree);
12048   DECL_CONTEXT(key_field) = struct_type;
12049   TYPE_FIELDS(struct_type) = key_field;
12050
12051   Type* val_type = mt->val_type();
12052   id = get_identifier("__val");
12053   tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12054   if (val_type_tree == error_mark_node)
12055     return error_mark_node;
12056   tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12057                               val_type_tree);
12058   DECL_CONTEXT(val_field) = struct_type;
12059   DECL_CHAIN(key_field) = val_field;
12060
12061   layout_type(struct_type);
12062
12063   bool is_constant = true;
12064   size_t i = 0;
12065   tree valaddr;
12066   tree make_tmp;
12067
12068   if (this->vals_ == NULL || this->vals_->empty())
12069     {
12070       valaddr = null_pointer_node;
12071       make_tmp = NULL_TREE;
12072     }
12073   else
12074     {
12075       VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12076                                                   this->vals_->size() / 2);
12077
12078       for (Expression_list::const_iterator pv = this->vals_->begin();
12079            pv != this->vals_->end();
12080            ++pv, ++i)
12081         {
12082           bool one_is_constant = true;
12083
12084           VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12085
12086           constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12087           elt->index = key_field;
12088           tree val_tree = (*pv)->get_tree(context);
12089           elt->value = Expression::convert_for_assignment(context, key_type,
12090                                                           (*pv)->type(),
12091                                                           val_tree, loc);
12092           if (elt->value == error_mark_node)
12093             return error_mark_node;
12094           if (!TREE_CONSTANT(elt->value))
12095             one_is_constant = false;
12096
12097           ++pv;
12098
12099           elt = VEC_quick_push(constructor_elt, one, NULL);
12100           elt->index = val_field;
12101           val_tree = (*pv)->get_tree(context);
12102           elt->value = Expression::convert_for_assignment(context, val_type,
12103                                                           (*pv)->type(),
12104                                                           val_tree, loc);
12105           if (elt->value == error_mark_node)
12106             return error_mark_node;
12107           if (!TREE_CONSTANT(elt->value))
12108             one_is_constant = false;
12109
12110           elt = VEC_quick_push(constructor_elt, values, NULL);
12111           elt->index = size_int(i);
12112           elt->value = build_constructor(struct_type, one);
12113           if (one_is_constant)
12114             TREE_CONSTANT(elt->value) = 1;
12115           else
12116             is_constant = false;
12117         }
12118
12119       tree index_type = build_index_type(size_int(i - 1));
12120       tree array_type = build_array_type(struct_type, index_type);
12121       tree init = build_constructor(array_type, values);
12122       if (is_constant)
12123         TREE_CONSTANT(init) = 1;
12124       tree tmp;
12125       if (current_function_decl != NULL)
12126         {
12127           tmp = create_tmp_var(array_type, get_name(array_type));
12128           DECL_INITIAL(tmp) = init;
12129           make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
12130                                      void_type_node, tmp);
12131           TREE_ADDRESSABLE(tmp) = 1;
12132         }
12133       else
12134         {
12135           tmp = build_decl(loc.gcc_location(), VAR_DECL,
12136                            create_tmp_var_name("M"), array_type);
12137           DECL_EXTERNAL(tmp) = 0;
12138           TREE_PUBLIC(tmp) = 0;
12139           TREE_STATIC(tmp) = 1;
12140           DECL_ARTIFICIAL(tmp) = 1;
12141           if (!TREE_CONSTANT(init))
12142             make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
12143                                        void_type_node, tmp, init);
12144           else
12145             {
12146               TREE_READONLY(tmp) = 1;
12147               TREE_CONSTANT(tmp) = 1;
12148               DECL_INITIAL(tmp) = init;
12149               make_tmp = NULL_TREE;
12150             }
12151           rest_of_decl_compilation(tmp, 1, 0);
12152         }
12153
12154       valaddr = build_fold_addr_expr(tmp);
12155     }
12156
12157   tree descriptor = mt->map_descriptor_pointer(gogo, loc);
12158
12159   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12160   if (type_tree == error_mark_node)
12161     return error_mark_node;
12162
12163   static tree construct_map_fndecl;
12164   tree call = Gogo::call_builtin(&construct_map_fndecl,
12165                                  loc,
12166                                  "__go_construct_map",
12167                                  6,
12168                                  type_tree,
12169                                  TREE_TYPE(descriptor),
12170                                  descriptor,
12171                                  sizetype,
12172                                  size_int(i),
12173                                  sizetype,
12174                                  TYPE_SIZE_UNIT(struct_type),
12175                                  sizetype,
12176                                  byte_position(val_field),
12177                                  sizetype,
12178                                  TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
12179                                  const_ptr_type_node,
12180                                  fold_convert(const_ptr_type_node, valaddr));
12181   if (call == error_mark_node)
12182     return error_mark_node;
12183
12184   tree ret;
12185   if (make_tmp == NULL)
12186     ret = call;
12187   else
12188     ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12189                           make_tmp, call);
12190   return ret;
12191 }
12192
12193 // Export an array construction.
12194
12195 void
12196 Map_construction_expression::do_export(Export* exp) const
12197 {
12198   exp->write_c_string("convert(");
12199   exp->write_type(this->type_);
12200   for (Expression_list::const_iterator pv = this->vals_->begin();
12201        pv != this->vals_->end();
12202        ++pv)
12203     {
12204       exp->write_c_string(", ");
12205       (*pv)->export_expression(exp);
12206     }
12207   exp->write_c_string(")");
12208 }
12209
12210 // Dump ast representation for a map construction expression.
12211
12212 void
12213 Map_construction_expression::do_dump_expression(
12214     Ast_dump_context* ast_dump_context) const
12215 {
12216   ast_dump_context->ostream() << "{" ;
12217   ast_dump_context->dump_expression_list(this->vals_, true);
12218   ast_dump_context->ostream() << "}";
12219 }
12220
12221 // A general composite literal.  This is lowered to a type specific
12222 // version.
12223
12224 class Composite_literal_expression : public Parser_expression
12225 {
12226  public:
12227   Composite_literal_expression(Type* type, int depth, bool has_keys,
12228                                Expression_list* vals, Location location)
12229     : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12230       type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12231   { }
12232
12233  protected:
12234   int
12235   do_traverse(Traverse* traverse);
12236
12237   Expression*
12238   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12239
12240   Expression*
12241   do_copy()
12242   {
12243     return new Composite_literal_expression(this->type_, this->depth_,
12244                                             this->has_keys_,
12245                                             (this->vals_ == NULL
12246                                              ? NULL
12247                                              : this->vals_->copy()),
12248                                             this->location());
12249   }
12250
12251   void
12252   do_dump_expression(Ast_dump_context*) const;
12253   
12254  private:
12255   Expression*
12256   lower_struct(Gogo*, Type*);
12257
12258   Expression*
12259   lower_array(Type*);
12260
12261   Expression*
12262   make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12263
12264   Expression*
12265   lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12266
12267   // The type of the composite literal.
12268   Type* type_;
12269   // The depth within a list of composite literals within a composite
12270   // literal, when the type is omitted.
12271   int depth_;
12272   // The values to put in the composite literal.
12273   Expression_list* vals_;
12274   // If this is true, then VALS_ is a list of pairs: a key and a
12275   // value.  In an array initializer, a missing key will be NULL.
12276   bool has_keys_;
12277 };
12278
12279 // Traversal.
12280
12281 int
12282 Composite_literal_expression::do_traverse(Traverse* traverse)
12283 {
12284   if (this->vals_ != NULL
12285       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12286     return TRAVERSE_EXIT;
12287   return Type::traverse(this->type_, traverse);
12288 }
12289
12290 // Lower a generic composite literal into a specific version based on
12291 // the type.
12292
12293 Expression*
12294 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12295                                        Statement_inserter* inserter, int)
12296 {
12297   Type* type = this->type_;
12298
12299   for (int depth = this->depth_; depth > 0; --depth)
12300     {
12301       if (type->array_type() != NULL)
12302         type = type->array_type()->element_type();
12303       else if (type->map_type() != NULL)
12304         type = type->map_type()->val_type();
12305       else
12306         {
12307           if (!type->is_error())
12308             error_at(this->location(),
12309                      ("may only omit types within composite literals "
12310                       "of slice, array, or map type"));
12311           return Expression::make_error(this->location());
12312         }
12313     }
12314
12315   Type *pt = type->points_to();
12316   bool is_pointer = false;
12317   if (pt != NULL)
12318     {
12319       is_pointer = true;
12320       type = pt;
12321     }
12322
12323   Expression* ret;
12324   if (type->is_error())
12325     return Expression::make_error(this->location());
12326   else if (type->struct_type() != NULL)
12327     ret = this->lower_struct(gogo, type);
12328   else if (type->array_type() != NULL)
12329     ret = this->lower_array(type);
12330   else if (type->map_type() != NULL)
12331     ret = this->lower_map(gogo, function, inserter, type);
12332   else
12333     {
12334       error_at(this->location(),
12335                ("expected struct, slice, array, or map type "
12336                 "for composite literal"));
12337       return Expression::make_error(this->location());
12338     }
12339
12340   if (is_pointer)
12341     ret = Expression::make_heap_composite(ret, this->location());
12342
12343   return ret;
12344 }
12345
12346 // Lower a struct composite literal.
12347
12348 Expression*
12349 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12350 {
12351   Location location = this->location();
12352   Struct_type* st = type->struct_type();
12353   if (this->vals_ == NULL || !this->has_keys_)
12354     {
12355       if (this->vals_ != NULL
12356           && !this->vals_->empty()
12357           && type->named_type() != NULL
12358           && type->named_type()->named_object()->package() != NULL)
12359         {
12360           for (Struct_field_list::const_iterator pf = st->fields()->begin();
12361                pf != st->fields()->end();
12362                ++pf)
12363             {
12364               if (Gogo::is_hidden_name(pf->field_name()))
12365                 error_at(this->location(),
12366                          "assignment of unexported field %qs in %qs literal",
12367                          Gogo::message_name(pf->field_name()).c_str(),
12368                          type->named_type()->message_name().c_str());
12369             }
12370         }
12371
12372       return new Struct_construction_expression(type, this->vals_, location);
12373     }
12374
12375   size_t field_count = st->field_count();
12376   std::vector<Expression*> vals(field_count);
12377   std::vector<int>* traverse_order = new(std::vector<int>);
12378   Expression_list::const_iterator p = this->vals_->begin();
12379   while (p != this->vals_->end())
12380     {
12381       Expression* name_expr = *p;
12382
12383       ++p;
12384       go_assert(p != this->vals_->end());
12385       Expression* val = *p;
12386
12387       ++p;
12388
12389       if (name_expr == NULL)
12390         {
12391           error_at(val->location(), "mixture of field and value initializers");
12392           return Expression::make_error(location);
12393         }
12394
12395       bool bad_key = false;
12396       std::string name;
12397       const Named_object* no = NULL;
12398       switch (name_expr->classification())
12399         {
12400         case EXPRESSION_UNKNOWN_REFERENCE:
12401           name = name_expr->unknown_expression()->name();
12402           break;
12403
12404         case EXPRESSION_CONST_REFERENCE:
12405           no = static_cast<Const_expression*>(name_expr)->named_object();
12406           break;
12407
12408         case EXPRESSION_TYPE:
12409           {
12410             Type* t = name_expr->type();
12411             Named_type* nt = t->named_type();
12412             if (nt == NULL)
12413               bad_key = true;
12414             else
12415               no = nt->named_object();
12416           }
12417           break;
12418
12419         case EXPRESSION_VAR_REFERENCE:
12420           no = name_expr->var_expression()->named_object();
12421           break;
12422
12423         case EXPRESSION_FUNC_REFERENCE:
12424           no = name_expr->func_expression()->named_object();
12425           break;
12426
12427         case EXPRESSION_UNARY:
12428           // If there is a local variable around with the same name as
12429           // the field, and this occurs in the closure, then the
12430           // parser may turn the field reference into an indirection
12431           // through the closure.  FIXME: This is a mess.
12432           {
12433             bad_key = true;
12434             Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12435             if (ue->op() == OPERATOR_MULT)
12436               {
12437                 Field_reference_expression* fre =
12438                   ue->operand()->field_reference_expression();
12439                 if (fre != NULL)
12440                   {
12441                     Struct_type* st =
12442                       fre->expr()->type()->deref()->struct_type();
12443                     if (st != NULL)
12444                       {
12445                         const Struct_field* sf = st->field(fre->field_index());
12446                         name = sf->field_name();
12447
12448                         // See below.  FIXME.
12449                         if (!Gogo::is_hidden_name(name)
12450                             && name[0] >= 'a'
12451                             && name[0] <= 'z')
12452                           {
12453                             if (gogo->lookup_global(name.c_str()) != NULL)
12454                               name = gogo->pack_hidden_name(name, false);
12455                           }
12456
12457                         char buf[20];
12458                         snprintf(buf, sizeof buf, "%u", fre->field_index());
12459                         size_t buflen = strlen(buf);
12460                         if (name.compare(name.length() - buflen, buflen, buf)
12461                             == 0)
12462                           {
12463                             name = name.substr(0, name.length() - buflen);
12464                             bad_key = false;
12465                           }
12466                       }
12467                   }
12468               }
12469           }
12470           break;
12471
12472         default:
12473           bad_key = true;
12474           break;
12475         }
12476       if (bad_key)
12477         {
12478           error_at(name_expr->location(), "expected struct field name");
12479           return Expression::make_error(location);
12480         }
12481
12482       if (no != NULL)
12483         {
12484           name = no->name();
12485
12486           // A predefined name won't be packed.  If it starts with a
12487           // lower case letter we need to check for that case, because
12488           // the field name will be packed.  FIXME.
12489           if (!Gogo::is_hidden_name(name)
12490               && name[0] >= 'a'
12491               && name[0] <= 'z')
12492             {
12493               Named_object* gno = gogo->lookup_global(name.c_str());
12494               if (gno == no)
12495                 name = gogo->pack_hidden_name(name, false);
12496             }
12497         }
12498
12499       unsigned int index;
12500       const Struct_field* sf = st->find_local_field(name, &index);
12501       if (sf == NULL)
12502         {
12503           error_at(name_expr->location(), "unknown field %qs in %qs",
12504                    Gogo::message_name(name).c_str(),
12505                    (type->named_type() != NULL
12506                     ? type->named_type()->message_name().c_str()
12507                     : "unnamed struct"));
12508           return Expression::make_error(location);
12509         }
12510       if (vals[index] != NULL)
12511         {
12512           error_at(name_expr->location(),
12513                    "duplicate value for field %qs in %qs",
12514                    Gogo::message_name(name).c_str(),
12515                    (type->named_type() != NULL
12516                     ? type->named_type()->message_name().c_str()
12517                     : "unnamed struct"));
12518           return Expression::make_error(location);
12519         }
12520
12521       if (type->named_type() != NULL
12522           && type->named_type()->named_object()->package() != NULL
12523           && Gogo::is_hidden_name(sf->field_name()))
12524         error_at(name_expr->location(),
12525                  "assignment of unexported field %qs in %qs literal",
12526                  Gogo::message_name(sf->field_name()).c_str(),
12527                  type->named_type()->message_name().c_str());
12528
12529       vals[index] = val;
12530       traverse_order->push_back(index);
12531     }
12532
12533   Expression_list* list = new Expression_list;
12534   list->reserve(field_count);
12535   for (size_t i = 0; i < field_count; ++i)
12536     list->push_back(vals[i]);
12537
12538   Struct_construction_expression* ret =
12539     new Struct_construction_expression(type, list, location);
12540   ret->set_traverse_order(traverse_order);
12541   return ret;
12542 }
12543
12544 // Lower an array composite literal.
12545
12546 Expression*
12547 Composite_literal_expression::lower_array(Type* type)
12548 {
12549   Location location = this->location();
12550   if (this->vals_ == NULL || !this->has_keys_)
12551     return this->make_array(type, NULL, this->vals_);
12552
12553   std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12554   indexes->reserve(this->vals_->size());
12555   Expression_list* vals = new Expression_list();
12556   vals->reserve(this->vals_->size());
12557   unsigned long index = 0;
12558   Expression_list::const_iterator p = this->vals_->begin();
12559   while (p != this->vals_->end())
12560     {
12561       Expression* index_expr = *p;
12562
12563       ++p;
12564       go_assert(p != this->vals_->end());
12565       Expression* val = *p;
12566
12567       ++p;
12568
12569       if (index_expr == NULL)
12570         {
12571           if (!indexes->empty())
12572             indexes->push_back(index);
12573         }
12574       else
12575         {
12576           if (indexes->empty() && !vals->empty())
12577             {
12578               for (size_t i = 0; i < vals->size(); ++i)
12579                 indexes->push_back(i);
12580             }
12581
12582           Numeric_constant nc;
12583           if (!index_expr->numeric_constant_value(&nc))
12584             {
12585               error_at(index_expr->location(),
12586                        "index expression is not integer constant");
12587               return Expression::make_error(location);
12588             }
12589
12590           switch (nc.to_unsigned_long(&index))
12591             {
12592             case Numeric_constant::NC_UL_VALID:
12593               break;
12594             case Numeric_constant::NC_UL_NOTINT:
12595               error_at(index_expr->location(),
12596                        "index expression is not integer constant");
12597               return Expression::make_error(location);
12598             case Numeric_constant::NC_UL_NEGATIVE:
12599               error_at(index_expr->location(), "index expression is negative");
12600               return Expression::make_error(location);
12601             case Numeric_constant::NC_UL_BIG:
12602               error_at(index_expr->location(), "index value overflow");
12603               return Expression::make_error(location);
12604             default:
12605               go_unreachable();
12606             }
12607
12608           Named_type* ntype = Type::lookup_integer_type("int");
12609           Integer_type* inttype = ntype->integer_type();
12610           if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12611               && index >> (inttype->bits() - 1) != 0)
12612             {
12613               error_at(index_expr->location(), "index value overflow");
12614               return Expression::make_error(location);
12615             }
12616
12617           if (std::find(indexes->begin(), indexes->end(), index)
12618               != indexes->end())
12619             {
12620               error_at(index_expr->location(), "duplicate value for index %lu",
12621                        index);
12622               return Expression::make_error(location);
12623             }
12624
12625           indexes->push_back(index);
12626         }
12627
12628       vals->push_back(val);
12629
12630       ++index;
12631     }
12632
12633   if (indexes->empty())
12634     {
12635       delete indexes;
12636       indexes = NULL;
12637     }
12638
12639   return this->make_array(type, indexes, vals);
12640 }
12641
12642 // Actually build the array composite literal. This handles
12643 // [...]{...}.
12644
12645 Expression*
12646 Composite_literal_expression::make_array(
12647     Type* type,
12648     const std::vector<unsigned long>* indexes,
12649     Expression_list* vals)
12650 {
12651   Location location = this->location();
12652   Array_type* at = type->array_type();
12653
12654   if (at->length() != NULL && at->length()->is_nil_expression())
12655     {
12656       size_t size;
12657       if (vals == NULL)
12658         size = 0;
12659       else if (indexes == NULL)
12660         {
12661           size = vals->size();
12662           Integer_type* it = Type::lookup_integer_type("int")->integer_type();
12663           if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
12664               && size >> (it->bits() - 1) != 0)
12665             {
12666               error_at(location, "too many elements in composite literal");
12667               return Expression::make_error(location);
12668             }
12669         }
12670       else
12671         {
12672           size = *std::max_element(indexes->begin(), indexes->end());
12673           ++size;
12674         }
12675
12676       mpz_t vlen;
12677       mpz_init_set_ui(vlen, size);
12678       Expression* elen = Expression::make_integer(&vlen, NULL, location);
12679       mpz_clear(vlen);
12680       at = Type::make_array_type(at->element_type(), elen);
12681       type = at;
12682     }
12683   else if (at->length() != NULL
12684            && !at->length()->is_error_expression()
12685            && this->vals_ != NULL)
12686     {
12687       Numeric_constant nc;
12688       unsigned long val;
12689       if (at->length()->numeric_constant_value(&nc)
12690           && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
12691         {
12692           if (indexes == NULL)
12693             {
12694               if (this->vals_->size() > val)
12695                 {
12696                   error_at(location, "too many elements in composite literal");
12697                   return Expression::make_error(location);
12698                 }
12699             }
12700           else
12701             {
12702               unsigned long max = *std::max_element(indexes->begin(),
12703                                                     indexes->end());
12704               if (max >= val)
12705                 {
12706                   error_at(location,
12707                            ("some element keys in composite literal "
12708                             "are out of range"));
12709                   return Expression::make_error(location);
12710                 }
12711             }
12712         }
12713     }
12714
12715   if (at->length() != NULL)
12716     return new Fixed_array_construction_expression(type, indexes, vals,
12717                                                    location);
12718   else
12719     return new Open_array_construction_expression(type, indexes, vals,
12720                                                   location);
12721 }
12722
12723 // Lower a map composite literal.
12724
12725 Expression*
12726 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12727                                         Statement_inserter* inserter,
12728                                         Type* type)
12729 {
12730   Location location = this->location();
12731   if (this->vals_ != NULL)
12732     {
12733       if (!this->has_keys_)
12734         {
12735           error_at(location, "map composite literal must have keys");
12736           return Expression::make_error(location);
12737         }
12738
12739       for (Expression_list::iterator p = this->vals_->begin();
12740            p != this->vals_->end();
12741            p += 2)
12742         {
12743           if (*p == NULL)
12744             {
12745               ++p;
12746               error_at((*p)->location(),
12747                        "map composite literal must have keys for every value");
12748               return Expression::make_error(location);
12749             }
12750           // Make sure we have lowered the key; it may not have been
12751           // lowered in order to handle keys for struct composite
12752           // literals.  Lower it now to get the right error message.
12753           if ((*p)->unknown_expression() != NULL)
12754             {
12755               (*p)->unknown_expression()->clear_is_composite_literal_key();
12756               gogo->lower_expression(function, inserter, &*p);
12757               go_assert((*p)->is_error_expression());
12758               return Expression::make_error(location);
12759             }
12760         }
12761     }
12762
12763   return new Map_construction_expression(type, this->vals_, location);
12764 }
12765
12766 // Dump ast representation for a composite literal expression.
12767
12768 void
12769 Composite_literal_expression::do_dump_expression(
12770                                Ast_dump_context* ast_dump_context) const
12771 {
12772   ast_dump_context->ostream() << "composite(";
12773   ast_dump_context->dump_type(this->type_);
12774   ast_dump_context->ostream() << ", {";
12775   ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12776   ast_dump_context->ostream() << "})";
12777 }
12778
12779 // Make a composite literal expression.
12780
12781 Expression*
12782 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12783                                    Expression_list* vals,
12784                                    Location location)
12785 {
12786   return new Composite_literal_expression(type, depth, has_keys, vals,
12787                                           location);
12788 }
12789
12790 // Return whether this expression is a composite literal.
12791
12792 bool
12793 Expression::is_composite_literal() const
12794 {
12795   switch (this->classification_)
12796     {
12797     case EXPRESSION_COMPOSITE_LITERAL:
12798     case EXPRESSION_STRUCT_CONSTRUCTION:
12799     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12800     case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12801     case EXPRESSION_MAP_CONSTRUCTION:
12802       return true;
12803     default:
12804       return false;
12805     }
12806 }
12807
12808 // Return whether this expression is a composite literal which is not
12809 // constant.
12810
12811 bool
12812 Expression::is_nonconstant_composite_literal() const
12813 {
12814   switch (this->classification_)
12815     {
12816     case EXPRESSION_STRUCT_CONSTRUCTION:
12817       {
12818         const Struct_construction_expression *psce =
12819           static_cast<const Struct_construction_expression*>(this);
12820         return !psce->is_constant_struct();
12821       }
12822     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12823       {
12824         const Fixed_array_construction_expression *pace =
12825           static_cast<const Fixed_array_construction_expression*>(this);
12826         return !pace->is_constant_array();
12827       }
12828     case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12829       {
12830         const Open_array_construction_expression *pace =
12831           static_cast<const Open_array_construction_expression*>(this);
12832         return !pace->is_constant_array();
12833       }
12834     case EXPRESSION_MAP_CONSTRUCTION:
12835       return true;
12836     default:
12837       return false;
12838     }
12839 }
12840
12841 // Return true if this is a reference to a local variable.
12842
12843 bool
12844 Expression::is_local_variable() const
12845 {
12846   const Var_expression* ve = this->var_expression();
12847   if (ve == NULL)
12848     return false;
12849   const Named_object* no = ve->named_object();
12850   return (no->is_result_variable()
12851           || (no->is_variable() && !no->var_value()->is_global()));
12852 }
12853
12854 // Class Type_guard_expression.
12855
12856 // Traversal.
12857
12858 int
12859 Type_guard_expression::do_traverse(Traverse* traverse)
12860 {
12861   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12862       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12863     return TRAVERSE_EXIT;
12864   return TRAVERSE_CONTINUE;
12865 }
12866
12867 // Check types of a type guard expression.  The expression must have
12868 // an interface type, but the actual type conversion is checked at run
12869 // time.
12870
12871 void
12872 Type_guard_expression::do_check_types(Gogo*)
12873 {
12874   // 6g permits using a type guard with unsafe.pointer; we are
12875   // compatible.
12876   Type* expr_type = this->expr_->type();
12877   if (expr_type->is_unsafe_pointer_type())
12878     {
12879       if (this->type_->points_to() == NULL
12880           && (this->type_->integer_type() == NULL
12881               || (this->type_->forwarded()
12882                   != Type::lookup_integer_type("uintptr"))))
12883         this->report_error(_("invalid unsafe.Pointer conversion"));
12884     }
12885   else if (this->type_->is_unsafe_pointer_type())
12886     {
12887       if (expr_type->points_to() == NULL
12888           && (expr_type->integer_type() == NULL
12889               || (expr_type->forwarded()
12890                   != Type::lookup_integer_type("uintptr"))))
12891         this->report_error(_("invalid unsafe.Pointer conversion"));
12892     }
12893   else if (expr_type->interface_type() == NULL)
12894     {
12895       if (!expr_type->is_error() && !this->type_->is_error())
12896         this->report_error(_("type assertion only valid for interface types"));
12897       this->set_is_error();
12898     }
12899   else if (this->type_->interface_type() == NULL)
12900     {
12901       std::string reason;
12902       if (!expr_type->interface_type()->implements_interface(this->type_,
12903                                                              &reason))
12904         {
12905           if (!this->type_->is_error())
12906             {
12907               if (reason.empty())
12908                 this->report_error(_("impossible type assertion: "
12909                                      "type does not implement interface"));
12910               else
12911                 error_at(this->location(),
12912                          ("impossible type assertion: "
12913                           "type does not implement interface (%s)"),
12914                          reason.c_str());
12915             }
12916           this->set_is_error();
12917         }
12918     }
12919 }
12920
12921 // Return a tree for a type guard expression.
12922
12923 tree
12924 Type_guard_expression::do_get_tree(Translate_context* context)
12925 {
12926   Gogo* gogo = context->gogo();
12927   tree expr_tree = this->expr_->get_tree(context);
12928   if (expr_tree == error_mark_node)
12929     return error_mark_node;
12930   Type* expr_type = this->expr_->type();
12931   if ((this->type_->is_unsafe_pointer_type()
12932        && (expr_type->points_to() != NULL
12933            || expr_type->integer_type() != NULL))
12934       || (expr_type->is_unsafe_pointer_type()
12935           && this->type_->points_to() != NULL))
12936     return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
12937                               expr_tree);
12938   else if (expr_type->is_unsafe_pointer_type()
12939            && this->type_->integer_type() != NULL)
12940     return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
12941                               expr_tree);
12942   else if (this->type_->interface_type() != NULL)
12943     return Expression::convert_interface_to_interface(context, this->type_,
12944                                                       this->expr_->type(),
12945                                                       expr_tree, true,
12946                                                       this->location());
12947   else
12948     return Expression::convert_for_assignment(context, this->type_,
12949                                               this->expr_->type(), expr_tree,
12950                                               this->location());
12951 }
12952
12953 // Dump ast representation for a type guard expression.
12954
12955 void
12956 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
12957     const
12958 {
12959   this->expr_->dump_expression(ast_dump_context);
12960   ast_dump_context->ostream() <<  ".";
12961   ast_dump_context->dump_type(this->type_);
12962 }
12963
12964 // Make a type guard expression.
12965
12966 Expression*
12967 Expression::make_type_guard(Expression* expr, Type* type,
12968                             Location location)
12969 {
12970   return new Type_guard_expression(expr, type, location);
12971 }
12972
12973 // Class Heap_composite_expression.
12974
12975 // When you take the address of a composite literal, it is allocated
12976 // on the heap.  This class implements that.
12977
12978 class Heap_composite_expression : public Expression
12979 {
12980  public:
12981   Heap_composite_expression(Expression* expr, Location location)
12982     : Expression(EXPRESSION_HEAP_COMPOSITE, location),
12983       expr_(expr)
12984   { }
12985
12986  protected:
12987   int
12988   do_traverse(Traverse* traverse)
12989   { return Expression::traverse(&this->expr_, traverse); }
12990
12991   Type*
12992   do_type()
12993   { return Type::make_pointer_type(this->expr_->type()); }
12994
12995   void
12996   do_determine_type(const Type_context*)
12997   { this->expr_->determine_type_no_context(); }
12998
12999   Expression*
13000   do_copy()
13001   {
13002     return Expression::make_heap_composite(this->expr_->copy(),
13003                                            this->location());
13004   }
13005
13006   tree
13007   do_get_tree(Translate_context*);
13008
13009   // We only export global objects, and the parser does not generate
13010   // this in global scope.
13011   void
13012   do_export(Export*) const
13013   { go_unreachable(); }
13014
13015   void
13016   do_dump_expression(Ast_dump_context*) const;
13017
13018  private:
13019   // The composite literal which is being put on the heap.
13020   Expression* expr_;
13021 };
13022
13023 // Return a tree which allocates a composite literal on the heap.
13024
13025 tree
13026 Heap_composite_expression::do_get_tree(Translate_context* context)
13027 {
13028   tree expr_tree = this->expr_->get_tree(context);
13029   if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13030     return error_mark_node;
13031   tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13032   go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13033   tree space = context->gogo()->allocate_memory(this->expr_->type(),
13034                                                 expr_size, this->location());
13035   space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13036   space = save_expr(space);
13037   tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13038                                          space);
13039   TREE_THIS_NOTRAP(ref) = 1;
13040   tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13041                     build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13042                     space);
13043   SET_EXPR_LOCATION(ret, this->location().gcc_location());
13044   return ret;
13045 }
13046
13047 // Dump ast representation for a heap composite expression.
13048
13049 void
13050 Heap_composite_expression::do_dump_expression(
13051     Ast_dump_context* ast_dump_context) const
13052 {
13053   ast_dump_context->ostream() << "&(";
13054   ast_dump_context->dump_expression(this->expr_);
13055   ast_dump_context->ostream() << ")";
13056 }
13057
13058 // Allocate a composite literal on the heap.
13059
13060 Expression*
13061 Expression::make_heap_composite(Expression* expr, Location location)
13062 {
13063   return new Heap_composite_expression(expr, location);
13064 }
13065
13066 // Class Receive_expression.
13067
13068 // Return the type of a receive expression.
13069
13070 Type*
13071 Receive_expression::do_type()
13072 {
13073   Channel_type* channel_type = this->channel_->type()->channel_type();
13074   if (channel_type == NULL)
13075     return Type::make_error_type();
13076   return channel_type->element_type();
13077 }
13078
13079 // Check types for a receive expression.
13080
13081 void
13082 Receive_expression::do_check_types(Gogo*)
13083 {
13084   Type* type = this->channel_->type();
13085   if (type->is_error())
13086     {
13087       this->set_is_error();
13088       return;
13089     }
13090   if (type->channel_type() == NULL)
13091     {
13092       this->report_error(_("expected channel"));
13093       return;
13094     }
13095   if (!type->channel_type()->may_receive())
13096     {
13097       this->report_error(_("invalid receive on send-only channel"));
13098       return;
13099     }
13100 }
13101
13102 // Get a tree for a receive expression.
13103
13104 tree
13105 Receive_expression::do_get_tree(Translate_context* context)
13106 {
13107   Location loc = this->location();
13108
13109   Channel_type* channel_type = this->channel_->type()->channel_type();
13110   if (channel_type == NULL)
13111     {
13112       go_assert(this->channel_->type()->is_error());
13113       return error_mark_node;
13114     }
13115
13116   Expression* td = Expression::make_type_descriptor(channel_type, loc);
13117   tree td_tree = td->get_tree(context);
13118
13119   Type* element_type = channel_type->element_type();
13120   Btype* element_type_btype = element_type->get_backend(context->gogo());
13121   tree element_type_tree = type_to_tree(element_type_btype);
13122
13123   tree channel = this->channel_->get_tree(context);
13124   if (element_type_tree == error_mark_node || channel == error_mark_node)
13125     return error_mark_node;
13126
13127   return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13128 }
13129
13130 // Dump ast representation for a receive expression.
13131
13132 void
13133 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13134 {
13135   ast_dump_context->ostream() << " <- " ;
13136   ast_dump_context->dump_expression(channel_);
13137 }
13138
13139 // Make a receive expression.
13140
13141 Receive_expression*
13142 Expression::make_receive(Expression* channel, Location location)
13143 {
13144   return new Receive_expression(channel, location);
13145 }
13146
13147 // An expression which evaluates to a pointer to the type descriptor
13148 // of a type.
13149
13150 class Type_descriptor_expression : public Expression
13151 {
13152  public:
13153   Type_descriptor_expression(Type* type, Location location)
13154     : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13155       type_(type)
13156   { }
13157
13158  protected:
13159   Type*
13160   do_type()
13161   { return Type::make_type_descriptor_ptr_type(); }
13162
13163   void
13164   do_determine_type(const Type_context*)
13165   { }
13166
13167   Expression*
13168   do_copy()
13169   { return this; }
13170
13171   tree
13172   do_get_tree(Translate_context* context)
13173   {
13174     return this->type_->type_descriptor_pointer(context->gogo(),
13175                                                 this->location());
13176   }
13177
13178   void
13179   do_dump_expression(Ast_dump_context*) const;
13180
13181  private:
13182   // The type for which this is the descriptor.
13183   Type* type_;
13184 };
13185
13186 // Dump ast representation for a type descriptor expression.
13187
13188 void
13189 Type_descriptor_expression::do_dump_expression(
13190     Ast_dump_context* ast_dump_context) const
13191 {
13192   ast_dump_context->dump_type(this->type_);
13193 }
13194
13195 // Make a type descriptor expression.
13196
13197 Expression*
13198 Expression::make_type_descriptor(Type* type, Location location)
13199 {
13200   return new Type_descriptor_expression(type, location);
13201 }
13202
13203 // An expression which evaluates to some characteristic of a type.
13204 // This is only used to initialize fields of a type descriptor.  Using
13205 // a new expression class is slightly inefficient but gives us a good
13206 // separation between the frontend and the middle-end with regard to
13207 // how types are laid out.
13208
13209 class Type_info_expression : public Expression
13210 {
13211  public:
13212   Type_info_expression(Type* type, Type_info type_info)
13213     : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13214       type_(type), type_info_(type_info)
13215   { }
13216
13217  protected:
13218   Type*
13219   do_type();
13220
13221   void
13222   do_determine_type(const Type_context*)
13223   { }
13224
13225   Expression*
13226   do_copy()
13227   { return this; }
13228
13229   tree
13230   do_get_tree(Translate_context* context);
13231
13232   void
13233   do_dump_expression(Ast_dump_context*) const;
13234
13235  private:
13236   // The type for which we are getting information.
13237   Type* type_;
13238   // What information we want.
13239   Type_info type_info_;
13240 };
13241
13242 // The type is chosen to match what the type descriptor struct
13243 // expects.
13244
13245 Type*
13246 Type_info_expression::do_type()
13247 {
13248   switch (this->type_info_)
13249     {
13250     case TYPE_INFO_SIZE:
13251       return Type::lookup_integer_type("uintptr");
13252     case TYPE_INFO_ALIGNMENT:
13253     case TYPE_INFO_FIELD_ALIGNMENT:
13254       return Type::lookup_integer_type("uint8");
13255     default:
13256       go_unreachable();
13257     }
13258 }
13259
13260 // Return type information in GENERIC.
13261
13262 tree
13263 Type_info_expression::do_get_tree(Translate_context* context)
13264 {
13265   Btype* btype = this->type_->get_backend(context->gogo());
13266   Gogo* gogo = context->gogo();
13267   size_t val;
13268   switch (this->type_info_)
13269     {
13270     case TYPE_INFO_SIZE:
13271       val = gogo->backend()->type_size(btype);
13272       break;
13273     case TYPE_INFO_ALIGNMENT:
13274       val = gogo->backend()->type_alignment(btype);
13275       break;
13276     case TYPE_INFO_FIELD_ALIGNMENT:
13277       val = gogo->backend()->type_field_alignment(btype);
13278       break;
13279     default:
13280       go_unreachable();
13281     }
13282   tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13283   go_assert(val_type_tree != error_mark_node);
13284   return build_int_cstu(val_type_tree, val);
13285 }
13286
13287 // Dump ast representation for a type info expression.
13288
13289 void
13290 Type_info_expression::do_dump_expression(
13291     Ast_dump_context* ast_dump_context) const
13292 {
13293   ast_dump_context->ostream() << "typeinfo(";
13294   ast_dump_context->dump_type(this->type_);
13295   ast_dump_context->ostream() << ",";
13296   ast_dump_context->ostream() << 
13297     (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment" 
13298     : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13299     : this->type_info_ == TYPE_INFO_SIZE ? "size "
13300     : "unknown");
13301   ast_dump_context->ostream() << ")";
13302 }
13303
13304 // Make a type info expression.
13305
13306 Expression*
13307 Expression::make_type_info(Type* type, Type_info type_info)
13308 {
13309   return new Type_info_expression(type, type_info);
13310 }
13311
13312 // An expression which evaluates to the offset of a field within a
13313 // struct.  This, like Type_info_expression, q.v., is only used to
13314 // initialize fields of a type descriptor.
13315
13316 class Struct_field_offset_expression : public Expression
13317 {
13318  public:
13319   Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13320     : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13321                  Linemap::predeclared_location()),
13322       type_(type), field_(field)
13323   { }
13324
13325  protected:
13326   Type*
13327   do_type()
13328   { return Type::lookup_integer_type("uintptr"); }
13329
13330   void
13331   do_determine_type(const Type_context*)
13332   { }
13333
13334   Expression*
13335   do_copy()
13336   { return this; }
13337
13338   tree
13339   do_get_tree(Translate_context* context);
13340
13341   void
13342   do_dump_expression(Ast_dump_context*) const;
13343   
13344  private:
13345   // The type of the struct.
13346   Struct_type* type_;
13347   // The field.
13348   const Struct_field* field_;
13349 };
13350
13351 // Return a struct field offset in GENERIC.
13352
13353 tree
13354 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13355 {
13356   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13357   if (type_tree == error_mark_node)
13358     return error_mark_node;
13359
13360   tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13361   go_assert(val_type_tree != error_mark_node);
13362
13363   const Struct_field_list* fields = this->type_->fields();
13364   tree struct_field_tree = TYPE_FIELDS(type_tree);
13365   Struct_field_list::const_iterator p;
13366   for (p = fields->begin();
13367        p != fields->end();
13368        ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13369     {
13370       go_assert(struct_field_tree != NULL_TREE);
13371       if (&*p == this->field_)
13372         break;
13373     }
13374   go_assert(&*p == this->field_);
13375
13376   return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13377                           byte_position(struct_field_tree));
13378 }
13379
13380 // Dump ast representation for a struct field offset expression.
13381
13382 void
13383 Struct_field_offset_expression::do_dump_expression(
13384     Ast_dump_context* ast_dump_context) const
13385 {
13386   ast_dump_context->ostream() <<  "unsafe.Offsetof(";
13387   ast_dump_context->dump_type(this->type_);
13388   ast_dump_context->ostream() << '.';
13389   ast_dump_context->ostream() <<
13390     Gogo::message_name(this->field_->field_name());
13391   ast_dump_context->ostream() << ")";
13392 }
13393
13394 // Make an expression for a struct field offset.
13395
13396 Expression*
13397 Expression::make_struct_field_offset(Struct_type* type,
13398                                      const Struct_field* field)
13399 {
13400   return new Struct_field_offset_expression(type, field);
13401 }
13402
13403 // An expression which evaluates to a pointer to the map descriptor of
13404 // a map type.
13405
13406 class Map_descriptor_expression : public Expression
13407 {
13408  public:
13409   Map_descriptor_expression(Map_type* type, Location location)
13410     : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13411       type_(type)
13412   { }
13413
13414  protected:
13415   Type*
13416   do_type()
13417   { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13418
13419   void
13420   do_determine_type(const Type_context*)
13421   { }
13422
13423   Expression*
13424   do_copy()
13425   { return this; }
13426
13427   tree
13428   do_get_tree(Translate_context* context)
13429   {
13430     return this->type_->map_descriptor_pointer(context->gogo(),
13431                                                this->location());
13432   }
13433
13434   void
13435   do_dump_expression(Ast_dump_context*) const;
13436  
13437  private:
13438   // The type for which this is the descriptor.
13439   Map_type* type_;
13440 };
13441
13442 // Dump ast representation for a map descriptor expression.
13443
13444 void
13445 Map_descriptor_expression::do_dump_expression(
13446     Ast_dump_context* ast_dump_context) const
13447 {
13448   ast_dump_context->ostream() << "map_descriptor(";
13449   ast_dump_context->dump_type(this->type_);
13450   ast_dump_context->ostream() << ")";
13451 }
13452
13453 // Make a map descriptor expression.
13454
13455 Expression*
13456 Expression::make_map_descriptor(Map_type* type, Location location)
13457 {
13458   return new Map_descriptor_expression(type, location);
13459 }
13460
13461 // An expression which evaluates to the address of an unnamed label.
13462
13463 class Label_addr_expression : public Expression
13464 {
13465  public:
13466   Label_addr_expression(Label* label, Location location)
13467     : Expression(EXPRESSION_LABEL_ADDR, location),
13468       label_(label)
13469   { }
13470
13471  protected:
13472   Type*
13473   do_type()
13474   { return Type::make_pointer_type(Type::make_void_type()); }
13475
13476   void
13477   do_determine_type(const Type_context*)
13478   { }
13479
13480   Expression*
13481   do_copy()
13482   { return new Label_addr_expression(this->label_, this->location()); }
13483
13484   tree
13485   do_get_tree(Translate_context* context)
13486   {
13487     return expr_to_tree(this->label_->get_addr(context, this->location()));
13488   }
13489
13490   void
13491   do_dump_expression(Ast_dump_context* ast_dump_context) const
13492   { ast_dump_context->ostream() << this->label_->name(); }
13493   
13494  private:
13495   // The label whose address we are taking.
13496   Label* label_;
13497 };
13498
13499 // Make an expression for the address of an unnamed label.
13500
13501 Expression*
13502 Expression::make_label_addr(Label* label, Location location)
13503 {
13504   return new Label_addr_expression(label, location);
13505 }
13506
13507 // Import an expression.  This comes at the end in order to see the
13508 // various class definitions.
13509
13510 Expression*
13511 Expression::import_expression(Import* imp)
13512 {
13513   int c = imp->peek_char();
13514   if (imp->match_c_string("- ")
13515       || imp->match_c_string("! ")
13516       || imp->match_c_string("^ "))
13517     return Unary_expression::do_import(imp);
13518   else if (c == '(')
13519     return Binary_expression::do_import(imp);
13520   else if (imp->match_c_string("true")
13521            || imp->match_c_string("false"))
13522     return Boolean_expression::do_import(imp);
13523   else if (c == '"')
13524     return String_expression::do_import(imp);
13525   else if (c == '-' || (c >= '0' && c <= '9'))
13526     {
13527       // This handles integers, floats and complex constants.
13528       return Integer_expression::do_import(imp);
13529     }
13530   else if (imp->match_c_string("nil"))
13531     return Nil_expression::do_import(imp);
13532   else if (imp->match_c_string("convert"))
13533     return Type_conversion_expression::do_import(imp);
13534   else
13535     {
13536       error_at(imp->location(), "import error: expected expression");
13537       return Expression::make_error(imp->location());
13538     }
13539 }
13540
13541 // Class Expression_list.
13542
13543 // Traverse the list.
13544
13545 int
13546 Expression_list::traverse(Traverse* traverse)
13547 {
13548   for (Expression_list::iterator p = this->begin();
13549        p != this->end();
13550        ++p)
13551     {
13552       if (*p != NULL)
13553         {
13554           if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13555             return TRAVERSE_EXIT;
13556         }
13557     }
13558   return TRAVERSE_CONTINUE;
13559 }
13560
13561 // Copy the list.
13562
13563 Expression_list*
13564 Expression_list::copy()
13565 {
13566   Expression_list* ret = new Expression_list();
13567   for (Expression_list::iterator p = this->begin();
13568        p != this->end();
13569        ++p)
13570     {
13571       if (*p == NULL)
13572         ret->push_back(NULL);
13573       else
13574         ret->push_back((*p)->copy());
13575     }
13576   return ret;
13577 }
13578
13579 // Return whether an expression list has an error expression.
13580
13581 bool
13582 Expression_list::contains_error() const
13583 {
13584   for (Expression_list::const_iterator p = this->begin();
13585        p != this->end();
13586        ++p)
13587     if (*p != NULL && (*p)->is_error_expression())
13588       return true;
13589   return false;
13590 }
13591
13592 // Class Numeric_constant.
13593
13594 // Destructor.
13595
13596 Numeric_constant::~Numeric_constant()
13597 {
13598   this->clear();
13599 }
13600
13601 // Copy constructor.
13602
13603 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13604   : classification_(a.classification_), type_(a.type_)
13605 {
13606   switch (a.classification_)
13607     {
13608     case NC_INVALID:
13609       break;
13610     case NC_INT:
13611     case NC_RUNE:
13612       mpz_init_set(this->u_.int_val, a.u_.int_val);
13613       break;
13614     case NC_FLOAT:
13615       mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13616       break;
13617     case NC_COMPLEX:
13618       mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13619                     GMP_RNDN);
13620       mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13621                     GMP_RNDN);
13622       break;
13623     default:
13624       go_unreachable();
13625     }
13626 }
13627
13628 // Assignment operator.
13629
13630 Numeric_constant&
13631 Numeric_constant::operator=(const Numeric_constant& a)
13632 {
13633   this->clear();
13634   this->classification_ = a.classification_;
13635   this->type_ = a.type_;
13636   switch (a.classification_)
13637     {
13638     case NC_INVALID:
13639       break;
13640     case NC_INT:
13641     case NC_RUNE:
13642       mpz_init_set(this->u_.int_val, a.u_.int_val);
13643       break;
13644     case NC_FLOAT:
13645       mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13646       break;
13647     case NC_COMPLEX:
13648       mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13649                     GMP_RNDN);
13650       mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13651                     GMP_RNDN);
13652       break;
13653     default:
13654       go_unreachable();
13655     }
13656   return *this;
13657 }
13658
13659 // Clear the contents.
13660
13661 void
13662 Numeric_constant::clear()
13663 {
13664   switch (this->classification_)
13665     {
13666     case NC_INVALID:
13667       break;
13668     case NC_INT:
13669     case NC_RUNE:
13670       mpz_clear(this->u_.int_val);
13671       break;
13672     case NC_FLOAT:
13673       mpfr_clear(this->u_.float_val);
13674       break;
13675     case NC_COMPLEX:
13676       mpfr_clear(this->u_.complex_val.real);
13677       mpfr_clear(this->u_.complex_val.imag);
13678       break;
13679     default:
13680       go_unreachable();
13681     }
13682   this->classification_ = NC_INVALID;
13683 }
13684
13685 // Set to an unsigned long value.
13686
13687 void
13688 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13689 {
13690   this->clear();
13691   this->classification_ = NC_INT;
13692   this->type_ = type;
13693   mpz_init_set_ui(this->u_.int_val, val);
13694 }
13695
13696 // Set to an integer value.
13697
13698 void
13699 Numeric_constant::set_int(Type* type, const mpz_t val)
13700 {
13701   this->clear();
13702   this->classification_ = NC_INT;
13703   this->type_ = type;
13704   mpz_init_set(this->u_.int_val, val);
13705 }
13706
13707 // Set to a rune value.
13708
13709 void
13710 Numeric_constant::set_rune(Type* type, const mpz_t val)
13711 {
13712   this->clear();
13713   this->classification_ = NC_RUNE;
13714   this->type_ = type;
13715   mpz_init_set(this->u_.int_val, val);
13716 }
13717
13718 // Set to a floating point value.
13719
13720 void
13721 Numeric_constant::set_float(Type* type, const mpfr_t val)
13722 {
13723   this->clear();
13724   this->classification_ = NC_FLOAT;
13725   this->type_ = type;
13726   // Numeric constants do not have negative zero values, so remove
13727   // them here.  They also don't have infinity or NaN values, but we
13728   // should never see them here.
13729   if (mpfr_zero_p(val))
13730     mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
13731   else
13732     mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13733 }
13734
13735 // Set to a complex value.
13736
13737 void
13738 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13739 {
13740   this->clear();
13741   this->classification_ = NC_COMPLEX;
13742   this->type_ = type;
13743   mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13744   mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13745 }
13746
13747 // Get an int value.
13748
13749 void
13750 Numeric_constant::get_int(mpz_t* val) const
13751 {
13752   go_assert(this->is_int());
13753   mpz_init_set(*val, this->u_.int_val);
13754 }
13755
13756 // Get a rune value.
13757
13758 void
13759 Numeric_constant::get_rune(mpz_t* val) const
13760 {
13761   go_assert(this->is_rune());
13762   mpz_init_set(*val, this->u_.int_val);
13763 }
13764
13765 // Get a floating point value.
13766
13767 void
13768 Numeric_constant::get_float(mpfr_t* val) const
13769 {
13770   go_assert(this->is_float());
13771   mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13772 }
13773
13774 // Get a complex value.
13775
13776 void
13777 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13778 {
13779   go_assert(this->is_complex());
13780   mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13781   mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13782 }
13783
13784 // Express value as unsigned long if possible.
13785
13786 Numeric_constant::To_unsigned_long
13787 Numeric_constant::to_unsigned_long(unsigned long* val) const
13788 {
13789   switch (this->classification_)
13790     {
13791     case NC_INT:
13792     case NC_RUNE:
13793       return this->mpz_to_unsigned_long(this->u_.int_val, val);
13794     case NC_FLOAT:
13795       return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13796     case NC_COMPLEX:
13797       if (!mpfr_zero_p(this->u_.complex_val.imag))
13798         return NC_UL_NOTINT;
13799       return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13800     default:
13801       go_unreachable();
13802     }
13803 }
13804
13805 // Express integer value as unsigned long if possible.
13806
13807 Numeric_constant::To_unsigned_long
13808 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13809                                        unsigned long *val) const
13810 {
13811   if (mpz_sgn(ival) < 0)
13812     return NC_UL_NEGATIVE;
13813   unsigned long ui = mpz_get_ui(ival);
13814   if (mpz_cmp_ui(ival, ui) != 0)
13815     return NC_UL_BIG;
13816   *val = ui;
13817   return NC_UL_VALID;
13818 }
13819
13820 // Express floating point value as unsigned long if possible.
13821
13822 Numeric_constant::To_unsigned_long
13823 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13824                                         unsigned long *val) const
13825 {
13826   if (!mpfr_integer_p(fval))
13827     return NC_UL_NOTINT;
13828   mpz_t ival;
13829   mpz_init(ival);
13830   mpfr_get_z(ival, fval, GMP_RNDN);
13831   To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13832   mpz_clear(ival);
13833   return ret;
13834 }
13835
13836 // Convert value to integer if possible.
13837
13838 bool
13839 Numeric_constant::to_int(mpz_t* val) const
13840 {
13841   switch (this->classification_)
13842     {
13843     case NC_INT:
13844     case NC_RUNE:
13845       mpz_init_set(*val, this->u_.int_val);
13846       return true;
13847     case NC_FLOAT:
13848       if (!mpfr_integer_p(this->u_.float_val))
13849         return false;
13850       mpz_init(*val);
13851       mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13852       return true;
13853     case NC_COMPLEX:
13854       if (!mpfr_zero_p(this->u_.complex_val.imag)
13855           || !mpfr_integer_p(this->u_.complex_val.real))
13856         return false;
13857       mpz_init(*val);
13858       mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13859       return true;
13860     default:
13861       go_unreachable();
13862     }
13863 }
13864
13865 // Convert value to floating point if possible.
13866
13867 bool
13868 Numeric_constant::to_float(mpfr_t* val) const
13869 {
13870   switch (this->classification_)
13871     {
13872     case NC_INT:
13873     case NC_RUNE:
13874       mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13875       return true;
13876     case NC_FLOAT:
13877       mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13878       return true;
13879     case NC_COMPLEX:
13880       if (!mpfr_zero_p(this->u_.complex_val.imag))
13881         return false;
13882       mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13883       return true;
13884     default:
13885       go_unreachable();
13886     }
13887 }
13888
13889 // Convert value to complex.
13890
13891 bool
13892 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13893 {
13894   switch (this->classification_)
13895     {
13896     case NC_INT:
13897     case NC_RUNE:
13898       mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13899       mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13900       return true;
13901     case NC_FLOAT:
13902       mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13903       mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13904       return true;
13905     case NC_COMPLEX:
13906       mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13907       mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
13908       return true;
13909     default:
13910       go_unreachable();
13911     }
13912 }
13913
13914 // Get the type.
13915
13916 Type*
13917 Numeric_constant::type() const
13918 {
13919   if (this->type_ != NULL)
13920     return this->type_;
13921   switch (this->classification_)
13922     {
13923     case NC_INT:
13924       return Type::make_abstract_integer_type();
13925     case NC_RUNE:
13926       return Type::make_abstract_character_type();
13927     case NC_FLOAT:
13928       return Type::make_abstract_float_type();
13929     case NC_COMPLEX:
13930       return Type::make_abstract_complex_type();
13931     default:
13932       go_unreachable();
13933     }
13934 }
13935
13936 // If the constant can be expressed in TYPE, then set the type of the
13937 // constant to TYPE and return true.  Otherwise return false, and, if
13938 // ISSUE_ERROR is true, report an appropriate error message.
13939
13940 bool
13941 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
13942 {
13943   bool ret;
13944   if (type == NULL)
13945     ret = true;
13946   else if (type->integer_type() != NULL)
13947     ret = this->check_int_type(type->integer_type(), issue_error, loc);
13948   else if (type->float_type() != NULL)
13949     ret = this->check_float_type(type->float_type(), issue_error, loc);
13950   else if (type->complex_type() != NULL)
13951     ret = this->check_complex_type(type->complex_type(), issue_error, loc);
13952   else
13953     go_unreachable();
13954   if (ret)
13955     this->type_ = type;
13956   return ret;
13957 }
13958
13959 // Check whether the constant can be expressed in an integer type.
13960
13961 bool
13962 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
13963                                  Location location) const
13964 {
13965   mpz_t val;
13966   switch (this->classification_)
13967     {
13968     case NC_INT:
13969     case NC_RUNE:
13970       mpz_init_set(val, this->u_.int_val);
13971       break;
13972
13973     case NC_FLOAT:
13974       if (!mpfr_integer_p(this->u_.float_val))
13975         {
13976           if (issue_error)
13977             error_at(location, "floating point constant truncated to integer");
13978           return false;
13979         }
13980       mpz_init(val);
13981       mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
13982       break;
13983
13984     case NC_COMPLEX:
13985       if (!mpfr_integer_p(this->u_.complex_val.real)
13986           || !mpfr_zero_p(this->u_.complex_val.imag))
13987         {
13988           if (issue_error)
13989             error_at(location, "complex constant truncated to integer");
13990           return false;
13991         }
13992       mpz_init(val);
13993       mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
13994       break;
13995
13996     default:
13997       go_unreachable();
13998     }
13999
14000   bool ret;
14001   if (type->is_abstract())
14002     ret = true;
14003   else
14004     {
14005       int bits = mpz_sizeinbase(val, 2);
14006       if (type->is_unsigned())
14007         {
14008           // For an unsigned type we can only accept a nonnegative
14009           // number, and we must be able to represents at least BITS.
14010           ret = mpz_sgn(val) >= 0 && bits <= type->bits();
14011         }
14012       else
14013         {
14014           // For a signed type we need an extra bit to indicate the
14015           // sign.  We have to handle the most negative integer
14016           // specially.
14017           ret = (bits + 1 <= type->bits()
14018                  || (bits <= type->bits()
14019                      && mpz_sgn(val) < 0
14020                      && (mpz_scan1(val, 0)
14021                          == static_cast<unsigned long>(type->bits() - 1))
14022                      && mpz_scan0(val, type->bits()) == ULONG_MAX));
14023         }
14024     }
14025
14026   if (!ret && issue_error)
14027     error_at(location, "integer constant overflow");
14028
14029   return ret;
14030 }
14031
14032 // Check whether the constant can be expressed in a floating point
14033 // type.
14034
14035 bool
14036 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
14037                                    Location location) const
14038 {
14039   mpfr_t val;
14040   switch (this->classification_)
14041     {
14042     case NC_INT:
14043     case NC_RUNE:
14044       mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
14045       break;
14046
14047     case NC_FLOAT:
14048       mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
14049       break;
14050
14051     case NC_COMPLEX:
14052       if (!mpfr_zero_p(this->u_.complex_val.imag))
14053         {
14054           if (issue_error)
14055             error_at(location, "complex constant truncated to float");
14056           return false;
14057         }
14058       mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
14059       break;
14060
14061     default:
14062       go_unreachable();
14063     }
14064
14065   bool ret;
14066   if (type->is_abstract())
14067     ret = true;
14068   else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
14069     {
14070       // A NaN or Infinity always fits in the range of the type.
14071       ret = true;
14072     }
14073   else
14074     {
14075       mp_exp_t exp = mpfr_get_exp(val);
14076       mp_exp_t max_exp;
14077       switch (type->bits())
14078         {
14079         case 32:
14080           max_exp = 128;
14081           break;
14082         case 64:
14083           max_exp = 1024;
14084           break;
14085         default:
14086           go_unreachable();
14087         }
14088
14089       ret = exp <= max_exp;
14090     }
14091
14092   mpfr_clear(val);
14093
14094   if (!ret && issue_error)
14095     error_at(location, "floating point constant overflow");
14096
14097   return ret;
14098
14099
14100 // Check whether the constant can be expressed in a complex type.
14101
14102 bool
14103 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
14104                                      Location location) const
14105 {
14106   if (type->is_abstract())
14107     return true;
14108
14109   mp_exp_t max_exp;
14110   switch (type->bits())
14111     {
14112     case 64:
14113       max_exp = 128;
14114       break;
14115     case 128:
14116       max_exp = 1024;
14117       break;
14118     default:
14119       go_unreachable();
14120     }
14121
14122   mpfr_t real;
14123   switch (this->classification_)
14124     {
14125     case NC_INT:
14126     case NC_RUNE:
14127       mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
14128       break;
14129
14130     case NC_FLOAT:
14131       mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
14132       break;
14133
14134     case NC_COMPLEX:
14135       if (!mpfr_nan_p(this->u_.complex_val.imag)
14136           && !mpfr_inf_p(this->u_.complex_val.imag)
14137           && !mpfr_zero_p(this->u_.complex_val.imag))
14138         {
14139           if (mpfr_get_exp(this->u_.complex_val.imag) > max_exp)
14140             {
14141               if (issue_error)
14142                 error_at(location, "complex imaginary part overflow");
14143               return false;
14144             }
14145         }
14146       mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
14147       break;
14148
14149     default:
14150       go_unreachable();
14151     }
14152
14153   bool ret;
14154   if (mpfr_nan_p(real) || mpfr_inf_p(real) || mpfr_zero_p(real))
14155     ret = true;
14156   else
14157     ret = mpfr_get_exp(real) <= max_exp;
14158
14159   mpfr_clear(real);
14160
14161   if (!ret && issue_error)
14162     error_at(location, "complex real part overflow");
14163
14164   return ret;
14165 }
14166
14167 // Return an Expression for this value.
14168
14169 Expression*
14170 Numeric_constant::expression(Location loc) const
14171 {
14172   switch (this->classification_)
14173     {
14174     case NC_INT:
14175       return Expression::make_integer(&this->u_.int_val, this->type_, loc);
14176     case NC_RUNE:
14177       return Expression::make_character(&this->u_.int_val, this->type_, loc);
14178     case NC_FLOAT:
14179       return Expression::make_float(&this->u_.float_val, this->type_, loc);
14180     case NC_COMPLEX:
14181       return Expression::make_complex(&this->u_.complex_val.real,
14182                                       &this->u_.complex_val.imag,
14183                                       this->type_, loc);
14184     default:
14185       go_unreachable();
14186     }
14187 }