OSDN Git Service

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