OSDN Git Service

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