OSDN Git Service

compiler: reject NOT operator on integer types.
[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 <algorithm>
10
11 #include <gmp.h>
12
13 #ifndef ENABLE_BUILD_WITH_CXX
14 extern "C"
15 {
16 #endif
17
18 #include "toplev.h"
19 #include "intl.h"
20 #include "tree.h"
21 #include "gimple.h"
22 #include "tree-iterator.h"
23 #include "convert.h"
24 #include "real.h"
25 #include "realmpfr.h"
26
27 #ifndef ENABLE_BUILD_WITH_CXX
28 }
29 #endif
30
31 #include "go-c.h"
32 #include "gogo.h"
33 #include "types.h"
34 #include "export.h"
35 #include "import.h"
36 #include "statements.h"
37 #include "lex.h"
38 #include "runtime.h"
39 #include "backend.h"
40 #include "expressions.h"
41 #include "ast-dump.h"
42
43 // Class Expression.
44
45 Expression::Expression(Expression_classification classification,
46                        Location location)
47   : classification_(classification), location_(location)
48 {
49 }
50
51 Expression::~Expression()
52 {
53 }
54
55 // Traverse the expressions.
56
57 int
58 Expression::traverse(Expression** pexpr, Traverse* traverse)
59 {
60   Expression* expr = *pexpr;
61   if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
62     {
63       int t = traverse->expression(pexpr);
64       if (t == TRAVERSE_EXIT)
65         return TRAVERSE_EXIT;
66       else if (t == TRAVERSE_SKIP_COMPONENTS)
67         return TRAVERSE_CONTINUE;
68     }
69   return expr->do_traverse(traverse);
70 }
71
72 // Traverse subexpressions of this expression.
73
74 int
75 Expression::traverse_subexpressions(Traverse* traverse)
76 {
77   return this->do_traverse(traverse);
78 }
79
80 // Default implementation for do_traverse for child classes.
81
82 int
83 Expression::do_traverse(Traverse*)
84 {
85   return TRAVERSE_CONTINUE;
86 }
87
88 // This virtual function is called by the parser if the value of this
89 // expression is being discarded.  By default, we give an error.
90 // Expressions with side effects override.
91
92 void
93 Expression::do_discarding_value()
94 {
95   this->unused_value_error();
96 }
97
98 // This virtual function is called to export expressions.  This will
99 // only be used by expressions which may be constant.
100
101 void
102 Expression::do_export(Export*) const
103 {
104   go_unreachable();
105 }
106
107 // Give an error saying that the value of the expression is not used.
108
109 void
110 Expression::unused_value_error()
111 {
112   error_at(this->location(), "value computed is not used");
113 }
114
115 // Note that this expression is an error.  This is called by children
116 // when they discover an error.
117
118 void
119 Expression::set_is_error()
120 {
121   this->classification_ = EXPRESSION_ERROR;
122 }
123
124 // For children to call to report an error conveniently.
125
126 void
127 Expression::report_error(const char* msg)
128 {
129   error_at(this->location_, "%s", msg);
130   this->set_is_error();
131 }
132
133 // Set types of variables and constants.  This is implemented by the
134 // child class.
135
136 void
137 Expression::determine_type(const Type_context* context)
138 {
139   this->do_determine_type(context);
140 }
141
142 // Set types when there is no context.
143
144 void
145 Expression::determine_type_no_context()
146 {
147   Type_context context;
148   this->do_determine_type(&context);
149 }
150
151 // Return a tree handling any conversions which must be done during
152 // assignment.
153
154 tree
155 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
156                                    Type* rhs_type, tree rhs_tree,
157                                    Location location)
158 {
159   if (lhs_type->is_error() || rhs_type->is_error())
160     return error_mark_node;
161
162   if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
163     return error_mark_node;
164
165   Gogo* gogo = context->gogo();
166
167   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
168   if (lhs_type_tree == error_mark_node)
169     return error_mark_node;
170
171   if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
172     {
173       if (rhs_type->interface_type() == NULL)
174         return Expression::convert_type_to_interface(context, lhs_type,
175                                                      rhs_type, rhs_tree,
176                                                      location);
177       else
178         return Expression::convert_interface_to_interface(context, lhs_type,
179                                                           rhs_type, rhs_tree,
180                                                           false, location);
181     }
182   else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
183     return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
184                                                  rhs_tree, location);
185   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
186     {
187       // Assigning nil to an open array.
188       go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
189
190       VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
191
192       constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
193       tree field = TYPE_FIELDS(lhs_type_tree);
194       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
195                         "__values") == 0);
196       elt->index = field;
197       elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
198
199       elt = VEC_quick_push(constructor_elt, init, NULL);
200       field = DECL_CHAIN(field);
201       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
202                         "__count") == 0);
203       elt->index = field;
204       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
205
206       elt = VEC_quick_push(constructor_elt, init, NULL);
207       field = DECL_CHAIN(field);
208       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
209                         "__capacity") == 0);
210       elt->index = field;
211       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
212
213       tree val = build_constructor(lhs_type_tree, init);
214       TREE_CONSTANT(val) = 1;
215
216       return val;
217     }
218   else if (rhs_type->is_nil_type())
219     {
220       // The left hand side should be a pointer type at the tree
221       // level.
222       go_assert(POINTER_TYPE_P(lhs_type_tree));
223       return fold_convert(lhs_type_tree, null_pointer_node);
224     }
225   else if (lhs_type_tree == TREE_TYPE(rhs_tree))
226     {
227       // No conversion is needed.
228       return rhs_tree;
229     }
230   else if (POINTER_TYPE_P(lhs_type_tree)
231            || INTEGRAL_TYPE_P(lhs_type_tree)
232            || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
233            || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
234     return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
235   else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
236             && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
237            || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
238                && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
239     {
240       // Avoid confusion from zero sized variables which may be
241       // represented as non-zero-sized.
242       if (int_size_in_bytes(lhs_type_tree) == 0
243           || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
244         return rhs_tree;
245
246       // This conversion must be permitted by Go, or we wouldn't have
247       // gotten here.
248       go_assert(int_size_in_bytes(lhs_type_tree)
249                 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
250       return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
251                              lhs_type_tree, rhs_tree);
252     }
253   else
254     {
255       go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
256       return rhs_tree;
257     }
258 }
259
260 // Return a tree for a conversion from a non-interface type to an
261 // interface type.
262
263 tree
264 Expression::convert_type_to_interface(Translate_context* context,
265                                       Type* lhs_type, Type* rhs_type,
266                                       tree rhs_tree, Location location)
267 {
268   Gogo* gogo = context->gogo();
269   Interface_type* lhs_interface_type = lhs_type->interface_type();
270   bool lhs_is_empty = lhs_interface_type->is_empty();
271
272   // Since RHS_TYPE is a static type, we can create the interface
273   // method table at compile time.
274
275   // When setting an interface to nil, we just set both fields to
276   // NULL.
277   if (rhs_type->is_nil_type())
278     {
279       Btype* lhs_btype = lhs_type->get_backend(gogo);
280       return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
281     }
282
283   // This should have been checked already.
284   go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
285
286   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
287   if (lhs_type_tree == error_mark_node)
288     return error_mark_node;
289
290   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
291   // then the first field is the type descriptor for RHS_TYPE.
292   // Otherwise it is the interface method table for RHS_TYPE.
293   tree first_field_value;
294   if (lhs_is_empty)
295     first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
296   else
297     {
298       // Build the interface method table for this interface and this
299       // object type: a list of function pointers for each interface
300       // method.
301       Named_type* rhs_named_type = rhs_type->named_type();
302       bool is_pointer = false;
303       if (rhs_named_type == NULL)
304         {
305           rhs_named_type = rhs_type->deref()->named_type();
306           is_pointer = true;
307         }
308       tree method_table;
309       if (rhs_named_type == NULL)
310         method_table = null_pointer_node;
311       else
312         method_table =
313           rhs_named_type->interface_method_table(gogo, lhs_interface_type,
314                                                  is_pointer);
315       first_field_value = fold_convert_loc(location.gcc_location(),
316                                            const_ptr_type_node, method_table);
317     }
318   if (first_field_value == error_mark_node)
319     return error_mark_node;
320
321   // Start building a constructor for the value we will return.
322
323   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
324
325   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
326   tree field = TYPE_FIELDS(lhs_type_tree);
327   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
328                     (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
329   elt->index = field;
330   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
331                                 first_field_value);
332
333   elt = VEC_quick_push(constructor_elt, init, NULL);
334   field = DECL_CHAIN(field);
335   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
336   elt->index = field;
337
338   if (rhs_type->points_to() != NULL)
339     {
340       //  We are assigning a pointer to the interface; the interface
341       // holds the pointer itself.
342       elt->value = rhs_tree;
343       return build_constructor(lhs_type_tree, init);
344     }
345
346   // We are assigning a non-pointer value to the interface; the
347   // interface gets a copy of the value in the heap.
348
349   tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
350
351   tree space = gogo->allocate_memory(rhs_type, object_size, location);
352   space = fold_convert_loc(location.gcc_location(),
353                            build_pointer_type(TREE_TYPE(rhs_tree)), space);
354   space = save_expr(space);
355
356   tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
357   TREE_THIS_NOTRAP(ref) = 1;
358   tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
359                              void_type_node, ref, rhs_tree);
360
361   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
362                                 space);
363
364   return build2(COMPOUND_EXPR, lhs_type_tree, set,
365                 build_constructor(lhs_type_tree, init));
366 }
367
368 // Return a tree for the type descriptor of RHS_TREE, which has
369 // interface type RHS_TYPE.  If RHS_TREE is nil the result will be
370 // NULL.
371
372 tree
373 Expression::get_interface_type_descriptor(Translate_context*,
374                                           Type* rhs_type, tree rhs_tree,
375                                           Location location)
376 {
377   tree rhs_type_tree = TREE_TYPE(rhs_tree);
378   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
379   tree rhs_field = TYPE_FIELDS(rhs_type_tree);
380   tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
381                   NULL_TREE);
382   if (rhs_type->interface_type()->is_empty())
383     {
384       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
385                         "__type_descriptor") == 0);
386       return v;
387     }
388
389   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
390              == 0);
391   go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
392   v = save_expr(v);
393   tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
394   go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
395   tree f = TYPE_FIELDS(TREE_TYPE(v1));
396   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
397              == 0);
398   v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
399
400   tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
401                             v, fold_convert_loc(location.gcc_location(),
402                                                 TREE_TYPE(v),
403                                                 null_pointer_node));
404   tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
405                             null_pointer_node);
406   return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
407                          eq, n, v1);
408 }
409
410 // Return a tree for the conversion of an interface type to an
411 // interface type.
412
413 tree
414 Expression::convert_interface_to_interface(Translate_context* context,
415                                            Type *lhs_type, Type *rhs_type,
416                                            tree rhs_tree, bool for_type_guard,
417                                            Location location)
418 {
419   Gogo* gogo = context->gogo();
420   Interface_type* lhs_interface_type = lhs_type->interface_type();
421   bool lhs_is_empty = lhs_interface_type->is_empty();
422
423   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
424   if (lhs_type_tree == error_mark_node)
425     return error_mark_node;
426
427   // In the general case this requires runtime examination of the type
428   // method table to match it up with the interface methods.
429
430   // FIXME: If all of the methods in the right hand side interface
431   // also appear in the left hand side interface, then we don't need
432   // to do a runtime check, although we still need to build a new
433   // method table.
434
435   // Get the type descriptor for the right hand side.  This will be
436   // NULL for a nil interface.
437
438   if (!DECL_P(rhs_tree))
439     rhs_tree = save_expr(rhs_tree);
440
441   tree rhs_type_descriptor =
442     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
443                                               location);
444
445   // The result is going to be a two element constructor.
446
447   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
448
449   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
450   tree field = TYPE_FIELDS(lhs_type_tree);
451   elt->index = field;
452
453   if (for_type_guard)
454     {
455       // A type assertion fails when converting a nil interface.
456       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
457                                                                    location);
458       static tree assert_interface_decl;
459       tree call = Gogo::call_builtin(&assert_interface_decl,
460                                      location,
461                                      "__go_assert_interface",
462                                      2,
463                                      ptr_type_node,
464                                      TREE_TYPE(lhs_type_descriptor),
465                                      lhs_type_descriptor,
466                                      TREE_TYPE(rhs_type_descriptor),
467                                      rhs_type_descriptor);
468       if (call == error_mark_node)
469         return error_mark_node;
470       // This will panic if the interface conversion fails.
471       TREE_NOTHROW(assert_interface_decl) = 0;
472       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
473                                     call);
474     }
475   else if (lhs_is_empty)
476     {
477       // A convertion to an empty interface always succeeds, and the
478       // first field is just the type descriptor of the object.
479       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
480                         "__type_descriptor") == 0);
481       elt->value = fold_convert_loc(location.gcc_location(),
482                                     TREE_TYPE(field), rhs_type_descriptor);
483     }
484   else
485     {
486       // A conversion to a non-empty interface may fail, but unlike a
487       // type assertion converting nil will always succeed.
488       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
489                  == 0);
490       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
491                                                                    location);
492       static tree convert_interface_decl;
493       tree call = Gogo::call_builtin(&convert_interface_decl,
494                                      location,
495                                      "__go_convert_interface",
496                                      2,
497                                      ptr_type_node,
498                                      TREE_TYPE(lhs_type_descriptor),
499                                      lhs_type_descriptor,
500                                      TREE_TYPE(rhs_type_descriptor),
501                                      rhs_type_descriptor);
502       if (call == error_mark_node)
503         return error_mark_node;
504       // This will panic if the interface conversion fails.
505       TREE_NOTHROW(convert_interface_decl) = 0;
506       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
507                                     call);
508     }
509
510   // The second field is simply the object pointer.
511
512   elt = VEC_quick_push(constructor_elt, init, NULL);
513   field = DECL_CHAIN(field);
514   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
515   elt->index = field;
516
517   tree rhs_type_tree = TREE_TYPE(rhs_tree);
518   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
519   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
520   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
521   elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
522                       NULL_TREE);
523
524   return build_constructor(lhs_type_tree, init);
525 }
526
527 // Return a tree for the conversion of an interface type to a
528 // non-interface type.
529
530 tree
531 Expression::convert_interface_to_type(Translate_context* context,
532                                       Type *lhs_type, Type* rhs_type,
533                                       tree rhs_tree, Location location)
534 {
535   Gogo* gogo = context->gogo();
536   tree rhs_type_tree = TREE_TYPE(rhs_tree);
537
538   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
539   if (lhs_type_tree == error_mark_node)
540     return error_mark_node;
541
542   // Call a function to check that the type is valid.  The function
543   // will panic with an appropriate runtime type error if the type is
544   // not valid.
545
546   tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
547
548   if (!DECL_P(rhs_tree))
549     rhs_tree = save_expr(rhs_tree);
550
551   tree rhs_type_descriptor =
552     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
553                                               location);
554
555   tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
556                                                                 location);
557
558   static tree check_interface_type_decl;
559   tree call = Gogo::call_builtin(&check_interface_type_decl,
560                                  location,
561                                  "__go_check_interface_type",
562                                  3,
563                                  void_type_node,
564                                  TREE_TYPE(lhs_type_descriptor),
565                                  lhs_type_descriptor,
566                                  TREE_TYPE(rhs_type_descriptor),
567                                  rhs_type_descriptor,
568                                  TREE_TYPE(rhs_inter_descriptor),
569                                  rhs_inter_descriptor);
570   if (call == error_mark_node)
571     return error_mark_node;
572   // This call will panic if the conversion is invalid.
573   TREE_NOTHROW(check_interface_type_decl) = 0;
574
575   // If the call succeeds, pull out the value.
576   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
577   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
578   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
579   tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
580                     NULL_TREE);
581
582   // If the value is a pointer, then it is the value we want.
583   // Otherwise it points to the value.
584   if (lhs_type->points_to() == NULL)
585     {
586       val = fold_convert_loc(location.gcc_location(),
587                              build_pointer_type(lhs_type_tree), val);
588       val = build_fold_indirect_ref_loc(location.gcc_location(), val);
589     }
590
591   return build2(COMPOUND_EXPR, lhs_type_tree, call,
592                 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
593 }
594
595 // Convert an expression to a tree.  This is implemented by the child
596 // class.  Not that it is not in general safe to call this multiple
597 // times for a single expression, but that we don't catch such errors.
598
599 tree
600 Expression::get_tree(Translate_context* context)
601 {
602   // The child may have marked this expression as having an error.
603   if (this->classification_ == EXPRESSION_ERROR)
604     return error_mark_node;
605
606   return this->do_get_tree(context);
607 }
608
609 // Return a tree for VAL in TYPE.
610
611 tree
612 Expression::integer_constant_tree(mpz_t val, tree type)
613 {
614   if (type == error_mark_node)
615     return error_mark_node;
616   else if (TREE_CODE(type) == INTEGER_TYPE)
617     return double_int_to_tree(type,
618                               mpz_get_double_int(type, val, true));
619   else if (TREE_CODE(type) == REAL_TYPE)
620     {
621       mpfr_t fval;
622       mpfr_init_set_z(fval, val, GMP_RNDN);
623       tree ret = Expression::float_constant_tree(fval, type);
624       mpfr_clear(fval);
625       return ret;
626     }
627   else if (TREE_CODE(type) == COMPLEX_TYPE)
628     {
629       mpfr_t fval;
630       mpfr_init_set_z(fval, val, GMP_RNDN);
631       tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
632       mpfr_clear(fval);
633       tree imag = build_real_from_int_cst(TREE_TYPE(type),
634                                           integer_zero_node);
635       return build_complex(type, real, imag);
636     }
637   else
638     go_unreachable();
639 }
640
641 // Return a tree for VAL in TYPE.
642
643 tree
644 Expression::float_constant_tree(mpfr_t val, tree type)
645 {
646   if (type == error_mark_node)
647     return error_mark_node;
648   else if (TREE_CODE(type) == INTEGER_TYPE)
649     {
650       mpz_t ival;
651       mpz_init(ival);
652       mpfr_get_z(ival, val, GMP_RNDN);
653       tree ret = Expression::integer_constant_tree(ival, type);
654       mpz_clear(ival);
655       return ret;
656     }
657   else if (TREE_CODE(type) == REAL_TYPE)
658     {
659       REAL_VALUE_TYPE r1;
660       real_from_mpfr(&r1, val, type, GMP_RNDN);
661       REAL_VALUE_TYPE r2;
662       real_convert(&r2, TYPE_MODE(type), &r1);
663       return build_real(type, r2);
664     }
665   else if (TREE_CODE(type) == COMPLEX_TYPE)
666     {
667       REAL_VALUE_TYPE r1;
668       real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
669       REAL_VALUE_TYPE r2;
670       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
671       tree imag = build_real_from_int_cst(TREE_TYPE(type),
672                                           integer_zero_node);
673       return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
674     }
675   else
676     go_unreachable();
677 }
678
679 // Return a tree for REAL/IMAG in TYPE.
680
681 tree
682 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
683 {
684   if (type == error_mark_node)
685     return error_mark_node;
686   else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
687     return Expression::float_constant_tree(real, type);
688   else if (TREE_CODE(type) == COMPLEX_TYPE)
689     {
690       REAL_VALUE_TYPE r1;
691       real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
692       REAL_VALUE_TYPE r2;
693       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
694
695       REAL_VALUE_TYPE r3;
696       real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
697       REAL_VALUE_TYPE r4;
698       real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
699
700       return build_complex(type, build_real(TREE_TYPE(type), r2),
701                            build_real(TREE_TYPE(type), r4));
702     }
703   else
704     go_unreachable();
705 }
706
707 // Return a tree which evaluates to true if VAL, of arbitrary integer
708 // type, is negative or is more than the maximum value of BOUND_TYPE.
709 // If SOFAR is not NULL, it is or'red into the result.  The return
710 // value may be NULL if SOFAR is NULL.
711
712 tree
713 Expression::check_bounds(tree val, tree bound_type, tree sofar,
714                          Location loc)
715 {
716   tree val_type = TREE_TYPE(val);
717   tree ret = NULL_TREE;
718
719   if (!TYPE_UNSIGNED(val_type))
720     {
721       ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
722                             build_int_cst(val_type, 0));
723       if (ret == boolean_false_node)
724         ret = NULL_TREE;
725     }
726
727   HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
728   HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
729   go_assert(val_type_size != -1 && bound_type_size != -1);
730   if (val_type_size > bound_type_size
731       || (val_type_size == bound_type_size
732           && TYPE_UNSIGNED(val_type)
733           && !TYPE_UNSIGNED(bound_type)))
734     {
735       tree max = TYPE_MAX_VALUE(bound_type);
736       tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
737                                  val, fold_convert_loc(loc.gcc_location(),
738                                                        val_type, max));
739       if (big == boolean_false_node)
740         ;
741       else if (ret == NULL_TREE)
742         ret = big;
743       else
744         ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
745                               boolean_type_node, ret, big);
746     }
747
748   if (ret == NULL_TREE)
749     return sofar;
750   else if (sofar == NULL_TREE)
751     return ret;
752   else
753     return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
754                            sofar, ret);
755 }
756
757 void
758 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
759 {
760   this->do_dump_expression(ast_dump_context);
761 }
762
763 // Error expressions.  This are used to avoid cascading errors.
764
765 class Error_expression : public Expression
766 {
767  public:
768   Error_expression(Location location)
769     : Expression(EXPRESSION_ERROR, location)
770   { }
771
772  protected:
773   bool
774   do_is_constant() const
775   { return true; }
776
777   bool
778   do_numeric_constant_value(Numeric_constant* nc) const
779   {
780     nc->set_unsigned_long(NULL, 0);
781     return true;
782   }
783
784   void
785   do_discarding_value()
786   { }
787
788   Type*
789   do_type()
790   { return Type::make_error_type(); }
791
792   void
793   do_determine_type(const Type_context*)
794   { }
795
796   Expression*
797   do_copy()
798   { return this; }
799
800   bool
801   do_is_addressable() const
802   { return true; }
803
804   tree
805   do_get_tree(Translate_context*)
806   { return error_mark_node; }
807
808   void
809   do_dump_expression(Ast_dump_context*) const;
810 };
811
812 // Dump the ast representation for an error expression to a dump context.
813
814 void
815 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
816 {
817   ast_dump_context->ostream() << "_Error_" ;
818 }
819
820 Expression*
821 Expression::make_error(Location location)
822 {
823   return new Error_expression(location);
824 }
825
826 // An expression which is really a type.  This is used during parsing.
827 // It is an error if these survive after lowering.
828
829 class
830 Type_expression : public Expression
831 {
832  public:
833   Type_expression(Type* type, Location location)
834     : Expression(EXPRESSION_TYPE, location),
835       type_(type)
836   { }
837
838  protected:
839   int
840   do_traverse(Traverse* traverse)
841   { return Type::traverse(this->type_, traverse); }
842
843   Type*
844   do_type()
845   { return this->type_; }
846
847   void
848   do_determine_type(const Type_context*)
849   { }
850
851   void
852   do_check_types(Gogo*)
853   { this->report_error(_("invalid use of type")); }
854
855   Expression*
856   do_copy()
857   { return this; }
858
859   tree
860   do_get_tree(Translate_context*)
861   { go_unreachable(); }
862
863   void do_dump_expression(Ast_dump_context*) const;
864  
865  private:
866   // The type which we are representing as an expression.
867   Type* type_;
868 };
869
870 void
871 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
872 {
873   ast_dump_context->dump_type(this->type_);
874 }
875
876 Expression*
877 Expression::make_type(Type* type, Location location)
878 {
879   return new Type_expression(type, location);
880 }
881
882 // Class Parser_expression.
883
884 Type*
885 Parser_expression::do_type()
886 {
887   // We should never really ask for the type of a Parser_expression.
888   // However, it can happen, at least when we have an invalid const
889   // whose initializer refers to the const itself.  In that case we
890   // may ask for the type when lowering the const itself.
891   go_assert(saw_errors());
892   return Type::make_error_type();
893 }
894
895 // Class Var_expression.
896
897 // Lower a variable expression.  Here we just make sure that the
898 // initialization expression of the variable has been lowered.  This
899 // ensures that we will be able to determine the type of the variable
900 // if necessary.
901
902 Expression*
903 Var_expression::do_lower(Gogo* gogo, Named_object* function,
904                          Statement_inserter* inserter, int)
905 {
906   if (this->variable_->is_variable())
907     {
908       Variable* var = this->variable_->var_value();
909       // This is either a local variable or a global variable.  A
910       // reference to a variable which is local to an enclosing
911       // function will be a reference to a field in a closure.
912       if (var->is_global())
913         {
914           function = NULL;
915           inserter = NULL;
916         }
917       var->lower_init_expression(gogo, function, inserter);
918     }
919   return this;
920 }
921
922 // Return the type of a reference to a variable.
923
924 Type*
925 Var_expression::do_type()
926 {
927   if (this->variable_->is_variable())
928     return this->variable_->var_value()->type();
929   else if (this->variable_->is_result_variable())
930     return this->variable_->result_var_value()->type();
931   else
932     go_unreachable();
933 }
934
935 // Determine the type of a reference to a variable.
936
937 void
938 Var_expression::do_determine_type(const Type_context*)
939 {
940   if (this->variable_->is_variable())
941     this->variable_->var_value()->determine_type();
942 }
943
944 // Something takes the address of this variable.  This means that we
945 // may want to move the variable onto the heap.
946
947 void
948 Var_expression::do_address_taken(bool escapes)
949 {
950   if (!escapes)
951     {
952       if (this->variable_->is_variable())
953         this->variable_->var_value()->set_non_escaping_address_taken();
954       else if (this->variable_->is_result_variable())
955         this->variable_->result_var_value()->set_non_escaping_address_taken();
956       else
957         go_unreachable();
958     }
959   else
960     {
961       if (this->variable_->is_variable())
962         this->variable_->var_value()->set_address_taken();
963       else if (this->variable_->is_result_variable())
964         this->variable_->result_var_value()->set_address_taken();
965       else
966         go_unreachable();
967     }
968 }
969
970 // Get the tree for a reference to a variable.
971
972 tree
973 Var_expression::do_get_tree(Translate_context* context)
974 {
975   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
976                                                           context->function());
977   tree ret = var_to_tree(bvar);
978   if (ret == error_mark_node)
979     return error_mark_node;
980   bool is_in_heap;
981   if (this->variable_->is_variable())
982     is_in_heap = this->variable_->var_value()->is_in_heap();
983   else if (this->variable_->is_result_variable())
984     is_in_heap = this->variable_->result_var_value()->is_in_heap();
985   else
986     go_unreachable();
987   if (is_in_heap)
988     {
989       ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
990       TREE_THIS_NOTRAP(ret) = 1;
991     }
992   return ret;
993 }
994
995 // Ast dump for variable expression.
996
997 void
998 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
999 {
1000   ast_dump_context->ostream() << this->variable_->name() ;
1001 }
1002
1003 // Make a reference to a variable in an expression.
1004
1005 Expression*
1006 Expression::make_var_reference(Named_object* var, Location location)
1007 {
1008   if (var->is_sink())
1009     return Expression::make_sink(location);
1010
1011   // FIXME: Creating a new object for each reference to a variable is
1012   // wasteful.
1013   return new Var_expression(var, location);
1014 }
1015
1016 // Class Temporary_reference_expression.
1017
1018 // The type.
1019
1020 Type*
1021 Temporary_reference_expression::do_type()
1022 {
1023   return this->statement_->type();
1024 }
1025
1026 // Called if something takes the address of this temporary variable.
1027 // We never have to move temporary variables to the heap, but we do
1028 // need to know that they must live in the stack rather than in a
1029 // register.
1030
1031 void
1032 Temporary_reference_expression::do_address_taken(bool)
1033 {
1034   this->statement_->set_is_address_taken();
1035 }
1036
1037 // Get a tree referring to the variable.
1038
1039 tree
1040 Temporary_reference_expression::do_get_tree(Translate_context* context)
1041 {
1042   Bvariable* bvar = this->statement_->get_backend_variable(context);
1043
1044   // The gcc backend can't represent the same set of recursive types
1045   // that the Go frontend can.  In some cases this means that a
1046   // temporary variable won't have the right backend type.  Correct
1047   // that here by adding a type cast.  We need to use base() to push
1048   // the circularity down one level.
1049   tree ret = var_to_tree(bvar);
1050   if (!this->is_lvalue_
1051       && POINTER_TYPE_P(TREE_TYPE(ret))
1052       && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1053     {
1054       Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1055       tree type_tree = type_to_tree(type_btype);
1056       ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1057     }
1058   return ret;
1059 }
1060
1061 // Ast dump for temporary reference.
1062
1063 void
1064 Temporary_reference_expression::do_dump_expression(
1065                                 Ast_dump_context* ast_dump_context) const
1066 {
1067   ast_dump_context->dump_temp_variable_name(this->statement_);
1068 }
1069
1070 // Make a reference to a temporary variable.
1071
1072 Temporary_reference_expression*
1073 Expression::make_temporary_reference(Temporary_statement* statement,
1074                                      Location location)
1075 {
1076   return new Temporary_reference_expression(statement, location);
1077 }
1078
1079 // Class Set_and_use_temporary_expression.
1080
1081 // Return the type.
1082
1083 Type*
1084 Set_and_use_temporary_expression::do_type()
1085 {
1086   return this->statement_->type();
1087 }
1088
1089 // Take the address.
1090
1091 void
1092 Set_and_use_temporary_expression::do_address_taken(bool)
1093 {
1094   this->statement_->set_is_address_taken();
1095 }
1096
1097 // Return the backend representation.
1098
1099 tree
1100 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1101 {
1102   Bvariable* bvar = this->statement_->get_backend_variable(context);
1103   tree var_tree = var_to_tree(bvar);
1104   tree expr_tree = this->expr_->get_tree(context);
1105   if (var_tree == error_mark_node || expr_tree == error_mark_node)
1106     return error_mark_node;
1107   Location loc = this->location();
1108   return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1109                     build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1110                                var_tree, expr_tree),
1111                     var_tree);
1112 }
1113
1114 // Dump.
1115
1116 void
1117 Set_and_use_temporary_expression::do_dump_expression(
1118     Ast_dump_context* ast_dump_context) const
1119 {
1120   ast_dump_context->ostream() << '(';
1121   ast_dump_context->dump_temp_variable_name(this->statement_);
1122   ast_dump_context->ostream() << " = ";
1123   this->expr_->dump_expression(ast_dump_context);
1124   ast_dump_context->ostream() << ')';
1125 }
1126
1127 // Make a set-and-use temporary.
1128
1129 Set_and_use_temporary_expression*
1130 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1131                                        Expression* expr, Location location)
1132 {
1133   return new Set_and_use_temporary_expression(statement, expr, location);
1134 }
1135
1136 // A sink expression--a use of the blank identifier _.
1137
1138 class Sink_expression : public Expression
1139 {
1140  public:
1141   Sink_expression(Location location)
1142     : Expression(EXPRESSION_SINK, location),
1143       type_(NULL), var_(NULL_TREE)
1144   { }
1145
1146  protected:
1147   void
1148   do_discarding_value()
1149   { }
1150
1151   Type*
1152   do_type();
1153
1154   void
1155   do_determine_type(const Type_context*);
1156
1157   Expression*
1158   do_copy()
1159   { return new Sink_expression(this->location()); }
1160
1161   tree
1162   do_get_tree(Translate_context*);
1163
1164   void
1165   do_dump_expression(Ast_dump_context*) const;
1166
1167  private:
1168   // The type of this sink variable.
1169   Type* type_;
1170   // The temporary variable we generate.
1171   tree var_;
1172 };
1173
1174 // Return the type of a sink expression.
1175
1176 Type*
1177 Sink_expression::do_type()
1178 {
1179   if (this->type_ == NULL)
1180     return Type::make_sink_type();
1181   return this->type_;
1182 }
1183
1184 // Determine the type of a sink expression.
1185
1186 void
1187 Sink_expression::do_determine_type(const Type_context* context)
1188 {
1189   if (context->type != NULL)
1190     this->type_ = context->type;
1191 }
1192
1193 // Return a temporary variable for a sink expression.  This will
1194 // presumably be a write-only variable which the middle-end will drop.
1195
1196 tree
1197 Sink_expression::do_get_tree(Translate_context* context)
1198 {
1199   if (this->var_ == NULL_TREE)
1200     {
1201       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1202       Btype* bt = this->type_->get_backend(context->gogo());
1203       this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1204     }
1205   return this->var_;
1206 }
1207
1208 // Ast dump for sink expression.
1209
1210 void
1211 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1212 {
1213   ast_dump_context->ostream() << "_" ;
1214 }
1215
1216 // Make a sink expression.
1217
1218 Expression*
1219 Expression::make_sink(Location location)
1220 {
1221   return new Sink_expression(location);
1222 }
1223
1224 // Class Func_expression.
1225
1226 // FIXME: Can a function expression appear in a constant expression?
1227 // The value is unchanging.  Initializing a constant to the address of
1228 // a function seems like it could work, though there might be little
1229 // point to it.
1230
1231 // Traversal.
1232
1233 int
1234 Func_expression::do_traverse(Traverse* traverse)
1235 {
1236   return (this->closure_ == NULL
1237           ? TRAVERSE_CONTINUE
1238           : Expression::traverse(&this->closure_, traverse));
1239 }
1240
1241 // Return the type of a function expression.
1242
1243 Type*
1244 Func_expression::do_type()
1245 {
1246   if (this->function_->is_function())
1247     return this->function_->func_value()->type();
1248   else if (this->function_->is_function_declaration())
1249     return this->function_->func_declaration_value()->type();
1250   else
1251     go_unreachable();
1252 }
1253
1254 // Get the tree for a function expression without evaluating the
1255 // closure.
1256
1257 tree
1258 Func_expression::get_tree_without_closure(Gogo* gogo)
1259 {
1260   Function_type* fntype;
1261   if (this->function_->is_function())
1262     fntype = this->function_->func_value()->type();
1263   else if (this->function_->is_function_declaration())
1264     fntype = this->function_->func_declaration_value()->type();
1265   else
1266     go_unreachable();
1267
1268   // Builtin functions are handled specially by Call_expression.  We
1269   // can't take their address.
1270   if (fntype->is_builtin())
1271     {
1272       error_at(this->location(),
1273                "invalid use of special builtin function %qs; must be called",
1274                this->function_->name().c_str());
1275       return error_mark_node;
1276     }
1277
1278   Named_object* no = this->function_;
1279
1280   tree id = no->get_id(gogo);
1281   if (id == error_mark_node)
1282     return error_mark_node;
1283
1284   tree fndecl;
1285   if (no->is_function())
1286     fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1287   else if (no->is_function_declaration())
1288     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1289   else
1290     go_unreachable();
1291
1292   if (fndecl == error_mark_node)
1293     return error_mark_node;
1294
1295   return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1296 }
1297
1298 // Get the tree for a function expression.  This is used when we take
1299 // the address of a function rather than simply calling it.  If the
1300 // function has a closure, we must use a trampoline.
1301
1302 tree
1303 Func_expression::do_get_tree(Translate_context* context)
1304 {
1305   Gogo* gogo = context->gogo();
1306
1307   tree fnaddr = this->get_tree_without_closure(gogo);
1308   if (fnaddr == error_mark_node)
1309     return error_mark_node;
1310
1311   go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1312              && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1313   TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1314
1315   // For a normal non-nested function call, that is all we have to do.
1316   if (!this->function_->is_function()
1317       || this->function_->func_value()->enclosing() == NULL)
1318     {
1319       go_assert(this->closure_ == NULL);
1320       return fnaddr;
1321     }
1322
1323   // For a nested function call, we have to always allocate a
1324   // trampoline.  If we don't always allocate, then closures will not
1325   // be reliably distinct.
1326   Expression* closure = this->closure_;
1327   tree closure_tree;
1328   if (closure == NULL)
1329     closure_tree = null_pointer_node;
1330   else
1331     {
1332       // Get the value of the closure.  This will be a pointer to
1333       // space allocated on the heap.
1334       closure_tree = closure->get_tree(context);
1335       if (closure_tree == error_mark_node)
1336         return error_mark_node;
1337       go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1338     }
1339
1340   // Now we need to build some code on the heap.  This code will load
1341   // the static chain pointer with the closure and then jump to the
1342   // body of the function.  The normal gcc approach is to build the
1343   // code on the stack.  Unfortunately we can not do that, as Go
1344   // permits us to return the function pointer.
1345
1346   return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1347 }
1348
1349 // Ast dump for function.
1350
1351 void
1352 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1353 {
1354   ast_dump_context->ostream() << this->function_->name();
1355   if (this->closure_ != NULL)
1356     {
1357       ast_dump_context->ostream() << " {closure =  ";
1358       this->closure_->dump_expression(ast_dump_context);
1359       ast_dump_context->ostream() << "}";
1360     }
1361 }
1362
1363 // Make a reference to a function in an expression.
1364
1365 Expression*
1366 Expression::make_func_reference(Named_object* function, Expression* closure,
1367                                 Location location)
1368 {
1369   return new Func_expression(function, closure, location);
1370 }
1371
1372 // Class Unknown_expression.
1373
1374 // Return the name of an unknown expression.
1375
1376 const std::string&
1377 Unknown_expression::name() const
1378 {
1379   return this->named_object_->name();
1380 }
1381
1382 // Lower a reference to an unknown name.
1383
1384 Expression*
1385 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1386 {
1387   Location location = this->location();
1388   Named_object* no = this->named_object_;
1389   Named_object* real;
1390   if (!no->is_unknown())
1391     real = no;
1392   else
1393     {
1394       real = no->unknown_value()->real_named_object();
1395       if (real == NULL)
1396         {
1397           if (this->is_composite_literal_key_)
1398             return this;
1399           if (!this->no_error_message_)
1400             error_at(location, "reference to undefined name %qs",
1401                      this->named_object_->message_name().c_str());
1402           return Expression::make_error(location);
1403         }
1404     }
1405   switch (real->classification())
1406     {
1407     case Named_object::NAMED_OBJECT_CONST:
1408       return Expression::make_const_reference(real, location);
1409     case Named_object::NAMED_OBJECT_TYPE:
1410       return Expression::make_type(real->type_value(), location);
1411     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1412       if (this->is_composite_literal_key_)
1413         return this;
1414       if (!this->no_error_message_)
1415         error_at(location, "reference to undefined type %qs",
1416                  real->message_name().c_str());
1417       return Expression::make_error(location);
1418     case Named_object::NAMED_OBJECT_VAR:
1419       real->var_value()->set_is_used();
1420       return Expression::make_var_reference(real, location);
1421     case Named_object::NAMED_OBJECT_FUNC:
1422     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1423       return Expression::make_func_reference(real, NULL, location);
1424     case Named_object::NAMED_OBJECT_PACKAGE:
1425       if (this->is_composite_literal_key_)
1426         return this;
1427       if (!this->no_error_message_)
1428         error_at(location, "unexpected reference to package");
1429       return Expression::make_error(location);
1430     default:
1431       go_unreachable();
1432     }
1433 }
1434
1435 // Dump the ast representation for an unknown expression to a dump context.
1436
1437 void
1438 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1439 {
1440   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1441                               << ")";
1442 }
1443
1444 // Make a reference to an unknown name.
1445
1446 Unknown_expression*
1447 Expression::make_unknown_reference(Named_object* no, Location location)
1448 {
1449   return new Unknown_expression(no, location);
1450 }
1451
1452 // A boolean expression.
1453
1454 class Boolean_expression : public Expression
1455 {
1456  public:
1457   Boolean_expression(bool val, Location location)
1458     : Expression(EXPRESSION_BOOLEAN, location),
1459       val_(val), type_(NULL)
1460   { }
1461
1462   static Expression*
1463   do_import(Import*);
1464
1465  protected:
1466   bool
1467   do_is_constant() const
1468   { return true; }
1469
1470   Type*
1471   do_type();
1472
1473   void
1474   do_determine_type(const Type_context*);
1475
1476   Expression*
1477   do_copy()
1478   { return this; }
1479
1480   tree
1481   do_get_tree(Translate_context*)
1482   { return this->val_ ? boolean_true_node : boolean_false_node; }
1483
1484   void
1485   do_export(Export* exp) const
1486   { exp->write_c_string(this->val_ ? "true" : "false"); }
1487
1488   void
1489   do_dump_expression(Ast_dump_context* ast_dump_context) const
1490   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1491   
1492  private:
1493   // The constant.
1494   bool val_;
1495   // The type as determined by context.
1496   Type* type_;
1497 };
1498
1499 // Get the type.
1500
1501 Type*
1502 Boolean_expression::do_type()
1503 {
1504   if (this->type_ == NULL)
1505     this->type_ = Type::make_boolean_type();
1506   return this->type_;
1507 }
1508
1509 // Set the type from the context.
1510
1511 void
1512 Boolean_expression::do_determine_type(const Type_context* context)
1513 {
1514   if (this->type_ != NULL && !this->type_->is_abstract())
1515     ;
1516   else if (context->type != NULL && context->type->is_boolean_type())
1517     this->type_ = context->type;
1518   else if (!context->may_be_abstract)
1519     this->type_ = Type::lookup_bool_type();
1520 }
1521
1522 // Import a boolean constant.
1523
1524 Expression*
1525 Boolean_expression::do_import(Import* imp)
1526 {
1527   if (imp->peek_char() == 't')
1528     {
1529       imp->require_c_string("true");
1530       return Expression::make_boolean(true, imp->location());
1531     }
1532   else
1533     {
1534       imp->require_c_string("false");
1535       return Expression::make_boolean(false, imp->location());
1536     }
1537 }
1538
1539 // Make a boolean expression.
1540
1541 Expression*
1542 Expression::make_boolean(bool val, Location location)
1543 {
1544   return new Boolean_expression(val, location);
1545 }
1546
1547 // Class String_expression.
1548
1549 // Get the type.
1550
1551 Type*
1552 String_expression::do_type()
1553 {
1554   if (this->type_ == NULL)
1555     this->type_ = Type::make_string_type();
1556   return this->type_;
1557 }
1558
1559 // Set the type from the context.
1560
1561 void
1562 String_expression::do_determine_type(const Type_context* context)
1563 {
1564   if (this->type_ != NULL && !this->type_->is_abstract())
1565     ;
1566   else if (context->type != NULL && context->type->is_string_type())
1567     this->type_ = context->type;
1568   else if (!context->may_be_abstract)
1569     this->type_ = Type::lookup_string_type();
1570 }
1571
1572 // Build a string constant.
1573
1574 tree
1575 String_expression::do_get_tree(Translate_context* context)
1576 {
1577   return context->gogo()->go_string_constant_tree(this->val_);
1578 }
1579
1580  // Write string literal to string dump.
1581
1582 void
1583 String_expression::export_string(String_dump* exp,
1584                                  const String_expression* str)
1585 {
1586   std::string s;
1587   s.reserve(str->val_.length() * 4 + 2);
1588   s += '"';
1589   for (std::string::const_iterator p = str->val_.begin();
1590        p != str->val_.end();
1591        ++p)
1592     {
1593       if (*p == '\\' || *p == '"')
1594         {
1595           s += '\\';
1596           s += *p;
1597         }
1598       else if (*p >= 0x20 && *p < 0x7f)
1599         s += *p;
1600       else if (*p == '\n')
1601         s += "\\n";
1602       else if (*p == '\t')
1603         s += "\\t";
1604       else
1605         {
1606           s += "\\x";
1607           unsigned char c = *p;
1608           unsigned int dig = c >> 4;
1609           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1610           dig = c & 0xf;
1611           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1612         }
1613     }
1614   s += '"';
1615   exp->write_string(s);
1616 }
1617
1618 // Export a string expression.
1619
1620 void
1621 String_expression::do_export(Export* exp) const
1622 {
1623   String_expression::export_string(exp, this);
1624 }
1625
1626 // Import a string expression.
1627
1628 Expression*
1629 String_expression::do_import(Import* imp)
1630 {
1631   imp->require_c_string("\"");
1632   std::string val;
1633   while (true)
1634     {
1635       int c = imp->get_char();
1636       if (c == '"' || c == -1)
1637         break;
1638       if (c != '\\')
1639         val += static_cast<char>(c);
1640       else
1641         {
1642           c = imp->get_char();
1643           if (c == '\\' || c == '"')
1644             val += static_cast<char>(c);
1645           else if (c == 'n')
1646             val += '\n';
1647           else if (c == 't')
1648             val += '\t';
1649           else if (c == 'x')
1650             {
1651               c = imp->get_char();
1652               unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1653               c = imp->get_char();
1654               unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1655               char v = (vh << 4) | vl;
1656               val += v;
1657             }
1658           else
1659             {
1660               error_at(imp->location(), "bad string constant");
1661               return Expression::make_error(imp->location());
1662             }
1663         }
1664     }
1665   return Expression::make_string(val, imp->location());
1666 }
1667
1668 // Ast dump for string expression.
1669
1670 void
1671 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1672 {
1673   String_expression::export_string(ast_dump_context, this);
1674 }
1675
1676 // Make a string expression.
1677
1678 Expression*
1679 Expression::make_string(const std::string& val, Location location)
1680 {
1681   return new String_expression(val, location);
1682 }
1683
1684 // Make an integer expression.
1685
1686 class Integer_expression : public Expression
1687 {
1688  public:
1689   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1690                      Location location)
1691     : Expression(EXPRESSION_INTEGER, location),
1692       type_(type), is_character_constant_(is_character_constant)
1693   { mpz_init_set(this->val_, *val); }
1694
1695   static Expression*
1696   do_import(Import*);
1697
1698   // Write VAL to string dump.
1699   static void
1700   export_integer(String_dump* exp, const mpz_t val);
1701
1702   // Write VAL to dump context.
1703   static void
1704   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1705
1706  protected:
1707   bool
1708   do_is_constant() const
1709   { return true; }
1710
1711   bool
1712   do_numeric_constant_value(Numeric_constant* nc) const;
1713
1714   Type*
1715   do_type();
1716
1717   void
1718   do_determine_type(const Type_context* context);
1719
1720   void
1721   do_check_types(Gogo*);
1722
1723   tree
1724   do_get_tree(Translate_context*);
1725
1726   Expression*
1727   do_copy()
1728   {
1729     if (this->is_character_constant_)
1730       return Expression::make_character(&this->val_, this->type_,
1731                                         this->location());
1732     else
1733       return Expression::make_integer(&this->val_, this->type_,
1734                                       this->location());
1735   }
1736
1737   void
1738   do_export(Export*) const;
1739
1740   void
1741   do_dump_expression(Ast_dump_context*) const;
1742
1743  private:
1744   // The integer value.
1745   mpz_t val_;
1746   // The type so far.
1747   Type* type_;
1748   // Whether this is a character constant.
1749   bool is_character_constant_;
1750 };
1751
1752 // Return a numeric constant for this expression.  We have to mark
1753 // this as a character when appropriate.
1754
1755 bool
1756 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1757 {
1758   if (this->is_character_constant_)
1759     nc->set_rune(this->type_, this->val_);
1760   else
1761     nc->set_int(this->type_, this->val_);
1762   return true;
1763 }
1764
1765 // Return the current type.  If we haven't set the type yet, we return
1766 // an abstract integer type.
1767
1768 Type*
1769 Integer_expression::do_type()
1770 {
1771   if (this->type_ == NULL)
1772     {
1773       if (this->is_character_constant_)
1774         this->type_ = Type::make_abstract_character_type();
1775       else
1776         this->type_ = Type::make_abstract_integer_type();
1777     }
1778   return this->type_;
1779 }
1780
1781 // Set the type of the integer value.  Here we may switch from an
1782 // abstract type to a real type.
1783
1784 void
1785 Integer_expression::do_determine_type(const Type_context* context)
1786 {
1787   if (this->type_ != NULL && !this->type_->is_abstract())
1788     ;
1789   else if (context->type != NULL && context->type->is_numeric_type())
1790     this->type_ = context->type;
1791   else if (!context->may_be_abstract)
1792     {
1793       if (this->is_character_constant_)
1794         this->type_ = Type::lookup_integer_type("int32");
1795       else
1796         this->type_ = Type::lookup_integer_type("int");
1797     }
1798 }
1799
1800 // Check the type of an integer constant.
1801
1802 void
1803 Integer_expression::do_check_types(Gogo*)
1804 {
1805   Type* type = this->type_;
1806   if (type == NULL)
1807     return;
1808   Numeric_constant nc;
1809   if (this->is_character_constant_)
1810     nc.set_rune(NULL, this->val_);
1811   else
1812     nc.set_int(NULL, this->val_);
1813   if (!nc.set_type(type, true, this->location()))
1814     this->set_is_error();
1815 }
1816
1817 // Get a tree for an integer constant.
1818
1819 tree
1820 Integer_expression::do_get_tree(Translate_context* context)
1821 {
1822   Gogo* gogo = context->gogo();
1823   tree type;
1824   if (this->type_ != NULL && !this->type_->is_abstract())
1825     type = type_to_tree(this->type_->get_backend(gogo));
1826   else if (this->type_ != NULL && this->type_->float_type() != NULL)
1827     {
1828       // We are converting to an abstract floating point type.
1829       Type* ftype = Type::lookup_float_type("float64");
1830       type = type_to_tree(ftype->get_backend(gogo));
1831     }
1832   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1833     {
1834       // We are converting to an abstract complex type.
1835       Type* ctype = Type::lookup_complex_type("complex128");
1836       type = type_to_tree(ctype->get_backend(gogo));
1837     }
1838   else
1839     {
1840       // If we still have an abstract type here, then this is being
1841       // used in a constant expression which didn't get reduced for
1842       // some reason.  Use a type which will fit the value.  We use <,
1843       // not <=, because we need an extra bit for the sign bit.
1844       int bits = mpz_sizeinbase(this->val_, 2);
1845       if (bits < INT_TYPE_SIZE)
1846         {
1847           Type* t = Type::lookup_integer_type("int");
1848           type = type_to_tree(t->get_backend(gogo));
1849         }
1850       else if (bits < 64)
1851         {
1852           Type* t = Type::lookup_integer_type("int64");
1853           type = type_to_tree(t->get_backend(gogo));
1854         }
1855       else
1856         type = long_long_integer_type_node;
1857     }
1858   return Expression::integer_constant_tree(this->val_, type);
1859 }
1860
1861 // Write VAL to export data.
1862
1863 void
1864 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1865 {
1866   char* s = mpz_get_str(NULL, 10, val);
1867   exp->write_c_string(s);
1868   free(s);
1869 }
1870
1871 // Export an integer in a constant expression.
1872
1873 void
1874 Integer_expression::do_export(Export* exp) const
1875 {
1876   Integer_expression::export_integer(exp, this->val_);
1877   if (this->is_character_constant_)
1878     exp->write_c_string("'");
1879   // A trailing space lets us reliably identify the end of the number.
1880   exp->write_c_string(" ");
1881 }
1882
1883 // Import an integer, floating point, or complex value.  This handles
1884 // all these types because they all start with digits.
1885
1886 Expression*
1887 Integer_expression::do_import(Import* imp)
1888 {
1889   std::string num = imp->read_identifier();
1890   imp->require_c_string(" ");
1891   if (!num.empty() && num[num.length() - 1] == 'i')
1892     {
1893       mpfr_t real;
1894       size_t plus_pos = num.find('+', 1);
1895       size_t minus_pos = num.find('-', 1);
1896       size_t pos;
1897       if (plus_pos == std::string::npos)
1898         pos = minus_pos;
1899       else if (minus_pos == std::string::npos)
1900         pos = plus_pos;
1901       else
1902         {
1903           error_at(imp->location(), "bad number in import data: %qs",
1904                    num.c_str());
1905           return Expression::make_error(imp->location());
1906         }
1907       if (pos == std::string::npos)
1908         mpfr_set_ui(real, 0, GMP_RNDN);
1909       else
1910         {
1911           std::string real_str = num.substr(0, pos);
1912           if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1913             {
1914               error_at(imp->location(), "bad number in import data: %qs",
1915                        real_str.c_str());
1916               return Expression::make_error(imp->location());
1917             }
1918         }
1919
1920       std::string imag_str;
1921       if (pos == std::string::npos)
1922         imag_str = num;
1923       else
1924         imag_str = num.substr(pos);
1925       imag_str = imag_str.substr(0, imag_str.size() - 1);
1926       mpfr_t imag;
1927       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1928         {
1929           error_at(imp->location(), "bad number in import data: %qs",
1930                    imag_str.c_str());
1931           return Expression::make_error(imp->location());
1932         }
1933       Expression* ret = Expression::make_complex(&real, &imag, NULL,
1934                                                  imp->location());
1935       mpfr_clear(real);
1936       mpfr_clear(imag);
1937       return ret;
1938     }
1939   else if (num.find('.') == std::string::npos
1940            && num.find('E') == std::string::npos)
1941     {
1942       bool is_character_constant = (!num.empty()
1943                                     && num[num.length() - 1] == '\'');
1944       if (is_character_constant)
1945         num = num.substr(0, num.length() - 1);
1946       mpz_t val;
1947       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1948         {
1949           error_at(imp->location(), "bad number in import data: %qs",
1950                    num.c_str());
1951           return Expression::make_error(imp->location());
1952         }
1953       Expression* ret;
1954       if (is_character_constant)
1955         ret = Expression::make_character(&val, NULL, imp->location());
1956       else
1957         ret = Expression::make_integer(&val, NULL, imp->location());
1958       mpz_clear(val);
1959       return ret;
1960     }
1961   else
1962     {
1963       mpfr_t val;
1964       if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1965         {
1966           error_at(imp->location(), "bad number in import data: %qs",
1967                    num.c_str());
1968           return Expression::make_error(imp->location());
1969         }
1970       Expression* ret = Expression::make_float(&val, NULL, imp->location());
1971       mpfr_clear(val);
1972       return ret;
1973     }
1974 }
1975 // Ast dump for integer expression.
1976
1977 void
1978 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1979 {
1980   if (this->is_character_constant_)
1981     ast_dump_context->ostream() << '\'';
1982   Integer_expression::export_integer(ast_dump_context, this->val_);
1983   if (this->is_character_constant_)
1984     ast_dump_context->ostream() << '\'';
1985 }
1986
1987 // Build a new integer value.
1988
1989 Expression*
1990 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1991 {
1992   return new Integer_expression(val, type, false, location);
1993 }
1994
1995 // Build a new character constant value.
1996
1997 Expression*
1998 Expression::make_character(const mpz_t* val, Type* type, Location location)
1999 {
2000   return new Integer_expression(val, type, true, location);
2001 }
2002
2003 // Floats.
2004
2005 class Float_expression : public Expression
2006 {
2007  public:
2008   Float_expression(const mpfr_t* val, Type* type, Location location)
2009     : Expression(EXPRESSION_FLOAT, location),
2010       type_(type)
2011   {
2012     mpfr_init_set(this->val_, *val, GMP_RNDN);
2013   }
2014
2015   // Write VAL to export data.
2016   static void
2017   export_float(String_dump* exp, const mpfr_t val);
2018
2019   // Write VAL to dump file.
2020   static void
2021   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2022
2023  protected:
2024   bool
2025   do_is_constant() const
2026   { return true; }
2027
2028   bool
2029   do_numeric_constant_value(Numeric_constant* nc) const
2030   {
2031     nc->set_float(this->type_, this->val_);
2032     return true;
2033   }
2034
2035   Type*
2036   do_type();
2037
2038   void
2039   do_determine_type(const Type_context*);
2040
2041   void
2042   do_check_types(Gogo*);
2043
2044   Expression*
2045   do_copy()
2046   { return Expression::make_float(&this->val_, this->type_,
2047                                   this->location()); }
2048
2049   tree
2050   do_get_tree(Translate_context*);
2051
2052   void
2053   do_export(Export*) const;
2054
2055   void
2056   do_dump_expression(Ast_dump_context*) const;
2057
2058  private:
2059   // The floating point value.
2060   mpfr_t val_;
2061   // The type so far.
2062   Type* type_;
2063 };
2064
2065 // Return the current type.  If we haven't set the type yet, we return
2066 // an abstract float type.
2067
2068 Type*
2069 Float_expression::do_type()
2070 {
2071   if (this->type_ == NULL)
2072     this->type_ = Type::make_abstract_float_type();
2073   return this->type_;
2074 }
2075
2076 // Set the type of the float value.  Here we may switch from an
2077 // abstract type to a real type.
2078
2079 void
2080 Float_expression::do_determine_type(const Type_context* context)
2081 {
2082   if (this->type_ != NULL && !this->type_->is_abstract())
2083     ;
2084   else if (context->type != NULL
2085            && (context->type->integer_type() != NULL
2086                || context->type->float_type() != NULL
2087                || context->type->complex_type() != NULL))
2088     this->type_ = context->type;
2089   else if (!context->may_be_abstract)
2090     this->type_ = Type::lookup_float_type("float64");
2091 }
2092
2093 // Check the type of a float value.
2094
2095 void
2096 Float_expression::do_check_types(Gogo*)
2097 {
2098   Type* type = this->type_;
2099   if (type == NULL)
2100     return;
2101   Numeric_constant nc;
2102   nc.set_float(NULL, this->val_);
2103   if (!nc.set_type(this->type_, true, this->location()))
2104     this->set_is_error();
2105 }
2106
2107 // Get a tree for a float constant.
2108
2109 tree
2110 Float_expression::do_get_tree(Translate_context* context)
2111 {
2112   Gogo* gogo = context->gogo();
2113   tree type;
2114   if (this->type_ != NULL && !this->type_->is_abstract())
2115     type = type_to_tree(this->type_->get_backend(gogo));
2116   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2117     {
2118       // We have an abstract integer type.  We just hope for the best.
2119       type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2120     }
2121   else
2122     {
2123       // If we still have an abstract type here, then this is being
2124       // used in a constant expression which didn't get reduced.  We
2125       // just use float64 and hope for the best.
2126       Type* ft = Type::lookup_float_type("float64");
2127       type = type_to_tree(ft->get_backend(gogo));
2128     }
2129   return Expression::float_constant_tree(this->val_, type);
2130 }
2131
2132 // Write a floating point number to a string dump.
2133
2134 void
2135 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2136 {
2137   mp_exp_t exponent;
2138   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2139   if (*s == '-')
2140     exp->write_c_string("-");
2141   exp->write_c_string("0.");
2142   exp->write_c_string(*s == '-' ? s + 1 : s);
2143   mpfr_free_str(s);
2144   char buf[30];
2145   snprintf(buf, sizeof buf, "E%ld", exponent);
2146   exp->write_c_string(buf);
2147 }
2148
2149 // Export a floating point number in a constant expression.
2150
2151 void
2152 Float_expression::do_export(Export* exp) const
2153 {
2154   Float_expression::export_float(exp, this->val_);
2155   // A trailing space lets us reliably identify the end of the number.
2156   exp->write_c_string(" ");
2157 }
2158
2159 // Dump a floating point number to the dump file.
2160
2161 void
2162 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2163 {
2164   Float_expression::export_float(ast_dump_context, this->val_);
2165 }
2166
2167 // Make a float expression.
2168
2169 Expression*
2170 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2171 {
2172   return new Float_expression(val, type, location);
2173 }
2174
2175 // Complex numbers.
2176
2177 class Complex_expression : public Expression
2178 {
2179  public:
2180   Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2181                      Location location)
2182     : Expression(EXPRESSION_COMPLEX, location),
2183       type_(type)
2184   {
2185     mpfr_init_set(this->real_, *real, GMP_RNDN);
2186     mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2187   }
2188
2189   // Write REAL/IMAG to string dump.
2190   static void
2191   export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2192
2193   // Write REAL/IMAG to dump context.
2194   static void
2195   dump_complex(Ast_dump_context* ast_dump_context, 
2196                const mpfr_t real, const mpfr_t val);
2197   
2198  protected:
2199   bool
2200   do_is_constant() const
2201   { return true; }
2202
2203   bool
2204   do_numeric_constant_value(Numeric_constant* nc) const
2205   {
2206     nc->set_complex(this->type_, this->real_, this->imag_);
2207     return true;
2208   }
2209
2210   Type*
2211   do_type();
2212
2213   void
2214   do_determine_type(const Type_context*);
2215
2216   void
2217   do_check_types(Gogo*);
2218
2219   Expression*
2220   do_copy()
2221   {
2222     return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2223                                     this->location());
2224   }
2225
2226   tree
2227   do_get_tree(Translate_context*);
2228
2229   void
2230   do_export(Export*) const;
2231
2232   void
2233   do_dump_expression(Ast_dump_context*) const;
2234   
2235  private:
2236   // The real part.
2237   mpfr_t real_;
2238   // The imaginary part;
2239   mpfr_t imag_;
2240   // The type if known.
2241   Type* type_;
2242 };
2243
2244 // Return the current type.  If we haven't set the type yet, we return
2245 // an abstract complex type.
2246
2247 Type*
2248 Complex_expression::do_type()
2249 {
2250   if (this->type_ == NULL)
2251     this->type_ = Type::make_abstract_complex_type();
2252   return this->type_;
2253 }
2254
2255 // Set the type of the complex value.  Here we may switch from an
2256 // abstract type to a real type.
2257
2258 void
2259 Complex_expression::do_determine_type(const Type_context* context)
2260 {
2261   if (this->type_ != NULL && !this->type_->is_abstract())
2262     ;
2263   else if (context->type != NULL
2264            && context->type->complex_type() != NULL)
2265     this->type_ = context->type;
2266   else if (!context->may_be_abstract)
2267     this->type_ = Type::lookup_complex_type("complex128");
2268 }
2269
2270 // Check the type of a complex value.
2271
2272 void
2273 Complex_expression::do_check_types(Gogo*)
2274 {
2275   Type* type = this->type_;
2276   if (type == NULL)
2277     return;
2278   Numeric_constant nc;
2279   nc.set_complex(NULL, this->real_, this->imag_);
2280   if (!nc.set_type(this->type_, true, this->location()))
2281     this->set_is_error();
2282 }
2283
2284 // Get a tree for a complex constant.
2285
2286 tree
2287 Complex_expression::do_get_tree(Translate_context* context)
2288 {
2289   Gogo* gogo = context->gogo();
2290   tree type;
2291   if (this->type_ != NULL && !this->type_->is_abstract())
2292     type = type_to_tree(this->type_->get_backend(gogo));
2293   else
2294     {
2295       // If we still have an abstract type here, this this is being
2296       // used in a constant expression which didn't get reduced.  We
2297       // just use complex128 and hope for the best.
2298       Type* ct = Type::lookup_complex_type("complex128");
2299       type = type_to_tree(ct->get_backend(gogo));
2300     }
2301   return Expression::complex_constant_tree(this->real_, this->imag_, type);
2302 }
2303
2304 // Write REAL/IMAG to export data.
2305
2306 void
2307 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2308                                    const mpfr_t imag)
2309 {
2310   if (!mpfr_zero_p(real))
2311     {
2312       Float_expression::export_float(exp, real);
2313       if (mpfr_sgn(imag) > 0)
2314         exp->write_c_string("+");
2315     }
2316   Float_expression::export_float(exp, imag);
2317   exp->write_c_string("i");
2318 }
2319
2320 // Export a complex number in a constant expression.
2321
2322 void
2323 Complex_expression::do_export(Export* exp) const
2324 {
2325   Complex_expression::export_complex(exp, this->real_, this->imag_);
2326   // A trailing space lets us reliably identify the end of the number.
2327   exp->write_c_string(" ");
2328 }
2329
2330 // Dump a complex expression to the dump file.
2331
2332 void
2333 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2334 {
2335   Complex_expression::export_complex(ast_dump_context,
2336                                       this->real_,
2337                                       this->imag_);
2338 }
2339
2340 // Make a complex expression.
2341
2342 Expression*
2343 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2344                          Location location)
2345 {
2346   return new Complex_expression(real, imag, type, location);
2347 }
2348
2349 // Find a named object in an expression.
2350
2351 class Find_named_object : public Traverse
2352 {
2353  public:
2354   Find_named_object(Named_object* no)
2355     : Traverse(traverse_expressions),
2356       no_(no), found_(false)
2357   { }
2358
2359   // Whether we found the object.
2360   bool
2361   found() const
2362   { return this->found_; }
2363
2364  protected:
2365   int
2366   expression(Expression**);
2367
2368  private:
2369   // The object we are looking for.
2370   Named_object* no_;
2371   // Whether we found it.
2372   bool found_;
2373 };
2374
2375 // A reference to a const in an expression.
2376
2377 class Const_expression : public Expression
2378 {
2379  public:
2380   Const_expression(Named_object* constant, Location location)
2381     : Expression(EXPRESSION_CONST_REFERENCE, location),
2382       constant_(constant), type_(NULL), seen_(false)
2383   { }
2384
2385   Named_object*
2386   named_object()
2387   { return this->constant_; }
2388
2389   // Check that the initializer does not refer to the constant itself.
2390   void
2391   check_for_init_loop();
2392
2393  protected:
2394   int
2395   do_traverse(Traverse*);
2396
2397   Expression*
2398   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2399
2400   bool
2401   do_is_constant() const
2402   { return true; }
2403
2404   bool
2405   do_numeric_constant_value(Numeric_constant* nc) const;
2406
2407   bool
2408   do_string_constant_value(std::string* val) const;
2409
2410   Type*
2411   do_type();
2412
2413   // The type of a const is set by the declaration, not the use.
2414   void
2415   do_determine_type(const Type_context*);
2416
2417   void
2418   do_check_types(Gogo*);
2419
2420   Expression*
2421   do_copy()
2422   { return this; }
2423
2424   tree
2425   do_get_tree(Translate_context* context);
2426
2427   // When exporting a reference to a const as part of a const
2428   // expression, we export the value.  We ignore the fact that it has
2429   // a name.
2430   void
2431   do_export(Export* exp) const
2432   { this->constant_->const_value()->expr()->export_expression(exp); }
2433
2434   void
2435   do_dump_expression(Ast_dump_context*) const;
2436
2437  private:
2438   // The constant.
2439   Named_object* constant_;
2440   // The type of this reference.  This is used if the constant has an
2441   // abstract type.
2442   Type* type_;
2443   // Used to prevent infinite recursion when a constant incorrectly
2444   // refers to itself.
2445   mutable bool seen_;
2446 };
2447
2448 // Traversal.
2449
2450 int
2451 Const_expression::do_traverse(Traverse* traverse)
2452 {
2453   if (this->type_ != NULL)
2454     return Type::traverse(this->type_, traverse);
2455   return TRAVERSE_CONTINUE;
2456 }
2457
2458 // Lower a constant expression.  This is where we convert the
2459 // predeclared constant iota into an integer value.
2460
2461 Expression*
2462 Const_expression::do_lower(Gogo* gogo, Named_object*,
2463                            Statement_inserter*, int iota_value)
2464 {
2465   if (this->constant_->const_value()->expr()->classification()
2466       == EXPRESSION_IOTA)
2467     {
2468       if (iota_value == -1)
2469         {
2470           error_at(this->location(),
2471                    "iota is only defined in const declarations");
2472           iota_value = 0;
2473         }
2474       mpz_t val;
2475       mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2476       Expression* ret = Expression::make_integer(&val, NULL,
2477                                                  this->location());
2478       mpz_clear(val);
2479       return ret;
2480     }
2481
2482   // Make sure that the constant itself has been lowered.
2483   gogo->lower_constant(this->constant_);
2484
2485   return this;
2486 }
2487
2488 // Return a numeric constant value.
2489
2490 bool
2491 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2492 {
2493   if (this->seen_)
2494     return false;
2495
2496   Expression* e = this->constant_->const_value()->expr();
2497   
2498   this->seen_ = true;
2499
2500   bool r = e->numeric_constant_value(nc);
2501
2502   this->seen_ = false;
2503
2504   Type* ctype;
2505   if (this->type_ != NULL)
2506     ctype = this->type_;
2507   else
2508     ctype = this->constant_->const_value()->type();
2509   if (r && ctype != NULL)
2510     {
2511       if (!nc->set_type(ctype, false, this->location()))
2512         return false;
2513     }
2514
2515   return r;
2516 }
2517
2518 bool
2519 Const_expression::do_string_constant_value(std::string* val) const
2520 {
2521   if (this->seen_)
2522     return false;
2523
2524   Expression* e = this->constant_->const_value()->expr();
2525
2526   this->seen_ = true;
2527   bool ok = e->string_constant_value(val);
2528   this->seen_ = false;
2529
2530   return ok;
2531 }
2532
2533 // Return the type of the const reference.
2534
2535 Type*
2536 Const_expression::do_type()
2537 {
2538   if (this->type_ != NULL)
2539     return this->type_;
2540
2541   Named_constant* nc = this->constant_->const_value();
2542
2543   if (this->seen_ || nc->lowering())
2544     {
2545       this->report_error(_("constant refers to itself"));
2546       this->type_ = Type::make_error_type();
2547       return this->type_;
2548     }
2549
2550   this->seen_ = true;
2551
2552   Type* ret = nc->type();
2553
2554   if (ret != NULL)
2555     {
2556       this->seen_ = false;
2557       return ret;
2558     }
2559
2560   // During parsing, a named constant may have a NULL type, but we
2561   // must not return a NULL type here.
2562   ret = nc->expr()->type();
2563
2564   this->seen_ = false;
2565
2566   return ret;
2567 }
2568
2569 // Set the type of the const reference.
2570
2571 void
2572 Const_expression::do_determine_type(const Type_context* context)
2573 {
2574   Type* ctype = this->constant_->const_value()->type();
2575   Type* cetype = (ctype != NULL
2576                   ? ctype
2577                   : this->constant_->const_value()->expr()->type());
2578   if (ctype != NULL && !ctype->is_abstract())
2579     ;
2580   else if (context->type != NULL
2581            && context->type->is_numeric_type()
2582            && cetype->is_numeric_type())
2583     this->type_ = context->type;
2584   else if (context->type != NULL
2585            && context->type->is_string_type()
2586            && cetype->is_string_type())
2587     this->type_ = context->type;
2588   else if (context->type != NULL
2589            && context->type->is_boolean_type()
2590            && cetype->is_boolean_type())
2591     this->type_ = context->type;
2592   else if (!context->may_be_abstract)
2593     {
2594       if (cetype->is_abstract())
2595         cetype = cetype->make_non_abstract_type();
2596       this->type_ = cetype;
2597     }
2598 }
2599
2600 // Check for a loop in which the initializer of a constant refers to
2601 // the constant itself.
2602
2603 void
2604 Const_expression::check_for_init_loop()
2605 {
2606   if (this->type_ != NULL && this->type_->is_error())
2607     return;
2608
2609   if (this->seen_)
2610     {
2611       this->report_error(_("constant refers to itself"));
2612       this->type_ = Type::make_error_type();
2613       return;
2614     }
2615
2616   Expression* init = this->constant_->const_value()->expr();
2617   Find_named_object find_named_object(this->constant_);
2618
2619   this->seen_ = true;
2620   Expression::traverse(&init, &find_named_object);
2621   this->seen_ = false;
2622
2623   if (find_named_object.found())
2624     {
2625       if (this->type_ == NULL || !this->type_->is_error())
2626         {
2627           this->report_error(_("constant refers to itself"));
2628           this->type_ = Type::make_error_type();
2629         }
2630       return;
2631     }
2632 }
2633
2634 // Check types of a const reference.
2635
2636 void
2637 Const_expression::do_check_types(Gogo*)
2638 {
2639   if (this->type_ != NULL && this->type_->is_error())
2640     return;
2641
2642   this->check_for_init_loop();
2643
2644   // Check that numeric constant fits in type.
2645   if (this->type_ != NULL && this->type_->is_numeric_type())
2646     {
2647       Numeric_constant nc;
2648       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2649         {
2650           if (!nc.set_type(this->type_, true, this->location()))
2651             this->set_is_error();
2652         }
2653     }
2654 }
2655
2656 // Return a tree for the const reference.
2657
2658 tree
2659 Const_expression::do_get_tree(Translate_context* context)
2660 {
2661   Gogo* gogo = context->gogo();
2662   tree type_tree;
2663   if (this->type_ == NULL)
2664     type_tree = NULL_TREE;
2665   else
2666     {
2667       type_tree = type_to_tree(this->type_->get_backend(gogo));
2668       if (type_tree == error_mark_node)
2669         return error_mark_node;
2670     }
2671
2672   // If the type has been set for this expression, but the underlying
2673   // object is an abstract int or float, we try to get the abstract
2674   // value.  Otherwise we may lose something in the conversion.
2675   if (this->type_ != NULL
2676       && this->type_->is_numeric_type()
2677       && (this->constant_->const_value()->type() == NULL
2678           || this->constant_->const_value()->type()->is_abstract()))
2679     {
2680       Expression* expr = this->constant_->const_value()->expr();
2681       Numeric_constant nc;
2682       if (expr->numeric_constant_value(&nc)
2683           && nc.set_type(this->type_, false, this->location()))
2684         {
2685           Expression* e = nc.expression(this->location());
2686           return e->get_tree(context);
2687         }
2688     }
2689
2690   tree const_tree = this->constant_->get_tree(gogo, context->function());
2691   if (this->type_ == NULL
2692       || const_tree == error_mark_node
2693       || TREE_TYPE(const_tree) == error_mark_node)
2694     return const_tree;
2695
2696   tree ret;
2697   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2698     ret = fold_convert(type_tree, const_tree);
2699   else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2700     ret = fold(convert_to_integer(type_tree, const_tree));
2701   else if (TREE_CODE(type_tree) == REAL_TYPE)
2702     ret = fold(convert_to_real(type_tree, const_tree));
2703   else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2704     ret = fold(convert_to_complex(type_tree, const_tree));
2705   else
2706     go_unreachable();
2707   return ret;
2708 }
2709
2710 // Dump ast representation for constant expression.
2711
2712 void
2713 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2714 {
2715   ast_dump_context->ostream() << this->constant_->name();
2716 }
2717
2718 // Make a reference to a constant in an expression.
2719
2720 Expression*
2721 Expression::make_const_reference(Named_object* constant,
2722                                  Location location)
2723 {
2724   return new Const_expression(constant, location);
2725 }
2726
2727 // Find a named object in an expression.
2728
2729 int
2730 Find_named_object::expression(Expression** pexpr)
2731 {
2732   switch ((*pexpr)->classification())
2733     {
2734     case Expression::EXPRESSION_CONST_REFERENCE:
2735       {
2736         Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2737         if (ce->named_object() == this->no_)
2738           break;
2739
2740         // We need to check a constant initializer explicitly, as
2741         // loops here will not be caught by the loop checking for
2742         // variable initializers.
2743         ce->check_for_init_loop();
2744
2745         return TRAVERSE_CONTINUE;
2746       }
2747
2748     case Expression::EXPRESSION_VAR_REFERENCE:
2749       if ((*pexpr)->var_expression()->named_object() == this->no_)
2750         break;
2751       return TRAVERSE_CONTINUE;
2752     case Expression::EXPRESSION_FUNC_REFERENCE:
2753       if ((*pexpr)->func_expression()->named_object() == this->no_)
2754         break;
2755       return TRAVERSE_CONTINUE;
2756     default:
2757       return TRAVERSE_CONTINUE;
2758     }
2759   this->found_ = true;
2760   return TRAVERSE_EXIT;
2761 }
2762
2763 // The nil value.
2764
2765 class Nil_expression : public Expression
2766 {
2767  public:
2768   Nil_expression(Location location)
2769     : Expression(EXPRESSION_NIL, location)
2770   { }
2771
2772   static Expression*
2773   do_import(Import*);
2774
2775  protected:
2776   bool
2777   do_is_constant() const
2778   { return true; }
2779
2780   Type*
2781   do_type()
2782   { return Type::make_nil_type(); }
2783
2784   void
2785   do_determine_type(const Type_context*)
2786   { }
2787
2788   Expression*
2789   do_copy()
2790   { return this; }
2791
2792   tree
2793   do_get_tree(Translate_context*)
2794   { return null_pointer_node; }
2795
2796   void
2797   do_export(Export* exp) const
2798   { exp->write_c_string("nil"); }
2799
2800   void
2801   do_dump_expression(Ast_dump_context* ast_dump_context) const
2802   { ast_dump_context->ostream() << "nil"; }
2803 };
2804
2805 // Import a nil expression.
2806
2807 Expression*
2808 Nil_expression::do_import(Import* imp)
2809 {
2810   imp->require_c_string("nil");
2811   return Expression::make_nil(imp->location());
2812 }
2813
2814 // Make a nil expression.
2815
2816 Expression*
2817 Expression::make_nil(Location location)
2818 {
2819   return new Nil_expression(location);
2820 }
2821
2822 // The value of the predeclared constant iota.  This is little more
2823 // than a marker.  This will be lowered to an integer in
2824 // Const_expression::do_lower, which is where we know the value that
2825 // it should have.
2826
2827 class Iota_expression : public Parser_expression
2828 {
2829  public:
2830   Iota_expression(Location location)
2831     : Parser_expression(EXPRESSION_IOTA, location)
2832   { }
2833
2834  protected:
2835   Expression*
2836   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2837   { go_unreachable(); }
2838
2839   // There should only ever be one of these.
2840   Expression*
2841   do_copy()
2842   { go_unreachable(); }
2843   
2844   void
2845   do_dump_expression(Ast_dump_context* ast_dump_context) const
2846   { ast_dump_context->ostream() << "iota"; } 
2847 };
2848
2849 // Make an iota expression.  This is only called for one case: the
2850 // value of the predeclared constant iota.
2851
2852 Expression*
2853 Expression::make_iota()
2854 {
2855   static Iota_expression iota_expression(Linemap::unknown_location());
2856   return &iota_expression;
2857 }
2858
2859 // A type conversion expression.
2860
2861 class Type_conversion_expression : public Expression
2862 {
2863  public:
2864   Type_conversion_expression(Type* type, Expression* expr,
2865                              Location location)
2866     : Expression(EXPRESSION_CONVERSION, location),
2867       type_(type), expr_(expr), may_convert_function_types_(false)
2868   { }
2869
2870   // Return the type to which we are converting.
2871   Type*
2872   type() const
2873   { return this->type_; }
2874
2875   // Return the expression which we are converting.
2876   Expression*
2877   expr() const
2878   { return this->expr_; }
2879
2880   // Permit converting from one function type to another.  This is
2881   // used internally for method expressions.
2882   void
2883   set_may_convert_function_types()
2884   {
2885     this->may_convert_function_types_ = true;
2886   }
2887
2888   // Import a type conversion expression.
2889   static Expression*
2890   do_import(Import*);
2891
2892  protected:
2893   int
2894   do_traverse(Traverse* traverse);
2895
2896   Expression*
2897   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2898
2899   bool
2900   do_is_constant() const
2901   { return this->expr_->is_constant(); }
2902
2903   bool
2904   do_numeric_constant_value(Numeric_constant*) const;
2905
2906   bool
2907   do_string_constant_value(std::string*) const;
2908
2909   Type*
2910   do_type()
2911   { return this->type_; }
2912
2913   void
2914   do_determine_type(const Type_context*)
2915   {
2916     Type_context subcontext(this->type_, false);
2917     this->expr_->determine_type(&subcontext);
2918   }
2919
2920   void
2921   do_check_types(Gogo*);
2922
2923   Expression*
2924   do_copy()
2925   {
2926     return new Type_conversion_expression(this->type_, this->expr_->copy(),
2927                                           this->location());
2928   }
2929
2930   tree
2931   do_get_tree(Translate_context* context);
2932
2933   void
2934   do_export(Export*) const;
2935
2936   void
2937   do_dump_expression(Ast_dump_context*) const;
2938
2939  private:
2940   // The type to convert to.
2941   Type* type_;
2942   // The expression to convert.
2943   Expression* expr_;
2944   // True if this is permitted to convert function types.  This is
2945   // used internally for method expressions.
2946   bool may_convert_function_types_;
2947 };
2948
2949 // Traversal.
2950
2951 int
2952 Type_conversion_expression::do_traverse(Traverse* traverse)
2953 {
2954   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2955       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2956     return TRAVERSE_EXIT;
2957   return TRAVERSE_CONTINUE;
2958 }
2959
2960 // Convert to a constant at lowering time.
2961
2962 Expression*
2963 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2964                                      Statement_inserter*, int)
2965 {
2966   Type* type = this->type_;
2967   Expression* val = this->expr_;
2968   Location location = this->location();
2969
2970   if (type->is_numeric_type())
2971     {
2972       Numeric_constant nc;
2973       if (val->numeric_constant_value(&nc))
2974         {
2975           if (!nc.set_type(type, true, location))
2976             return Expression::make_error(location);
2977           return nc.expression(location);
2978         }
2979     }
2980
2981   if (type->is_slice_type())
2982     {
2983       Type* element_type = type->array_type()->element_type()->forwarded();
2984       bool is_byte = (element_type->integer_type() != NULL
2985                       && element_type->integer_type()->is_byte());
2986       bool is_rune = (element_type->integer_type() != NULL
2987                       && element_type->integer_type()->is_rune());
2988       if (is_byte || is_rune)
2989         {
2990           std::string s;
2991           if (val->string_constant_value(&s))
2992             {
2993               Expression_list* vals = new Expression_list();
2994               if (is_byte)
2995                 {
2996                   for (std::string::const_iterator p = s.begin();
2997                        p != s.end();
2998                        p++)
2999                     {
3000                       mpz_t val;
3001                       mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3002                       Expression* v = Expression::make_integer(&val,
3003                                                                element_type,
3004                                                                location);
3005                       vals->push_back(v);
3006                       mpz_clear(val);
3007                     }
3008                 }
3009               else
3010                 {
3011                   const char *p = s.data();
3012                   const char *pend = s.data() + s.length();
3013                   while (p < pend)
3014                     {
3015                       unsigned int c;
3016                       int adv = Lex::fetch_char(p, &c);
3017                       if (adv == 0)
3018                         {
3019                           warning_at(this->location(), 0,
3020                                      "invalid UTF-8 encoding");
3021                           adv = 1;
3022                         }
3023                       p += adv;
3024                       mpz_t val;
3025                       mpz_init_set_ui(val, c);
3026                       Expression* v = Expression::make_integer(&val,
3027                                                                element_type,
3028                                                                location);
3029                       vals->push_back(v);
3030                       mpz_clear(val);
3031                     }
3032                 }
3033
3034               return Expression::make_slice_composite_literal(type, vals,
3035                                                               location);
3036             }
3037         }
3038     }
3039
3040   return this;
3041 }
3042
3043 // Return the constant numeric value if there is one.
3044
3045 bool
3046 Type_conversion_expression::do_numeric_constant_value(
3047     Numeric_constant* nc) const
3048 {
3049   if (!this->type_->is_numeric_type())
3050     return false;
3051   if (!this->expr_->numeric_constant_value(nc))
3052     return false;
3053   return nc->set_type(this->type_, false, this->location());
3054 }
3055
3056 // Return the constant string value if there is one.
3057
3058 bool
3059 Type_conversion_expression::do_string_constant_value(std::string* val) const
3060 {
3061   if (this->type_->is_string_type()
3062       && this->expr_->type()->integer_type() != NULL)
3063     {
3064       Numeric_constant nc;
3065       if (this->expr_->numeric_constant_value(&nc))
3066         {
3067           unsigned long ival;
3068           if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3069             {
3070               val->clear();
3071               Lex::append_char(ival, true, val, this->location());
3072               return true;
3073             }
3074         }
3075     }
3076
3077   // FIXME: Could handle conversion from const []int here.
3078
3079   return false;
3080 }
3081
3082 // Check that types are convertible.
3083
3084 void
3085 Type_conversion_expression::do_check_types(Gogo*)
3086 {
3087   Type* type = this->type_;
3088   Type* expr_type = this->expr_->type();
3089   std::string reason;
3090
3091   if (type->is_error() || expr_type->is_error())
3092     {
3093       this->set_is_error();
3094       return;
3095     }
3096
3097   if (this->may_convert_function_types_
3098       && type->function_type() != NULL
3099       && expr_type->function_type() != NULL)
3100     return;
3101
3102   if (Type::are_convertible(type, expr_type, &reason))
3103     return;
3104
3105   error_at(this->location(), "%s", reason.c_str());
3106   this->set_is_error();
3107 }
3108
3109 // Get a tree for a type conversion.
3110
3111 tree
3112 Type_conversion_expression::do_get_tree(Translate_context* context)
3113 {
3114   Gogo* gogo = context->gogo();
3115   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3116   tree expr_tree = this->expr_->get_tree(context);
3117
3118   if (type_tree == error_mark_node
3119       || expr_tree == error_mark_node
3120       || TREE_TYPE(expr_tree) == error_mark_node)
3121     return error_mark_node;
3122
3123   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3124     return fold_convert(type_tree, expr_tree);
3125
3126   Type* type = this->type_;
3127   Type* expr_type = this->expr_->type();
3128   tree ret;
3129   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3130     ret = Expression::convert_for_assignment(context, type, expr_type,
3131                                              expr_tree, this->location());
3132   else if (type->integer_type() != NULL)
3133     {
3134       if (expr_type->integer_type() != NULL
3135           || expr_type->float_type() != NULL
3136           || expr_type->is_unsafe_pointer_type())
3137         ret = fold(convert_to_integer(type_tree, expr_tree));
3138       else
3139         go_unreachable();
3140     }
3141   else if (type->float_type() != NULL)
3142     {
3143       if (expr_type->integer_type() != NULL
3144           || expr_type->float_type() != NULL)
3145         ret = fold(convert_to_real(type_tree, expr_tree));
3146       else
3147         go_unreachable();
3148     }
3149   else if (type->complex_type() != NULL)
3150     {
3151       if (expr_type->complex_type() != NULL)
3152         ret = fold(convert_to_complex(type_tree, expr_tree));
3153       else
3154         go_unreachable();
3155     }
3156   else if (type->is_string_type()
3157            && expr_type->integer_type() != NULL)
3158     {
3159       expr_tree = fold_convert(integer_type_node, expr_tree);
3160       if (host_integerp(expr_tree, 0))
3161         {
3162           HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3163           std::string s;
3164           Lex::append_char(intval, true, &s, this->location());
3165           Expression* se = Expression::make_string(s, this->location());
3166           return se->get_tree(context);
3167         }
3168
3169       static tree int_to_string_fndecl;
3170       ret = Gogo::call_builtin(&int_to_string_fndecl,
3171                                this->location(),
3172                                "__go_int_to_string",
3173                                1,
3174                                type_tree,
3175                                integer_type_node,
3176                                fold_convert(integer_type_node, expr_tree));
3177     }
3178   else if (type->is_string_type() && expr_type->is_slice_type())
3179     {
3180       if (!DECL_P(expr_tree))
3181         expr_tree = save_expr(expr_tree);
3182       Array_type* a = expr_type->array_type();
3183       Type* e = a->element_type()->forwarded();
3184       go_assert(e->integer_type() != NULL);
3185       tree valptr = fold_convert(const_ptr_type_node,
3186                                  a->value_pointer_tree(gogo, expr_tree));
3187       tree len = a->length_tree(gogo, expr_tree);
3188       len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3189                              len);
3190       if (e->integer_type()->is_byte())
3191         {
3192           static tree byte_array_to_string_fndecl;
3193           ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3194                                    this->location(),
3195                                    "__go_byte_array_to_string",
3196                                    2,
3197                                    type_tree,
3198                                    const_ptr_type_node,
3199                                    valptr,
3200                                    integer_type_node,
3201                                    len);
3202         }
3203       else
3204         {
3205           go_assert(e->integer_type()->is_rune());
3206           static tree int_array_to_string_fndecl;
3207           ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3208                                    this->location(),
3209                                    "__go_int_array_to_string",
3210                                    2,
3211                                    type_tree,
3212                                    const_ptr_type_node,
3213                                    valptr,
3214                                    integer_type_node,
3215                                    len);
3216         }
3217     }
3218   else if (type->is_slice_type() && expr_type->is_string_type())
3219     {
3220       Type* e = type->array_type()->element_type()->forwarded();
3221       go_assert(e->integer_type() != NULL);
3222       if (e->integer_type()->is_byte())
3223         {
3224           tree string_to_byte_array_fndecl = NULL_TREE;
3225           ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3226                                    this->location(),
3227                                    "__go_string_to_byte_array",
3228                                    1,
3229                                    type_tree,
3230                                    TREE_TYPE(expr_tree),
3231                                    expr_tree);
3232         }
3233       else
3234         {
3235           go_assert(e->integer_type()->is_rune());
3236           tree string_to_int_array_fndecl = NULL_TREE;
3237           ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3238                                    this->location(),
3239                                    "__go_string_to_int_array",
3240                                    1,
3241                                    type_tree,
3242                                    TREE_TYPE(expr_tree),
3243                                    expr_tree);
3244         }
3245     }
3246   else if ((type->is_unsafe_pointer_type()
3247             && expr_type->points_to() != NULL)
3248            || (expr_type->is_unsafe_pointer_type()
3249                && type->points_to() != NULL))
3250     ret = fold_convert(type_tree, expr_tree);
3251   else if (type->is_unsafe_pointer_type()
3252            && expr_type->integer_type() != NULL)
3253     ret = convert_to_pointer(type_tree, expr_tree);
3254   else if (this->may_convert_function_types_
3255            && type->function_type() != NULL
3256            && expr_type->function_type() != NULL)
3257     ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3258                            expr_tree);
3259   else
3260     ret = Expression::convert_for_assignment(context, type, expr_type,
3261                                              expr_tree, this->location());
3262
3263   return ret;
3264 }
3265
3266 // Output a type conversion in a constant expression.
3267
3268 void
3269 Type_conversion_expression::do_export(Export* exp) const
3270 {
3271   exp->write_c_string("convert(");
3272   exp->write_type(this->type_);
3273   exp->write_c_string(", ");
3274   this->expr_->export_expression(exp);
3275   exp->write_c_string(")");
3276 }
3277
3278 // Import a type conversion or a struct construction.
3279
3280 Expression*
3281 Type_conversion_expression::do_import(Import* imp)
3282 {
3283   imp->require_c_string("convert(");
3284   Type* type = imp->read_type();
3285   imp->require_c_string(", ");
3286   Expression* val = Expression::import_expression(imp);
3287   imp->require_c_string(")");
3288   return Expression::make_cast(type, val, imp->location());
3289 }
3290
3291 // Dump ast representation for a type conversion expression.
3292
3293 void
3294 Type_conversion_expression::do_dump_expression(
3295     Ast_dump_context* ast_dump_context) const
3296 {
3297   ast_dump_context->dump_type(this->type_);
3298   ast_dump_context->ostream() << "(";
3299   ast_dump_context->dump_expression(this->expr_);
3300   ast_dump_context->ostream() << ") ";
3301 }
3302
3303 // Make a type cast expression.
3304
3305 Expression*
3306 Expression::make_cast(Type* type, Expression* val, Location location)
3307 {
3308   if (type->is_error_type() || val->is_error_expression())
3309     return Expression::make_error(location);
3310   return new Type_conversion_expression(type, val, location);
3311 }
3312
3313 // An unsafe type conversion, used to pass values to builtin functions.
3314
3315 class Unsafe_type_conversion_expression : public Expression
3316 {
3317  public:
3318   Unsafe_type_conversion_expression(Type* type, Expression* expr,
3319                                     Location location)
3320     : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3321       type_(type), expr_(expr)
3322   { }
3323
3324  protected:
3325   int
3326   do_traverse(Traverse* traverse);
3327
3328   Type*
3329   do_type()
3330   { return this->type_; }
3331
3332   void
3333   do_determine_type(const Type_context*)
3334   { this->expr_->determine_type_no_context(); }
3335
3336   Expression*
3337   do_copy()
3338   {
3339     return new Unsafe_type_conversion_expression(this->type_,
3340                                                  this->expr_->copy(),
3341                                                  this->location());
3342   }
3343
3344   tree
3345   do_get_tree(Translate_context*);
3346
3347   void
3348   do_dump_expression(Ast_dump_context*) const;
3349
3350  private:
3351   // The type to convert to.
3352   Type* type_;
3353   // The expression to convert.
3354   Expression* expr_;
3355 };
3356
3357 // Traversal.
3358
3359 int
3360 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3361 {
3362   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3363       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3364     return TRAVERSE_EXIT;
3365   return TRAVERSE_CONTINUE;
3366 }
3367
3368 // Convert to backend representation.
3369
3370 tree
3371 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3372 {
3373   // We are only called for a limited number of cases.
3374
3375   Type* t = this->type_;
3376   Type* et = this->expr_->type();
3377
3378   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3379   tree expr_tree = this->expr_->get_tree(context);
3380   if (type_tree == error_mark_node || expr_tree == error_mark_node)
3381     return error_mark_node;
3382
3383   Location loc = this->location();
3384
3385   bool use_view_convert = false;
3386   if (t->is_slice_type())
3387     {
3388       go_assert(et->is_slice_type());
3389       use_view_convert = true;
3390     }
3391   else if (t->map_type() != NULL)
3392     go_assert(et->map_type() != NULL);
3393   else if (t->channel_type() != NULL)
3394     go_assert(et->channel_type() != NULL);
3395   else if (t->points_to() != NULL)
3396     go_assert(et->points_to() != NULL || et->is_nil_type());
3397   else if (et->is_unsafe_pointer_type())
3398     go_assert(t->points_to() != NULL);
3399   else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3400     {
3401       go_assert(et->interface_type() != NULL
3402                  && !et->interface_type()->is_empty());
3403       use_view_convert = true;
3404     }
3405   else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3406     {
3407       go_assert(et->interface_type() != NULL
3408                  && et->interface_type()->is_empty());
3409       use_view_convert = true;
3410     }
3411   else if (t->integer_type() != NULL)
3412     {
3413       go_assert(et->is_boolean_type()
3414                  || et->integer_type() != NULL
3415                  || et->function_type() != NULL
3416                  || et->points_to() != NULL
3417                  || et->map_type() != NULL
3418                  || et->channel_type() != NULL);
3419       return convert_to_integer(type_tree, expr_tree);
3420     }
3421   else
3422     go_unreachable();
3423
3424   if (use_view_convert)
3425     return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3426                            expr_tree);
3427   else
3428     return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3429 }
3430
3431 // Dump ast representation for an unsafe type conversion expression.
3432
3433 void
3434 Unsafe_type_conversion_expression::do_dump_expression(
3435     Ast_dump_context* ast_dump_context) const
3436 {
3437   ast_dump_context->dump_type(this->type_);
3438   ast_dump_context->ostream() << "(";
3439   ast_dump_context->dump_expression(this->expr_);
3440   ast_dump_context->ostream() << ") ";
3441 }
3442
3443 // Make an unsafe type conversion expression.
3444
3445 Expression*
3446 Expression::make_unsafe_cast(Type* type, Expression* expr,
3447                              Location location)
3448 {
3449   return new Unsafe_type_conversion_expression(type, expr, location);
3450 }
3451
3452 // Unary expressions.
3453
3454 class Unary_expression : public Expression
3455 {
3456  public:
3457   Unary_expression(Operator op, Expression* expr, Location location)
3458     : Expression(EXPRESSION_UNARY, location),
3459       op_(op), escapes_(true), create_temp_(false), expr_(expr)
3460   { }
3461
3462   // Return the operator.
3463   Operator
3464   op() const
3465   { return this->op_; }
3466
3467   // Return the operand.
3468   Expression*
3469   operand() const
3470   { return this->expr_; }
3471
3472   // Record that an address expression does not escape.
3473   void
3474   set_does_not_escape()
3475   {
3476     go_assert(this->op_ == OPERATOR_AND);
3477     this->escapes_ = false;
3478   }
3479
3480   // Record that this is an address expression which should create a
3481   // temporary variable if necessary.  This is used for method calls.
3482   void
3483   set_create_temp()
3484   {
3485     go_assert(this->op_ == OPERATOR_AND);
3486     this->create_temp_ = true;
3487   }
3488
3489   // Apply unary opcode OP to UNC, setting NC.  Return true if this
3490   // could be done, false if not.  Issue errors for overflow.
3491   static bool
3492   eval_constant(Operator op, const Numeric_constant* unc,
3493                 Location, Numeric_constant* nc);
3494
3495   static Expression*
3496   do_import(Import*);
3497
3498  protected:
3499   int
3500   do_traverse(Traverse* traverse)
3501   { return Expression::traverse(&this->expr_, traverse); }
3502
3503   Expression*
3504   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3505
3506   bool
3507   do_is_constant() const;
3508
3509   bool
3510   do_numeric_constant_value(Numeric_constant*) const;
3511
3512   Type*
3513   do_type();
3514
3515   void
3516   do_determine_type(const Type_context*);
3517
3518   void
3519   do_check_types(Gogo*);
3520
3521   Expression*
3522   do_copy()
3523   {
3524     return Expression::make_unary(this->op_, this->expr_->copy(),
3525                                   this->location());
3526   }
3527