OSDN Git Service

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