OSDN Git Service

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