OSDN Git Service

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