OSDN Git Service

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