OSDN Git Service

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