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 "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
24 
25 // Class Expression.
26 
Expression(Expression_classification classification,Location location)27 Expression::Expression(Expression_classification classification,
28 		       Location location)
29   : classification_(classification), location_(location)
30 {
31 }
32 
~Expression()33 Expression::~Expression()
34 {
35 }
36 
37 // Traverse the expressions.
38 
39 int
traverse(Expression ** pexpr,Traverse * traverse)40 Expression::traverse(Expression** pexpr, Traverse* traverse)
41 {
42   Expression* expr = *pexpr;
43   if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
44     {
45       int t = traverse->expression(pexpr);
46       if (t == TRAVERSE_EXIT)
47 	return TRAVERSE_EXIT;
48       else if (t == TRAVERSE_SKIP_COMPONENTS)
49 	return TRAVERSE_CONTINUE;
50     }
51   return expr->do_traverse(traverse);
52 }
53 
54 // Traverse subexpressions of this expression.
55 
56 int
traverse_subexpressions(Traverse * traverse)57 Expression::traverse_subexpressions(Traverse* traverse)
58 {
59   return this->do_traverse(traverse);
60 }
61 
62 // Default implementation for do_traverse for child classes.
63 
64 int
do_traverse(Traverse *)65 Expression::do_traverse(Traverse*)
66 {
67   return TRAVERSE_CONTINUE;
68 }
69 
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded.  By default, we give an error.
72 // Expressions with side effects override.
73 
74 bool
do_discarding_value()75 Expression::do_discarding_value()
76 {
77   this->unused_value_error();
78   return false;
79 }
80 
81 // This virtual function is called to export expressions.  This will
82 // only be used by expressions which may be constant.
83 
84 void
do_export(Export *) const85 Expression::do_export(Export*) const
86 {
87   go_unreachable();
88 }
89 
90 // Give an error saying that the value of the expression is not used.
91 
92 void
unused_value_error()93 Expression::unused_value_error()
94 {
95   this->report_error(_("value computed is not used"));
96 }
97 
98 // Note that this expression is an error.  This is called by children
99 // when they discover an error.
100 
101 void
set_is_error()102 Expression::set_is_error()
103 {
104   this->classification_ = EXPRESSION_ERROR;
105 }
106 
107 // For children to call to report an error conveniently.
108 
109 void
report_error(const char * msg)110 Expression::report_error(const char* msg)
111 {
112   go_error_at(this->location_, "%s", msg);
113   this->set_is_error();
114 }
115 
116 // Set types of variables and constants.  This is implemented by the
117 // child class.
118 
119 void
determine_type(const Type_context * context)120 Expression::determine_type(const Type_context* context)
121 {
122   this->do_determine_type(context);
123 }
124 
125 // Set types when there is no context.
126 
127 void
determine_type_no_context()128 Expression::determine_type_no_context()
129 {
130   Type_context context;
131   this->do_determine_type(&context);
132 }
133 
134 // Return an expression handling any conversions which must be done during
135 // assignment.
136 
137 Expression*
convert_for_assignment(Gogo *,Type * lhs_type,Expression * rhs,Location location)138 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
139 				   Expression* rhs, Location location)
140 {
141   Type* rhs_type = rhs->type();
142   if (lhs_type->is_error()
143       || rhs_type->is_error()
144       || rhs->is_error_expression())
145     return Expression::make_error(location);
146 
147   bool are_identical = Type::are_identical(lhs_type, rhs_type, false, NULL);
148   if (!are_identical && lhs_type->interface_type() != NULL)
149     {
150       if (rhs_type->interface_type() == NULL)
151         return Expression::convert_type_to_interface(lhs_type, rhs, location);
152       else
153         return Expression::convert_interface_to_interface(lhs_type, rhs, false,
154                                                           location);
155     }
156   else if (!are_identical && rhs_type->interface_type() != NULL)
157     return Expression::convert_interface_to_type(lhs_type, rhs, location);
158   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
159     {
160       // Assigning nil to a slice.
161       Expression* nil = Expression::make_nil(location);
162       Expression* zero = Expression::make_integer_ul(0, NULL, location);
163       return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
164     }
165   else if (rhs_type->is_nil_type())
166     return Expression::make_nil(location);
167   else if (are_identical)
168     {
169       if (lhs_type->forwarded() != rhs_type->forwarded())
170 	{
171 	  // Different but identical types require an explicit
172 	  // conversion.  This happens with type aliases.
173 	  return Expression::make_cast(lhs_type, rhs, location);
174 	}
175 
176       // No conversion is needed.
177       return rhs;
178     }
179   else if (lhs_type->points_to() != NULL)
180     return Expression::make_unsafe_cast(lhs_type, rhs, location);
181   else if (lhs_type->is_numeric_type())
182     return Expression::make_cast(lhs_type, rhs, location);
183   else if ((lhs_type->struct_type() != NULL
184             && rhs_type->struct_type() != NULL)
185            || (lhs_type->array_type() != NULL
186                && rhs_type->array_type() != NULL))
187     {
188       // This conversion must be permitted by Go, or we wouldn't have
189       // gotten here.
190       return Expression::make_unsafe_cast(lhs_type, rhs, location);
191     }
192   else
193     return rhs;
194 }
195 
196 // Return an expression for a conversion from a non-interface type to an
197 // interface type.
198 
199 Expression*
convert_type_to_interface(Type * lhs_type,Expression * rhs,Location location)200 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
201                                       Location location)
202 {
203   Interface_type* lhs_interface_type = lhs_type->interface_type();
204   bool lhs_is_empty = lhs_interface_type->is_empty();
205 
206   // Since RHS_TYPE is a static type, we can create the interface
207   // method table at compile time.
208 
209   // When setting an interface to nil, we just set both fields to
210   // NULL.
211   Type* rhs_type = rhs->type();
212   if (rhs_type->is_nil_type())
213     {
214       Expression* nil = Expression::make_nil(location);
215       return Expression::make_interface_value(lhs_type, nil, nil, location);
216     }
217 
218   // This should have been checked already.
219   if (!lhs_interface_type->implements_interface(rhs_type, NULL))
220     {
221       go_assert(saw_errors());
222       return Expression::make_error(location);
223     }
224 
225   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
226   // then the first field is the type descriptor for RHS_TYPE.
227   // Otherwise it is the interface method table for RHS_TYPE.
228   Expression* first_field;
229   if (lhs_is_empty)
230     first_field = Expression::make_type_descriptor(rhs_type, location);
231   else
232     {
233       // Build the interface method table for this interface and this
234       // object type: a list of function pointers for each interface
235       // method.
236       Named_type* rhs_named_type = rhs_type->named_type();
237       Struct_type* rhs_struct_type = rhs_type->struct_type();
238       bool is_pointer = false;
239       if (rhs_named_type == NULL && rhs_struct_type == NULL)
240 	{
241 	  rhs_named_type = rhs_type->deref()->named_type();
242 	  rhs_struct_type = rhs_type->deref()->struct_type();
243 	  is_pointer = true;
244 	}
245       if (rhs_named_type != NULL)
246 	first_field =
247 	  rhs_named_type->interface_method_table(lhs_interface_type,
248                                                  is_pointer);
249       else if (rhs_struct_type != NULL)
250 	first_field =
251 	  rhs_struct_type->interface_method_table(lhs_interface_type,
252                                                   is_pointer);
253       else
254 	first_field = Expression::make_nil(location);
255     }
256 
257   Expression* obj;
258   if (rhs_type->points_to() != NULL)
259     {
260       // We are assigning a pointer to the interface; the interface
261       // holds the pointer itself.
262       obj = rhs;
263     }
264   else
265     {
266       // We are assigning a non-pointer value to the interface; the
267       // interface gets a copy of the value in the heap if it escapes.
268       // TODO(cmang): Associate escape state state of RHS with newly
269       // created OBJ.
270       obj = Expression::make_heap_expression(rhs, location);
271     }
272 
273   return Expression::make_interface_value(lhs_type, first_field, obj, location);
274 }
275 
276 // Return an expression for the type descriptor of RHS.
277 
278 Expression*
get_interface_type_descriptor(Expression * rhs)279 Expression::get_interface_type_descriptor(Expression* rhs)
280 {
281   go_assert(rhs->type()->interface_type() != NULL);
282   Location location = rhs->location();
283 
284   // The type descriptor is the first field of an empty interface.
285   if (rhs->type()->interface_type()->is_empty())
286     return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
287                                            location);
288 
289   Expression* mtable =
290       Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
291 
292   Expression* descriptor =
293       Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
294   descriptor = Expression::make_field_reference(descriptor, 0, location);
295   Expression* nil = Expression::make_nil(location);
296 
297   Expression* eq =
298       Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
299   return Expression::make_conditional(eq, nil, descriptor, location);
300 }
301 
302 // Return an expression for the conversion of an interface type to an
303 // interface type.
304 
305 Expression*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)306 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
307                                            bool for_type_guard,
308                                            Location location)
309 {
310   if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
311     return rhs;
312 
313   Interface_type* lhs_interface_type = lhs_type->interface_type();
314   bool lhs_is_empty = lhs_interface_type->is_empty();
315 
316   // In the general case this requires runtime examination of the type
317   // method table to match it up with the interface methods.
318 
319   // FIXME: If all of the methods in the right hand side interface
320   // also appear in the left hand side interface, then we don't need
321   // to do a runtime check, although we still need to build a new
322   // method table.
323 
324   // We are going to evaluate RHS multiple times.
325   go_assert(rhs->is_variable());
326 
327   // Get the type descriptor for the right hand side.  This will be
328   // NULL for a nil interface.
329   Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
330   Expression* lhs_type_expr =
331       Expression::make_type_descriptor(lhs_type, location);
332 
333   Expression* first_field;
334   if (for_type_guard)
335     {
336       // A type assertion fails when converting a nil interface.
337       first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
338 				       lhs_type_expr, rhs_type_expr);
339     }
340   else if (lhs_is_empty)
341     {
342       // A conversion to an empty interface always succeeds, and the
343       // first field is just the type descriptor of the object.
344       first_field = rhs_type_expr;
345     }
346   else
347     {
348       // A conversion to a non-empty interface may fail, but unlike a
349       // type assertion converting nil will always succeed.
350       first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
351 				       lhs_type_expr, rhs_type_expr);
352     }
353 
354   // The second field is simply the object pointer.
355   Expression* obj =
356       Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
357   return Expression::make_interface_value(lhs_type, first_field, obj, location);
358 }
359 
360 // Return an expression for the conversion of an interface type to a
361 // non-interface type.
362 
363 Expression*
convert_interface_to_type(Type * lhs_type,Expression * rhs,Location location)364 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
365                                       Location location)
366 {
367   // We are going to evaluate RHS multiple times.
368   go_assert(rhs->is_variable());
369 
370   // Call a function to check that the type is valid.  The function
371   // will panic with an appropriate runtime type error if the type is
372   // not valid.
373   Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
374                                                                 location);
375   Expression* rhs_descriptor =
376       Expression::get_interface_type_descriptor(rhs);
377 
378   Type* rhs_type = rhs->type();
379   Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
380                                                                 location);
381 
382   Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
383                                                location, 3, lhs_type_expr,
384                                                rhs_descriptor, rhs_inter_expr);
385 
386   // If the call succeeds, pull out the value.
387   Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
388                                                     location);
389 
390   // If the value is a pointer, then it is the value we want.
391   // Otherwise it points to the value.
392   if (lhs_type->points_to() == NULL)
393     {
394       obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
395                                          location);
396       obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
397                                          location);
398     }
399   return Expression::make_compound(check_iface, obj, location);
400 }
401 
402 // Convert an expression to its backend representation.  This is implemented by
403 // the child class.  Not that it is not in general safe to call this multiple
404 // times for a single expression, but that we don't catch such errors.
405 
406 Bexpression*
get_backend(Translate_context * context)407 Expression::get_backend(Translate_context* context)
408 {
409   // The child may have marked this expression as having an error.
410   if (this->classification_ == EXPRESSION_ERROR)
411     return context->backend()->error_expression();
412 
413   return this->do_get_backend(context);
414 }
415 
416 // Return a backend expression for VAL.
417 Bexpression*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)418 Expression::backend_numeric_constant_expression(Translate_context* context,
419                                                 Numeric_constant* val)
420 {
421   Gogo* gogo = context->gogo();
422   Type* type = val->type();
423   if (type == NULL)
424     return gogo->backend()->error_expression();
425 
426   Btype* btype = type->get_backend(gogo);
427   Bexpression* ret;
428   if (type->integer_type() != NULL)
429     {
430       mpz_t ival;
431       if (!val->to_int(&ival))
432         {
433           go_assert(saw_errors());
434           return gogo->backend()->error_expression();
435         }
436       ret = gogo->backend()->integer_constant_expression(btype, ival);
437       mpz_clear(ival);
438     }
439   else if (type->float_type() != NULL)
440     {
441       mpfr_t fval;
442       if (!val->to_float(&fval))
443         {
444           go_assert(saw_errors());
445           return gogo->backend()->error_expression();
446         }
447       ret = gogo->backend()->float_constant_expression(btype, fval);
448       mpfr_clear(fval);
449     }
450   else if (type->complex_type() != NULL)
451     {
452       mpc_t cval;
453       if (!val->to_complex(&cval))
454         {
455           go_assert(saw_errors());
456           return gogo->backend()->error_expression();
457         }
458       ret = gogo->backend()->complex_constant_expression(btype, cval);
459       mpc_clear(cval);
460     }
461   else
462     go_unreachable();
463 
464   return ret;
465 }
466 
467 // Return an expression which evaluates to true if VAL, of arbitrary integer
468 // type, is negative or is more than the maximum value of the Go type "int".
469 
470 Expression*
check_bounds(Expression * val,Location loc)471 Expression::check_bounds(Expression* val, Location loc)
472 {
473   Type* val_type = val->type();
474   Type* bound_type = Type::lookup_integer_type("int");
475 
476   int val_type_size;
477   bool val_is_unsigned = false;
478   if (val_type->integer_type() != NULL)
479     {
480       val_type_size = val_type->integer_type()->bits();
481       val_is_unsigned = val_type->integer_type()->is_unsigned();
482     }
483   else
484     {
485       if (!val_type->is_numeric_type()
486           || !Type::are_convertible(bound_type, val_type, NULL))
487         {
488           go_assert(saw_errors());
489           return Expression::make_boolean(true, loc);
490         }
491 
492       if (val_type->complex_type() != NULL)
493         val_type_size = val_type->complex_type()->bits();
494       else
495         val_type_size = val_type->float_type()->bits();
496     }
497 
498   Expression* negative_index = Expression::make_boolean(false, loc);
499   Expression* index_overflows = Expression::make_boolean(false, loc);
500   if (!val_is_unsigned)
501     {
502       Expression* zero = Expression::make_integer_ul(0, val_type, loc);
503       negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
504     }
505 
506   int bound_type_size = bound_type->integer_type()->bits();
507   if (val_type_size > bound_type_size
508       || (val_type_size == bound_type_size
509 	  && val_is_unsigned))
510     {
511       mpz_t one;
512       mpz_init_set_ui(one, 1UL);
513 
514       // maxval = 2^(bound_type_size - 1) - 1
515       mpz_t maxval;
516       mpz_init(maxval);
517       mpz_mul_2exp(maxval, one, bound_type_size - 1);
518       mpz_sub_ui(maxval, maxval, 1);
519       Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
520       mpz_clear(one);
521       mpz_clear(maxval);
522 
523       index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
524     }
525 
526   return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
527                                  loc);
528 }
529 
530 void
dump_expression(Ast_dump_context * ast_dump_context) const531 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
532 {
533   this->do_dump_expression(ast_dump_context);
534 }
535 
536 // Error expressions.  This are used to avoid cascading errors.
537 
538 class Error_expression : public Expression
539 {
540  public:
Error_expression(Location location)541   Error_expression(Location location)
542     : Expression(EXPRESSION_ERROR, location)
543   { }
544 
545  protected:
546   bool
do_is_constant() const547   do_is_constant() const
548   { return true; }
549 
550   bool
do_numeric_constant_value(Numeric_constant * nc) const551   do_numeric_constant_value(Numeric_constant* nc) const
552   {
553     nc->set_unsigned_long(NULL, 0);
554     return true;
555   }
556 
557   bool
do_discarding_value()558   do_discarding_value()
559   { return true; }
560 
561   Type*
do_type()562   do_type()
563   { return Type::make_error_type(); }
564 
565   void
do_determine_type(const Type_context *)566   do_determine_type(const Type_context*)
567   { }
568 
569   Expression*
do_copy()570   do_copy()
571   { return this; }
572 
573   bool
do_is_addressable() const574   do_is_addressable() const
575   { return true; }
576 
577   Bexpression*
do_get_backend(Translate_context * context)578   do_get_backend(Translate_context* context)
579   { return context->backend()->error_expression(); }
580 
581   void
582   do_dump_expression(Ast_dump_context*) const;
583 };
584 
585 // Dump the ast representation for an error expression to a dump context.
586 
587 void
do_dump_expression(Ast_dump_context * ast_dump_context) const588 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
589 {
590   ast_dump_context->ostream() << "_Error_" ;
591 }
592 
593 Expression*
make_error(Location location)594 Expression::make_error(Location location)
595 {
596   return new Error_expression(location);
597 }
598 
599 // An expression which is really a type.  This is used during parsing.
600 // It is an error if these survive after lowering.
601 
602 class
603 Type_expression : public Expression
604 {
605  public:
Type_expression(Type * type,Location location)606   Type_expression(Type* type, Location location)
607     : Expression(EXPRESSION_TYPE, location),
608       type_(type)
609   { }
610 
611  protected:
612   int
do_traverse(Traverse * traverse)613   do_traverse(Traverse* traverse)
614   { return Type::traverse(this->type_, traverse); }
615 
616   Type*
do_type()617   do_type()
618   { return this->type_; }
619 
620   void
do_determine_type(const Type_context *)621   do_determine_type(const Type_context*)
622   { }
623 
624   void
do_check_types(Gogo *)625   do_check_types(Gogo*)
626   { this->report_error(_("invalid use of type")); }
627 
628   Expression*
do_copy()629   do_copy()
630   { return this; }
631 
632   Bexpression*
do_get_backend(Translate_context *)633   do_get_backend(Translate_context*)
634   { go_unreachable(); }
635 
636   void do_dump_expression(Ast_dump_context*) const;
637 
638  private:
639   // The type which we are representing as an expression.
640   Type* type_;
641 };
642 
643 void
do_dump_expression(Ast_dump_context * ast_dump_context) const644 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
645 {
646   ast_dump_context->dump_type(this->type_);
647 }
648 
649 Expression*
make_type(Type * type,Location location)650 Expression::make_type(Type* type, Location location)
651 {
652   return new Type_expression(type, location);
653 }
654 
655 // Class Parser_expression.
656 
657 Type*
do_type()658 Parser_expression::do_type()
659 {
660   // We should never really ask for the type of a Parser_expression.
661   // However, it can happen, at least when we have an invalid const
662   // whose initializer refers to the const itself.  In that case we
663   // may ask for the type when lowering the const itself.
664   go_assert(saw_errors());
665   return Type::make_error_type();
666 }
667 
668 // Class Var_expression.
669 
670 // Lower a variable expression.  Here we just make sure that the
671 // initialization expression of the variable has been lowered.  This
672 // ensures that we will be able to determine the type of the variable
673 // if necessary.
674 
675 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)676 Var_expression::do_lower(Gogo* gogo, Named_object* function,
677 			 Statement_inserter* inserter, int)
678 {
679   if (this->variable_->is_variable())
680     {
681       Variable* var = this->variable_->var_value();
682       // This is either a local variable or a global variable.  A
683       // reference to a variable which is local to an enclosing
684       // function will be a reference to a field in a closure.
685       if (var->is_global())
686 	{
687 	  function = NULL;
688 	  inserter = NULL;
689 	}
690       var->lower_init_expression(gogo, function, inserter);
691     }
692   return this;
693 }
694 
695 // Return the type of a reference to a variable.
696 
697 Type*
do_type()698 Var_expression::do_type()
699 {
700   if (this->variable_->is_variable())
701     return this->variable_->var_value()->type();
702   else if (this->variable_->is_result_variable())
703     return this->variable_->result_var_value()->type();
704   else
705     go_unreachable();
706 }
707 
708 // Determine the type of a reference to a variable.
709 
710 void
do_determine_type(const Type_context *)711 Var_expression::do_determine_type(const Type_context*)
712 {
713   if (this->variable_->is_variable())
714     this->variable_->var_value()->determine_type();
715 }
716 
717 // Something takes the address of this variable.  This means that we
718 // may want to move the variable onto the heap.
719 
720 void
do_address_taken(bool escapes)721 Var_expression::do_address_taken(bool escapes)
722 {
723   if (!escapes)
724     {
725       if (this->variable_->is_variable())
726 	this->variable_->var_value()->set_non_escaping_address_taken();
727       else if (this->variable_->is_result_variable())
728 	this->variable_->result_var_value()->set_non_escaping_address_taken();
729       else
730 	go_unreachable();
731     }
732   else
733     {
734       if (this->variable_->is_variable())
735 	this->variable_->var_value()->set_address_taken();
736       else if (this->variable_->is_result_variable())
737 	this->variable_->result_var_value()->set_address_taken();
738       else
739 	go_unreachable();
740     }
741 
742   if (this->variable_->is_variable()
743       && this->variable_->var_value()->is_in_heap())
744     {
745       Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
746       Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
747     }
748 }
749 
750 // Get the backend representation for a reference to a variable.
751 
752 Bexpression*
do_get_backend(Translate_context * context)753 Var_expression::do_get_backend(Translate_context* context)
754 {
755   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
756 							  context->function());
757   bool is_in_heap;
758   Location loc = this->location();
759   Btype* btype;
760   Gogo* gogo = context->gogo();
761   if (this->variable_->is_variable())
762     {
763       is_in_heap = this->variable_->var_value()->is_in_heap();
764       btype = this->variable_->var_value()->type()->get_backend(gogo);
765     }
766   else if (this->variable_->is_result_variable())
767     {
768       is_in_heap = this->variable_->result_var_value()->is_in_heap();
769       btype = this->variable_->result_var_value()->type()->get_backend(gogo);
770     }
771   else
772     go_unreachable();
773 
774   Bexpression* ret =
775       context->backend()->var_expression(bvar, loc);
776   if (is_in_heap)
777     ret = context->backend()->indirect_expression(btype, ret, true, loc);
778   return ret;
779 }
780 
781 // Ast dump for variable expression.
782 
783 void
do_dump_expression(Ast_dump_context * ast_dump_context) const784 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
785 {
786   ast_dump_context->ostream() << this->variable_->message_name() ;
787 }
788 
789 // Make a reference to a variable in an expression.
790 
791 Expression*
make_var_reference(Named_object * var,Location location)792 Expression::make_var_reference(Named_object* var, Location location)
793 {
794   if (var->is_sink())
795     return Expression::make_sink(location);
796 
797   // FIXME: Creating a new object for each reference to a variable is
798   // wasteful.
799   return new Var_expression(var, location);
800 }
801 
802 // Class Enclosed_var_expression.
803 
804 int
do_traverse(Traverse *)805 Enclosed_var_expression::do_traverse(Traverse*)
806 {
807   return TRAVERSE_CONTINUE;
808 }
809 
810 // Lower the reference to the enclosed variable.
811 
812 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)813 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
814 				  Statement_inserter* inserter, int)
815 {
816   gogo->lower_expression(function, inserter, &this->reference_);
817   return this;
818 }
819 
820 // Flatten the reference to the enclosed variable.
821 
822 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)823 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
824 				    Statement_inserter* inserter)
825 {
826   gogo->flatten_expression(function, inserter, &this->reference_);
827   return this;
828 }
829 
830 void
do_address_taken(bool escapes)831 Enclosed_var_expression::do_address_taken(bool escapes)
832 {
833   if (!escapes)
834     {
835       if (this->variable_->is_variable())
836 	this->variable_->var_value()->set_non_escaping_address_taken();
837       else if (this->variable_->is_result_variable())
838 	this->variable_->result_var_value()->set_non_escaping_address_taken();
839       else
840 	go_unreachable();
841     }
842   else
843     {
844       if (this->variable_->is_variable())
845 	this->variable_->var_value()->set_address_taken();
846       else if (this->variable_->is_result_variable())
847 	this->variable_->result_var_value()->set_address_taken();
848       else
849 	go_unreachable();
850     }
851 
852   if (this->variable_->is_variable()
853       && this->variable_->var_value()->is_in_heap())
854     Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
855 }
856 
857 // Ast dump for enclosed variable expression.
858 
859 void
do_dump_expression(Ast_dump_context * adc) const860 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
861 {
862   adc->ostream() << this->variable_->message_name();
863 }
864 
865 // Make a reference to a variable within an enclosing function.
866 
867 Expression*
make_enclosing_var_reference(Expression * reference,Named_object * var,Location location)868 Expression::make_enclosing_var_reference(Expression* reference,
869 					 Named_object* var, Location location)
870 {
871   return new Enclosed_var_expression(reference, var, location);
872 }
873 
874 // Class Temporary_reference_expression.
875 
876 // The type.
877 
878 Type*
do_type()879 Temporary_reference_expression::do_type()
880 {
881   return this->statement_->type();
882 }
883 
884 // Called if something takes the address of this temporary variable.
885 // We never have to move temporary variables to the heap, but we do
886 // need to know that they must live in the stack rather than in a
887 // register.
888 
889 void
do_address_taken(bool)890 Temporary_reference_expression::do_address_taken(bool)
891 {
892   this->statement_->set_is_address_taken();
893 }
894 
895 // Get a backend expression referring to the variable.
896 
897 Bexpression*
do_get_backend(Translate_context * context)898 Temporary_reference_expression::do_get_backend(Translate_context* context)
899 {
900   Gogo* gogo = context->gogo();
901   Bvariable* bvar = this->statement_->get_backend_variable(context);
902   Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
903 
904   // The backend can't always represent the same set of recursive types
905   // that the Go frontend can.  In some cases this means that a
906   // temporary variable won't have the right backend type.  Correct
907   // that here by adding a type cast.  We need to use base() to push
908   // the circularity down one level.
909   Type* stype = this->statement_->type();
910   if (!this->is_lvalue_
911       && stype->points_to() != NULL
912       && stype->points_to()->is_void_type())
913     {
914       Btype* btype = this->type()->base()->get_backend(gogo);
915       ret = gogo->backend()->convert_expression(btype, ret, this->location());
916     }
917   return ret;
918 }
919 
920 // Ast dump for temporary reference.
921 
922 void
do_dump_expression(Ast_dump_context * ast_dump_context) const923 Temporary_reference_expression::do_dump_expression(
924                                 Ast_dump_context* ast_dump_context) const
925 {
926   ast_dump_context->dump_temp_variable_name(this->statement_);
927 }
928 
929 // Make a reference to a temporary variable.
930 
931 Temporary_reference_expression*
make_temporary_reference(Temporary_statement * statement,Location location)932 Expression::make_temporary_reference(Temporary_statement* statement,
933 				     Location location)
934 {
935   return new Temporary_reference_expression(statement, location);
936 }
937 
938 // Class Set_and_use_temporary_expression.
939 
940 // Return the type.
941 
942 Type*
do_type()943 Set_and_use_temporary_expression::do_type()
944 {
945   return this->statement_->type();
946 }
947 
948 // Determine the type of the expression.
949 
950 void
do_determine_type(const Type_context * context)951 Set_and_use_temporary_expression::do_determine_type(
952     const Type_context* context)
953 {
954   this->expr_->determine_type(context);
955 }
956 
957 // Take the address.
958 
959 void
do_address_taken(bool)960 Set_and_use_temporary_expression::do_address_taken(bool)
961 {
962   this->statement_->set_is_address_taken();
963 }
964 
965 // Return the backend representation.
966 
967 Bexpression*
do_get_backend(Translate_context * context)968 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
969 {
970   Location loc = this->location();
971   Gogo* gogo = context->gogo();
972   Bvariable* bvar = this->statement_->get_backend_variable(context);
973   Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
974 
975   Named_object* fn = context->function();
976   go_assert(fn != NULL);
977   Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
978   Bexpression* bexpr = this->expr_->get_backend(context);
979   Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
980                                                           bexpr, loc);
981   Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
982   Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
983   return ret;
984 }
985 
986 // Dump.
987 
988 void
do_dump_expression(Ast_dump_context * ast_dump_context) const989 Set_and_use_temporary_expression::do_dump_expression(
990     Ast_dump_context* ast_dump_context) const
991 {
992   ast_dump_context->ostream() << '(';
993   ast_dump_context->dump_temp_variable_name(this->statement_);
994   ast_dump_context->ostream() << " = ";
995   this->expr_->dump_expression(ast_dump_context);
996   ast_dump_context->ostream() << ')';
997 }
998 
999 // Make a set-and-use temporary.
1000 
1001 Set_and_use_temporary_expression*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)1002 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1003 				       Expression* expr, Location location)
1004 {
1005   return new Set_and_use_temporary_expression(statement, expr, location);
1006 }
1007 
1008 // A sink expression--a use of the blank identifier _.
1009 
1010 class Sink_expression : public Expression
1011 {
1012  public:
Sink_expression(Location location)1013   Sink_expression(Location location)
1014     : Expression(EXPRESSION_SINK, location),
1015       type_(NULL), bvar_(NULL)
1016   { }
1017 
1018  protected:
1019   bool
do_discarding_value()1020   do_discarding_value()
1021   { return true; }
1022 
1023   Type*
1024   do_type();
1025 
1026   void
1027   do_determine_type(const Type_context*);
1028 
1029   Expression*
do_copy()1030   do_copy()
1031   { return new Sink_expression(this->location()); }
1032 
1033   Bexpression*
1034   do_get_backend(Translate_context*);
1035 
1036   void
1037   do_dump_expression(Ast_dump_context*) const;
1038 
1039  private:
1040   // The type of this sink variable.
1041   Type* type_;
1042   // The temporary variable we generate.
1043   Bvariable* bvar_;
1044 };
1045 
1046 // Return the type of a sink expression.
1047 
1048 Type*
do_type()1049 Sink_expression::do_type()
1050 {
1051   if (this->type_ == NULL)
1052     return Type::make_sink_type();
1053   return this->type_;
1054 }
1055 
1056 // Determine the type of a sink expression.
1057 
1058 void
do_determine_type(const Type_context * context)1059 Sink_expression::do_determine_type(const Type_context* context)
1060 {
1061   if (context->type != NULL)
1062     this->type_ = context->type;
1063 }
1064 
1065 // Return a temporary variable for a sink expression.  This will
1066 // presumably be a write-only variable which the middle-end will drop.
1067 
1068 Bexpression*
do_get_backend(Translate_context * context)1069 Sink_expression::do_get_backend(Translate_context* context)
1070 {
1071   Location loc = this->location();
1072   Gogo* gogo = context->gogo();
1073   if (this->bvar_ == NULL)
1074     {
1075       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1076       Named_object* fn = context->function();
1077       go_assert(fn != NULL);
1078       Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1079       Btype* bt = this->type_->get_backend(context->gogo());
1080       Bstatement* decl;
1081       this->bvar_ =
1082 	gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1083 					    false, loc, &decl);
1084       Bexpression* var_ref =
1085           gogo->backend()->var_expression(this->bvar_, loc);
1086       var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1087       return var_ref;
1088     }
1089   return gogo->backend()->var_expression(this->bvar_, loc);
1090 }
1091 
1092 // Ast dump for sink expression.
1093 
1094 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1095 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1096 {
1097   ast_dump_context->ostream() << "_" ;
1098 }
1099 
1100 // Make a sink expression.
1101 
1102 Expression*
make_sink(Location location)1103 Expression::make_sink(Location location)
1104 {
1105   return new Sink_expression(location);
1106 }
1107 
1108 // Class Func_expression.
1109 
1110 // FIXME: Can a function expression appear in a constant expression?
1111 // The value is unchanging.  Initializing a constant to the address of
1112 // a function seems like it could work, though there might be little
1113 // point to it.
1114 
1115 // Traversal.
1116 
1117 int
do_traverse(Traverse * traverse)1118 Func_expression::do_traverse(Traverse* traverse)
1119 {
1120   return (this->closure_ == NULL
1121 	  ? TRAVERSE_CONTINUE
1122 	  : Expression::traverse(&this->closure_, traverse));
1123 }
1124 
1125 // Return the type of a function expression.
1126 
1127 Type*
do_type()1128 Func_expression::do_type()
1129 {
1130   if (this->function_->is_function())
1131     return this->function_->func_value()->type();
1132   else if (this->function_->is_function_declaration())
1133     return this->function_->func_declaration_value()->type();
1134   else
1135     go_unreachable();
1136 }
1137 
1138 // Get the backend representation for the code of a function expression.
1139 
1140 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1141 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1142 {
1143   Function_type* fntype;
1144   if (no->is_function())
1145     fntype = no->func_value()->type();
1146   else if (no->is_function_declaration())
1147     fntype = no->func_declaration_value()->type();
1148   else
1149     go_unreachable();
1150 
1151   // Builtin functions are handled specially by Call_expression.  We
1152   // can't take their address.
1153   if (fntype->is_builtin())
1154     {
1155       go_error_at(loc,
1156 		  "invalid use of special builtin function %qs; must be called",
1157 		  no->message_name().c_str());
1158       return gogo->backend()->error_expression();
1159     }
1160 
1161   Bfunction* fndecl;
1162   if (no->is_function())
1163     fndecl = no->func_value()->get_or_make_decl(gogo, no);
1164   else if (no->is_function_declaration())
1165     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1166   else
1167     go_unreachable();
1168 
1169   return gogo->backend()->function_code_expression(fndecl, loc);
1170 }
1171 
1172 // Get the backend representation for a function expression.  This is used when
1173 // we take the address of a function rather than simply calling it.  A func
1174 // value is represented as a pointer to a block of memory.  The first
1175 // word of that memory is a pointer to the function code.  The
1176 // remaining parts of that memory are the addresses of variables that
1177 // the function closes over.
1178 
1179 Bexpression*
do_get_backend(Translate_context * context)1180 Func_expression::do_get_backend(Translate_context* context)
1181 {
1182   // If there is no closure, just use the function descriptor.
1183   if (this->closure_ == NULL)
1184     {
1185       Gogo* gogo = context->gogo();
1186       Named_object* no = this->function_;
1187       Expression* descriptor;
1188       if (no->is_function())
1189 	descriptor = no->func_value()->descriptor(gogo, no);
1190       else if (no->is_function_declaration())
1191 	{
1192 	  if (no->func_declaration_value()->type()->is_builtin())
1193 	    {
1194 	      go_error_at(this->location(),
1195 			  ("invalid use of special builtin function %qs; "
1196 			   "must be called"),
1197 			  no->message_name().c_str());
1198 	      return gogo->backend()->error_expression();
1199 	    }
1200 	  descriptor = no->func_declaration_value()->descriptor(gogo, no);
1201 	}
1202       else
1203 	go_unreachable();
1204 
1205       Bexpression* bdesc = descriptor->get_backend(context);
1206       return gogo->backend()->address_expression(bdesc, this->location());
1207     }
1208 
1209   go_assert(this->function_->func_value()->enclosing() != NULL);
1210 
1211   // If there is a closure, then the closure is itself the function
1212   // expression.  It is a pointer to a struct whose first field points
1213   // to the function code and whose remaining fields are the addresses
1214   // of the closed-over variables.
1215   Bexpression *bexpr = this->closure_->get_backend(context);
1216 
1217   // Introduce a backend type conversion, to account for any differences
1218   // between the argument type (function descriptor, struct with a
1219   // single field) and the closure (struct with multiple fields).
1220   Gogo* gogo = context->gogo();
1221   Btype *btype = this->type()->get_backend(gogo);
1222   return gogo->backend()->convert_expression(btype, bexpr, this->location());
1223 }
1224 
1225 // Ast dump for function.
1226 
1227 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1228 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1229 {
1230   ast_dump_context->ostream() << this->function_->name();
1231   if (this->closure_ != NULL)
1232     {
1233       ast_dump_context->ostream() << " {closure =  ";
1234       this->closure_->dump_expression(ast_dump_context);
1235       ast_dump_context->ostream() << "}";
1236     }
1237 }
1238 
1239 // Make a reference to a function in an expression.
1240 
1241 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1242 Expression::make_func_reference(Named_object* function, Expression* closure,
1243 				Location location)
1244 {
1245   Func_expression* fe = new Func_expression(function, closure, location);
1246 
1247   // Detect references to builtin functions and set the runtime code if
1248   // appropriate.
1249   if (function->is_function_declaration())
1250     fe->set_runtime_code(Runtime::name_to_code(function->name()));
1251   return fe;
1252 }
1253 
1254 // Class Func_descriptor_expression.
1255 
1256 // Constructor.
1257 
Func_descriptor_expression(Named_object * fn)1258 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1259   : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1260     fn_(fn), dvar_(NULL)
1261 {
1262   go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1263 }
1264 
1265 // Traversal.
1266 
1267 int
do_traverse(Traverse *)1268 Func_descriptor_expression::do_traverse(Traverse*)
1269 {
1270   return TRAVERSE_CONTINUE;
1271 }
1272 
1273 // All function descriptors have the same type.
1274 
1275 Type* Func_descriptor_expression::descriptor_type;
1276 
1277 void
make_func_descriptor_type()1278 Func_descriptor_expression::make_func_descriptor_type()
1279 {
1280   if (Func_descriptor_expression::descriptor_type != NULL)
1281     return;
1282   Type* uintptr_type = Type::lookup_integer_type("uintptr");
1283   Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1284   Func_descriptor_expression::descriptor_type =
1285     Type::make_builtin_named_type("functionDescriptor", struct_type);
1286 }
1287 
1288 Type*
do_type()1289 Func_descriptor_expression::do_type()
1290 {
1291   Func_descriptor_expression::make_func_descriptor_type();
1292   return Func_descriptor_expression::descriptor_type;
1293 }
1294 
1295 // The backend representation for a function descriptor.
1296 
1297 Bexpression*
do_get_backend(Translate_context * context)1298 Func_descriptor_expression::do_get_backend(Translate_context* context)
1299 {
1300   Named_object* no = this->fn_;
1301   Location loc = no->location();
1302   if (this->dvar_ != NULL)
1303     return context->backend()->var_expression(this->dvar_, loc);
1304 
1305   Gogo* gogo = context->gogo();
1306   std::string var_name(gogo->function_descriptor_name(no));
1307   bool is_descriptor = false;
1308   if (no->is_function_declaration()
1309       && !no->func_declaration_value()->asm_name().empty()
1310       && Linemap::is_predeclared_location(no->location()))
1311     is_descriptor = true;
1312 
1313   // The runtime package implements some functions defined in the
1314   // syscall package.  Let the syscall package define the descriptor
1315   // in this case.
1316   if (gogo->compiling_runtime()
1317       && gogo->package_name() == "runtime"
1318       && no->is_function()
1319       && !no->func_value()->asm_name().empty()
1320       && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1321     is_descriptor = true;
1322 
1323   Btype* btype = this->type()->get_backend(gogo);
1324 
1325   Bvariable* bvar;
1326   std::string asm_name(go_selectively_encode_id(var_name));
1327   if (no->package() != NULL || is_descriptor)
1328     bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1329                                                           btype, loc);
1330   else
1331     {
1332       Location bloc = Linemap::predeclared_location();
1333 
1334       // The runtime package has hash/equality functions that are
1335       // referenced by type descriptors outside of the runtime, so the
1336       // function descriptors must be visible even though they are not
1337       // exported.
1338       bool is_exported_runtime = false;
1339       if (gogo->compiling_runtime()
1340 	  && gogo->package_name() == "runtime"
1341 	  && (no->name().find("hash") != std::string::npos
1342 	      || no->name().find("equal") != std::string::npos))
1343 	is_exported_runtime = true;
1344 
1345       bool is_hidden = ((no->is_function()
1346 			 && no->func_value()->enclosing() != NULL)
1347 			|| (Gogo::is_hidden_name(no->name())
1348 			    && !is_exported_runtime)
1349 			|| Gogo::is_thunk(no));
1350 
1351       bvar = context->backend()->immutable_struct(var_name, asm_name,
1352                                                   is_hidden, false,
1353 						  btype, bloc);
1354       Expression_list* vals = new Expression_list();
1355       vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1356       Expression* init =
1357 	Expression::make_struct_composite_literal(this->type(), vals, bloc);
1358       Translate_context bcontext(gogo, NULL, NULL, NULL);
1359       bcontext.set_is_const();
1360       Bexpression* binit = init->get_backend(&bcontext);
1361       context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1362 						    false, btype, bloc, binit);
1363     }
1364 
1365   this->dvar_ = bvar;
1366   return gogo->backend()->var_expression(bvar, loc);
1367 }
1368 
1369 // Print a function descriptor expression.
1370 
1371 void
do_dump_expression(Ast_dump_context * context) const1372 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1373 {
1374   context->ostream() << "[descriptor " << this->fn_->name() << "]";
1375 }
1376 
1377 // Make a function descriptor expression.
1378 
1379 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1380 Expression::make_func_descriptor(Named_object* fn)
1381 {
1382   return new Func_descriptor_expression(fn);
1383 }
1384 
1385 // Make the function descriptor type, so that it can be converted.
1386 
1387 void
make_func_descriptor_type()1388 Expression::make_func_descriptor_type()
1389 {
1390   Func_descriptor_expression::make_func_descriptor_type();
1391 }
1392 
1393 // A reference to just the code of a function.
1394 
1395 class Func_code_reference_expression : public Expression
1396 {
1397  public:
Func_code_reference_expression(Named_object * function,Location location)1398   Func_code_reference_expression(Named_object* function, Location location)
1399     : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1400       function_(function)
1401   { }
1402 
1403  protected:
1404   int
do_traverse(Traverse *)1405   do_traverse(Traverse*)
1406   { return TRAVERSE_CONTINUE; }
1407 
1408   bool
do_is_static_initializer() const1409   do_is_static_initializer() const
1410   { return true; }
1411 
1412   Type*
do_type()1413   do_type()
1414   { return Type::make_pointer_type(Type::make_void_type()); }
1415 
1416   void
do_determine_type(const Type_context *)1417   do_determine_type(const Type_context*)
1418   { }
1419 
1420   Expression*
do_copy()1421   do_copy()
1422   {
1423     return Expression::make_func_code_reference(this->function_,
1424 						this->location());
1425   }
1426 
1427   Bexpression*
1428   do_get_backend(Translate_context*);
1429 
1430   void
do_dump_expression(Ast_dump_context * context) const1431   do_dump_expression(Ast_dump_context* context) const
1432   { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1433 
1434  private:
1435   // The function.
1436   Named_object* function_;
1437 };
1438 
1439 // Get the backend representation for a reference to function code.
1440 
1441 Bexpression*
do_get_backend(Translate_context * context)1442 Func_code_reference_expression::do_get_backend(Translate_context* context)
1443 {
1444   return Func_expression::get_code_pointer(context->gogo(), this->function_,
1445 					   this->location());
1446 }
1447 
1448 // Make a reference to the code of a function.
1449 
1450 Expression*
make_func_code_reference(Named_object * function,Location location)1451 Expression::make_func_code_reference(Named_object* function, Location location)
1452 {
1453   return new Func_code_reference_expression(function, location);
1454 }
1455 
1456 // Class Unknown_expression.
1457 
1458 // Return the name of an unknown expression.
1459 
1460 const std::string&
name() const1461 Unknown_expression::name() const
1462 {
1463   return this->named_object_->name();
1464 }
1465 
1466 // Lower a reference to an unknown name.
1467 
1468 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1469 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1470 {
1471   Location location = this->location();
1472   Named_object* no = this->named_object_;
1473   Named_object* real;
1474   if (!no->is_unknown())
1475     real = no;
1476   else
1477     {
1478       real = no->unknown_value()->real_named_object();
1479       if (real == NULL)
1480 	{
1481 	  if (this->is_composite_literal_key_)
1482 	    return this;
1483 	  if (!this->no_error_message_)
1484 	    go_error_at(location, "reference to undefined name %qs",
1485 			this->named_object_->message_name().c_str());
1486 	  return Expression::make_error(location);
1487 	}
1488     }
1489   switch (real->classification())
1490     {
1491     case Named_object::NAMED_OBJECT_CONST:
1492       return Expression::make_const_reference(real, location);
1493     case Named_object::NAMED_OBJECT_TYPE:
1494       return Expression::make_type(real->type_value(), location);
1495     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1496       if (this->is_composite_literal_key_)
1497 	return this;
1498       if (!this->no_error_message_)
1499 	go_error_at(location, "reference to undefined type %qs",
1500 		    real->message_name().c_str());
1501       return Expression::make_error(location);
1502     case Named_object::NAMED_OBJECT_VAR:
1503       real->var_value()->set_is_used();
1504       return Expression::make_var_reference(real, location);
1505     case Named_object::NAMED_OBJECT_FUNC:
1506     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1507       return Expression::make_func_reference(real, NULL, location);
1508     case Named_object::NAMED_OBJECT_PACKAGE:
1509       if (this->is_composite_literal_key_)
1510 	return this;
1511       if (!this->no_error_message_)
1512 	go_error_at(location, "unexpected reference to package");
1513       return Expression::make_error(location);
1514     default:
1515       go_unreachable();
1516     }
1517 }
1518 
1519 // Dump the ast representation for an unknown expression to a dump context.
1520 
1521 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1522 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1523 {
1524   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1525 			      << ")";
1526 }
1527 
1528 // Make a reference to an unknown name.
1529 
1530 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1531 Expression::make_unknown_reference(Named_object* no, Location location)
1532 {
1533   return new Unknown_expression(no, location);
1534 }
1535 
1536 // A boolean expression.
1537 
1538 class Boolean_expression : public Expression
1539 {
1540  public:
Boolean_expression(bool val,Location location)1541   Boolean_expression(bool val, Location location)
1542     : Expression(EXPRESSION_BOOLEAN, location),
1543       val_(val), type_(NULL)
1544   { }
1545 
1546   static Expression*
1547   do_import(Import*);
1548 
1549  protected:
1550   bool
do_is_constant() const1551   do_is_constant() const
1552   { return true; }
1553 
1554   bool
do_is_static_initializer() const1555   do_is_static_initializer() const
1556   { return true; }
1557 
1558   Type*
1559   do_type();
1560 
1561   void
1562   do_determine_type(const Type_context*);
1563 
1564   Expression*
do_copy()1565   do_copy()
1566   { return this; }
1567 
1568   Bexpression*
do_get_backend(Translate_context * context)1569   do_get_backend(Translate_context* context)
1570   { return context->backend()->boolean_constant_expression(this->val_); }
1571 
1572   void
do_export(Export * exp) const1573   do_export(Export* exp) const
1574   { exp->write_c_string(this->val_ ? "true" : "false"); }
1575 
1576   void
do_dump_expression(Ast_dump_context * ast_dump_context) const1577   do_dump_expression(Ast_dump_context* ast_dump_context) const
1578   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1579 
1580  private:
1581   // The constant.
1582   bool val_;
1583   // The type as determined by context.
1584   Type* type_;
1585 };
1586 
1587 // Get the type.
1588 
1589 Type*
do_type()1590 Boolean_expression::do_type()
1591 {
1592   if (this->type_ == NULL)
1593     this->type_ = Type::make_boolean_type();
1594   return this->type_;
1595 }
1596 
1597 // Set the type from the context.
1598 
1599 void
do_determine_type(const Type_context * context)1600 Boolean_expression::do_determine_type(const Type_context* context)
1601 {
1602   if (this->type_ != NULL && !this->type_->is_abstract())
1603     ;
1604   else if (context->type != NULL && context->type->is_boolean_type())
1605     this->type_ = context->type;
1606   else if (!context->may_be_abstract)
1607     this->type_ = Type::lookup_bool_type();
1608 }
1609 
1610 // Import a boolean constant.
1611 
1612 Expression*
do_import(Import * imp)1613 Boolean_expression::do_import(Import* imp)
1614 {
1615   if (imp->peek_char() == 't')
1616     {
1617       imp->require_c_string("true");
1618       return Expression::make_boolean(true, imp->location());
1619     }
1620   else
1621     {
1622       imp->require_c_string("false");
1623       return Expression::make_boolean(false, imp->location());
1624     }
1625 }
1626 
1627 // Make a boolean expression.
1628 
1629 Expression*
make_boolean(bool val,Location location)1630 Expression::make_boolean(bool val, Location location)
1631 {
1632   return new Boolean_expression(val, location);
1633 }
1634 
1635 // Class String_expression.
1636 
1637 // Get the type.
1638 
1639 Type*
do_type()1640 String_expression::do_type()
1641 {
1642   if (this->type_ == NULL)
1643     this->type_ = Type::make_string_type();
1644   return this->type_;
1645 }
1646 
1647 // Set the type from the context.
1648 
1649 void
do_determine_type(const Type_context * context)1650 String_expression::do_determine_type(const Type_context* context)
1651 {
1652   if (this->type_ != NULL && !this->type_->is_abstract())
1653     ;
1654   else if (context->type != NULL && context->type->is_string_type())
1655     this->type_ = context->type;
1656   else if (!context->may_be_abstract)
1657     this->type_ = Type::lookup_string_type();
1658 }
1659 
1660 // Build a string constant.
1661 
1662 Bexpression*
do_get_backend(Translate_context * context)1663 String_expression::do_get_backend(Translate_context* context)
1664 {
1665   Gogo* gogo = context->gogo();
1666   Btype* btype = Type::make_string_type()->get_backend(gogo);
1667 
1668   Location loc = this->location();
1669   std::vector<Bexpression*> init(2);
1670   Bexpression* str_cst =
1671       gogo->backend()->string_constant_expression(this->val_);
1672   init[0] = gogo->backend()->address_expression(str_cst, loc);
1673 
1674   Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1675   mpz_t lenval;
1676   mpz_init_set_ui(lenval, this->val_.length());
1677   init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1678   mpz_clear(lenval);
1679 
1680   return gogo->backend()->constructor_expression(btype, init, loc);
1681 }
1682 
1683  // Write string literal to string dump.
1684 
1685 void
export_string(String_dump * exp,const String_expression * str)1686 String_expression::export_string(String_dump* exp,
1687 				 const String_expression* str)
1688 {
1689   std::string s;
1690   s.reserve(str->val_.length() * 4 + 2);
1691   s += '"';
1692   for (std::string::const_iterator p = str->val_.begin();
1693        p != str->val_.end();
1694        ++p)
1695     {
1696       if (*p == '\\' || *p == '"')
1697 	{
1698 	  s += '\\';
1699 	  s += *p;
1700 	}
1701       else if (*p >= 0x20 && *p < 0x7f)
1702 	s += *p;
1703       else if (*p == '\n')
1704 	s += "\\n";
1705       else if (*p == '\t')
1706 	s += "\\t";
1707       else
1708 	{
1709 	  s += "\\x";
1710 	  unsigned char c = *p;
1711 	  unsigned int dig = c >> 4;
1712 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1713 	  dig = c & 0xf;
1714 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1715 	}
1716     }
1717   s += '"';
1718   exp->write_string(s);
1719 }
1720 
1721 // Export a string expression.
1722 
1723 void
do_export(Export * exp) const1724 String_expression::do_export(Export* exp) const
1725 {
1726   String_expression::export_string(exp, this);
1727 }
1728 
1729 // Import a string expression.
1730 
1731 Expression*
do_import(Import * imp)1732 String_expression::do_import(Import* imp)
1733 {
1734   imp->require_c_string("\"");
1735   std::string val;
1736   while (true)
1737     {
1738       int c = imp->get_char();
1739       if (c == '"' || c == -1)
1740 	break;
1741       if (c != '\\')
1742 	val += static_cast<char>(c);
1743       else
1744 	{
1745 	  c = imp->get_char();
1746 	  if (c == '\\' || c == '"')
1747 	    val += static_cast<char>(c);
1748 	  else if (c == 'n')
1749 	    val += '\n';
1750 	  else if (c == 't')
1751 	    val += '\t';
1752 	  else if (c == 'x')
1753 	    {
1754 	      c = imp->get_char();
1755 	      unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1756 	      c = imp->get_char();
1757 	      unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1758 	      char v = (vh << 4) | vl;
1759 	      val += v;
1760 	    }
1761 	  else
1762 	    {
1763 	      go_error_at(imp->location(), "bad string constant");
1764 	      return Expression::make_error(imp->location());
1765 	    }
1766 	}
1767     }
1768   return Expression::make_string(val, imp->location());
1769 }
1770 
1771 // Ast dump for string expression.
1772 
1773 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1774 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1775 {
1776   String_expression::export_string(ast_dump_context, this);
1777 }
1778 
1779 // Make a string expression.
1780 
1781 Expression*
make_string(const std::string & val,Location location)1782 Expression::make_string(const std::string& val, Location location)
1783 {
1784   return new String_expression(val, location);
1785 }
1786 
1787 // An expression that evaluates to some characteristic of a string.
1788 // This is used when indexing, bound-checking, or nil checking a string.
1789 
1790 class String_info_expression : public Expression
1791 {
1792  public:
String_info_expression(Expression * string,String_info string_info,Location location)1793   String_info_expression(Expression* string, String_info string_info,
1794                         Location location)
1795     : Expression(EXPRESSION_STRING_INFO, location),
1796       string_(string), string_info_(string_info)
1797   { }
1798 
1799  protected:
1800   Type*
1801   do_type();
1802 
1803   void
do_determine_type(const Type_context *)1804   do_determine_type(const Type_context*)
1805   { go_unreachable(); }
1806 
1807   Expression*
do_copy()1808   do_copy()
1809   {
1810     return new String_info_expression(this->string_->copy(), this->string_info_,
1811 				      this->location());
1812   }
1813 
1814   Bexpression*
1815   do_get_backend(Translate_context* context);
1816 
1817   void
1818   do_dump_expression(Ast_dump_context*) const;
1819 
1820   void
do_issue_nil_check()1821   do_issue_nil_check()
1822   { this->string_->issue_nil_check(); }
1823 
1824  private:
1825   // The string for which we are getting information.
1826   Expression* string_;
1827   // What information we want.
1828   String_info string_info_;
1829 };
1830 
1831 // Return the type of the string info.
1832 
1833 Type*
do_type()1834 String_info_expression::do_type()
1835 {
1836   switch (this->string_info_)
1837     {
1838     case STRING_INFO_DATA:
1839       {
1840 	Type* byte_type = Type::lookup_integer_type("uint8");
1841 	return Type::make_pointer_type(byte_type);
1842       }
1843     case STRING_INFO_LENGTH:
1844         return Type::lookup_integer_type("int");
1845     default:
1846       go_unreachable();
1847     }
1848 }
1849 
1850 // Return string information in GENERIC.
1851 
1852 Bexpression*
do_get_backend(Translate_context * context)1853 String_info_expression::do_get_backend(Translate_context* context)
1854 {
1855   Gogo* gogo = context->gogo();
1856 
1857   Bexpression* bstring = this->string_->get_backend(context);
1858   switch (this->string_info_)
1859     {
1860     case STRING_INFO_DATA:
1861     case STRING_INFO_LENGTH:
1862       return gogo->backend()->struct_field_expression(bstring,
1863 						      this->string_info_,
1864 						      this->location());
1865       break;
1866     default:
1867       go_unreachable();
1868     }
1869 }
1870 
1871 // Dump ast representation for a type info expression.
1872 
1873 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1874 String_info_expression::do_dump_expression(
1875     Ast_dump_context* ast_dump_context) const
1876 {
1877   ast_dump_context->ostream() << "stringinfo(";
1878   this->string_->dump_expression(ast_dump_context);
1879   ast_dump_context->ostream() << ",";
1880   ast_dump_context->ostream() <<
1881       (this->string_info_ == STRING_INFO_DATA ? "data"
1882     : this->string_info_ == STRING_INFO_LENGTH ? "length"
1883     : "unknown");
1884   ast_dump_context->ostream() << ")";
1885 }
1886 
1887 // Make a string info expression.
1888 
1889 Expression*
make_string_info(Expression * string,String_info string_info,Location location)1890 Expression::make_string_info(Expression* string, String_info string_info,
1891                             Location location)
1892 {
1893   return new String_info_expression(string, string_info, location);
1894 }
1895 
1896 // Make an integer expression.
1897 
1898 class Integer_expression : public Expression
1899 {
1900  public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)1901   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1902 		     Location location)
1903     : Expression(EXPRESSION_INTEGER, location),
1904       type_(type), is_character_constant_(is_character_constant)
1905   { mpz_init_set(this->val_, *val); }
1906 
1907   static Expression*
1908   do_import(Import*);
1909 
1910   // Write VAL to string dump.
1911   static void
1912   export_integer(String_dump* exp, const mpz_t val);
1913 
1914   // Write VAL to dump context.
1915   static void
1916   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1917 
1918  protected:
1919   bool
do_is_constant() const1920   do_is_constant() const
1921   { return true; }
1922 
1923   bool
do_is_static_initializer() const1924   do_is_static_initializer() const
1925   { return true; }
1926 
1927   bool
1928   do_numeric_constant_value(Numeric_constant* nc) const;
1929 
1930   Type*
1931   do_type();
1932 
1933   void
1934   do_determine_type(const Type_context* context);
1935 
1936   void
1937   do_check_types(Gogo*);
1938 
1939   Bexpression*
1940   do_get_backend(Translate_context*);
1941 
1942   Expression*
do_copy()1943   do_copy()
1944   {
1945     if (this->is_character_constant_)
1946       return Expression::make_character(&this->val_,
1947 					(this->type_ == NULL
1948 					 ? NULL
1949 					 : this->type_->copy_expressions()),
1950 					this->location());
1951     else
1952       return Expression::make_integer_z(&this->val_,
1953 					(this->type_ == NULL
1954 					 ? NULL
1955 					 : this->type_->copy_expressions()),
1956 					this->location());
1957   }
1958 
1959   void
1960   do_export(Export*) const;
1961 
1962   void
1963   do_dump_expression(Ast_dump_context*) const;
1964 
1965  private:
1966   // The integer value.
1967   mpz_t val_;
1968   // The type so far.
1969   Type* type_;
1970   // Whether this is a character constant.
1971   bool is_character_constant_;
1972 };
1973 
1974 // Return a numeric constant for this expression.  We have to mark
1975 // this as a character when appropriate.
1976 
1977 bool
do_numeric_constant_value(Numeric_constant * nc) const1978 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1979 {
1980   if (this->is_character_constant_)
1981     nc->set_rune(this->type_, this->val_);
1982   else
1983     nc->set_int(this->type_, this->val_);
1984   return true;
1985 }
1986 
1987 // Return the current type.  If we haven't set the type yet, we return
1988 // an abstract integer type.
1989 
1990 Type*
do_type()1991 Integer_expression::do_type()
1992 {
1993   if (this->type_ == NULL)
1994     {
1995       if (this->is_character_constant_)
1996 	this->type_ = Type::make_abstract_character_type();
1997       else
1998 	this->type_ = Type::make_abstract_integer_type();
1999     }
2000   return this->type_;
2001 }
2002 
2003 // Set the type of the integer value.  Here we may switch from an
2004 // abstract type to a real type.
2005 
2006 void
do_determine_type(const Type_context * context)2007 Integer_expression::do_determine_type(const Type_context* context)
2008 {
2009   if (this->type_ != NULL && !this->type_->is_abstract())
2010     ;
2011   else if (context->type != NULL && context->type->is_numeric_type())
2012     this->type_ = context->type;
2013   else if (!context->may_be_abstract)
2014     {
2015       if (this->is_character_constant_)
2016 	this->type_ = Type::lookup_integer_type("int32");
2017       else
2018 	this->type_ = Type::lookup_integer_type("int");
2019     }
2020 }
2021 
2022 // Check the type of an integer constant.
2023 
2024 void
do_check_types(Gogo *)2025 Integer_expression::do_check_types(Gogo*)
2026 {
2027   Type* type = this->type_;
2028   if (type == NULL)
2029     return;
2030   Numeric_constant nc;
2031   if (this->is_character_constant_)
2032     nc.set_rune(NULL, this->val_);
2033   else
2034     nc.set_int(NULL, this->val_);
2035   if (!nc.set_type(type, true, this->location()))
2036     this->set_is_error();
2037 }
2038 
2039 // Get the backend representation for an integer constant.
2040 
2041 Bexpression*
do_get_backend(Translate_context * context)2042 Integer_expression::do_get_backend(Translate_context* context)
2043 {
2044   if (this->is_error_expression()
2045       || (this->type_ != NULL && this->type_->is_error_type()))
2046     {
2047       go_assert(saw_errors());
2048       return context->gogo()->backend()->error_expression();
2049     }
2050 
2051   Type* resolved_type = NULL;
2052   if (this->type_ != NULL && !this->type_->is_abstract())
2053     resolved_type = this->type_;
2054   else if (this->type_ != NULL && this->type_->float_type() != NULL)
2055     {
2056       // We are converting to an abstract floating point type.
2057       resolved_type = Type::lookup_float_type("float64");
2058     }
2059   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2060     {
2061       // We are converting to an abstract complex type.
2062       resolved_type = Type::lookup_complex_type("complex128");
2063     }
2064   else
2065     {
2066       // If we still have an abstract type here, then this is being
2067       // used in a constant expression which didn't get reduced for
2068       // some reason.  Use a type which will fit the value.  We use <,
2069       // not <=, because we need an extra bit for the sign bit.
2070       int bits = mpz_sizeinbase(this->val_, 2);
2071       Type* int_type = Type::lookup_integer_type("int");
2072       if (bits < int_type->integer_type()->bits())
2073 	resolved_type = int_type;
2074       else if (bits < 64)
2075         resolved_type = Type::lookup_integer_type("int64");
2076       else
2077         {
2078           if (!saw_errors())
2079             go_error_at(this->location(),
2080                         "unknown type for large integer constant");
2081           return context->gogo()->backend()->error_expression();
2082         }
2083     }
2084   Numeric_constant nc;
2085   nc.set_int(resolved_type, this->val_);
2086   return Expression::backend_numeric_constant_expression(context, &nc);
2087 }
2088 
2089 // Write VAL to export data.
2090 
2091 void
export_integer(String_dump * exp,const mpz_t val)2092 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2093 {
2094   char* s = mpz_get_str(NULL, 10, val);
2095   exp->write_c_string(s);
2096   free(s);
2097 }
2098 
2099 // Export an integer in a constant expression.
2100 
2101 void
do_export(Export * exp) const2102 Integer_expression::do_export(Export* exp) const
2103 {
2104   Integer_expression::export_integer(exp, this->val_);
2105   if (this->is_character_constant_)
2106     exp->write_c_string("'");
2107   // A trailing space lets us reliably identify the end of the number.
2108   exp->write_c_string(" ");
2109 }
2110 
2111 // Import an integer, floating point, or complex value.  This handles
2112 // all these types because they all start with digits.
2113 
2114 Expression*
do_import(Import * imp)2115 Integer_expression::do_import(Import* imp)
2116 {
2117   std::string num = imp->read_identifier();
2118   imp->require_c_string(" ");
2119   if (!num.empty() && num[num.length() - 1] == 'i')
2120     {
2121       mpfr_t real;
2122       size_t plus_pos = num.find('+', 1);
2123       size_t minus_pos = num.find('-', 1);
2124       size_t pos;
2125       if (plus_pos == std::string::npos)
2126 	pos = minus_pos;
2127       else if (minus_pos == std::string::npos)
2128 	pos = plus_pos;
2129       else
2130 	{
2131 	  go_error_at(imp->location(), "bad number in import data: %qs",
2132 		      num.c_str());
2133 	  return Expression::make_error(imp->location());
2134 	}
2135       if (pos == std::string::npos)
2136 	mpfr_set_ui(real, 0, GMP_RNDN);
2137       else
2138 	{
2139 	  std::string real_str = num.substr(0, pos);
2140 	  if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2141 	    {
2142 	      go_error_at(imp->location(), "bad number in import data: %qs",
2143 			  real_str.c_str());
2144 	      return Expression::make_error(imp->location());
2145 	    }
2146 	}
2147 
2148       std::string imag_str;
2149       if (pos == std::string::npos)
2150 	imag_str = num;
2151       else
2152 	imag_str = num.substr(pos);
2153       imag_str = imag_str.substr(0, imag_str.size() - 1);
2154       mpfr_t imag;
2155       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2156 	{
2157 	  go_error_at(imp->location(), "bad number in import data: %qs",
2158 		      imag_str.c_str());
2159 	  return Expression::make_error(imp->location());
2160 	}
2161       mpc_t cval;
2162       mpc_init2(cval, mpc_precision);
2163       mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2164       mpfr_clear(real);
2165       mpfr_clear(imag);
2166       Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2167       mpc_clear(cval);
2168       return ret;
2169     }
2170   else if (num.find('.') == std::string::npos
2171 	   && num.find('E') == std::string::npos)
2172     {
2173       bool is_character_constant = (!num.empty()
2174 				    && num[num.length() - 1] == '\'');
2175       if (is_character_constant)
2176 	num = num.substr(0, num.length() - 1);
2177       mpz_t val;
2178       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2179 	{
2180 	  go_error_at(imp->location(), "bad number in import data: %qs",
2181 		      num.c_str());
2182 	  return Expression::make_error(imp->location());
2183 	}
2184       Expression* ret;
2185       if (is_character_constant)
2186 	ret = Expression::make_character(&val, NULL, imp->location());
2187       else
2188 	ret = Expression::make_integer_z(&val, NULL, imp->location());
2189       mpz_clear(val);
2190       return ret;
2191     }
2192   else
2193     {
2194       mpfr_t val;
2195       if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2196 	{
2197 	  go_error_at(imp->location(), "bad number in import data: %qs",
2198 		      num.c_str());
2199 	  return Expression::make_error(imp->location());
2200 	}
2201       Expression* ret = Expression::make_float(&val, NULL, imp->location());
2202       mpfr_clear(val);
2203       return ret;
2204     }
2205 }
2206 // Ast dump for integer expression.
2207 
2208 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2209 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2210 {
2211   if (this->is_character_constant_)
2212     ast_dump_context->ostream() << '\'';
2213   Integer_expression::export_integer(ast_dump_context, this->val_);
2214   if (this->is_character_constant_)
2215     ast_dump_context->ostream() << '\'';
2216 }
2217 
2218 // Build a new integer value from a multi-precision integer.
2219 
2220 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2221 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2222 {
2223   return new Integer_expression(val, type, false, location);
2224 }
2225 
2226 // Build a new integer value from an unsigned long.
2227 
2228 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2229 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2230 {
2231   mpz_t zval;
2232   mpz_init_set_ui(zval, val);
2233   Expression* ret = Expression::make_integer_z(&zval, type, location);
2234   mpz_clear(zval);
2235   return ret;
2236 }
2237 
2238 // Build a new integer value from a signed long.
2239 
2240 Expression*
make_integer_sl(long val,Type * type,Location location)2241 Expression::make_integer_sl(long val, Type *type, Location location)
2242 {
2243   mpz_t zval;
2244   mpz_init_set_si(zval, val);
2245   Expression* ret = Expression::make_integer_z(&zval, type, location);
2246   mpz_clear(zval);
2247   return ret;
2248 }
2249 
2250 // Store an int64_t in an uninitialized mpz_t.
2251 
2252 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2253 set_mpz_from_int64(mpz_t* zval, int64_t val)
2254 {
2255   if (val >= 0)
2256     {
2257       unsigned long ul = static_cast<unsigned long>(val);
2258       if (static_cast<int64_t>(ul) == val)
2259 	{
2260 	  mpz_init_set_ui(*zval, ul);
2261 	  return;
2262 	}
2263     }
2264   uint64_t uv;
2265   if (val >= 0)
2266     uv = static_cast<uint64_t>(val);
2267   else
2268     uv = static_cast<uint64_t>(- val);
2269   unsigned long ul = uv & 0xffffffffUL;
2270   mpz_init_set_ui(*zval, ul);
2271   mpz_t hval;
2272   mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2273   mpz_mul_2exp(hval, hval, 32);
2274   mpz_add(*zval, *zval, hval);
2275   mpz_clear(hval);
2276   if (val < 0)
2277     mpz_neg(*zval, *zval);
2278 }
2279 
2280 // Build a new integer value from an int64_t.
2281 
2282 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2283 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2284 {
2285   mpz_t zval;
2286   set_mpz_from_int64(&zval, val);
2287   Expression* ret = Expression::make_integer_z(&zval, type, location);
2288   mpz_clear(zval);
2289   return ret;
2290 }
2291 
2292 // Build a new character constant value.
2293 
2294 Expression*
make_character(const mpz_t * val,Type * type,Location location)2295 Expression::make_character(const mpz_t* val, Type* type, Location location)
2296 {
2297   return new Integer_expression(val, type, true, location);
2298 }
2299 
2300 // Floats.
2301 
2302 class Float_expression : public Expression
2303 {
2304  public:
Float_expression(const mpfr_t * val,Type * type,Location location)2305   Float_expression(const mpfr_t* val, Type* type, Location location)
2306     : Expression(EXPRESSION_FLOAT, location),
2307       type_(type)
2308   {
2309     mpfr_init_set(this->val_, *val, GMP_RNDN);
2310   }
2311 
2312   // Write VAL to export data.
2313   static void
2314   export_float(String_dump* exp, const mpfr_t val);
2315 
2316   // Write VAL to dump file.
2317   static void
2318   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2319 
2320  protected:
2321   bool
do_is_constant() const2322   do_is_constant() const
2323   { return true; }
2324 
2325   bool
do_is_static_initializer() const2326   do_is_static_initializer() const
2327   { return true; }
2328 
2329   bool
do_numeric_constant_value(Numeric_constant * nc) const2330   do_numeric_constant_value(Numeric_constant* nc) const
2331   {
2332     nc->set_float(this->type_, this->val_);
2333     return true;
2334   }
2335 
2336   Type*
2337   do_type();
2338 
2339   void
2340   do_determine_type(const Type_context*);
2341 
2342   void
2343   do_check_types(Gogo*);
2344 
2345   Expression*
do_copy()2346   do_copy()
2347   { return Expression::make_float(&this->val_,
2348 				  (this->type_ == NULL
2349 				   ? NULL
2350 				   : this->type_->copy_expressions()),
2351 				  this->location()); }
2352 
2353   Bexpression*
2354   do_get_backend(Translate_context*);
2355 
2356   void
2357   do_export(Export*) const;
2358 
2359   void
2360   do_dump_expression(Ast_dump_context*) const;
2361 
2362  private:
2363   // The floating point value.
2364   mpfr_t val_;
2365   // The type so far.
2366   Type* type_;
2367 };
2368 
2369 // Return the current type.  If we haven't set the type yet, we return
2370 // an abstract float type.
2371 
2372 Type*
do_type()2373 Float_expression::do_type()
2374 {
2375   if (this->type_ == NULL)
2376     this->type_ = Type::make_abstract_float_type();
2377   return this->type_;
2378 }
2379 
2380 // Set the type of the float value.  Here we may switch from an
2381 // abstract type to a real type.
2382 
2383 void
do_determine_type(const Type_context * context)2384 Float_expression::do_determine_type(const Type_context* context)
2385 {
2386   if (this->type_ != NULL && !this->type_->is_abstract())
2387     ;
2388   else if (context->type != NULL
2389 	   && (context->type->integer_type() != NULL
2390 	       || context->type->float_type() != NULL
2391 	       || context->type->complex_type() != NULL))
2392     this->type_ = context->type;
2393   else if (!context->may_be_abstract)
2394     this->type_ = Type::lookup_float_type("float64");
2395 }
2396 
2397 // Check the type of a float value.
2398 
2399 void
do_check_types(Gogo *)2400 Float_expression::do_check_types(Gogo*)
2401 {
2402   Type* type = this->type_;
2403   if (type == NULL)
2404     return;
2405   Numeric_constant nc;
2406   nc.set_float(NULL, this->val_);
2407   if (!nc.set_type(this->type_, true, this->location()))
2408     this->set_is_error();
2409 }
2410 
2411 // Get the backend representation for a float constant.
2412 
2413 Bexpression*
do_get_backend(Translate_context * context)2414 Float_expression::do_get_backend(Translate_context* context)
2415 {
2416   if (this->is_error_expression()
2417       || (this->type_ != NULL && this->type_->is_error_type()))
2418     {
2419       go_assert(saw_errors());
2420       return context->gogo()->backend()->error_expression();
2421     }
2422 
2423   Type* resolved_type;
2424   if (this->type_ != NULL && !this->type_->is_abstract())
2425     resolved_type = this->type_;
2426   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2427     {
2428       // We have an abstract integer type.  We just hope for the best.
2429       resolved_type = Type::lookup_integer_type("int");
2430     }
2431   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2432     {
2433       // We are converting to an abstract complex type.
2434       resolved_type = Type::lookup_complex_type("complex128");
2435     }
2436   else
2437     {
2438       // If we still have an abstract type here, then this is being
2439       // used in a constant expression which didn't get reduced.  We
2440       // just use float64 and hope for the best.
2441       resolved_type = Type::lookup_float_type("float64");
2442     }
2443 
2444   Numeric_constant nc;
2445   nc.set_float(resolved_type, this->val_);
2446   return Expression::backend_numeric_constant_expression(context, &nc);
2447 }
2448 
2449 // Write a floating point number to a string dump.
2450 
2451 void
export_float(String_dump * exp,const mpfr_t val)2452 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2453 {
2454   mp_exp_t exponent;
2455   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2456   if (*s == '-')
2457     exp->write_c_string("-");
2458   exp->write_c_string("0.");
2459   exp->write_c_string(*s == '-' ? s + 1 : s);
2460   mpfr_free_str(s);
2461   char buf[30];
2462   snprintf(buf, sizeof buf, "E%ld", exponent);
2463   exp->write_c_string(buf);
2464 }
2465 
2466 // Export a floating point number in a constant expression.
2467 
2468 void
do_export(Export * exp) const2469 Float_expression::do_export(Export* exp) const
2470 {
2471   Float_expression::export_float(exp, this->val_);
2472   // A trailing space lets us reliably identify the end of the number.
2473   exp->write_c_string(" ");
2474 }
2475 
2476 // Dump a floating point number to the dump file.
2477 
2478 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2479 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2480 {
2481   Float_expression::export_float(ast_dump_context, this->val_);
2482 }
2483 
2484 // Make a float expression.
2485 
2486 Expression*
make_float(const mpfr_t * val,Type * type,Location location)2487 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2488 {
2489   return new Float_expression(val, type, location);
2490 }
2491 
2492 // Complex numbers.
2493 
2494 class Complex_expression : public Expression
2495 {
2496  public:
Complex_expression(const mpc_t * val,Type * type,Location location)2497   Complex_expression(const mpc_t* val, Type* type, Location location)
2498     : Expression(EXPRESSION_COMPLEX, location),
2499       type_(type)
2500   {
2501     mpc_init2(this->val_, mpc_precision);
2502     mpc_set(this->val_, *val, MPC_RNDNN);
2503   }
2504 
2505   // Write VAL to string dump.
2506   static void
2507   export_complex(String_dump* exp, const mpc_t val);
2508 
2509   // Write REAL/IMAG to dump context.
2510   static void
2511   dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2512 
2513  protected:
2514   bool
do_is_constant() const2515   do_is_constant() const
2516   { return true; }
2517 
2518   bool
do_is_static_initializer() const2519   do_is_static_initializer() const
2520   { return true; }
2521 
2522   bool
do_numeric_constant_value(Numeric_constant * nc) const2523   do_numeric_constant_value(Numeric_constant* nc) const
2524   {
2525     nc->set_complex(this->type_, this->val_);
2526     return true;
2527   }
2528 
2529   Type*
2530   do_type();
2531 
2532   void
2533   do_determine_type(const Type_context*);
2534 
2535   void
2536   do_check_types(Gogo*);
2537 
2538   Expression*
do_copy()2539   do_copy()
2540   {
2541     return Expression::make_complex(&this->val_,
2542 				    (this->type_ == NULL
2543 				     ? NULL
2544 				     : this->type_->copy_expressions()),
2545 				    this->location());
2546   }
2547 
2548   Bexpression*
2549   do_get_backend(Translate_context*);
2550 
2551   void
2552   do_export(Export*) const;
2553 
2554   void
2555   do_dump_expression(Ast_dump_context*) const;
2556 
2557  private:
2558   // The complex value.
2559   mpc_t val_;
2560   // The type if known.
2561   Type* type_;
2562 };
2563 
2564 // Return the current type.  If we haven't set the type yet, we return
2565 // an abstract complex type.
2566 
2567 Type*
do_type()2568 Complex_expression::do_type()
2569 {
2570   if (this->type_ == NULL)
2571     this->type_ = Type::make_abstract_complex_type();
2572   return this->type_;
2573 }
2574 
2575 // Set the type of the complex value.  Here we may switch from an
2576 // abstract type to a real type.
2577 
2578 void
do_determine_type(const Type_context * context)2579 Complex_expression::do_determine_type(const Type_context* context)
2580 {
2581   if (this->type_ != NULL && !this->type_->is_abstract())
2582     ;
2583   else if (context->type != NULL && context->type->is_numeric_type())
2584     this->type_ = context->type;
2585   else if (!context->may_be_abstract)
2586     this->type_ = Type::lookup_complex_type("complex128");
2587 }
2588 
2589 // Check the type of a complex value.
2590 
2591 void
do_check_types(Gogo *)2592 Complex_expression::do_check_types(Gogo*)
2593 {
2594   Type* type = this->type_;
2595   if (type == NULL)
2596     return;
2597   Numeric_constant nc;
2598   nc.set_complex(NULL, this->val_);
2599   if (!nc.set_type(this->type_, true, this->location()))
2600     this->set_is_error();
2601 }
2602 
2603 // Get the backend representation for a complex constant.
2604 
2605 Bexpression*
do_get_backend(Translate_context * context)2606 Complex_expression::do_get_backend(Translate_context* context)
2607 {
2608   if (this->is_error_expression()
2609       || (this->type_ != NULL && this->type_->is_error_type()))
2610     {
2611       go_assert(saw_errors());
2612       return context->gogo()->backend()->error_expression();
2613     }
2614 
2615   Type* resolved_type;
2616   if (this->type_ != NULL && !this->type_->is_abstract())
2617     resolved_type = this->type_;
2618   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2619     {
2620       // We are converting to an abstract integer type.
2621       resolved_type = Type::lookup_integer_type("int");
2622     }
2623   else if (this->type_ != NULL && this->type_->float_type() != NULL)
2624     {
2625       // We are converting to an abstract float type.
2626       resolved_type = Type::lookup_float_type("float64");
2627     }
2628   else
2629     {
2630       // If we still have an abstract type here, this is being
2631       // used in a constant expression which didn't get reduced.  We
2632       // just use complex128 and hope for the best.
2633       resolved_type = Type::lookup_complex_type("complex128");
2634     }
2635 
2636   Numeric_constant nc;
2637   nc.set_complex(resolved_type, this->val_);
2638   return Expression::backend_numeric_constant_expression(context, &nc);
2639 }
2640 
2641 // Write REAL/IMAG to export data.
2642 
2643 void
export_complex(String_dump * exp,const mpc_t val)2644 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2645 {
2646   if (!mpfr_zero_p(mpc_realref(val)))
2647     {
2648       Float_expression::export_float(exp, mpc_realref(val));
2649       if (mpfr_sgn(mpc_imagref(val)) >= 0)
2650 	exp->write_c_string("+");
2651     }
2652   Float_expression::export_float(exp, mpc_imagref(val));
2653   exp->write_c_string("i");
2654 }
2655 
2656 // Export a complex number in a constant expression.
2657 
2658 void
do_export(Export * exp) const2659 Complex_expression::do_export(Export* exp) const
2660 {
2661   Complex_expression::export_complex(exp, this->val_);
2662   // A trailing space lets us reliably identify the end of the number.
2663   exp->write_c_string(" ");
2664 }
2665 
2666 // Dump a complex expression to the dump file.
2667 
2668 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2669 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2670 {
2671   Complex_expression::export_complex(ast_dump_context, this->val_);
2672 }
2673 
2674 // Make a complex expression.
2675 
2676 Expression*
make_complex(const mpc_t * val,Type * type,Location location)2677 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2678 {
2679   return new Complex_expression(val, type, location);
2680 }
2681 
2682 // Find a named object in an expression.
2683 
2684 class Find_named_object : public Traverse
2685 {
2686  public:
Find_named_object(Named_object * no)2687   Find_named_object(Named_object* no)
2688     : Traverse(traverse_expressions),
2689       no_(no), found_(false)
2690   { }
2691 
2692   // Whether we found the object.
2693   bool
found() const2694   found() const
2695   { return this->found_; }
2696 
2697  protected:
2698   int
2699   expression(Expression**);
2700 
2701  private:
2702   // The object we are looking for.
2703   Named_object* no_;
2704   // Whether we found it.
2705   bool found_;
2706 };
2707 
2708 // A reference to a const in an expression.
2709 
2710 class Const_expression : public Expression
2711 {
2712  public:
Const_expression(Named_object * constant,Location location)2713   Const_expression(Named_object* constant, Location location)
2714     : Expression(EXPRESSION_CONST_REFERENCE, location),
2715       constant_(constant), type_(NULL), seen_(false)
2716   { }
2717 
2718   Named_object*
named_object()2719   named_object()
2720   { return this->constant_; }
2721 
2722   // Check that the initializer does not refer to the constant itself.
2723   void
2724   check_for_init_loop();
2725 
2726  protected:
2727   int
2728   do_traverse(Traverse*);
2729 
2730   Expression*
2731   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2732 
2733   bool
do_is_constant() const2734   do_is_constant() const
2735   { return true; }
2736 
2737   bool
do_is_static_initializer() const2738   do_is_static_initializer() const
2739   { return true; }
2740 
2741   bool
2742   do_numeric_constant_value(Numeric_constant* nc) const;
2743 
2744   bool
2745   do_string_constant_value(std::string* val) const;
2746 
2747   Type*
2748   do_type();
2749 
2750   // The type of a const is set by the declaration, not the use.
2751   void
2752   do_determine_type(const Type_context*);
2753 
2754   void
2755   do_check_types(Gogo*);
2756 
2757   Expression*
do_copy()2758   do_copy()
2759   { return this; }
2760 
2761   Bexpression*
2762   do_get_backend(Translate_context* context);
2763 
2764   // When exporting a reference to a const as part of a const
2765   // expression, we export the value.  We ignore the fact that it has
2766   // a name.
2767   void
do_export(Export * exp) const2768   do_export(Export* exp) const
2769   { this->constant_->const_value()->expr()->export_expression(exp); }
2770 
2771   void
2772   do_dump_expression(Ast_dump_context*) const;
2773 
2774  private:
2775   // The constant.
2776   Named_object* constant_;
2777   // The type of this reference.  This is used if the constant has an
2778   // abstract type.
2779   Type* type_;
2780   // Used to prevent infinite recursion when a constant incorrectly
2781   // refers to itself.
2782   mutable bool seen_;
2783 };
2784 
2785 // Traversal.
2786 
2787 int
do_traverse(Traverse * traverse)2788 Const_expression::do_traverse(Traverse* traverse)
2789 {
2790   if (this->type_ != NULL)
2791     return Type::traverse(this->type_, traverse);
2792   return TRAVERSE_CONTINUE;
2793 }
2794 
2795 // Lower a constant expression.  This is where we convert the
2796 // predeclared constant iota into an integer value.
2797 
2798 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)2799 Const_expression::do_lower(Gogo* gogo, Named_object*,
2800 			   Statement_inserter*, int iota_value)
2801 {
2802   if (this->constant_->const_value()->expr()->classification()
2803       == EXPRESSION_IOTA)
2804     {
2805       if (iota_value == -1)
2806 	{
2807 	  go_error_at(this->location(),
2808 		      "iota is only defined in const declarations");
2809 	  iota_value = 0;
2810 	}
2811       return Expression::make_integer_ul(iota_value, NULL, this->location());
2812     }
2813 
2814   // Make sure that the constant itself has been lowered.
2815   gogo->lower_constant(this->constant_);
2816 
2817   return this;
2818 }
2819 
2820 // Return a numeric constant value.
2821 
2822 bool
do_numeric_constant_value(Numeric_constant * nc) const2823 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2824 {
2825   if (this->seen_)
2826     return false;
2827 
2828   Expression* e = this->constant_->const_value()->expr();
2829 
2830   this->seen_ = true;
2831 
2832   bool r = e->numeric_constant_value(nc);
2833 
2834   this->seen_ = false;
2835 
2836   Type* ctype;
2837   if (this->type_ != NULL)
2838     ctype = this->type_;
2839   else
2840     ctype = this->constant_->const_value()->type();
2841   if (r && ctype != NULL)
2842     {
2843       if (!nc->set_type(ctype, false, this->location()))
2844 	return false;
2845     }
2846 
2847   return r;
2848 }
2849 
2850 bool
do_string_constant_value(std::string * val) const2851 Const_expression::do_string_constant_value(std::string* val) const
2852 {
2853   if (this->seen_)
2854     return false;
2855 
2856   Expression* e = this->constant_->const_value()->expr();
2857 
2858   this->seen_ = true;
2859   bool ok = e->string_constant_value(val);
2860   this->seen_ = false;
2861 
2862   return ok;
2863 }
2864 
2865 // Return the type of the const reference.
2866 
2867 Type*
do_type()2868 Const_expression::do_type()
2869 {
2870   if (this->type_ != NULL)
2871     return this->type_;
2872 
2873   Named_constant* nc = this->constant_->const_value();
2874 
2875   if (this->seen_ || nc->lowering())
2876     {
2877       if (nc->type() == NULL || !nc->type()->is_error_type())
2878 	{
2879 	  Location loc = this->location();
2880 	  if (!this->seen_)
2881 	    loc = nc->location();
2882 	  go_error_at(loc, "constant refers to itself");
2883 	}
2884       this->set_is_error();
2885       this->type_ = Type::make_error_type();
2886       nc->set_type(this->type_);
2887       return this->type_;
2888     }
2889 
2890   this->seen_ = true;
2891 
2892   Type* ret = nc->type();
2893 
2894   if (ret != NULL)
2895     {
2896       this->seen_ = false;
2897       return ret;
2898     }
2899 
2900   // During parsing, a named constant may have a NULL type, but we
2901   // must not return a NULL type here.
2902   ret = nc->expr()->type();
2903 
2904   this->seen_ = false;
2905 
2906   if (ret->is_error_type())
2907     nc->set_type(ret);
2908 
2909   return ret;
2910 }
2911 
2912 // Set the type of the const reference.
2913 
2914 void
do_determine_type(const Type_context * context)2915 Const_expression::do_determine_type(const Type_context* context)
2916 {
2917   Type* ctype = this->constant_->const_value()->type();
2918   Type* cetype = (ctype != NULL
2919 		  ? ctype
2920 		  : this->constant_->const_value()->expr()->type());
2921   if (ctype != NULL && !ctype->is_abstract())
2922     ;
2923   else if (context->type != NULL
2924 	   && context->type->is_numeric_type()
2925 	   && cetype->is_numeric_type())
2926     this->type_ = context->type;
2927   else if (context->type != NULL
2928 	   && context->type->is_string_type()
2929 	   && cetype->is_string_type())
2930     this->type_ = context->type;
2931   else if (context->type != NULL
2932 	   && context->type->is_boolean_type()
2933 	   && cetype->is_boolean_type())
2934     this->type_ = context->type;
2935   else if (!context->may_be_abstract)
2936     {
2937       if (cetype->is_abstract())
2938 	cetype = cetype->make_non_abstract_type();
2939       this->type_ = cetype;
2940     }
2941 }
2942 
2943 // Check for a loop in which the initializer of a constant refers to
2944 // the constant itself.
2945 
2946 void
check_for_init_loop()2947 Const_expression::check_for_init_loop()
2948 {
2949   if (this->type_ != NULL && this->type_->is_error())
2950     return;
2951 
2952   if (this->seen_)
2953     {
2954       this->report_error(_("constant refers to itself"));
2955       this->type_ = Type::make_error_type();
2956       return;
2957     }
2958 
2959   Expression* init = this->constant_->const_value()->expr();
2960   Find_named_object find_named_object(this->constant_);
2961 
2962   this->seen_ = true;
2963   Expression::traverse(&init, &find_named_object);
2964   this->seen_ = false;
2965 
2966   if (find_named_object.found())
2967     {
2968       if (this->type_ == NULL || !this->type_->is_error())
2969 	{
2970 	  this->report_error(_("constant refers to itself"));
2971 	  this->type_ = Type::make_error_type();
2972 	}
2973       return;
2974     }
2975 }
2976 
2977 // Check types of a const reference.
2978 
2979 void
do_check_types(Gogo *)2980 Const_expression::do_check_types(Gogo*)
2981 {
2982   if (this->type_ != NULL && this->type_->is_error())
2983     return;
2984 
2985   this->check_for_init_loop();
2986 
2987   // Check that numeric constant fits in type.
2988   if (this->type_ != NULL && this->type_->is_numeric_type())
2989     {
2990       Numeric_constant nc;
2991       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2992 	{
2993 	  if (!nc.set_type(this->type_, true, this->location()))
2994 	    this->set_is_error();
2995 	}
2996     }
2997 }
2998 
2999 // Return the backend representation for a const reference.
3000 
3001 Bexpression*
do_get_backend(Translate_context * context)3002 Const_expression::do_get_backend(Translate_context* context)
3003 {
3004   if (this->is_error_expression()
3005       || (this->type_ != NULL && this->type_->is_error()))
3006     {
3007       go_assert(saw_errors());
3008       return context->backend()->error_expression();
3009     }
3010 
3011   // If the type has been set for this expression, but the underlying
3012   // object is an abstract int or float, we try to get the abstract
3013   // value.  Otherwise we may lose something in the conversion.
3014   Expression* expr = this->constant_->const_value()->expr();
3015   if (this->type_ != NULL
3016       && this->type_->is_numeric_type()
3017       && (this->constant_->const_value()->type() == NULL
3018 	  || this->constant_->const_value()->type()->is_abstract()))
3019     {
3020       Numeric_constant nc;
3021       if (expr->numeric_constant_value(&nc)
3022 	  && nc.set_type(this->type_, false, this->location()))
3023 	{
3024 	  Expression* e = nc.expression(this->location());
3025 	  return e->get_backend(context);
3026 	}
3027     }
3028 
3029   if (this->type_ != NULL)
3030     expr = Expression::make_cast(this->type_, expr, this->location());
3031   return expr->get_backend(context);
3032 }
3033 
3034 // Dump ast representation for constant expression.
3035 
3036 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3037 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3038 {
3039   ast_dump_context->ostream() << this->constant_->name();
3040 }
3041 
3042 // Make a reference to a constant in an expression.
3043 
3044 Expression*
make_const_reference(Named_object * constant,Location location)3045 Expression::make_const_reference(Named_object* constant,
3046 				 Location location)
3047 {
3048   return new Const_expression(constant, location);
3049 }
3050 
3051 // Find a named object in an expression.
3052 
3053 int
expression(Expression ** pexpr)3054 Find_named_object::expression(Expression** pexpr)
3055 {
3056   switch ((*pexpr)->classification())
3057     {
3058     case Expression::EXPRESSION_CONST_REFERENCE:
3059       {
3060 	Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3061 	if (ce->named_object() == this->no_)
3062 	  break;
3063 
3064 	// We need to check a constant initializer explicitly, as
3065 	// loops here will not be caught by the loop checking for
3066 	// variable initializers.
3067 	ce->check_for_init_loop();
3068 
3069 	return TRAVERSE_CONTINUE;
3070       }
3071 
3072     case Expression::EXPRESSION_VAR_REFERENCE:
3073       if ((*pexpr)->var_expression()->named_object() == this->no_)
3074 	break;
3075       return TRAVERSE_CONTINUE;
3076     case Expression::EXPRESSION_FUNC_REFERENCE:
3077       if ((*pexpr)->func_expression()->named_object() == this->no_)
3078 	break;
3079       return TRAVERSE_CONTINUE;
3080     default:
3081       return TRAVERSE_CONTINUE;
3082     }
3083   this->found_ = true;
3084   return TRAVERSE_EXIT;
3085 }
3086 
3087 // The nil value.
3088 
3089 class Nil_expression : public Expression
3090 {
3091  public:
Nil_expression(Location location)3092   Nil_expression(Location location)
3093     : Expression(EXPRESSION_NIL, location)
3094   { }
3095 
3096   static Expression*
3097   do_import(Import*);
3098 
3099  protected:
3100   bool
do_is_constant() const3101   do_is_constant() const
3102   { return true; }
3103 
3104   bool
do_is_static_initializer() const3105   do_is_static_initializer() const
3106   { return true; }
3107 
3108   Type*
do_type()3109   do_type()
3110   { return Type::make_nil_type(); }
3111 
3112   void
do_determine_type(const Type_context *)3113   do_determine_type(const Type_context*)
3114   { }
3115 
3116   Expression*
do_copy()3117   do_copy()
3118   { return this; }
3119 
3120   Bexpression*
do_get_backend(Translate_context * context)3121   do_get_backend(Translate_context* context)
3122   { return context->backend()->nil_pointer_expression(); }
3123 
3124   void
do_export(Export * exp) const3125   do_export(Export* exp) const
3126   { exp->write_c_string("nil"); }
3127 
3128   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3129   do_dump_expression(Ast_dump_context* ast_dump_context) const
3130   { ast_dump_context->ostream() << "nil"; }
3131 };
3132 
3133 // Import a nil expression.
3134 
3135 Expression*
do_import(Import * imp)3136 Nil_expression::do_import(Import* imp)
3137 {
3138   imp->require_c_string("nil");
3139   return Expression::make_nil(imp->location());
3140 }
3141 
3142 // Make a nil expression.
3143 
3144 Expression*
make_nil(Location location)3145 Expression::make_nil(Location location)
3146 {
3147   return new Nil_expression(location);
3148 }
3149 
3150 // The value of the predeclared constant iota.  This is little more
3151 // than a marker.  This will be lowered to an integer in
3152 // Const_expression::do_lower, which is where we know the value that
3153 // it should have.
3154 
3155 class Iota_expression : public Parser_expression
3156 {
3157  public:
Iota_expression(Location location)3158   Iota_expression(Location location)
3159     : Parser_expression(EXPRESSION_IOTA, location)
3160   { }
3161 
3162  protected:
3163   Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3164   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3165   { go_unreachable(); }
3166 
3167   // There should only ever be one of these.
3168   Expression*
do_copy()3169   do_copy()
3170   { go_unreachable(); }
3171 
3172   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3173   do_dump_expression(Ast_dump_context* ast_dump_context) const
3174   { ast_dump_context->ostream() << "iota"; }
3175 };
3176 
3177 // Make an iota expression.  This is only called for one case: the
3178 // value of the predeclared constant iota.
3179 
3180 Expression*
make_iota()3181 Expression::make_iota()
3182 {
3183   static Iota_expression iota_expression(Linemap::unknown_location());
3184   return &iota_expression;
3185 }
3186 
3187 // Class Type_conversion_expression.
3188 
3189 // Traversal.
3190 
3191 int
do_traverse(Traverse * traverse)3192 Type_conversion_expression::do_traverse(Traverse* traverse)
3193 {
3194   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3195       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3196     return TRAVERSE_EXIT;
3197   return TRAVERSE_CONTINUE;
3198 }
3199 
3200 // Convert to a constant at lowering time.
3201 
3202 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3203 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3204 				     Statement_inserter*, int)
3205 {
3206   Type* type = this->type_;
3207   Expression* val = this->expr_;
3208   Location location = this->location();
3209 
3210   if (type->is_numeric_type())
3211     {
3212       Numeric_constant nc;
3213       if (val->numeric_constant_value(&nc))
3214 	{
3215 	  if (!nc.set_type(type, true, location))
3216 	    return Expression::make_error(location);
3217 	  return nc.expression(location);
3218 	}
3219     }
3220 
3221   // According to the language specification on string conversions
3222   // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3223   // When converting an integer into a string, the string will be a UTF-8
3224   // representation of the integer and integers "outside the range of valid
3225   // Unicode code points are converted to '\uFFFD'."
3226   if (type->is_string_type())
3227     {
3228       Numeric_constant nc;
3229       if (val->numeric_constant_value(&nc) && nc.is_int())
3230         {
3231           // An integer value doesn't fit in the Unicode code point range if it
3232           // overflows the Go "int" type or is negative.
3233           unsigned long ul;
3234           if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3235               || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3236             return Expression::make_string("\ufffd", location);
3237         }
3238     }
3239 
3240   if (type->is_slice_type())
3241     {
3242       Type* element_type = type->array_type()->element_type()->forwarded();
3243       bool is_byte = (element_type->integer_type() != NULL
3244 		      && element_type->integer_type()->is_byte());
3245       bool is_rune = (element_type->integer_type() != NULL
3246 		      && element_type->integer_type()->is_rune());
3247       if (is_byte || is_rune)
3248 	{
3249 	  std::string s;
3250 	  if (val->string_constant_value(&s))
3251 	    {
3252 	      Expression_list* vals = new Expression_list();
3253 	      if (is_byte)
3254 		{
3255 		  for (std::string::const_iterator p = s.begin();
3256 		       p != s.end();
3257 		       p++)
3258 		    {
3259 		      unsigned char c = static_cast<unsigned char>(*p);
3260 		      vals->push_back(Expression::make_integer_ul(c,
3261 								  element_type,
3262 								  location));
3263 		    }
3264 		}
3265 	      else
3266 		{
3267 		  const char *p = s.data();
3268 		  const char *pend = s.data() + s.length();
3269 		  while (p < pend)
3270 		    {
3271 		      unsigned int c;
3272 		      int adv = Lex::fetch_char(p, &c);
3273 		      if (adv == 0)
3274 			{
3275 			  go_warning_at(this->location(), 0,
3276 				     "invalid UTF-8 encoding");
3277 			  adv = 1;
3278 			}
3279 		      p += adv;
3280 		      vals->push_back(Expression::make_integer_ul(c,
3281 								  element_type,
3282 								  location));
3283 		    }
3284 		}
3285 
3286 	      return Expression::make_slice_composite_literal(type, vals,
3287 							      location);
3288 	    }
3289 	}
3290     }
3291 
3292   return this;
3293 }
3294 
3295 // Flatten a type conversion by using a temporary variable for the slice
3296 // in slice to string conversions.
3297 
3298 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)3299 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3300                                        Statement_inserter* inserter)
3301 {
3302   if (this->type()->is_error_type() || this->expr_->is_error_expression())
3303     {
3304       go_assert(saw_errors());
3305       return Expression::make_error(this->location());
3306     }
3307 
3308   if (((this->type()->is_string_type()
3309         && this->expr_->type()->is_slice_type())
3310        || this->expr_->type()->interface_type() != NULL)
3311       && !this->expr_->is_variable())
3312     {
3313       Temporary_statement* temp =
3314           Statement::make_temporary(NULL, this->expr_, this->location());
3315       inserter->insert(temp);
3316       this->expr_ = Expression::make_temporary_reference(temp, this->location());
3317     }
3318   return this;
3319 }
3320 
3321 // Return whether a type conversion is a constant.
3322 
3323 bool
do_is_constant() const3324 Type_conversion_expression::do_is_constant() const
3325 {
3326   if (!this->expr_->is_constant())
3327     return false;
3328 
3329   // A conversion to a type that may not be used as a constant is not
3330   // a constant.  For example, []byte(nil).
3331   Type* type = this->type_;
3332   if (type->integer_type() == NULL
3333       && type->float_type() == NULL
3334       && type->complex_type() == NULL
3335       && !type->is_boolean_type()
3336       && !type->is_string_type())
3337     return false;
3338 
3339   return true;
3340 }
3341 
3342 // Return whether a type conversion can be used in a constant
3343 // initializer.
3344 
3345 bool
do_is_static_initializer() const3346 Type_conversion_expression::do_is_static_initializer() const
3347 {
3348   Type* type = this->type_;
3349   Type* expr_type = this->expr_->type();
3350 
3351   if (type->interface_type() != NULL
3352       || expr_type->interface_type() != NULL)
3353     return false;
3354 
3355   if (!this->expr_->is_static_initializer())
3356     return false;
3357 
3358   if (Type::are_identical(type, expr_type, false, NULL))
3359     return true;
3360 
3361   if (type->is_string_type() && expr_type->is_string_type())
3362     return true;
3363 
3364   if ((type->is_numeric_type()
3365        || type->is_boolean_type()
3366        || type->points_to() != NULL)
3367       && (expr_type->is_numeric_type()
3368 	  || expr_type->is_boolean_type()
3369 	  || expr_type->points_to() != NULL))
3370     return true;
3371 
3372   return false;
3373 }
3374 
3375 // Return the constant numeric value if there is one.
3376 
3377 bool
do_numeric_constant_value(Numeric_constant * nc) const3378 Type_conversion_expression::do_numeric_constant_value(
3379     Numeric_constant* nc) const
3380 {
3381   if (!this->type_->is_numeric_type())
3382     return false;
3383   if (!this->expr_->numeric_constant_value(nc))
3384     return false;
3385   return nc->set_type(this->type_, false, this->location());
3386 }
3387 
3388 // Return the constant string value if there is one.
3389 
3390 bool
do_string_constant_value(std::string * val) const3391 Type_conversion_expression::do_string_constant_value(std::string* val) const
3392 {
3393   if (this->type_->is_string_type()
3394       && this->expr_->type()->integer_type() != NULL)
3395     {
3396       Numeric_constant nc;
3397       if (this->expr_->numeric_constant_value(&nc))
3398 	{
3399 	  unsigned long ival;
3400 	  if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3401 	    {
3402 	      val->clear();
3403 	      Lex::append_char(ival, true, val, this->location());
3404 	      return true;
3405 	    }
3406 	}
3407     }
3408 
3409   // FIXME: Could handle conversion from const []int here.
3410 
3411   return false;
3412 }
3413 
3414 // Determine the resulting type of the conversion.
3415 
3416 void
do_determine_type(const Type_context *)3417 Type_conversion_expression::do_determine_type(const Type_context*)
3418 {
3419   Type_context subcontext(this->type_, false);
3420   this->expr_->determine_type(&subcontext);
3421 }
3422 
3423 // Check that types are convertible.
3424 
3425 void
do_check_types(Gogo *)3426 Type_conversion_expression::do_check_types(Gogo*)
3427 {
3428   Type* type = this->type_;
3429   Type* expr_type = this->expr_->type();
3430   std::string reason;
3431 
3432   if (type->is_error() || expr_type->is_error())
3433     {
3434       this->set_is_error();
3435       return;
3436     }
3437 
3438   if (this->may_convert_function_types_
3439       && type->function_type() != NULL
3440       && expr_type->function_type() != NULL)
3441     return;
3442 
3443   if (Type::are_convertible(type, expr_type, &reason))
3444     return;
3445 
3446   go_error_at(this->location(), "%s", reason.c_str());
3447   this->set_is_error();
3448 }
3449 
3450 // Copy.
3451 
3452 Expression*
do_copy()3453 Type_conversion_expression::do_copy()
3454 {
3455   return new Type_conversion_expression(this->type_->copy_expressions(),
3456 					this->expr_->copy(),
3457 					this->location());
3458 }
3459 
3460 // Get the backend representation for a type conversion.
3461 
3462 Bexpression*
do_get_backend(Translate_context * context)3463 Type_conversion_expression::do_get_backend(Translate_context* context)
3464 {
3465   Type* type = this->type_;
3466   Type* expr_type = this->expr_->type();
3467 
3468   Gogo* gogo = context->gogo();
3469   Btype* btype = type->get_backend(gogo);
3470   Location loc = this->location();
3471 
3472   if (Type::are_identical(type, expr_type, false, NULL))
3473     {
3474       Bexpression* bexpr = this->expr_->get_backend(context);
3475       return gogo->backend()->convert_expression(btype, bexpr, loc);
3476     }
3477   else if (type->interface_type() != NULL
3478 	   || expr_type->interface_type() != NULL)
3479     {
3480       Expression* conversion =
3481           Expression::convert_for_assignment(gogo, type, this->expr_,
3482                                              this->location());
3483       return conversion->get_backend(context);
3484     }
3485   else if (type->is_string_type()
3486 	   && expr_type->integer_type() != NULL)
3487     {
3488       mpz_t intval;
3489       Numeric_constant nc;
3490       if (this->expr_->numeric_constant_value(&nc)
3491 	  && nc.to_int(&intval)
3492 	  && mpz_fits_ushort_p(intval))
3493 	{
3494 	  std::string s;
3495 	  Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3496 	  mpz_clear(intval);
3497 	  Expression* se = Expression::make_string(s, loc);
3498 	  return se->get_backend(context);
3499 	}
3500 
3501       Expression* i2s_expr =
3502           Runtime::make_call(Runtime::INTSTRING, loc, 2,
3503 			     Expression::make_nil(loc), this->expr_);
3504       return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3505     }
3506   else if (type->is_string_type() && expr_type->is_slice_type())
3507     {
3508       Array_type* a = expr_type->array_type();
3509       Type* e = a->element_type()->forwarded();
3510       go_assert(e->integer_type() != NULL);
3511       go_assert(this->expr_->is_variable());
3512 
3513       Runtime::Function code;
3514       if (e->integer_type()->is_byte())
3515         code = Runtime::SLICEBYTETOSTRING;
3516       else
3517         {
3518           go_assert(e->integer_type()->is_rune());
3519           code = Runtime::SLICERUNETOSTRING;
3520         }
3521       return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3522 				this->expr_)->get_backend(context);
3523     }
3524   else if (type->is_slice_type() && expr_type->is_string_type())
3525     {
3526       Type* e = type->array_type()->element_type()->forwarded();
3527       go_assert(e->integer_type() != NULL);
3528 
3529       Runtime::Function code;
3530       if (e->integer_type()->is_byte())
3531 	code = Runtime::STRINGTOSLICEBYTE;
3532       else
3533 	{
3534 	  go_assert(e->integer_type()->is_rune());
3535 	  code = Runtime::STRINGTOSLICERUNE;
3536 	}
3537       Expression* s2a = Runtime::make_call(code, loc, 2,
3538 					   Expression::make_nil(loc),
3539 					   this->expr_);
3540       return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3541     }
3542   else if (type->is_numeric_type())
3543     {
3544       go_assert(Type::are_convertible(type, expr_type, NULL));
3545       Bexpression* bexpr = this->expr_->get_backend(context);
3546       return gogo->backend()->convert_expression(btype, bexpr, loc);
3547     }
3548   else if ((type->is_unsafe_pointer_type()
3549 	    && (expr_type->points_to() != NULL
3550                 || expr_type->integer_type()))
3551            || (expr_type->is_unsafe_pointer_type()
3552 	       && type->points_to() != NULL)
3553            || (this->may_convert_function_types_
3554                && type->function_type() != NULL
3555                && expr_type->function_type() != NULL))
3556     {
3557       Bexpression* bexpr = this->expr_->get_backend(context);
3558       return gogo->backend()->convert_expression(btype, bexpr, loc);
3559     }
3560   else
3561     {
3562       Expression* conversion =
3563           Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3564       return conversion->get_backend(context);
3565     }
3566 }
3567 
3568 // Output a type conversion in a constant expression.
3569 
3570 void
do_export(Export * exp) const3571 Type_conversion_expression::do_export(Export* exp) const
3572 {
3573   exp->write_c_string("convert(");
3574   exp->write_type(this->type_);
3575   exp->write_c_string(", ");
3576   this->expr_->export_expression(exp);
3577   exp->write_c_string(")");
3578 }
3579 
3580 // Import a type conversion or a struct construction.
3581 
3582 Expression*
do_import(Import * imp)3583 Type_conversion_expression::do_import(Import* imp)
3584 {
3585   imp->require_c_string("convert(");
3586   Type* type = imp->read_type();
3587   imp->require_c_string(", ");
3588   Expression* val = Expression::import_expression(imp);
3589   imp->require_c_string(")");
3590   return Expression::make_cast(type, val, imp->location());
3591 }
3592 
3593 // Dump ast representation for a type conversion expression.
3594 
3595 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3596 Type_conversion_expression::do_dump_expression(
3597     Ast_dump_context* ast_dump_context) const
3598 {
3599   ast_dump_context->dump_type(this->type_);
3600   ast_dump_context->ostream() << "(";
3601   ast_dump_context->dump_expression(this->expr_);
3602   ast_dump_context->ostream() << ") ";
3603 }
3604 
3605 // Make a type cast expression.
3606 
3607 Expression*
make_cast(Type * type,Expression * val,Location location)3608 Expression::make_cast(Type* type, Expression* val, Location location)
3609 {
3610   if (type->is_error_type() || val->is_error_expression())
3611     return Expression::make_error(location);
3612   return new Type_conversion_expression(type, val, location);
3613 }
3614 
3615 // Class Unsafe_type_conversion_expression.
3616 
3617 // Traversal.
3618 
3619 int
do_traverse(Traverse * traverse)3620 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3621 {
3622   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3623       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3624     return TRAVERSE_EXIT;
3625   return TRAVERSE_CONTINUE;
3626 }
3627 
3628 // Return whether an unsafe type conversion can be used as a constant
3629 // initializer.
3630 
3631 bool
do_is_static_initializer() const3632 Unsafe_type_conversion_expression::do_is_static_initializer() const
3633 {
3634   Type* type = this->type_;
3635   Type* expr_type = this->expr_->type();
3636 
3637   if (type->interface_type() != NULL
3638       || expr_type->interface_type() != NULL)
3639     return false;
3640 
3641   if (!this->expr_->is_static_initializer())
3642     return false;
3643 
3644   if (Type::are_convertible(type, expr_type, NULL))
3645     return true;
3646 
3647   if (type->is_string_type() && expr_type->is_string_type())
3648     return true;
3649 
3650   if ((type->is_numeric_type()
3651        || type->is_boolean_type()
3652        || type->points_to() != NULL)
3653       && (expr_type->is_numeric_type()
3654 	  || expr_type->is_boolean_type()
3655 	  || expr_type->points_to() != NULL))
3656     return true;
3657 
3658   return false;
3659 }
3660 
3661 // Copy.
3662 
3663 Expression*
do_copy()3664 Unsafe_type_conversion_expression::do_copy()
3665 {
3666   return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
3667 					       this->expr_->copy(),
3668 					       this->location());
3669 }
3670 
3671 // Convert to backend representation.
3672 
3673 Bexpression*
do_get_backend(Translate_context * context)3674 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3675 {
3676   // We are only called for a limited number of cases.
3677 
3678   Type* t = this->type_;
3679   Type* et = this->expr_->type();
3680 
3681   if (t->is_error_type()
3682       || this->expr_->is_error_expression()
3683       || et->is_error_type())
3684     {
3685       go_assert(saw_errors());
3686       return context->backend()->error_expression();
3687     }
3688 
3689   if (t->array_type() != NULL)
3690     go_assert(et->array_type() != NULL
3691               && t->is_slice_type() == et->is_slice_type());
3692   else if (t->struct_type() != NULL)
3693     {
3694       if (t->named_type() != NULL
3695           && et->named_type() != NULL
3696           && !Type::are_convertible(t, et, NULL))
3697 	{
3698 	  go_assert(saw_errors());
3699 	  return context->backend()->error_expression();
3700 	}
3701 
3702       go_assert(et->struct_type() != NULL
3703                 && Type::are_convertible(t, et, NULL));
3704     }
3705   else if (t->map_type() != NULL)
3706     go_assert(et->map_type() != NULL);
3707   else if (t->channel_type() != NULL)
3708     go_assert(et->channel_type() != NULL);
3709   else if (t->points_to() != NULL)
3710     go_assert(et->points_to() != NULL
3711               || et->channel_type() != NULL
3712               || et->map_type() != NULL
3713               || et->function_type() != NULL
3714 	      || et->integer_type() != NULL
3715               || et->is_nil_type());
3716   else if (et->is_unsafe_pointer_type())
3717     go_assert(t->points_to() != NULL);
3718   else if (t->interface_type() != NULL)
3719     {
3720       bool empty_iface = t->interface_type()->is_empty();
3721       go_assert(et->interface_type() != NULL
3722                 && et->interface_type()->is_empty() == empty_iface);
3723     }
3724   else if (t->integer_type() != NULL)
3725     go_assert(et->is_boolean_type()
3726               || et->integer_type() != NULL
3727               || et->function_type() != NULL
3728               || et->points_to() != NULL
3729               || et->map_type() != NULL
3730               || et->channel_type() != NULL
3731 	      || et->is_nil_type());
3732   else if (t->function_type() != NULL)
3733     go_assert(et->points_to() != NULL);
3734   else
3735     go_unreachable();
3736 
3737   Gogo* gogo = context->gogo();
3738   Btype* btype = t->get_backend(gogo);
3739   Bexpression* bexpr = this->expr_->get_backend(context);
3740   Location loc = this->location();
3741   return gogo->backend()->convert_expression(btype, bexpr, loc);
3742 }
3743 
3744 // Dump ast representation for an unsafe type conversion expression.
3745 
3746 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3747 Unsafe_type_conversion_expression::do_dump_expression(
3748     Ast_dump_context* ast_dump_context) const
3749 {
3750   ast_dump_context->dump_type(this->type_);
3751   ast_dump_context->ostream() << "(";
3752   ast_dump_context->dump_expression(this->expr_);
3753   ast_dump_context->ostream() << ") ";
3754 }
3755 
3756 // Make an unsafe type conversion expression.
3757 
3758 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)3759 Expression::make_unsafe_cast(Type* type, Expression* expr,
3760 			     Location location)
3761 {
3762   return new Unsafe_type_conversion_expression(type, expr, location);
3763 }
3764 
3765 // Class Unary_expression.
3766 
3767 // Call the address_taken method of the operand if needed.  This is
3768 // called after escape analysis but before inserting write barriers.
3769 
3770 void
check_operand_address_taken(Gogo *)3771 Unary_expression::check_operand_address_taken(Gogo*)
3772 {
3773   if (this->op_ != OPERATOR_AND)
3774     return;
3775 
3776   // If this->escapes_ is false at this point, then it was set to
3777   // false by an explicit call to set_does_not_escape, and the value
3778   // does not escape.  If this->escapes_ is true, we may be able to
3779   // set it to false if taking the address of a variable that does not
3780   // escape.
3781   Node* n = Node::make_node(this);
3782   if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3783     this->escapes_ = false;
3784 
3785   Named_object* var = NULL;
3786   if (this->expr_->var_expression() != NULL)
3787     var = this->expr_->var_expression()->named_object();
3788   else if (this->expr_->enclosed_var_expression() != NULL)
3789     var = this->expr_->enclosed_var_expression()->variable();
3790 
3791   if (this->escapes_ && var != NULL)
3792     {
3793       if (var->is_variable())
3794 	this->escapes_ = var->var_value()->escapes();
3795       if (var->is_result_variable())
3796 	this->escapes_ = var->result_var_value()->escapes();
3797     }
3798 
3799   this->expr_->address_taken(this->escapes_);
3800 }
3801 
3802 // If we are taking the address of a composite literal, and the
3803 // contents are not constant, then we want to make a heap expression
3804 // instead.
3805 
3806 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3807 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3808 {
3809   Location loc = this->location();
3810   Operator op = this->op_;
3811   Expression* expr = this->expr_;
3812 
3813   if (op == OPERATOR_MULT && expr->is_type_expression())
3814     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3815 
3816   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
3817   // moving x to the heap.  FIXME: Is it worth doing a real escape
3818   // analysis here?  This case is found in math/unsafe.go and is
3819   // therefore worth special casing.
3820   if (op == OPERATOR_MULT)
3821     {
3822       Expression* e = expr;
3823       while (e->classification() == EXPRESSION_CONVERSION)
3824 	{
3825 	  Type_conversion_expression* te
3826 	    = static_cast<Type_conversion_expression*>(e);
3827 	  e = te->expr();
3828 	}
3829 
3830       if (e->classification() == EXPRESSION_UNARY)
3831 	{
3832 	  Unary_expression* ue = static_cast<Unary_expression*>(e);
3833 	  if (ue->op_ == OPERATOR_AND)
3834 	    {
3835 	      if (e == expr)
3836 		{
3837 		  // *&x == x.
3838 		  if (!ue->expr_->is_addressable() && !ue->create_temp_)
3839 		    {
3840 		      go_error_at(ue->location(),
3841 				  "invalid operand for unary %<&%>");
3842 		      this->set_is_error();
3843 		    }
3844 		  return ue->expr_;
3845 		}
3846 	      ue->set_does_not_escape();
3847 	    }
3848 	}
3849     }
3850 
3851   // Catching an invalid indirection of unsafe.Pointer here avoid
3852   // having to deal with TYPE_VOID in other places.
3853   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3854     {
3855       go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3856       return Expression::make_error(this->location());
3857     }
3858 
3859   // Check for an invalid pointer dereference.  We need to do this
3860   // here because Unary_expression::do_type will return an error type
3861   // in this case.  That can cause code to appear erroneous, and
3862   // therefore disappear at lowering time, without any error message.
3863   if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3864     {
3865       this->report_error(_("expected pointer"));
3866       return Expression::make_error(this->location());
3867     }
3868 
3869   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3870     {
3871       Numeric_constant nc;
3872       if (expr->numeric_constant_value(&nc))
3873 	{
3874 	  Numeric_constant result;
3875 	  bool issued_error;
3876 	  if (Unary_expression::eval_constant(op, &nc, loc, &result,
3877 					      &issued_error))
3878 	    return result.expression(loc);
3879 	  else if (issued_error)
3880 	    return Expression::make_error(this->location());
3881 	}
3882     }
3883 
3884   return this;
3885 }
3886 
3887 // Flatten expression if a nil check must be performed and create temporary
3888 // variables if necessary.
3889 
3890 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)3891 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3892                              Statement_inserter* inserter)
3893 {
3894   if (this->is_error_expression()
3895       || this->expr_->is_error_expression()
3896       || this->expr_->type()->is_error_type())
3897     {
3898       go_assert(saw_errors());
3899       return Expression::make_error(this->location());
3900     }
3901 
3902   Location location = this->location();
3903   if (this->op_ == OPERATOR_MULT
3904       && !this->expr_->is_variable())
3905     {
3906       go_assert(this->expr_->type()->points_to() != NULL);
3907       switch (this->requires_nil_check(gogo))
3908         {
3909           case NIL_CHECK_ERROR_ENCOUNTERED:
3910             {
3911               go_assert(saw_errors());
3912               return Expression::make_error(this->location());
3913             }
3914           case NIL_CHECK_NOT_NEEDED:
3915             break;
3916           case NIL_CHECK_NEEDED:
3917             this->create_temp_ = true;
3918             break;
3919           case NIL_CHECK_DEFAULT:
3920             go_unreachable();
3921         }
3922     }
3923 
3924   if (this->create_temp_ && !this->expr_->is_variable())
3925     {
3926       Temporary_statement* temp =
3927           Statement::make_temporary(NULL, this->expr_, location);
3928       inserter->insert(temp);
3929       this->expr_ = Expression::make_temporary_reference(temp, location);
3930     }
3931 
3932   return this;
3933 }
3934 
3935 // Return whether a unary expression is a constant.
3936 
3937 bool
do_is_constant() const3938 Unary_expression::do_is_constant() const
3939 {
3940   if (this->op_ == OPERATOR_MULT)
3941     {
3942       // Indirecting through a pointer is only constant if the object
3943       // to which the expression points is constant, but we currently
3944       // have no way to determine that.
3945       return false;
3946     }
3947   else if (this->op_ == OPERATOR_AND)
3948     {
3949       // Taking the address of a variable is constant if it is a
3950       // global variable, not constant otherwise.  In other cases taking the
3951       // address is probably not a constant.
3952       Var_expression* ve = this->expr_->var_expression();
3953       if (ve != NULL)
3954 	{
3955 	  Named_object* no = ve->named_object();
3956 	  return no->is_variable() && no->var_value()->is_global();
3957 	}
3958       return false;
3959     }
3960   else
3961     return this->expr_->is_constant();
3962 }
3963 
3964 // Return whether a unary expression can be used as a constant
3965 // initializer.
3966 
3967 bool
do_is_static_initializer() const3968 Unary_expression::do_is_static_initializer() const
3969 {
3970   if (this->op_ == OPERATOR_MULT)
3971     return false;
3972   else if (this->op_ == OPERATOR_AND)
3973     return Unary_expression::base_is_static_initializer(this->expr_);
3974   else
3975     return this->expr_->is_static_initializer();
3976 }
3977 
3978 // Return whether the address of EXPR can be used as a static
3979 // initializer.
3980 
3981 bool
base_is_static_initializer(Expression * expr)3982 Unary_expression::base_is_static_initializer(Expression* expr)
3983 {
3984   // The address of a field reference can be a static initializer if
3985   // the base can be a static initializer.
3986   Field_reference_expression* fre = expr->field_reference_expression();
3987   if (fre != NULL)
3988     return Unary_expression::base_is_static_initializer(fre->expr());
3989 
3990   // The address of an index expression can be a static initializer if
3991   // the base can be a static initializer and the index is constant.
3992   Array_index_expression* aind = expr->array_index_expression();
3993   if (aind != NULL)
3994     return (aind->end() == NULL
3995 	    && aind->start()->is_constant()
3996 	    && Unary_expression::base_is_static_initializer(aind->array()));
3997 
3998   // The address of a global variable can be a static initializer.
3999   Var_expression* ve = expr->var_expression();
4000   if (ve != NULL)
4001     {
4002       Named_object* no = ve->named_object();
4003       return no->is_variable() && no->var_value()->is_global();
4004     }
4005 
4006   // The address of a composite literal can be used as a static
4007   // initializer if the composite literal is itself usable as a
4008   // static initializer.
4009   if (expr->is_composite_literal() && expr->is_static_initializer())
4010     return true;
4011 
4012   // The address of a string constant can be used as a static
4013   // initializer.  This can not be written in Go itself but this is
4014   // used when building a type descriptor.
4015   if (expr->string_expression() != NULL)
4016     return true;
4017 
4018   return false;
4019 }
4020 
4021 // Return whether this dereference expression requires an explicit nil
4022 // check. If we are dereferencing the pointer to a large struct
4023 // (greater than the specified size threshold), we need to check for
4024 // nil. We don't bother to check for small structs because we expect
4025 // the system to crash on a nil pointer dereference. However, if we
4026 // know the address of this expression is being taken, we must always
4027 // check for nil.
4028 Unary_expression::Nil_check_classification
requires_nil_check(Gogo * gogo)4029 Unary_expression::requires_nil_check(Gogo* gogo)
4030 {
4031   go_assert(this->op_ == OPERATOR_MULT);
4032   go_assert(this->expr_->type()->points_to() != NULL);
4033 
4034   if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4035     return NIL_CHECK_NEEDED;
4036   else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4037     return NIL_CHECK_NOT_NEEDED;
4038 
4039   Type* ptype = this->expr_->type()->points_to();
4040   int64_t type_size = -1;
4041   if (!ptype->is_void_type())
4042     {
4043       bool ok = ptype->backend_type_size(gogo, &type_size);
4044       if (!ok)
4045         return NIL_CHECK_ERROR_ENCOUNTERED;
4046     }
4047 
4048   int64_t size_cutoff = gogo->nil_check_size_threshold();
4049   if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4050     this->issue_nil_check_ = NIL_CHECK_NEEDED;
4051   else
4052     this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4053   return this->issue_nil_check_;
4054 }
4055 
4056 // Apply unary opcode OP to UNC, setting NC.  Return true if this
4057 // could be done, false if not.  On overflow, issues an error and sets
4058 // *ISSUED_ERROR.
4059 
4060 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)4061 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4062 				Location location, Numeric_constant* nc,
4063 				bool* issued_error)
4064 {
4065   *issued_error = false;
4066   switch (op)
4067     {
4068     case OPERATOR_PLUS:
4069       *nc = *unc;
4070       return true;
4071 
4072     case OPERATOR_MINUS:
4073       if (unc->is_int() || unc->is_rune())
4074 	break;
4075       else if (unc->is_float())
4076 	{
4077 	  mpfr_t uval;
4078 	  unc->get_float(&uval);
4079 	  mpfr_t val;
4080 	  mpfr_init(val);
4081 	  mpfr_neg(val, uval, GMP_RNDN);
4082 	  nc->set_float(unc->type(), val);
4083 	  mpfr_clear(uval);
4084 	  mpfr_clear(val);
4085 	  return true;
4086 	}
4087       else if (unc->is_complex())
4088 	{
4089 	  mpc_t uval;
4090 	  unc->get_complex(&uval);
4091 	  mpc_t val;
4092 	  mpc_init2(val, mpc_precision);
4093 	  mpc_neg(val, uval, MPC_RNDNN);
4094 	  nc->set_complex(unc->type(), val);
4095 	  mpc_clear(uval);
4096 	  mpc_clear(val);
4097 	  return true;
4098 	}
4099       else
4100 	go_unreachable();
4101 
4102     case OPERATOR_XOR:
4103       break;
4104 
4105     case OPERATOR_NOT:
4106     case OPERATOR_AND:
4107     case OPERATOR_MULT:
4108       return false;
4109 
4110     default:
4111       go_unreachable();
4112     }
4113 
4114   if (!unc->is_int() && !unc->is_rune())
4115     return false;
4116 
4117   mpz_t uval;
4118   if (unc->is_rune())
4119     unc->get_rune(&uval);
4120   else
4121     unc->get_int(&uval);
4122   mpz_t val;
4123   mpz_init(val);
4124 
4125   switch (op)
4126     {
4127     case OPERATOR_MINUS:
4128       mpz_neg(val, uval);
4129       break;
4130 
4131     case OPERATOR_NOT:
4132       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4133       break;
4134 
4135     case OPERATOR_XOR:
4136       {
4137 	Type* utype = unc->type();
4138 	if (utype->integer_type() == NULL
4139 	    || utype->integer_type()->is_abstract())
4140 	  mpz_com(val, uval);
4141 	else
4142 	  {
4143 	    // The number of HOST_WIDE_INTs that it takes to represent
4144 	    // UVAL.
4145 	    size_t count = ((mpz_sizeinbase(uval, 2)
4146 			     + HOST_BITS_PER_WIDE_INT
4147 			     - 1)
4148 			    / HOST_BITS_PER_WIDE_INT);
4149 
4150 	    unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4151 	    memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4152 
4153 	    size_t obits = utype->integer_type()->bits();
4154 
4155 	    if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4156 	      {
4157 		mpz_t adj;
4158 		mpz_init_set_ui(adj, 1);
4159 		mpz_mul_2exp(adj, adj, obits);
4160 		mpz_add(uval, uval, adj);
4161 		mpz_clear(adj);
4162 	      }
4163 
4164 	    size_t ecount;
4165 	    mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4166 	    go_assert(ecount <= count);
4167 
4168 	    // Trim down to the number of words required by the type.
4169 	    size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4170 			     / HOST_BITS_PER_WIDE_INT);
4171 	    go_assert(ocount <= count);
4172 
4173 	    for (size_t i = 0; i < ocount; ++i)
4174 	      phwi[i] = ~phwi[i];
4175 
4176 	    size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4177 	    if (clearbits != 0)
4178 	      phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4179 				   >> clearbits);
4180 
4181 	    mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4182 
4183 	    if (!utype->integer_type()->is_unsigned()
4184 		&& mpz_tstbit(val, obits - 1))
4185 	      {
4186 		mpz_t adj;
4187 		mpz_init_set_ui(adj, 1);
4188 		mpz_mul_2exp(adj, adj, obits);
4189 		mpz_sub(val, val, adj);
4190 		mpz_clear(adj);
4191 	      }
4192 
4193 	    delete[] phwi;
4194 	  }
4195       }
4196       break;
4197 
4198     default:
4199       go_unreachable();
4200     }
4201 
4202   if (unc->is_rune())
4203     nc->set_rune(NULL, val);
4204   else
4205     nc->set_int(NULL, val);
4206 
4207   mpz_clear(uval);
4208   mpz_clear(val);
4209 
4210   if (!nc->set_type(unc->type(), true, location))
4211     {
4212       *issued_error = true;
4213       return false;
4214     }
4215   return true;
4216 }
4217 
4218 // Return the integral constant value of a unary expression, if it has one.
4219 
4220 bool
do_numeric_constant_value(Numeric_constant * nc) const4221 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4222 {
4223   Numeric_constant unc;
4224   if (!this->expr_->numeric_constant_value(&unc))
4225     return false;
4226   bool issued_error;
4227   return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4228 					 nc, &issued_error);
4229 }
4230 
4231 // Return the type of a unary expression.
4232 
4233 Type*
do_type()4234 Unary_expression::do_type()
4235 {
4236   switch (this->op_)
4237     {
4238     case OPERATOR_PLUS:
4239     case OPERATOR_MINUS:
4240     case OPERATOR_NOT:
4241     case OPERATOR_XOR:
4242       return this->expr_->type();
4243 
4244     case OPERATOR_AND:
4245       return Type::make_pointer_type(this->expr_->type());
4246 
4247     case OPERATOR_MULT:
4248       {
4249 	Type* subtype = this->expr_->type();
4250 	Type* points_to = subtype->points_to();
4251 	if (points_to == NULL)
4252 	  return Type::make_error_type();
4253 	return points_to;
4254       }
4255 
4256     default:
4257       go_unreachable();
4258     }
4259 }
4260 
4261 // Determine abstract types for a unary expression.
4262 
4263 void
do_determine_type(const Type_context * context)4264 Unary_expression::do_determine_type(const Type_context* context)
4265 {
4266   switch (this->op_)
4267     {
4268     case OPERATOR_PLUS:
4269     case OPERATOR_MINUS:
4270     case OPERATOR_NOT:
4271     case OPERATOR_XOR:
4272       this->expr_->determine_type(context);
4273       break;
4274 
4275     case OPERATOR_AND:
4276       // Taking the address of something.
4277       {
4278 	Type* subtype = (context->type == NULL
4279 			 ? NULL
4280 			 : context->type->points_to());
4281 	Type_context subcontext(subtype, false);
4282 	this->expr_->determine_type(&subcontext);
4283       }
4284       break;
4285 
4286     case OPERATOR_MULT:
4287       // Indirecting through a pointer.
4288       {
4289 	Type* subtype = (context->type == NULL
4290 			 ? NULL
4291 			 : Type::make_pointer_type(context->type));
4292 	Type_context subcontext(subtype, false);
4293 	this->expr_->determine_type(&subcontext);
4294       }
4295       break;
4296 
4297     default:
4298       go_unreachable();
4299     }
4300 }
4301 
4302 // Check types for a unary expression.
4303 
4304 void
do_check_types(Gogo *)4305 Unary_expression::do_check_types(Gogo*)
4306 {
4307   Type* type = this->expr_->type();
4308   if (type->is_error())
4309     {
4310       this->set_is_error();
4311       return;
4312     }
4313 
4314   switch (this->op_)
4315     {
4316     case OPERATOR_PLUS:
4317     case OPERATOR_MINUS:
4318       if (type->integer_type() == NULL
4319 	  && type->float_type() == NULL
4320 	  && type->complex_type() == NULL)
4321 	this->report_error(_("expected numeric type"));
4322       break;
4323 
4324     case OPERATOR_NOT:
4325       if (!type->is_boolean_type())
4326 	this->report_error(_("expected boolean type"));
4327       break;
4328 
4329     case OPERATOR_XOR:
4330       if (type->integer_type() == NULL)
4331 	this->report_error(_("expected integer"));
4332       break;
4333 
4334     case OPERATOR_AND:
4335       if (!this->expr_->is_addressable())
4336 	{
4337 	  if (!this->create_temp_)
4338 	    {
4339 	      go_error_at(this->location(), "invalid operand for unary %<&%>");
4340 	      this->set_is_error();
4341 	    }
4342 	}
4343       else
4344 	this->expr_->issue_nil_check();
4345       break;
4346 
4347     case OPERATOR_MULT:
4348       // Indirecting through a pointer.
4349       if (type->points_to() == NULL)
4350 	this->report_error(_("expected pointer"));
4351       if (type->points_to()->is_error())
4352 	this->set_is_error();
4353       break;
4354 
4355     default:
4356       go_unreachable();
4357     }
4358 }
4359 
4360 // Get the backend representation for a unary expression.
4361 
4362 Bexpression*
do_get_backend(Translate_context * context)4363 Unary_expression::do_get_backend(Translate_context* context)
4364 {
4365   Gogo* gogo = context->gogo();
4366   Location loc = this->location();
4367 
4368   // Taking the address of a set-and-use-temporary expression requires
4369   // setting the temporary and then taking the address.
4370   if (this->op_ == OPERATOR_AND)
4371     {
4372       Set_and_use_temporary_expression* sut =
4373 	this->expr_->set_and_use_temporary_expression();
4374       if (sut != NULL)
4375 	{
4376 	  Temporary_statement* temp = sut->temporary();
4377 	  Bvariable* bvar = temp->get_backend_variable(context);
4378           Bexpression* bvar_expr =
4379               gogo->backend()->var_expression(bvar, loc);
4380           Bexpression* bval = sut->expression()->get_backend(context);
4381 
4382           Named_object* fn = context->function();
4383           go_assert(fn != NULL);
4384           Bfunction* bfn =
4385               fn->func_value()->get_or_make_decl(gogo, fn);
4386           Bstatement* bassign =
4387               gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4388           Bexpression* bvar_addr =
4389               gogo->backend()->address_expression(bvar_expr, loc);
4390 	  return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4391 	}
4392     }
4393 
4394   Bexpression* ret;
4395   Bexpression* bexpr = this->expr_->get_backend(context);
4396   Btype* btype = this->expr_->type()->get_backend(gogo);
4397   switch (this->op_)
4398     {
4399     case OPERATOR_PLUS:
4400       ret = bexpr;
4401       break;
4402 
4403     case OPERATOR_MINUS:
4404       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4405       ret = gogo->backend()->convert_expression(btype, ret, loc);
4406       break;
4407 
4408     case OPERATOR_NOT:
4409     case OPERATOR_XOR:
4410       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4411       break;
4412 
4413     case OPERATOR_AND:
4414       if (!this->create_temp_)
4415 	{
4416 	  // We should not see a non-constant constructor here; cases
4417 	  // where we would see one should have been moved onto the
4418 	  // heap at parse time.  Taking the address of a nonconstant
4419 	  // constructor will not do what the programmer expects.
4420 
4421           go_assert(!this->expr_->is_composite_literal()
4422                     || this->expr_->is_static_initializer());
4423 	  if (this->expr_->classification() == EXPRESSION_UNARY)
4424 	    {
4425 	      Unary_expression* ue =
4426 		static_cast<Unary_expression*>(this->expr_);
4427 	      go_assert(ue->op() != OPERATOR_AND);
4428 	    }
4429 	}
4430 
4431       if (this->is_gc_root_ || this->is_slice_init_)
4432 	{
4433 	  std::string var_name;
4434 	  bool copy_to_heap = false;
4435 	  if (this->is_gc_root_)
4436 	    {
4437 	      // Build a decl for a GC root variable.  GC roots are mutable, so
4438 	      // they cannot be represented as an immutable_struct in the
4439 	      // backend.
4440 	      var_name = gogo->gc_root_name();
4441 	    }
4442 	  else
4443 	    {
4444 	      // Build a decl for a slice value initializer.  An immutable slice
4445 	      // value initializer may have to be copied to the heap if it
4446 	      // contains pointers in a non-constant context.
4447 	      var_name = gogo->initializer_name();
4448 
4449 	      Array_type* at = this->expr_->type()->array_type();
4450 	      go_assert(at != NULL);
4451 
4452 	      // If we are not copying the value to the heap, we will only
4453 	      // initialize the value once, so we can use this directly
4454 	      // rather than copying it.  In that case we can't make it
4455 	      // read-only, because the program is permitted to change it.
4456 	      copy_to_heap = context->function() != NULL;
4457 	    }
4458 	  std::string asm_name(go_selectively_encode_id(var_name));
4459 	  Bvariable* implicit =
4460               gogo->backend()->implicit_variable(var_name, asm_name,
4461                                                  btype, true, copy_to_heap,
4462                                                  false, 0);
4463 	  gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4464 						      true, copy_to_heap, false,
4465 						      bexpr);
4466 	  bexpr = gogo->backend()->var_expression(implicit, loc);
4467 
4468 	  // If we are not copying a slice initializer to the heap,
4469 	  // then it can be changed by the program, so if it can
4470 	  // contain pointers we must register it as a GC root.
4471 	  if (this->is_slice_init_
4472 	      && !copy_to_heap
4473 	      && this->expr_->type()->has_pointer())
4474 	    {
4475 	      Bexpression* root =
4476                   gogo->backend()->var_expression(implicit, loc);
4477 	      root = gogo->backend()->address_expression(root, loc);
4478 	      Type* type = Type::make_pointer_type(this->expr_->type());
4479 	      gogo->add_gc_root(Expression::make_backend(root, type, loc));
4480 	    }
4481 	}
4482       else if ((this->expr_->is_composite_literal()
4483 		|| this->expr_->string_expression() != NULL)
4484 	       && this->expr_->is_static_initializer())
4485         {
4486 	  std::string var_name(gogo->initializer_name());
4487 	  std::string asm_name(go_selectively_encode_id(var_name));
4488           Bvariable* decl =
4489               gogo->backend()->immutable_struct(var_name, asm_name,
4490                                                 true, false, btype, loc);
4491           gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4492 						     false, btype, loc, bexpr);
4493           bexpr = gogo->backend()->var_expression(decl, loc);
4494         }
4495 
4496       go_assert(!this->create_temp_ || this->expr_->is_variable());
4497       ret = gogo->backend()->address_expression(bexpr, loc);
4498       break;
4499 
4500     case OPERATOR_MULT:
4501       {
4502         go_assert(this->expr_->type()->points_to() != NULL);
4503 
4504         bool known_valid = false;
4505         Type* ptype = this->expr_->type()->points_to();
4506         Btype* pbtype = ptype->get_backend(gogo);
4507         switch (this->requires_nil_check(gogo))
4508           {
4509             case NIL_CHECK_NOT_NEEDED:
4510               break;
4511             case NIL_CHECK_ERROR_ENCOUNTERED:
4512               {
4513                 go_assert(saw_errors());
4514                 return gogo->backend()->error_expression();
4515               }
4516             case NIL_CHECK_NEEDED:
4517               {
4518                 go_assert(this->expr_->is_variable());
4519 
4520                 // If we're nil-checking the result of a set-and-use-temporary
4521                 // expression, then pick out the target temp and use that
4522                 // for the final result of the conditional.
4523                 Bexpression* tbexpr = bexpr;
4524                 Bexpression* ubexpr = bexpr;
4525                 Set_and_use_temporary_expression* sut =
4526                     this->expr_->set_and_use_temporary_expression();
4527                 if (sut != NULL) {
4528                   Temporary_statement* temp = sut->temporary();
4529                   Bvariable* bvar = temp->get_backend_variable(context);
4530                   ubexpr = gogo->backend()->var_expression(bvar, loc);
4531                 }
4532                 Bexpression* nil =
4533                     Expression::make_nil(loc)->get_backend(context);
4534                 Bexpression* compare =
4535                     gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
4536                                                        nil, loc);
4537                 Bexpression* crash =
4538                     gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4539                                         loc)->get_backend(context);
4540                 Bfunction* bfn = context->function()->func_value()->get_decl();
4541                 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4542                                                                 compare,
4543                                                                 crash, ubexpr,
4544                                                                 loc);
4545                 known_valid = true;
4546                 break;
4547               }
4548             case NIL_CHECK_DEFAULT:
4549               go_unreachable();
4550           }
4551         ret = gogo->backend()->indirect_expression(pbtype, bexpr,
4552                                                    known_valid, loc);
4553       }
4554       break;
4555 
4556     default:
4557       go_unreachable();
4558     }
4559 
4560   return ret;
4561 }
4562 
4563 // Export a unary expression.
4564 
4565 void
do_export(Export * exp) const4566 Unary_expression::do_export(Export* exp) const
4567 {
4568   switch (this->op_)
4569     {
4570     case OPERATOR_PLUS:
4571       exp->write_c_string("+ ");
4572       break;
4573     case OPERATOR_MINUS:
4574       exp->write_c_string("- ");
4575       break;
4576     case OPERATOR_NOT:
4577       exp->write_c_string("! ");
4578       break;
4579     case OPERATOR_XOR:
4580       exp->write_c_string("^ ");
4581       break;
4582     case OPERATOR_AND:
4583     case OPERATOR_MULT:
4584     default:
4585       go_unreachable();
4586     }
4587   this->expr_->export_expression(exp);
4588 }
4589 
4590 // Import a unary expression.
4591 
4592 Expression*
do_import(Import * imp)4593 Unary_expression::do_import(Import* imp)
4594 {
4595   Operator op;
4596   switch (imp->get_char())
4597     {
4598     case '+':
4599       op = OPERATOR_PLUS;
4600       break;
4601     case '-':
4602       op = OPERATOR_MINUS;
4603       break;
4604     case '!':
4605       op = OPERATOR_NOT;
4606       break;
4607     case '^':
4608       op = OPERATOR_XOR;
4609       break;
4610     default:
4611       go_unreachable();
4612     }
4613   imp->require_c_string(" ");
4614   Expression* expr = Expression::import_expression(imp);
4615   return Expression::make_unary(op, expr, imp->location());
4616 }
4617 
4618 // Dump ast representation of an unary expression.
4619 
4620 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4621 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4622 {
4623   ast_dump_context->dump_operator(this->op_);
4624   ast_dump_context->ostream() << "(";
4625   ast_dump_context->dump_expression(this->expr_);
4626   ast_dump_context->ostream() << ") ";
4627 }
4628 
4629 // Make a unary expression.
4630 
4631 Expression*
make_unary(Operator op,Expression * expr,Location location)4632 Expression::make_unary(Operator op, Expression* expr, Location location)
4633 {
4634   return new Unary_expression(op, expr, location);
4635 }
4636 
4637 Expression*
make_dereference(Expression * ptr,Nil_check_classification docheck,Location location)4638 Expression::make_dereference(Expression* ptr,
4639                              Nil_check_classification docheck,
4640                              Location location)
4641 {
4642   Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
4643   if (docheck == NIL_CHECK_NEEDED)
4644     deref->unary_expression()->set_requires_nil_check(true);
4645   else if (docheck == NIL_CHECK_NOT_NEEDED)
4646     deref->unary_expression()->set_requires_nil_check(false);
4647   return deref;
4648 }
4649 
4650 // If this is an indirection through a pointer, return the expression
4651 // being pointed through.  Otherwise return this.
4652 
4653 Expression*
deref()4654 Expression::deref()
4655 {
4656   if (this->classification_ == EXPRESSION_UNARY)
4657     {
4658       Unary_expression* ue = static_cast<Unary_expression*>(this);
4659       if (ue->op() == OPERATOR_MULT)
4660 	return ue->operand();
4661     }
4662   return this;
4663 }
4664 
4665 // Class Binary_expression.
4666 
4667 // Traversal.
4668 
4669 int
do_traverse(Traverse * traverse)4670 Binary_expression::do_traverse(Traverse* traverse)
4671 {
4672   int t = Expression::traverse(&this->left_, traverse);
4673   if (t == TRAVERSE_EXIT)
4674     return TRAVERSE_EXIT;
4675   return Expression::traverse(&this->right_, traverse);
4676 }
4677 
4678 // Return whether this expression may be used as a static initializer.
4679 
4680 bool
do_is_static_initializer() const4681 Binary_expression::do_is_static_initializer() const
4682 {
4683   if (!this->left_->is_static_initializer()
4684       || !this->right_->is_static_initializer())
4685     return false;
4686 
4687   // Addresses can be static initializers, but we can't implement
4688   // arbitray binary expressions of them.
4689   Unary_expression* lu = this->left_->unary_expression();
4690   Unary_expression* ru = this->right_->unary_expression();
4691   if (lu != NULL && lu->op() == OPERATOR_AND)
4692     {
4693       if (ru != NULL && ru->op() == OPERATOR_AND)
4694 	return this->op_ == OPERATOR_MINUS;
4695       else
4696 	return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4697     }
4698   else if (ru != NULL && ru->op() == OPERATOR_AND)
4699     return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4700 
4701   // Other cases should resolve in the backend.
4702   return true;
4703 }
4704 
4705 // Return the type to use for a binary operation on operands of
4706 // LEFT_TYPE and RIGHT_TYPE.  These are the types of constants and as
4707 // such may be NULL or abstract.
4708 
4709 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)4710 Binary_expression::operation_type(Operator op, Type* left_type,
4711 				  Type* right_type, Type** result_type)
4712 {
4713   if (left_type != right_type
4714       && !left_type->is_abstract()
4715       && !right_type->is_abstract()
4716       && left_type->base() != right_type->base()
4717       && op != OPERATOR_LSHIFT
4718       && op != OPERATOR_RSHIFT)
4719     {
4720       // May be a type error--let it be diagnosed elsewhere.
4721       return false;
4722     }
4723 
4724   if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4725     {
4726       if (left_type->integer_type() != NULL)
4727 	*result_type = left_type;
4728       else
4729 	*result_type = Type::make_abstract_integer_type();
4730     }
4731   else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4732     *result_type = left_type;
4733   else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4734     *result_type = right_type;
4735   else if (!left_type->is_abstract())
4736     *result_type = left_type;
4737   else if (!right_type->is_abstract())
4738     *result_type = right_type;
4739   else if (left_type->complex_type() != NULL)
4740     *result_type = left_type;
4741   else if (right_type->complex_type() != NULL)
4742     *result_type = right_type;
4743   else if (left_type->float_type() != NULL)
4744     *result_type = left_type;
4745   else if (right_type->float_type() != NULL)
4746     *result_type = right_type;
4747   else if (left_type->integer_type() != NULL
4748 	   && left_type->integer_type()->is_rune())
4749     *result_type = left_type;
4750   else if (right_type->integer_type() != NULL
4751 	   && right_type->integer_type()->is_rune())
4752     *result_type = right_type;
4753   else
4754     *result_type = left_type;
4755 
4756   return true;
4757 }
4758 
4759 // Convert an integer comparison code and an operator to a boolean
4760 // value.
4761 
4762 bool
cmp_to_bool(Operator op,int cmp)4763 Binary_expression::cmp_to_bool(Operator op, int cmp)
4764 {
4765   switch (op)
4766     {
4767     case OPERATOR_EQEQ:
4768       return cmp == 0;
4769       break;
4770     case OPERATOR_NOTEQ:
4771       return cmp != 0;
4772       break;
4773     case OPERATOR_LT:
4774       return cmp < 0;
4775       break;
4776     case OPERATOR_LE:
4777       return cmp <= 0;
4778     case OPERATOR_GT:
4779       return cmp > 0;
4780     case OPERATOR_GE:
4781       return cmp >= 0;
4782     default:
4783       go_unreachable();
4784     }
4785 }
4786 
4787 // Compare constants according to OP.
4788 
4789 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)4790 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4791 				    Numeric_constant* right_nc,
4792 				    Location location, bool* result)
4793 {
4794   Type* left_type = left_nc->type();
4795   Type* right_type = right_nc->type();
4796 
4797   Type* type;
4798   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4799     return false;
4800 
4801   // When comparing an untyped operand to a typed operand, we are
4802   // effectively coercing the untyped operand to the other operand's
4803   // type, so make sure that is valid.
4804   if (!left_nc->set_type(type, true, location)
4805       || !right_nc->set_type(type, true, location))
4806     return false;
4807 
4808   bool ret;
4809   int cmp;
4810   if (type->complex_type() != NULL)
4811     {
4812       if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4813 	return false;
4814       ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4815     }
4816   else if (type->float_type() != NULL)
4817     ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4818   else
4819     ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4820 
4821   if (ret)
4822     *result = Binary_expression::cmp_to_bool(op, cmp);
4823 
4824   return ret;
4825 }
4826 
4827 // Compare integer constants.
4828 
4829 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)4830 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4831 				   const Numeric_constant* right_nc,
4832 				   int* cmp)
4833 {
4834   mpz_t left_val;
4835   if (!left_nc->to_int(&left_val))
4836     return false;
4837   mpz_t right_val;
4838   if (!right_nc->to_int(&right_val))
4839     {
4840       mpz_clear(left_val);
4841       return false;
4842     }
4843 
4844   *cmp = mpz_cmp(left_val, right_val);
4845 
4846   mpz_clear(left_val);
4847   mpz_clear(right_val);
4848 
4849   return true;
4850 }
4851 
4852 // Compare floating point constants.
4853 
4854 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)4855 Binary_expression::compare_float(const Numeric_constant* left_nc,
4856 				 const Numeric_constant* right_nc,
4857 				 int* cmp)
4858 {
4859   mpfr_t left_val;
4860   if (!left_nc->to_float(&left_val))
4861     return false;
4862   mpfr_t right_val;
4863   if (!right_nc->to_float(&right_val))
4864     {
4865       mpfr_clear(left_val);
4866       return false;
4867     }
4868 
4869   // We already coerced both operands to the same type.  If that type
4870   // is not an abstract type, we need to round the values accordingly.
4871   Type* type = left_nc->type();
4872   if (!type->is_abstract() && type->float_type() != NULL)
4873     {
4874       int bits = type->float_type()->bits();
4875       mpfr_prec_round(left_val, bits, GMP_RNDN);
4876       mpfr_prec_round(right_val, bits, GMP_RNDN);
4877     }
4878 
4879   *cmp = mpfr_cmp(left_val, right_val);
4880 
4881   mpfr_clear(left_val);
4882   mpfr_clear(right_val);
4883 
4884   return true;
4885 }
4886 
4887 // Compare complex constants.  Complex numbers may only be compared
4888 // for equality.
4889 
4890 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)4891 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4892 				   const Numeric_constant* right_nc,
4893 				   int* cmp)
4894 {
4895   mpc_t left_val;
4896   if (!left_nc->to_complex(&left_val))
4897     return false;
4898   mpc_t right_val;
4899   if (!right_nc->to_complex(&right_val))
4900     {
4901       mpc_clear(left_val);
4902       return false;
4903     }
4904 
4905   // We already coerced both operands to the same type.  If that type
4906   // is not an abstract type, we need to round the values accordingly.
4907   Type* type = left_nc->type();
4908   if (!type->is_abstract() && type->complex_type() != NULL)
4909     {
4910       int bits = type->complex_type()->bits();
4911       mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4912       mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4913       mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4914       mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4915     }
4916 
4917   *cmp = mpc_cmp(left_val, right_val) != 0;
4918 
4919   mpc_clear(left_val);
4920   mpc_clear(right_val);
4921 
4922   return true;
4923 }
4924 
4925 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC.  Return
4926 // true if this could be done, false if not.  Issue errors at LOCATION
4927 // as appropriate, and sets *ISSUED_ERROR if it did.
4928 
4929 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)4930 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4931 				 Numeric_constant* right_nc,
4932 				 Location location, Numeric_constant* nc,
4933 				 bool* issued_error)
4934 {
4935   *issued_error = false;
4936   switch (op)
4937     {
4938     case OPERATOR_OROR:
4939     case OPERATOR_ANDAND:
4940     case OPERATOR_EQEQ:
4941     case OPERATOR_NOTEQ:
4942     case OPERATOR_LT:
4943     case OPERATOR_LE:
4944     case OPERATOR_GT:
4945     case OPERATOR_GE:
4946       // These return boolean values, not numeric.
4947       return false;
4948     default:
4949       break;
4950     }
4951 
4952   Type* left_type = left_nc->type();
4953   Type* right_type = right_nc->type();
4954 
4955   Type* type;
4956   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4957     return false;
4958 
4959   bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4960 
4961   // When combining an untyped operand with a typed operand, we are
4962   // effectively coercing the untyped operand to the other operand's
4963   // type, so make sure that is valid.
4964   if (!left_nc->set_type(type, true, location))
4965     return false;
4966   if (!is_shift && !right_nc->set_type(type, true, location))
4967     return false;
4968   if (is_shift
4969       && ((left_type->integer_type() == NULL
4970            && !left_type->is_abstract())
4971           || (right_type->integer_type() == NULL
4972               && !right_type->is_abstract())))
4973     return false;
4974 
4975   bool r;
4976   if (type->complex_type() != NULL)
4977     r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4978   else if (type->float_type() != NULL)
4979     r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4980   else
4981     r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4982 
4983   if (r)
4984     {
4985       r = nc->set_type(type, true, location);
4986       if (!r)
4987 	*issued_error = true;
4988     }
4989 
4990   return r;
4991 }
4992 
4993 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4994 // integer operations.  Return true if this could be done, false if
4995 // not.
4996 
4997 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)4998 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4999 				const Numeric_constant* right_nc,
5000 				Location location, Numeric_constant* nc)
5001 {
5002   mpz_t left_val;
5003   if (!left_nc->to_int(&left_val))
5004     return false;
5005   mpz_t right_val;
5006   if (!right_nc->to_int(&right_val))
5007     {
5008       mpz_clear(left_val);
5009       return false;
5010     }
5011 
5012   mpz_t val;
5013   mpz_init(val);
5014 
5015   switch (op)
5016     {
5017     case OPERATOR_PLUS:
5018       mpz_add(val, left_val, right_val);
5019       if (mpz_sizeinbase(val, 2) > 0x100000)
5020 	{
5021 	  go_error_at(location, "constant addition overflow");
5022           nc->set_invalid();
5023 	  mpz_set_ui(val, 1);
5024 	}
5025       break;
5026     case OPERATOR_MINUS:
5027       mpz_sub(val, left_val, right_val);
5028       if (mpz_sizeinbase(val, 2) > 0x100000)
5029 	{
5030 	  go_error_at(location, "constant subtraction overflow");
5031           nc->set_invalid();
5032 	  mpz_set_ui(val, 1);
5033 	}
5034       break;
5035     case OPERATOR_OR:
5036       mpz_ior(val, left_val, right_val);
5037       break;
5038     case OPERATOR_XOR:
5039       mpz_xor(val, left_val, right_val);
5040       break;
5041     case OPERATOR_MULT:
5042       mpz_mul(val, left_val, right_val);
5043       if (mpz_sizeinbase(val, 2) > 0x100000)
5044 	{
5045 	  go_error_at(location, "constant multiplication overflow");
5046           nc->set_invalid();
5047 	  mpz_set_ui(val, 1);
5048 	}
5049       break;
5050     case OPERATOR_DIV:
5051       if (mpz_sgn(right_val) != 0)
5052 	mpz_tdiv_q(val, left_val, right_val);
5053       else
5054 	{
5055 	  go_error_at(location, "division by zero");
5056           nc->set_invalid();
5057 	  mpz_set_ui(val, 0);
5058 	}
5059       break;
5060     case OPERATOR_MOD:
5061       if (mpz_sgn(right_val) != 0)
5062 	mpz_tdiv_r(val, left_val, right_val);
5063       else
5064 	{
5065 	  go_error_at(location, "division by zero");
5066           nc->set_invalid();
5067 	  mpz_set_ui(val, 0);
5068 	}
5069       break;
5070     case OPERATOR_LSHIFT:
5071       {
5072 	unsigned long shift = mpz_get_ui(right_val);
5073 	if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5074 	  mpz_mul_2exp(val, left_val, shift);
5075 	else
5076 	  {
5077 	    go_error_at(location, "shift count overflow");
5078             nc->set_invalid();
5079 	    mpz_set_ui(val, 1);
5080 	  }
5081 	break;
5082       }
5083       break;
5084     case OPERATOR_RSHIFT:
5085       {
5086 	unsigned long shift = mpz_get_ui(right_val);
5087 	if (mpz_cmp_ui(right_val, shift) != 0)
5088 	  {
5089 	    go_error_at(location, "shift count overflow");
5090             nc->set_invalid();
5091 	    mpz_set_ui(val, 1);
5092 	  }
5093 	else
5094 	  {
5095 	    if (mpz_cmp_ui(left_val, 0) >= 0)
5096 	      mpz_tdiv_q_2exp(val, left_val, shift);
5097 	    else
5098 	      mpz_fdiv_q_2exp(val, left_val, shift);
5099 	  }
5100 	break;
5101       }
5102       break;
5103     case OPERATOR_AND:
5104       mpz_and(val, left_val, right_val);
5105       break;
5106     case OPERATOR_BITCLEAR:
5107       {
5108 	mpz_t tval;
5109 	mpz_init(tval);
5110 	mpz_com(tval, right_val);
5111 	mpz_and(val, left_val, tval);
5112 	mpz_clear(tval);
5113       }
5114       break;
5115     default:
5116       go_unreachable();
5117     }
5118 
5119   mpz_clear(left_val);
5120   mpz_clear(right_val);
5121 
5122   if (left_nc->is_rune()
5123       || (op != OPERATOR_LSHIFT
5124 	  && op != OPERATOR_RSHIFT
5125 	  && right_nc->is_rune()))
5126     nc->set_rune(NULL, val);
5127   else
5128     nc->set_int(NULL, val);
5129 
5130   mpz_clear(val);
5131 
5132   return true;
5133 }
5134 
5135 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5136 // floating point operations.  Return true if this could be done,
5137 // false if not.
5138 
5139 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5140 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5141 			      const Numeric_constant* right_nc,
5142 			      Location location, Numeric_constant* nc)
5143 {
5144   mpfr_t left_val;
5145   if (!left_nc->to_float(&left_val))
5146     return false;
5147   mpfr_t right_val;
5148   if (!right_nc->to_float(&right_val))
5149     {
5150       mpfr_clear(left_val);
5151       return false;
5152     }
5153 
5154   mpfr_t val;
5155   mpfr_init(val);
5156 
5157   bool ret = true;
5158   switch (op)
5159     {
5160     case OPERATOR_PLUS:
5161       mpfr_add(val, left_val, right_val, GMP_RNDN);
5162       break;
5163     case OPERATOR_MINUS:
5164       mpfr_sub(val, left_val, right_val, GMP_RNDN);
5165       break;
5166     case OPERATOR_OR:
5167     case OPERATOR_XOR:
5168     case OPERATOR_AND:
5169     case OPERATOR_BITCLEAR:
5170     case OPERATOR_MOD:
5171     case OPERATOR_LSHIFT:
5172     case OPERATOR_RSHIFT:
5173       mpfr_set_ui(val, 0, GMP_RNDN);
5174       ret = false;
5175       break;
5176     case OPERATOR_MULT:
5177       mpfr_mul(val, left_val, right_val, GMP_RNDN);
5178       break;
5179     case OPERATOR_DIV:
5180       if (!mpfr_zero_p(right_val))
5181 	mpfr_div(val, left_val, right_val, GMP_RNDN);
5182       else
5183 	{
5184 	  go_error_at(location, "division by zero");
5185           nc->set_invalid();
5186 	  mpfr_set_ui(val, 0, GMP_RNDN);
5187 	}
5188       break;
5189     default:
5190       go_unreachable();
5191     }
5192 
5193   mpfr_clear(left_val);
5194   mpfr_clear(right_val);
5195 
5196   nc->set_float(NULL, val);
5197   mpfr_clear(val);
5198 
5199   return ret;
5200 }
5201 
5202 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5203 // complex operations.  Return true if this could be done, false if
5204 // not.
5205 
5206 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5207 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5208 				const Numeric_constant* right_nc,
5209 				Location location, Numeric_constant* nc)
5210 {
5211   mpc_t left_val;
5212   if (!left_nc->to_complex(&left_val))
5213     return false;
5214   mpc_t right_val;
5215   if (!right_nc->to_complex(&right_val))
5216     {
5217       mpc_clear(left_val);
5218       return false;
5219     }
5220 
5221   mpc_t val;
5222   mpc_init2(val, mpc_precision);
5223 
5224   bool ret = true;
5225   switch (op)
5226     {
5227     case OPERATOR_PLUS:
5228       mpc_add(val, left_val, right_val, MPC_RNDNN);
5229       break;
5230     case OPERATOR_MINUS:
5231       mpc_sub(val, left_val, right_val, MPC_RNDNN);
5232       break;
5233     case OPERATOR_OR:
5234     case OPERATOR_XOR:
5235     case OPERATOR_AND:
5236     case OPERATOR_BITCLEAR:
5237     case OPERATOR_MOD:
5238     case OPERATOR_LSHIFT:
5239     case OPERATOR_RSHIFT:
5240       mpc_set_ui(val, 0, MPC_RNDNN);
5241       ret = false;
5242       break;
5243     case OPERATOR_MULT:
5244       mpc_mul(val, left_val, right_val, MPC_RNDNN);
5245       break;
5246     case OPERATOR_DIV:
5247       if (mpc_cmp_si(right_val, 0) == 0)
5248 	{
5249 	  go_error_at(location, "division by zero");
5250           nc->set_invalid();
5251 	  mpc_set_ui(val, 0, MPC_RNDNN);
5252 	  break;
5253 	}
5254       mpc_div(val, left_val, right_val, MPC_RNDNN);
5255       break;
5256     default:
5257       go_unreachable();
5258     }
5259 
5260   mpc_clear(left_val);
5261   mpc_clear(right_val);
5262 
5263   nc->set_complex(NULL, val);
5264   mpc_clear(val);
5265 
5266   return ret;
5267 }
5268 
5269 // Lower a binary expression.  We have to evaluate constant
5270 // expressions now, in order to implement Go's unlimited precision
5271 // constants.
5272 
5273 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)5274 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5275 			    Statement_inserter* inserter, int)
5276 {
5277   Location location = this->location();
5278   Operator op = this->op_;
5279   Expression* left = this->left_;
5280   Expression* right = this->right_;
5281 
5282   const bool is_comparison = (op == OPERATOR_EQEQ
5283 			      || op == OPERATOR_NOTEQ
5284 			      || op == OPERATOR_LT
5285 			      || op == OPERATOR_LE
5286 			      || op == OPERATOR_GT
5287 			      || op == OPERATOR_GE);
5288 
5289   // Numeric constant expressions.
5290   {
5291     Numeric_constant left_nc;
5292     Numeric_constant right_nc;
5293     if (left->numeric_constant_value(&left_nc)
5294 	&& right->numeric_constant_value(&right_nc))
5295       {
5296 	if (is_comparison)
5297 	  {
5298 	    bool result;
5299 	    if (!Binary_expression::compare_constant(op, &left_nc,
5300 						     &right_nc, location,
5301 						     &result))
5302 	      return this;
5303 	    return Expression::make_cast(Type::make_boolean_type(),
5304 					 Expression::make_boolean(result,
5305 								  location),
5306 					 location);
5307 	  }
5308 	else
5309 	  {
5310 	    Numeric_constant nc;
5311 	    bool issued_error;
5312 	    if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5313 						  location, &nc,
5314 						  &issued_error))
5315 	      {
5316 		if (issued_error)
5317 		  return Expression::make_error(location);
5318                 return this;
5319 	      }
5320 	    return nc.expression(location);
5321 	  }
5322       }
5323   }
5324 
5325   // String constant expressions.
5326   if (left->type()->is_string_type() && right->type()->is_string_type())
5327     {
5328       std::string left_string;
5329       std::string right_string;
5330       if (left->string_constant_value(&left_string)
5331 	  && right->string_constant_value(&right_string))
5332 	{
5333 	  if (op == OPERATOR_PLUS)
5334 	    return Expression::make_string(left_string + right_string,
5335 					   location);
5336 	  else if (is_comparison)
5337 	    {
5338 	      int cmp = left_string.compare(right_string);
5339 	      bool r = Binary_expression::cmp_to_bool(op, cmp);
5340 	      return Expression::make_boolean(r, location);
5341 	    }
5342 	}
5343     }
5344 
5345   // Lower struct, array, and some interface comparisons.
5346   if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5347     {
5348       if (left->type()->struct_type() != NULL
5349 	  && right->type()->struct_type() != NULL)
5350 	return this->lower_struct_comparison(gogo, inserter);
5351       else if (left->type()->array_type() != NULL
5352 	       && !left->type()->is_slice_type()
5353 	       && right->type()->array_type() != NULL
5354 	       && !right->type()->is_slice_type())
5355 	return this->lower_array_comparison(gogo, inserter);
5356       else if ((left->type()->interface_type() != NULL
5357                 && right->type()->interface_type() == NULL)
5358                || (left->type()->interface_type() == NULL
5359                    && right->type()->interface_type() != NULL))
5360 	return this->lower_interface_value_comparison(gogo, inserter);
5361     }
5362 
5363   // Lower string concatenation to String_concat_expression, so that
5364   // we can group sequences of string additions.
5365   if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5366     {
5367       Expression_list* exprs;
5368       String_concat_expression* left_sce =
5369 	this->left_->string_concat_expression();
5370       if (left_sce != NULL)
5371 	exprs = left_sce->exprs();
5372       else
5373 	{
5374 	  exprs = new Expression_list();
5375 	  exprs->push_back(this->left_);
5376 	}
5377 
5378       String_concat_expression* right_sce =
5379 	this->right_->string_concat_expression();
5380       if (right_sce != NULL)
5381 	exprs->append(right_sce->exprs());
5382       else
5383 	exprs->push_back(this->right_);
5384 
5385       return Expression::make_string_concat(exprs);
5386     }
5387 
5388   return this;
5389 }
5390 
5391 // Lower a struct comparison.
5392 
5393 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)5394 Binary_expression::lower_struct_comparison(Gogo* gogo,
5395 					   Statement_inserter* inserter)
5396 {
5397   Struct_type* st = this->left_->type()->struct_type();
5398   Struct_type* st2 = this->right_->type()->struct_type();
5399   if (st2 == NULL)
5400     return this;
5401   if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5402     return this;
5403   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5404 					   this->right_->type(), NULL))
5405     return this;
5406 
5407   // See if we can compare using memcmp.  As a heuristic, we use
5408   // memcmp rather than field references and comparisons if there are
5409   // more than two fields.
5410   if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5411     return this->lower_compare_to_memcmp(gogo, inserter);
5412 
5413   Location loc = this->location();
5414 
5415   Expression* left = this->left_;
5416   Temporary_statement* left_temp = NULL;
5417   if (left->var_expression() == NULL
5418       && left->temporary_reference_expression() == NULL)
5419     {
5420       left_temp = Statement::make_temporary(left->type(), NULL, loc);
5421       inserter->insert(left_temp);
5422       left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5423     }
5424 
5425   Expression* right = this->right_;
5426   Temporary_statement* right_temp = NULL;
5427   if (right->var_expression() == NULL
5428       && right->temporary_reference_expression() == NULL)
5429     {
5430       right_temp = Statement::make_temporary(right->type(), NULL, loc);
5431       inserter->insert(right_temp);
5432       right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5433     }
5434 
5435   Expression* ret = Expression::make_boolean(true, loc);
5436   const Struct_field_list* fields = st->fields();
5437   unsigned int field_index = 0;
5438   for (Struct_field_list::const_iterator pf = fields->begin();
5439        pf != fields->end();
5440        ++pf, ++field_index)
5441     {
5442       if (Gogo::is_sink_name(pf->field_name()))
5443 	continue;
5444 
5445       if (field_index > 0)
5446 	{
5447 	  if (left_temp == NULL)
5448 	    left = left->copy();
5449 	  else
5450 	    left = Expression::make_temporary_reference(left_temp, loc);
5451 	  if (right_temp == NULL)
5452 	    right = right->copy();
5453 	  else
5454 	    right = Expression::make_temporary_reference(right_temp, loc);
5455 	}
5456       Expression* f1 = Expression::make_field_reference(left, field_index,
5457 							loc);
5458       Expression* f2 = Expression::make_field_reference(right, field_index,
5459 							loc);
5460       Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5461       ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5462     }
5463 
5464   if (this->op_ == OPERATOR_NOTEQ)
5465     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5466 
5467   return ret;
5468 }
5469 
5470 // Lower an array comparison.
5471 
5472 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)5473 Binary_expression::lower_array_comparison(Gogo* gogo,
5474 					  Statement_inserter* inserter)
5475 {
5476   Array_type* at = this->left_->type()->array_type();
5477   Array_type* at2 = this->right_->type()->array_type();
5478   if (at2 == NULL)
5479     return this;
5480   if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5481     return this;
5482   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5483 					   this->right_->type(), NULL))
5484     return this;
5485 
5486   // Call memcmp directly if possible.  This may let the middle-end
5487   // optimize the call.
5488   if (at->compare_is_identity(gogo))
5489     return this->lower_compare_to_memcmp(gogo, inserter);
5490 
5491   // Call the array comparison function.
5492   Named_object* hash_fn;
5493   Named_object* equal_fn;
5494   at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5495 		     &hash_fn, &equal_fn);
5496 
5497   Location loc = this->location();
5498 
5499   Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5500 
5501   Expression_list* args = new Expression_list();
5502   args->push_back(this->operand_address(inserter, this->left_));
5503   args->push_back(this->operand_address(inserter, this->right_));
5504 
5505   Expression* ret = Expression::make_call(func, args, false, loc);
5506 
5507   if (this->op_ == OPERATOR_NOTEQ)
5508     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5509 
5510   return ret;
5511 }
5512 
5513 // Lower an interface to value comparison.
5514 
5515 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)5516 Binary_expression::lower_interface_value_comparison(Gogo*,
5517                                                     Statement_inserter* inserter)
5518 {
5519   Type* left_type = this->left_->type();
5520   Type* right_type = this->right_->type();
5521   Interface_type* ift;
5522   if (left_type->interface_type() != NULL)
5523     {
5524       ift = left_type->interface_type();
5525       if (!ift->implements_interface(right_type, NULL))
5526         return this;
5527     }
5528   else
5529     {
5530       ift = right_type->interface_type();
5531       if (!ift->implements_interface(left_type, NULL))
5532         return this;
5533     }
5534   if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5535     return this;
5536 
5537   Location loc = this->location();
5538 
5539   if (left_type->interface_type() == NULL
5540       && left_type->points_to() == NULL
5541       && !this->left_->is_addressable())
5542     {
5543       Temporary_statement* temp =
5544           Statement::make_temporary(left_type, NULL, loc);
5545       inserter->insert(temp);
5546       this->left_ =
5547           Expression::make_set_and_use_temporary(temp, this->left_, loc);
5548     }
5549 
5550   if (right_type->interface_type() == NULL
5551       && right_type->points_to() == NULL
5552       && !this->right_->is_addressable())
5553     {
5554       Temporary_statement* temp =
5555           Statement::make_temporary(right_type, NULL, loc);
5556       inserter->insert(temp);
5557       this->right_ =
5558           Expression::make_set_and_use_temporary(temp, this->right_, loc);
5559     }
5560 
5561   return this;
5562 }
5563 
5564 // Lower a struct or array comparison to a call to memcmp.
5565 
5566 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)5567 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5568 {
5569   Location loc = this->location();
5570 
5571   Expression* a1 = this->operand_address(inserter, this->left_);
5572   Expression* a2 = this->operand_address(inserter, this->right_);
5573   Expression* len = Expression::make_type_info(this->left_->type(),
5574 					       TYPE_INFO_SIZE);
5575 
5576   Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5577   Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5578   return Expression::make_binary(this->op_, call, zero, loc);
5579 }
5580 
5581 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)5582 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5583                               Statement_inserter* inserter)
5584 {
5585   Location loc = this->location();
5586   if (this->left_->type()->is_error_type()
5587       || this->right_->type()->is_error_type()
5588       || this->left_->is_error_expression()
5589       || this->right_->is_error_expression())
5590     {
5591       go_assert(saw_errors());
5592       return Expression::make_error(loc);
5593     }
5594 
5595   Temporary_statement* temp;
5596 
5597   Type* left_type = this->left_->type();
5598   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5599                       || this->op_ == OPERATOR_RSHIFT);
5600   bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5601                       left_type->integer_type() != NULL)
5602                      || this->op_ == OPERATOR_MOD);
5603 
5604   if (is_shift_op
5605       || (is_idiv_op
5606 	  && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5607     {
5608       if (!this->left_->is_variable() && !this->left_->is_constant())
5609         {
5610           temp = Statement::make_temporary(NULL, this->left_, loc);
5611           inserter->insert(temp);
5612           this->left_ = Expression::make_temporary_reference(temp, loc);
5613         }
5614       if (!this->right_->is_variable() && !this->right_->is_constant())
5615         {
5616           temp =
5617               Statement::make_temporary(NULL, this->right_, loc);
5618           this->right_ = Expression::make_temporary_reference(temp, loc);
5619           inserter->insert(temp);
5620         }
5621     }
5622   return this;
5623 }
5624 
5625 
5626 // Return the address of EXPR, cast to unsafe.Pointer.
5627 
5628 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)5629 Binary_expression::operand_address(Statement_inserter* inserter,
5630 				   Expression* expr)
5631 {
5632   Location loc = this->location();
5633 
5634   if (!expr->is_addressable())
5635     {
5636       Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5637 							    loc);
5638       inserter->insert(temp);
5639       expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5640     }
5641   expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5642   static_cast<Unary_expression*>(expr)->set_does_not_escape();
5643   Type* void_type = Type::make_void_type();
5644   Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5645   return Expression::make_cast(unsafe_pointer_type, expr, loc);
5646 }
5647 
5648 // Return the numeric constant value, if it has one.
5649 
5650 bool
do_numeric_constant_value(Numeric_constant * nc) const5651 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5652 {
5653   Numeric_constant left_nc;
5654   if (!this->left_->numeric_constant_value(&left_nc))
5655     return false;
5656   Numeric_constant right_nc;
5657   if (!this->right_->numeric_constant_value(&right_nc))
5658     return false;
5659   bool issued_error;
5660   return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5661 					  this->location(), nc, &issued_error);
5662 }
5663 
5664 // Note that the value is being discarded.
5665 
5666 bool
do_discarding_value()5667 Binary_expression::do_discarding_value()
5668 {
5669   if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5670     return this->right_->discarding_value();
5671   else
5672     {
5673       this->unused_value_error();
5674       return false;
5675     }
5676 }
5677 
5678 // Get type.
5679 
5680 Type*
do_type()5681 Binary_expression::do_type()
5682 {
5683   if (this->classification() == EXPRESSION_ERROR)
5684     return Type::make_error_type();
5685 
5686   switch (this->op_)
5687     {
5688     case OPERATOR_EQEQ:
5689     case OPERATOR_NOTEQ:
5690     case OPERATOR_LT:
5691     case OPERATOR_LE:
5692     case OPERATOR_GT:
5693     case OPERATOR_GE:
5694       if (this->type_ == NULL)
5695 	this->type_ = Type::make_boolean_type();
5696       return this->type_;
5697 
5698     case OPERATOR_PLUS:
5699     case OPERATOR_MINUS:
5700     case OPERATOR_OR:
5701     case OPERATOR_XOR:
5702     case OPERATOR_MULT:
5703     case OPERATOR_DIV:
5704     case OPERATOR_MOD:
5705     case OPERATOR_AND:
5706     case OPERATOR_BITCLEAR:
5707     case OPERATOR_OROR:
5708     case OPERATOR_ANDAND:
5709       {
5710 	Type* type;
5711 	if (!Binary_expression::operation_type(this->op_,
5712 					       this->left_->type(),
5713 					       this->right_->type(),
5714 					       &type))
5715 	  return Type::make_error_type();
5716 	return type;
5717       }
5718 
5719     case OPERATOR_LSHIFT:
5720     case OPERATOR_RSHIFT:
5721       return this->left_->type();
5722 
5723     default:
5724       go_unreachable();
5725     }
5726 }
5727 
5728 // Set type for a binary expression.
5729 
5730 void
do_determine_type(const Type_context * context)5731 Binary_expression::do_determine_type(const Type_context* context)
5732 {
5733   Type* tleft = this->left_->type();
5734   Type* tright = this->right_->type();
5735 
5736   // Both sides should have the same type, except for the shift
5737   // operations.  For a comparison, we should ignore the incoming
5738   // type.
5739 
5740   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5741 		      || this->op_ == OPERATOR_RSHIFT);
5742 
5743   bool is_comparison = (this->op_ == OPERATOR_EQEQ
5744 			|| this->op_ == OPERATOR_NOTEQ
5745 			|| this->op_ == OPERATOR_LT
5746 			|| this->op_ == OPERATOR_LE
5747 			|| this->op_ == OPERATOR_GT
5748 			|| this->op_ == OPERATOR_GE);
5749 
5750   // For constant expressions, the context of the result is not useful in
5751   // determining the types of the operands.  It is only legal to use abstract
5752   // boolean, numeric, and string constants as operands where it is legal to
5753   // use non-abstract boolean, numeric, and string constants, respectively.
5754   // Any issues with the operation will be resolved in the check_types pass.
5755   bool is_constant_expr = (this->left_->is_constant()
5756                            && this->right_->is_constant());
5757 
5758   Type_context subcontext(*context);
5759 
5760   if (is_constant_expr && !is_shift_op)
5761     {
5762       subcontext.type = NULL;
5763       subcontext.may_be_abstract = true;
5764     }
5765   else if (is_comparison)
5766     {
5767       // In a comparison, the context does not determine the types of
5768       // the operands.
5769       subcontext.type = NULL;
5770     }
5771 
5772   // Set the context for the left hand operand.
5773   if (is_shift_op)
5774     {
5775       // The right hand operand of a shift plays no role in
5776       // determining the type of the left hand operand.
5777     }
5778   else if (!tleft->is_abstract())
5779     subcontext.type = tleft;
5780   else if (!tright->is_abstract())
5781     subcontext.type = tright;
5782   else if (subcontext.type == NULL)
5783     {
5784       if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5785 	  || (tleft->float_type() != NULL && tright->float_type() != NULL)
5786 	  || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5787 	{
5788 	  // Both sides have an abstract integer, abstract float, or
5789 	  // abstract complex type.  Just let CONTEXT determine
5790 	  // whether they may remain abstract or not.
5791 	}
5792       else if (tleft->complex_type() != NULL)
5793 	subcontext.type = tleft;
5794       else if (tright->complex_type() != NULL)
5795 	subcontext.type = tright;
5796       else if (tleft->float_type() != NULL)
5797 	subcontext.type = tleft;
5798       else if (tright->float_type() != NULL)
5799 	subcontext.type = tright;
5800       else
5801 	subcontext.type = tleft;
5802 
5803       if (subcontext.type != NULL && !context->may_be_abstract)
5804 	subcontext.type = subcontext.type->make_non_abstract_type();
5805     }
5806 
5807   this->left_->determine_type(&subcontext);
5808 
5809   if (is_shift_op)
5810     {
5811       // We may have inherited an unusable type for the shift operand.
5812       // Give a useful error if that happened.
5813       if (tleft->is_abstract()
5814 	  && subcontext.type != NULL
5815 	  && !subcontext.may_be_abstract
5816 	  && subcontext.type->interface_type() == NULL
5817 	  && subcontext.type->integer_type() == NULL)
5818 	this->report_error(("invalid context-determined non-integer type "
5819 			    "for left operand of shift"));
5820 
5821       // The context for the right hand operand is the same as for the
5822       // left hand operand, except for a shift operator.
5823       subcontext.type = Type::lookup_integer_type("uint");
5824       subcontext.may_be_abstract = false;
5825     }
5826 
5827   this->right_->determine_type(&subcontext);
5828 
5829   if (is_comparison)
5830     {
5831       if (this->type_ != NULL && !this->type_->is_abstract())
5832 	;
5833       else if (context->type != NULL && context->type->is_boolean_type())
5834 	this->type_ = context->type;
5835       else if (!context->may_be_abstract)
5836 	this->type_ = Type::lookup_bool_type();
5837     }
5838 }
5839 
5840 // Report an error if the binary operator OP does not support TYPE.
5841 // OTYPE is the type of the other operand.  Return whether the
5842 // operation is OK.  This should not be used for shift.
5843 
5844 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)5845 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5846 				       Location location)
5847 {
5848   switch (op)
5849     {
5850     case OPERATOR_OROR:
5851     case OPERATOR_ANDAND:
5852       if (!type->is_boolean_type()
5853           || !otype->is_boolean_type())
5854 	{
5855 	  go_error_at(location, "expected boolean type");
5856 	  return false;
5857 	}
5858       break;
5859 
5860     case OPERATOR_EQEQ:
5861     case OPERATOR_NOTEQ:
5862       {
5863 	std::string reason;
5864 	if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5865 	  {
5866 	    go_error_at(location, "%s", reason.c_str());
5867 	    return false;
5868 	  }
5869       }
5870       break;
5871 
5872     case OPERATOR_LT:
5873     case OPERATOR_LE:
5874     case OPERATOR_GT:
5875     case OPERATOR_GE:
5876       {
5877 	std::string reason;
5878 	if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5879 	  {
5880 	    go_error_at(location, "%s", reason.c_str());
5881 	    return false;
5882 	  }
5883       }
5884       break;
5885 
5886     case OPERATOR_PLUS:
5887     case OPERATOR_PLUSEQ:
5888       if ((!type->is_numeric_type() && !type->is_string_type())
5889           || (!otype->is_numeric_type() && !otype->is_string_type()))
5890 	{
5891 	  go_error_at(location,
5892 		   "expected integer, floating, complex, or string type");
5893 	  return false;
5894 	}
5895       break;
5896 
5897     case OPERATOR_MINUS:
5898     case OPERATOR_MINUSEQ:
5899     case OPERATOR_MULT:
5900     case OPERATOR_MULTEQ:
5901     case OPERATOR_DIV:
5902     case OPERATOR_DIVEQ:
5903       if (!type->is_numeric_type() || !otype->is_numeric_type())
5904 	{
5905 	  go_error_at(location, "expected integer, floating, or complex type");
5906 	  return false;
5907 	}
5908       break;
5909 
5910     case OPERATOR_MOD:
5911     case OPERATOR_MODEQ:
5912     case OPERATOR_OR:
5913     case OPERATOR_OREQ:
5914     case OPERATOR_AND:
5915     case OPERATOR_ANDEQ:
5916     case OPERATOR_XOR:
5917     case OPERATOR_XOREQ:
5918     case OPERATOR_BITCLEAR:
5919     case OPERATOR_BITCLEAREQ:
5920       if (type->integer_type() == NULL || otype->integer_type() == NULL)
5921 	{
5922 	  go_error_at(location, "expected integer type");
5923 	  return false;
5924 	}
5925       break;
5926 
5927     default:
5928       go_unreachable();
5929     }
5930 
5931   return true;
5932 }
5933 
5934 // Check types.
5935 
5936 void
do_check_types(Gogo *)5937 Binary_expression::do_check_types(Gogo*)
5938 {
5939   if (this->classification() == EXPRESSION_ERROR)
5940     return;
5941 
5942   Type* left_type = this->left_->type();
5943   Type* right_type = this->right_->type();
5944   if (left_type->is_error() || right_type->is_error())
5945     {
5946       this->set_is_error();
5947       return;
5948     }
5949 
5950   if (this->op_ == OPERATOR_EQEQ
5951       || this->op_ == OPERATOR_NOTEQ
5952       || this->op_ == OPERATOR_LT
5953       || this->op_ == OPERATOR_LE
5954       || this->op_ == OPERATOR_GT
5955       || this->op_ == OPERATOR_GE)
5956     {
5957       if (left_type->is_nil_type() && right_type->is_nil_type())
5958 	{
5959 	  this->report_error(_("invalid comparison of nil with nil"));
5960 	  return;
5961 	}
5962       if (!Type::are_assignable(left_type, right_type, NULL)
5963 	  && !Type::are_assignable(right_type, left_type, NULL))
5964 	{
5965 	  this->report_error(_("incompatible types in binary expression"));
5966 	  return;
5967 	}
5968       if (!Binary_expression::check_operator_type(this->op_, left_type,
5969 						  right_type,
5970 						  this->location())
5971 	  || !Binary_expression::check_operator_type(this->op_, right_type,
5972 						     left_type,
5973 						     this->location()))
5974 	{
5975 	  this->set_is_error();
5976 	  return;
5977 	}
5978     }
5979   else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5980     {
5981       if (!Type::are_compatible_for_binop(left_type, right_type))
5982 	{
5983 	  this->report_error(_("incompatible types in binary expression"));
5984 	  return;
5985 	}
5986       if (!Binary_expression::check_operator_type(this->op_, left_type,
5987 						  right_type,
5988 						  this->location()))
5989 	{
5990 	  this->set_is_error();
5991 	  return;
5992 	}
5993       if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5994 	{
5995 	  // Division by a zero integer constant is an error.
5996 	  Numeric_constant rconst;
5997 	  unsigned long rval;
5998 	  if (left_type->integer_type() != NULL
5999 	      && this->right_->numeric_constant_value(&rconst)
6000 	      && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6001 	      && rval == 0)
6002 	    {
6003 	      this->report_error(_("integer division by zero"));
6004 	      return;
6005 	    }
6006 	}
6007     }
6008   else
6009     {
6010       if (left_type->integer_type() == NULL)
6011 	this->report_error(_("shift of non-integer operand"));
6012 
6013       if (right_type->is_string_type())
6014         this->report_error(_("shift count not unsigned integer"));
6015       else if (!right_type->is_abstract()
6016 	  && (right_type->integer_type() == NULL
6017 	      || !right_type->integer_type()->is_unsigned()))
6018 	this->report_error(_("shift count not unsigned integer"));
6019       else
6020 	{
6021 	  Numeric_constant nc;
6022 	  if (this->right_->numeric_constant_value(&nc))
6023 	    {
6024 	      mpz_t val;
6025 	      if (!nc.to_int(&val))
6026 		this->report_error(_("shift count not unsigned integer"));
6027 	      else
6028 		{
6029 		  if (mpz_sgn(val) < 0)
6030 		    {
6031 		      this->report_error(_("negative shift count"));
6032 		      Location rloc = this->right_->location();
6033 		      this->right_ = Expression::make_integer_ul(0, right_type,
6034 								 rloc);
6035 		    }
6036 		  mpz_clear(val);
6037 		}
6038 	    }
6039 	}
6040     }
6041 }
6042 
6043 // Get the backend representation for a binary expression.
6044 
6045 Bexpression*
do_get_backend(Translate_context * context)6046 Binary_expression::do_get_backend(Translate_context* context)
6047 {
6048   Gogo* gogo = context->gogo();
6049   Location loc = this->location();
6050   Type* left_type = this->left_->type();
6051   Type* right_type = this->right_->type();
6052 
6053   bool use_left_type = true;
6054   bool is_shift_op = false;
6055   bool is_idiv_op = false;
6056   switch (this->op_)
6057     {
6058     case OPERATOR_EQEQ:
6059     case OPERATOR_NOTEQ:
6060     case OPERATOR_LT:
6061     case OPERATOR_LE:
6062     case OPERATOR_GT:
6063     case OPERATOR_GE:
6064       return Expression::comparison(context, this->type_, this->op_,
6065 				    this->left_, this->right_, loc);
6066 
6067     case OPERATOR_OROR:
6068     case OPERATOR_ANDAND:
6069       use_left_type = false;
6070       break;
6071     case OPERATOR_PLUS:
6072     case OPERATOR_MINUS:
6073     case OPERATOR_OR:
6074     case OPERATOR_XOR:
6075     case OPERATOR_MULT:
6076       break;
6077     case OPERATOR_DIV:
6078       if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6079         break;
6080       // Fall through.
6081     case OPERATOR_MOD:
6082       is_idiv_op = true;
6083       break;
6084     case OPERATOR_LSHIFT:
6085     case OPERATOR_RSHIFT:
6086       is_shift_op = true;
6087       break;
6088     case OPERATOR_BITCLEAR:
6089       this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6090     case OPERATOR_AND:
6091       break;
6092     default:
6093       go_unreachable();
6094     }
6095 
6096   // The only binary operation for string is +, and that should have
6097   // been converted to a String_concat_expression in do_lower.
6098   go_assert(!left_type->is_string_type());
6099 
6100   // For complex division Go might want slightly different results than the
6101   // backend implementation provides, so we have our own runtime routine.
6102   if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6103     {
6104       Runtime::Function complex_code;
6105       switch (this->left_->type()->complex_type()->bits())
6106 	{
6107 	case 64:
6108           complex_code = Runtime::COMPLEX64_DIV;
6109 	  break;
6110 	case 128:
6111           complex_code = Runtime::COMPLEX128_DIV;
6112 	  break;
6113 	default:
6114 	  go_unreachable();
6115 	}
6116       Expression* complex_div =
6117           Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6118       return complex_div->get_backend(context);
6119     }
6120 
6121   Bexpression* left = this->left_->get_backend(context);
6122   Bexpression* right = this->right_->get_backend(context);
6123 
6124   Type* type = use_left_type ? left_type : right_type;
6125   Btype* btype = type->get_backend(gogo);
6126 
6127   Bexpression* ret =
6128       gogo->backend()->binary_expression(this->op_, left, right, loc);
6129   ret = gogo->backend()->convert_expression(btype, ret, loc);
6130 
6131   // Initialize overflow constants.
6132   Bexpression* overflow;
6133   mpz_t zero;
6134   mpz_init_set_ui(zero, 0UL);
6135   mpz_t one;
6136   mpz_init_set_ui(one, 1UL);
6137   mpz_t neg_one;
6138   mpz_init_set_si(neg_one, -1);
6139 
6140   Btype* left_btype = left_type->get_backend(gogo);
6141   Btype* right_btype = right_type->get_backend(gogo);
6142 
6143   // In Go, a shift larger than the size of the type is well-defined.
6144   // This is not true in C, so we need to insert a conditional.
6145   if (is_shift_op)
6146     {
6147       go_assert(left_type->integer_type() != NULL);
6148 
6149       int bits = left_type->integer_type()->bits();
6150 
6151       Numeric_constant nc;
6152       unsigned long ul;
6153       if (!this->right_->numeric_constant_value(&nc)
6154 	  || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6155 	  || ul >= static_cast<unsigned long>(bits))
6156 	{
6157 	  mpz_t bitsval;
6158 	  mpz_init_set_ui(bitsval, bits);
6159 	  Bexpression* bits_expr =
6160 	    gogo->backend()->integer_constant_expression(right_btype, bitsval);
6161 	  Bexpression* compare =
6162 	    gogo->backend()->binary_expression(OPERATOR_LT,
6163 					       right, bits_expr, loc);
6164 
6165 	  Bexpression* zero_expr =
6166 	    gogo->backend()->integer_constant_expression(left_btype, zero);
6167 	  overflow = zero_expr;
6168 	  Bfunction* bfn = context->function()->func_value()->get_decl();
6169 	  if (this->op_ == OPERATOR_RSHIFT
6170 	      && !left_type->integer_type()->is_unsigned())
6171 	    {
6172 	      Bexpression* neg_expr =
6173 		gogo->backend()->binary_expression(OPERATOR_LT, left,
6174 						   zero_expr, loc);
6175 	      Bexpression* neg_one_expr =
6176 		gogo->backend()->integer_constant_expression(left_btype,
6177 							     neg_one);
6178 	      overflow = gogo->backend()->conditional_expression(bfn,
6179 								 btype,
6180 								 neg_expr,
6181 								 neg_one_expr,
6182 								 zero_expr,
6183 								 loc);
6184 	    }
6185 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6186 							ret, overflow, loc);
6187 	  mpz_clear(bitsval);
6188 	}
6189     }
6190 
6191   // Add checks for division by zero and division overflow as needed.
6192   if (is_idiv_op)
6193     {
6194       if (gogo->check_divide_by_zero())
6195 	{
6196 	  // right == 0
6197           Bexpression* zero_expr =
6198               gogo->backend()->integer_constant_expression(right_btype, zero);
6199           Bexpression* check =
6200               gogo->backend()->binary_expression(OPERATOR_EQEQ,
6201                                                  right, zero_expr, loc);
6202 
6203 	  // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6204 	  int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6205 	  Bexpression* crash = gogo->runtime_error(errcode,
6206 						   loc)->get_backend(context);
6207 
6208 	  // right == 0 ? (__go_runtime_error(...), 0) : ret
6209           Bfunction* bfn = context->function()->func_value()->get_decl();
6210           ret = gogo->backend()->conditional_expression(bfn, btype,
6211                                                         check, crash,
6212 							ret, loc);
6213 	}
6214 
6215       if (gogo->check_divide_overflow())
6216 	{
6217 	  // right == -1
6218 	  // FIXME: It would be nice to say that this test is expected
6219 	  // to return false.
6220 
6221           Bexpression* neg_one_expr =
6222               gogo->backend()->integer_constant_expression(right_btype, neg_one);
6223           Bexpression* check =
6224               gogo->backend()->binary_expression(OPERATOR_EQEQ,
6225                                                  right, neg_one_expr, loc);
6226 
6227           Bexpression* zero_expr =
6228               gogo->backend()->integer_constant_expression(btype, zero);
6229           Bexpression* one_expr =
6230               gogo->backend()->integer_constant_expression(btype, one);
6231           Bfunction* bfn = context->function()->func_value()->get_decl();
6232 
6233 	  if (type->integer_type()->is_unsigned())
6234 	    {
6235 	      // An unsigned -1 is the largest possible number, so
6236 	      // dividing is always 1 or 0.
6237 
6238               Bexpression* cmp =
6239                   gogo->backend()->binary_expression(OPERATOR_EQEQ,
6240                                                      left, right, loc);
6241 	      if (this->op_ == OPERATOR_DIV)
6242                 overflow =
6243                     gogo->backend()->conditional_expression(bfn, btype, cmp,
6244                                                             one_expr, zero_expr,
6245                                                             loc);
6246 	      else
6247                 overflow =
6248                     gogo->backend()->conditional_expression(bfn, btype, cmp,
6249                                                             zero_expr, left,
6250                                                             loc);
6251 	    }
6252 	  else
6253 	    {
6254 	      // Computing left / -1 is the same as computing - left,
6255 	      // which does not overflow since Go sets -fwrapv.
6256 	      if (this->op_ == OPERATOR_DIV)
6257                 {
6258                   Expression* negate_expr =
6259                       Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6260                   overflow = negate_expr->get_backend(context);
6261                 }
6262 	      else
6263                 overflow = zero_expr;
6264 	    }
6265           overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6266 
6267 	  // right == -1 ? - left : ret
6268           ret = gogo->backend()->conditional_expression(bfn, btype,
6269                                                         check, overflow,
6270                                                         ret, loc);
6271 	}
6272     }
6273 
6274   mpz_clear(zero);
6275   mpz_clear(one);
6276   mpz_clear(neg_one);
6277   return ret;
6278 }
6279 
6280 // Export a binary expression.
6281 
6282 void
do_export(Export * exp) const6283 Binary_expression::do_export(Export* exp) const
6284 {
6285   exp->write_c_string("(");
6286   this->left_->export_expression(exp);
6287   switch (this->op_)
6288     {
6289     case OPERATOR_OROR:
6290       exp->write_c_string(" || ");
6291       break;
6292     case OPERATOR_ANDAND:
6293       exp->write_c_string(" && ");
6294       break;
6295     case OPERATOR_EQEQ:
6296       exp->write_c_string(" == ");
6297       break;
6298     case OPERATOR_NOTEQ:
6299       exp->write_c_string(" != ");
6300       break;
6301     case OPERATOR_LT:
6302       exp->write_c_string(" < ");
6303       break;
6304     case OPERATOR_LE:
6305       exp->write_c_string(" <= ");
6306       break;
6307     case OPERATOR_GT:
6308       exp->write_c_string(" > ");
6309       break;
6310     case OPERATOR_GE:
6311       exp->write_c_string(" >= ");
6312       break;
6313     case OPERATOR_PLUS:
6314       exp->write_c_string(" + ");
6315       break;
6316     case OPERATOR_MINUS:
6317       exp->write_c_string(" - ");
6318       break;
6319     case OPERATOR_OR:
6320       exp->write_c_string(" | ");
6321       break;
6322     case OPERATOR_XOR:
6323       exp->write_c_string(" ^ ");
6324       break;
6325     case OPERATOR_MULT:
6326       exp->write_c_string(" * ");
6327       break;
6328     case OPERATOR_DIV:
6329       exp->write_c_string(" / ");
6330       break;
6331     case OPERATOR_MOD:
6332       exp->write_c_string(" % ");
6333       break;
6334     case OPERATOR_LSHIFT:
6335       exp->write_c_string(" << ");
6336       break;
6337     case OPERATOR_RSHIFT:
6338       exp->write_c_string(" >> ");
6339       break;
6340     case OPERATOR_AND:
6341       exp->write_c_string(" & ");
6342       break;
6343     case OPERATOR_BITCLEAR:
6344       exp->write_c_string(" &^ ");
6345       break;
6346     default:
6347       go_unreachable();
6348     }
6349   this->right_->export_expression(exp);
6350   exp->write_c_string(")");
6351 }
6352 
6353 // Import a binary expression.
6354 
6355 Expression*
do_import(Import * imp)6356 Binary_expression::do_import(Import* imp)
6357 {
6358   imp->require_c_string("(");
6359 
6360   Expression* left = Expression::import_expression(imp);
6361 
6362   Operator op;
6363   if (imp->match_c_string(" || "))
6364     {
6365       op = OPERATOR_OROR;
6366       imp->advance(4);
6367     }
6368   else if (imp->match_c_string(" && "))
6369     {
6370       op = OPERATOR_ANDAND;
6371       imp->advance(4);
6372     }
6373   else if (imp->match_c_string(" == "))
6374     {
6375       op = OPERATOR_EQEQ;
6376       imp->advance(4);
6377     }
6378   else if (imp->match_c_string(" != "))
6379     {
6380       op = OPERATOR_NOTEQ;
6381       imp->advance(4);
6382     }
6383   else if (imp->match_c_string(" < "))
6384     {
6385       op = OPERATOR_LT;
6386       imp->advance(3);
6387     }
6388   else if (imp->match_c_string(" <= "))
6389     {
6390       op = OPERATOR_LE;
6391       imp->advance(4);
6392     }
6393   else if (imp->match_c_string(" > "))
6394     {
6395       op = OPERATOR_GT;
6396       imp->advance(3);
6397     }
6398   else if (imp->match_c_string(" >= "))
6399     {
6400       op = OPERATOR_GE;
6401       imp->advance(4);
6402     }
6403   else if (imp->match_c_string(" + "))
6404     {
6405       op = OPERATOR_PLUS;
6406       imp->advance(3);
6407     }
6408   else if (imp->match_c_string(" - "))
6409     {
6410       op = OPERATOR_MINUS;
6411       imp->advance(3);
6412     }
6413   else if (imp->match_c_string(" | "))
6414     {
6415       op = OPERATOR_OR;
6416       imp->advance(3);
6417     }
6418   else if (imp->match_c_string(" ^ "))
6419     {
6420       op = OPERATOR_XOR;
6421       imp->advance(3);
6422     }
6423   else if (imp->match_c_string(" * "))
6424     {
6425       op = OPERATOR_MULT;
6426       imp->advance(3);
6427     }
6428   else if (imp->match_c_string(" / "))
6429     {
6430       op = OPERATOR_DIV;
6431       imp->advance(3);
6432     }
6433   else if (imp->match_c_string(" % "))
6434     {
6435       op = OPERATOR_MOD;
6436       imp->advance(3);
6437     }
6438   else if (imp->match_c_string(" << "))
6439     {
6440       op = OPERATOR_LSHIFT;
6441       imp->advance(4);
6442     }
6443   else if (imp->match_c_string(" >> "))
6444     {
6445       op = OPERATOR_RSHIFT;
6446       imp->advance(4);
6447     }
6448   else if (imp->match_c_string(" & "))
6449     {
6450       op = OPERATOR_AND;
6451       imp->advance(3);
6452     }
6453   else if (imp->match_c_string(" &^ "))
6454     {
6455       op = OPERATOR_BITCLEAR;
6456       imp->advance(4);
6457     }
6458   else
6459     {
6460       go_error_at(imp->location(), "unrecognized binary operator");
6461       return Expression::make_error(imp->location());
6462     }
6463 
6464   Expression* right = Expression::import_expression(imp);
6465 
6466   imp->require_c_string(")");
6467 
6468   return Expression::make_binary(op, left, right, imp->location());
6469 }
6470 
6471 // Dump ast representation of a binary expression.
6472 
6473 void
do_dump_expression(Ast_dump_context * ast_dump_context) const6474 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6475 {
6476   ast_dump_context->ostream() << "(";
6477   ast_dump_context->dump_expression(this->left_);
6478   ast_dump_context->ostream() << " ";
6479   ast_dump_context->dump_operator(this->op_);
6480   ast_dump_context->ostream() << " ";
6481   ast_dump_context->dump_expression(this->right_);
6482   ast_dump_context->ostream() << ") ";
6483 }
6484 
6485 // Make a binary expression.
6486 
6487 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)6488 Expression::make_binary(Operator op, Expression* left, Expression* right,
6489 			Location location)
6490 {
6491   return new Binary_expression(op, left, right, location);
6492 }
6493 
6494 // Implement a comparison.
6495 
6496 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)6497 Expression::comparison(Translate_context* context, Type* result_type,
6498 		       Operator op, Expression* left, Expression* right,
6499 		       Location location)
6500 {
6501   Type* left_type = left->type();
6502   Type* right_type = right->type();
6503 
6504   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6505 
6506   if (left_type->is_string_type() && right_type->is_string_type())
6507     {
6508       if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6509 	{
6510 	  left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6511 				    left, right);
6512 	  right = Expression::make_boolean(true, location);
6513 	}
6514       else
6515 	{
6516 	  left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6517 				    left, right);
6518 	  right = zexpr;
6519 	}
6520     }
6521   else if ((left_type->interface_type() != NULL
6522 	    && right_type->interface_type() == NULL
6523 	    && !right_type->is_nil_type())
6524 	   || (left_type->interface_type() == NULL
6525 	       && !left_type->is_nil_type()
6526 	       && right_type->interface_type() != NULL))
6527     {
6528       // Comparing an interface value to a non-interface value.
6529       if (left_type->interface_type() == NULL)
6530 	{
6531 	  std::swap(left_type, right_type);
6532 	  std::swap(left, right);
6533 	}
6534 
6535       // The right operand is not an interface.  We need to take its
6536       // address if it is not a pointer.
6537       Expression* pointer_arg = NULL;
6538       if (right_type->points_to() != NULL)
6539         pointer_arg = right;
6540       else
6541 	{
6542           go_assert(right->is_addressable());
6543           pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6544                                                location);
6545 	}
6546 
6547       Expression* descriptor =
6548           Expression::make_type_descriptor(right_type, location);
6549       left =
6550           Runtime::make_call((left_type->interface_type()->is_empty()
6551                               ? Runtime::EFACEVALEQ
6552                               : Runtime::IFACEVALEQ),
6553                              location, 3, left, descriptor,
6554                              pointer_arg);
6555       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6556       right = Expression::make_boolean(true, location);
6557     }
6558   else if (left_type->interface_type() != NULL
6559 	   && right_type->interface_type() != NULL)
6560     {
6561       Runtime::Function compare_function;
6562       if (left_type->interface_type()->is_empty()
6563 	  && right_type->interface_type()->is_empty())
6564 	compare_function = Runtime::EFACEEQ;
6565       else if (!left_type->interface_type()->is_empty()
6566 	       && !right_type->interface_type()->is_empty())
6567 	compare_function = Runtime::IFACEEQ;
6568       else
6569 	{
6570 	  if (left_type->interface_type()->is_empty())
6571 	    {
6572 	      std::swap(left_type, right_type);
6573 	      std::swap(left, right);
6574 	    }
6575 	  go_assert(!left_type->interface_type()->is_empty());
6576 	  go_assert(right_type->interface_type()->is_empty());
6577 	  compare_function = Runtime::IFACEEFACEEQ;
6578 	}
6579 
6580       left = Runtime::make_call(compare_function, location, 2, left, right);
6581       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6582       right = Expression::make_boolean(true, location);
6583     }
6584 
6585   if (left_type->is_nil_type()
6586       && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6587     {
6588       std::swap(left_type, right_type);
6589       std::swap(left, right);
6590     }
6591 
6592   if (right_type->is_nil_type())
6593     {
6594       right = Expression::make_nil(location);
6595       if (left_type->array_type() != NULL
6596 	  && left_type->array_type()->length() == NULL)
6597 	{
6598 	  Array_type* at = left_type->array_type();
6599           bool is_lvalue = false;
6600           left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6601 	}
6602       else if (left_type->interface_type() != NULL)
6603 	{
6604 	  // An interface is nil if the first field is nil.
6605           left = Expression::make_field_reference(left, 0, location);
6606 	}
6607     }
6608 
6609   Bexpression* left_bexpr = left->get_backend(context);
6610   Bexpression* right_bexpr = right->get_backend(context);
6611 
6612   Gogo* gogo = context->gogo();
6613   Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6614                                                         right_bexpr, location);
6615   if (result_type != NULL)
6616     ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6617                                               ret, location);
6618   return ret;
6619 }
6620 
6621 // Class String_concat_expression.
6622 
6623 bool
do_is_constant() const6624 String_concat_expression::do_is_constant() const
6625 {
6626   for (Expression_list::const_iterator pe = this->exprs_->begin();
6627        pe != this->exprs_->end();
6628        ++pe)
6629     {
6630       if (!(*pe)->is_constant())
6631 	return false;
6632     }
6633   return true;
6634 }
6635 
6636 bool
do_is_static_initializer() const6637 String_concat_expression::do_is_static_initializer() const
6638 {
6639   for (Expression_list::const_iterator pe = this->exprs_->begin();
6640        pe != this->exprs_->end();
6641        ++pe)
6642     {
6643       if (!(*pe)->is_static_initializer())
6644 	return false;
6645     }
6646   return true;
6647 }
6648 
6649 Type*
do_type()6650 String_concat_expression::do_type()
6651 {
6652   Type* t = this->exprs_->front()->type();
6653   Expression_list::iterator pe = this->exprs_->begin();
6654   ++pe;
6655   for (; pe != this->exprs_->end(); ++pe)
6656     {
6657       Type* t1;
6658       if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6659 					     (*pe)->type(),
6660 					     &t1))
6661 	return Type::make_error_type();
6662       t = t1;
6663     }
6664   return t;
6665 }
6666 
6667 void
do_determine_type(const Type_context * context)6668 String_concat_expression::do_determine_type(const Type_context* context)
6669 {
6670   Type_context subcontext(*context);
6671   for (Expression_list::iterator pe = this->exprs_->begin();
6672        pe != this->exprs_->end();
6673        ++pe)
6674     {
6675       Type* t = (*pe)->type();
6676       if (!t->is_abstract())
6677 	{
6678 	  subcontext.type = t;
6679 	  break;
6680 	}
6681     }
6682   if (subcontext.type == NULL)
6683     subcontext.type = this->exprs_->front()->type();
6684   for (Expression_list::iterator pe = this->exprs_->begin();
6685        pe != this->exprs_->end();
6686        ++pe)
6687     (*pe)->determine_type(&subcontext);
6688 }
6689 
6690 void
do_check_types(Gogo *)6691 String_concat_expression::do_check_types(Gogo*)
6692 {
6693   if (this->is_error_expression())
6694     return;
6695   Type* t = this->exprs_->front()->type();
6696   if (t->is_error())
6697     {
6698       this->set_is_error();
6699       return;
6700     }
6701   Expression_list::iterator pe = this->exprs_->begin();
6702   ++pe;
6703   for (; pe != this->exprs_->end(); ++pe)
6704     {
6705       Type* t1 = (*pe)->type();
6706       if (!Type::are_compatible_for_binop(t, t1))
6707 	{
6708 	  this->report_error("incompatible types in binary expression");
6709 	  return;
6710 	}
6711       if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6712 						  this->location()))
6713 	{
6714 	  this->set_is_error();
6715 	  return;
6716 	}
6717     }
6718 }
6719 
6720 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter *)6721 String_concat_expression::do_flatten(Gogo*, Named_object*,
6722 				     Statement_inserter*)
6723 {
6724   if (this->is_error_expression())
6725     return this;
6726   Location loc = this->location();
6727   Type* type = this->type();
6728   Expression* nil_arg = Expression::make_nil(loc);
6729   Expression* call;
6730   switch (this->exprs_->size())
6731     {
6732     case 0: case 1:
6733       go_unreachable();
6734 
6735     case 2: case 3: case 4: case 5:
6736       {
6737 	Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6738 						      NULL, loc);
6739 	Array_type* arg_type = Type::make_array_type(type, len);
6740 	arg_type->set_is_array_incomparable();
6741 	Expression* arg =
6742 	  Expression::make_array_composite_literal(arg_type, this->exprs_,
6743 						   loc);
6744 	Runtime::Function code;
6745 	switch (this->exprs_->size())
6746 	  {
6747 	  default:
6748 	    go_unreachable();
6749 	  case 2:
6750 	    code = Runtime::CONCATSTRING2;
6751 	    break;
6752 	  case 3:
6753 	    code = Runtime::CONCATSTRING3;
6754 	    break;
6755 	  case 4:
6756 	    code = Runtime::CONCATSTRING4;
6757 	    break;
6758 	  case 5:
6759 	    code = Runtime::CONCATSTRING5;
6760 	    break;
6761 	  }
6762 	call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6763       }
6764       break;
6765 
6766     default:
6767       {
6768 	Type* arg_type = Type::make_array_type(type, NULL);
6769 	Slice_construction_expression* sce =
6770 	  Expression::make_slice_composite_literal(arg_type, this->exprs_,
6771 						   loc);
6772 	sce->set_storage_does_not_escape();
6773 	call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6774 				  sce);
6775       }
6776       break;
6777     }
6778 
6779   return Expression::make_cast(type, call, loc);
6780 }
6781 
6782 void
do_dump_expression(Ast_dump_context * ast_dump_context) const6783 String_concat_expression::do_dump_expression(
6784     Ast_dump_context* ast_dump_context) const
6785 {
6786   ast_dump_context->ostream() << "concat(";
6787   ast_dump_context->dump_expression_list(this->exprs_, false);
6788   ast_dump_context->ostream() << ")";
6789 }
6790 
6791 Expression*
make_string_concat(Expression_list * exprs)6792 Expression::make_string_concat(Expression_list* exprs)
6793 {
6794   return new String_concat_expression(exprs);
6795 }
6796 
6797 // Class Bound_method_expression.
6798 
6799 // Traversal.
6800 
6801 int
do_traverse(Traverse * traverse)6802 Bound_method_expression::do_traverse(Traverse* traverse)
6803 {
6804   return Expression::traverse(&this->expr_, traverse);
6805 }
6806 
6807 // Return the type of a bound method expression.  The type of this
6808 // object is simply the type of the method with no receiver.
6809 
6810 Type*
do_type()6811 Bound_method_expression::do_type()
6812 {
6813   Named_object* fn = this->method_->named_object();
6814   Function_type* fntype;
6815   if (fn->is_function())
6816     fntype = fn->func_value()->type();
6817   else if (fn->is_function_declaration())
6818     fntype = fn->func_declaration_value()->type();
6819   else
6820     return Type::make_error_type();
6821   return fntype->copy_without_receiver();
6822 }
6823 
6824 // Determine the types of a method expression.
6825 
6826 void
do_determine_type(const Type_context *)6827 Bound_method_expression::do_determine_type(const Type_context*)
6828 {
6829   Named_object* fn = this->method_->named_object();
6830   Function_type* fntype;
6831   if (fn->is_function())
6832     fntype = fn->func_value()->type();
6833   else if (fn->is_function_declaration())
6834     fntype = fn->func_declaration_value()->type();
6835   else
6836     fntype = NULL;
6837   if (fntype == NULL || !fntype->is_method())
6838     this->expr_->determine_type_no_context();
6839   else
6840     {
6841       Type_context subcontext(fntype->receiver()->type(), false);
6842       this->expr_->determine_type(&subcontext);
6843     }
6844 }
6845 
6846 // Check the types of a method expression.
6847 
6848 void
do_check_types(Gogo *)6849 Bound_method_expression::do_check_types(Gogo*)
6850 {
6851   Named_object* fn = this->method_->named_object();
6852   if (!fn->is_function() && !fn->is_function_declaration())
6853     {
6854       this->report_error(_("object is not a method"));
6855       return;
6856     }
6857 
6858   Function_type* fntype;
6859   if (fn->is_function())
6860     fntype = fn->func_value()->type();
6861   else if (fn->is_function_declaration())
6862     fntype = fn->func_declaration_value()->type();
6863   else
6864     go_unreachable();
6865   Type* rtype = fntype->receiver()->type()->deref();
6866   Type* etype = (this->expr_type_ != NULL
6867 		 ? this->expr_type_
6868 		 : this->expr_->type());
6869   etype = etype->deref();
6870   if (!Type::are_identical(rtype, etype, true, NULL))
6871     this->report_error(_("method type does not match object type"));
6872 }
6873 
6874 // If a bound method expression is not simply called, then it is
6875 // represented as a closure.  The closure will hold a single variable,
6876 // the receiver to pass to the method.  The function will be a simple
6877 // thunk that pulls that value from the closure and calls the method
6878 // with the remaining arguments.
6879 //
6880 // Because method values are not common, we don't build all thunks for
6881 // every methods, but instead only build them as we need them.  In
6882 // particular, we even build them on demand for methods defined in
6883 // other packages.
6884 
6885 Bound_method_expression::Method_value_thunks
6886   Bound_method_expression::method_value_thunks;
6887 
6888 // Find or create the thunk for METHOD.
6889 
6890 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)6891 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6892 				      Named_object* fn)
6893 {
6894   std::pair<Named_object*, Named_object*> val(fn, NULL);
6895   std::pair<Method_value_thunks::iterator, bool> ins =
6896     Bound_method_expression::method_value_thunks.insert(val);
6897   if (!ins.second)
6898     {
6899       // We have seen this method before.
6900       go_assert(ins.first->second != NULL);
6901       return ins.first->second;
6902     }
6903 
6904   Location loc = fn->location();
6905 
6906   Function_type* orig_fntype;
6907   if (fn->is_function())
6908     orig_fntype = fn->func_value()->type();
6909   else if (fn->is_function_declaration())
6910     orig_fntype = fn->func_declaration_value()->type();
6911   else
6912     orig_fntype = NULL;
6913 
6914   if (orig_fntype == NULL || !orig_fntype->is_method())
6915     {
6916       ins.first->second =
6917 	Named_object::make_erroneous_name(gogo->thunk_name());
6918       return ins.first->second;
6919     }
6920 
6921   Struct_field_list* sfl = new Struct_field_list();
6922   // The type here is wrong--it should be the C function type.  But it
6923   // doesn't really matter.
6924   Type* vt = Type::make_pointer_type(Type::make_void_type());
6925   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
6926   sfl->push_back(Struct_field(Typed_identifier("val",
6927 					       orig_fntype->receiver()->type(),
6928 					       loc)));
6929   Struct_type* st = Type::make_struct_type(sfl, loc);
6930   st->set_is_struct_incomparable();
6931   Type* closure_type = Type::make_pointer_type(st);
6932 
6933   Function_type* new_fntype = orig_fntype->copy_with_names();
6934 
6935   std::string thunk_name = gogo->thunk_name();
6936   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6937 					      false, loc);
6938 
6939   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6940   cvar->set_is_used();
6941   cvar->set_is_closure();
6942   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6943 						 NULL, cvar);
6944   new_no->func_value()->set_closure_var(cp);
6945 
6946   gogo->start_block(loc);
6947 
6948   // Field 0 of the closure is the function code pointer, field 1 is
6949   // the value on which to invoke the method.
6950   Expression* arg = Expression::make_var_reference(cp, loc);
6951   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
6952   arg = Expression::make_field_reference(arg, 1, loc);
6953 
6954   Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6955 
6956   const Typed_identifier_list* orig_params = orig_fntype->parameters();
6957   Expression_list* args;
6958   if (orig_params == NULL || orig_params->empty())
6959     args = NULL;
6960   else
6961     {
6962       const Typed_identifier_list* new_params = new_fntype->parameters();
6963       args = new Expression_list();
6964       for (Typed_identifier_list::const_iterator p = new_params->begin();
6965 	   p != new_params->end();
6966 	   ++p)
6967 	{
6968 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
6969 	  go_assert(p_no != NULL
6970 		    && p_no->is_variable()
6971 		    && p_no->var_value()->is_parameter());
6972 	  args->push_back(Expression::make_var_reference(p_no, loc));
6973 	}
6974     }
6975 
6976   Call_expression* call = Expression::make_call(bme, args,
6977 						orig_fntype->is_varargs(),
6978 						loc);
6979   call->set_varargs_are_lowered();
6980 
6981   Statement* s = Statement::make_return_from_call(call, loc);
6982   gogo->add_statement(s);
6983   Block* b = gogo->finish_block(loc);
6984   gogo->add_block(b, loc);
6985   gogo->lower_block(new_no, b);
6986   gogo->flatten_block(new_no, b);
6987   gogo->finish_function(loc);
6988 
6989   ins.first->second = new_no;
6990   return new_no;
6991 }
6992 
6993 // Return an expression to check *REF for nil while dereferencing
6994 // according to FIELD_INDEXES.  Update *REF to build up the field
6995 // reference.  This is a static function so that we don't have to
6996 // worry about declaring Field_indexes in expressions.h.
6997 
6998 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)6999 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
7000 	      Expression** ref)
7001 {
7002   if (field_indexes == NULL)
7003     return Expression::make_boolean(false, loc);
7004   Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
7005   Struct_type* stype = (*ref)->type()->deref()->struct_type();
7006   go_assert(stype != NULL
7007 	    && field_indexes->field_index < stype->field_count());
7008   if ((*ref)->type()->struct_type() == NULL)
7009     {
7010       go_assert((*ref)->type()->points_to() != NULL);
7011       Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
7012 					      Expression::make_nil(loc),
7013 					      loc);
7014       cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
7015       *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
7016                                           loc);
7017       go_assert((*ref)->type()->struct_type() == stype);
7018     }
7019   *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
7020 					  loc);
7021   return cond;
7022 }
7023 
7024 // Flatten a method value into a struct with nil checks.  We can't do
7025 // this in the lowering phase, because if the method value is called
7026 // directly we don't need a thunk.  That case will have been handled
7027 // by Call_expression::do_lower, so if we get here then we do need a
7028 // thunk.
7029 
7030 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)7031 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
7032 				    Statement_inserter* inserter)
7033 {
7034   Location loc = this->location();
7035 
7036   Named_object* thunk = Bound_method_expression::create_thunk(gogo,
7037 							      this->method_,
7038 							      this->function_);
7039   if (thunk->is_erroneous())
7040     {
7041       go_assert(saw_errors());
7042       return Expression::make_error(loc);
7043     }
7044 
7045   // Force the expression into a variable.  This is only necessary if
7046   // we are going to do nil checks below, but it's easy enough to
7047   // always do it.
7048   Expression* expr = this->expr_;
7049   if (!expr->is_variable())
7050     {
7051       Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
7052       inserter->insert(etemp);
7053       expr = Expression::make_temporary_reference(etemp, loc);
7054     }
7055 
7056   // If the method expects a value, and we have a pointer, we need to
7057   // dereference the pointer.
7058 
7059   Named_object* fn = this->method_->named_object();
7060   Function_type *fntype;
7061   if (fn->is_function())
7062     fntype = fn->func_value()->type();
7063   else if (fn->is_function_declaration())
7064     fntype = fn->func_declaration_value()->type();
7065   else
7066     go_unreachable();
7067 
7068   Expression* val = expr;
7069   if (fntype->receiver()->type()->points_to() == NULL
7070       && val->type()->points_to() != NULL)
7071     val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
7072 
7073   // Note that we are ignoring this->expr_type_ here.  The thunk will
7074   // expect a closure whose second field has type this->expr_type_ (if
7075   // that is not NULL).  We are going to pass it a closure whose
7076   // second field has type this->expr_->type().  Since
7077   // this->expr_type_ is only not-NULL for pointer types, we can get
7078   // away with this.
7079 
7080   Struct_field_list* fields = new Struct_field_list();
7081   fields->push_back(Struct_field(Typed_identifier("fn",
7082 						  thunk->func_value()->type(),
7083 						  loc)));
7084   fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
7085   Struct_type* st = Type::make_struct_type(fields, loc);
7086   st->set_is_struct_incomparable();
7087 
7088   Expression_list* vals = new Expression_list();
7089   vals->push_back(Expression::make_func_code_reference(thunk, loc));
7090   vals->push_back(val);
7091 
7092   Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7093   ret = Expression::make_heap_expression(ret, loc);
7094 
7095   Node* n = Node::make_node(this);
7096   if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7097     ret->heap_expression()->set_allocate_on_stack();
7098   else if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
7099     go_error_at(loc, "%s escapes to heap, not allowed in runtime",
7100                 n->ast_format(gogo).c_str());
7101 
7102   // If necessary, check whether the expression or any embedded
7103   // pointers are nil.
7104 
7105   Expression* nil_check = NULL;
7106   if (this->method_->field_indexes() != NULL)
7107     {
7108       Expression* ref = expr;
7109       nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7110       expr = ref;
7111     }
7112 
7113   if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7114     {
7115       Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7116 					      Expression::make_nil(loc),
7117 					      loc);
7118       if (nil_check == NULL)
7119 	nil_check = n;
7120       else
7121 	nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7122     }
7123 
7124   if (nil_check != NULL)
7125     {
7126       Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7127 					      loc);
7128       // Fix the type of the conditional expression by pretending to
7129       // evaluate to RET either way through the conditional.
7130       crash = Expression::make_compound(crash, ret, loc);
7131       ret = Expression::make_conditional(nil_check, crash, ret, loc);
7132     }
7133 
7134   // RET is a pointer to a struct, but we want a function type.
7135   ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7136 
7137   return ret;
7138 }
7139 
7140 // Dump ast representation of a bound method expression.
7141 
7142 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7143 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7144     const
7145 {
7146   if (this->expr_type_ != NULL)
7147     ast_dump_context->ostream() << "(";
7148   ast_dump_context->dump_expression(this->expr_);
7149   if (this->expr_type_ != NULL)
7150     {
7151       ast_dump_context->ostream() << ":";
7152       ast_dump_context->dump_type(this->expr_type_);
7153       ast_dump_context->ostream() << ")";
7154     }
7155 
7156   ast_dump_context->ostream() << "." << this->function_->name();
7157 }
7158 
7159 // Make a method expression.
7160 
7161 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)7162 Expression::make_bound_method(Expression* expr, const Method* method,
7163 			      Named_object* function, Location location)
7164 {
7165   return new Bound_method_expression(expr, method, function, location);
7166 }
7167 
7168 // Class Builtin_call_expression.  This is used for a call to a
7169 // builtin function.
7170 
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)7171 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7172 						 Expression* fn,
7173 						 Expression_list* args,
7174 						 bool is_varargs,
7175 						 Location location)
7176   : Call_expression(fn, args, is_varargs, location),
7177     gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7178     recover_arg_is_set_(false)
7179 {
7180   Func_expression* fnexp = this->fn()->func_expression();
7181   if (fnexp == NULL)
7182     {
7183       this->code_ = BUILTIN_INVALID;
7184       return;
7185     }
7186   const std::string& name(fnexp->named_object()->name());
7187   if (name == "append")
7188     this->code_ = BUILTIN_APPEND;
7189   else if (name == "cap")
7190     this->code_ = BUILTIN_CAP;
7191   else if (name == "close")
7192     this->code_ = BUILTIN_CLOSE;
7193   else if (name == "complex")
7194     this->code_ = BUILTIN_COMPLEX;
7195   else if (name == "copy")
7196     this->code_ = BUILTIN_COPY;
7197   else if (name == "delete")
7198     this->code_ = BUILTIN_DELETE;
7199   else if (name == "imag")
7200     this->code_ = BUILTIN_IMAG;
7201   else if (name == "len")
7202     this->code_ = BUILTIN_LEN;
7203   else if (name == "make")
7204     this->code_ = BUILTIN_MAKE;
7205   else if (name == "new")
7206     this->code_ = BUILTIN_NEW;
7207   else if (name == "panic")
7208     this->code_ = BUILTIN_PANIC;
7209   else if (name == "print")
7210     this->code_ = BUILTIN_PRINT;
7211   else if (name == "println")
7212     this->code_ = BUILTIN_PRINTLN;
7213   else if (name == "real")
7214     this->code_ = BUILTIN_REAL;
7215   else if (name == "recover")
7216     this->code_ = BUILTIN_RECOVER;
7217   else if (name == "Alignof")
7218     this->code_ = BUILTIN_ALIGNOF;
7219   else if (name == "Offsetof")
7220     this->code_ = BUILTIN_OFFSETOF;
7221   else if (name == "Sizeof")
7222     this->code_ = BUILTIN_SIZEOF;
7223   else
7224     go_unreachable();
7225 }
7226 
7227 // Return whether this is a call to recover.  This is a virtual
7228 // function called from the parent class.
7229 
7230 bool
do_is_recover_call() const7231 Builtin_call_expression::do_is_recover_call() const
7232 {
7233   if (this->classification() == EXPRESSION_ERROR)
7234     return false;
7235   return this->code_ == BUILTIN_RECOVER;
7236 }
7237 
7238 // Set the argument for a call to recover.
7239 
7240 void
do_set_recover_arg(Expression * arg)7241 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7242 {
7243   const Expression_list* args = this->args();
7244   go_assert(args == NULL || args->empty());
7245   Expression_list* new_args = new Expression_list();
7246   new_args->push_back(arg);
7247   this->set_args(new_args);
7248   this->recover_arg_is_set_ = true;
7249 }
7250 
7251 // Lower a builtin call expression.  This turns new and make into
7252 // specific expressions.  We also convert to a constant if we can.
7253 
7254 Expression*
do_lower(Gogo *,Named_object * function,Statement_inserter * inserter,int)7255 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7256 				  Statement_inserter* inserter, int)
7257 {
7258   if (this->is_error_expression())
7259     return this;
7260 
7261   Location loc = this->location();
7262 
7263   if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7264     {
7265       this->report_error(_("invalid use of %<...%> with builtin function"));
7266       return Expression::make_error(loc);
7267     }
7268 
7269   if (this->code_ == BUILTIN_OFFSETOF)
7270     {
7271       Expression* arg = this->one_arg();
7272 
7273       if (arg->bound_method_expression() != NULL
7274 	  || arg->interface_field_reference_expression() != NULL)
7275 	{
7276 	  this->report_error(_("invalid use of method value as argument "
7277 			       "of Offsetof"));
7278 	  return this;
7279 	}
7280 
7281       Field_reference_expression* farg = arg->field_reference_expression();
7282       while (farg != NULL)
7283 	{
7284 	  if (!farg->implicit())
7285 	    break;
7286 	  // When the selector refers to an embedded field,
7287 	  // it must not be reached through pointer indirections.
7288 	  if (farg->expr()->deref() != farg->expr())
7289 	    {
7290 	      this->report_error(_("argument of Offsetof implies "
7291 				   "indirection of an embedded field"));
7292 	      return this;
7293 	    }
7294 	  // Go up until we reach the original base.
7295 	  farg = farg->expr()->field_reference_expression();
7296 	}
7297     }
7298 
7299   if (this->is_constant())
7300     {
7301       Numeric_constant nc;
7302       if (this->numeric_constant_value(&nc))
7303 	return nc.expression(loc);
7304     }
7305 
7306   switch (this->code_)
7307     {
7308     default:
7309       break;
7310 
7311     case BUILTIN_NEW:
7312       {
7313 	const Expression_list* args = this->args();
7314 	if (args == NULL || args->size() < 1)
7315 	  this->report_error(_("not enough arguments"));
7316 	else if (args->size() > 1)
7317 	  this->report_error(_("too many arguments"));
7318 	else
7319 	  {
7320 	    Expression* arg = args->front();
7321 	    if (!arg->is_type_expression())
7322 	      {
7323 		go_error_at(arg->location(), "expected type");
7324 		this->set_is_error();
7325 	      }
7326 	    else
7327 	      return Expression::make_allocation(arg->type(), loc);
7328 	  }
7329       }
7330       break;
7331 
7332     case BUILTIN_MAKE:
7333       return this->lower_make(inserter);
7334 
7335     case BUILTIN_RECOVER:
7336       if (function != NULL)
7337 	function->func_value()->set_calls_recover();
7338       else
7339 	{
7340 	  // Calling recover outside of a function always returns the
7341 	  // nil empty interface.
7342 	  Type* eface = Type::make_empty_interface_type(loc);
7343 	  return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7344 	}
7345       break;
7346 
7347     case BUILTIN_DELETE:
7348       {
7349 	// Lower to a runtime function call.
7350 	const Expression_list* args = this->args();
7351 	if (args == NULL || args->size() < 2)
7352 	  this->report_error(_("not enough arguments"));
7353 	else if (args->size() > 2)
7354 	  this->report_error(_("too many arguments"));
7355 	else if (args->front()->type()->map_type() == NULL)
7356 	  this->report_error(_("argument 1 must be a map"));
7357 	else
7358 	  {
7359 	    // Since this function returns no value it must appear in
7360 	    // a statement by itself, so we don't have to worry about
7361 	    // order of evaluation of values around it.  Evaluate the
7362 	    // map first to get order of evaluation right.
7363 	    Map_type* mt = args->front()->type()->map_type();
7364 	    Temporary_statement* map_temp =
7365 	      Statement::make_temporary(mt, args->front(), loc);
7366 	    inserter->insert(map_temp);
7367 
7368 	    Temporary_statement* key_temp =
7369 	      Statement::make_temporary(mt->key_type(), args->back(), loc);
7370 	    inserter->insert(key_temp);
7371 
7372 	    Expression* e1 = Expression::make_type_descriptor(mt, loc);
7373 	    Expression* e2 = Expression::make_temporary_reference(map_temp,
7374 								  loc);
7375 	    Expression* e3 = Expression::make_temporary_reference(key_temp,
7376 								  loc);
7377 	    e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7378 	    return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7379 				      3, e1, e2, e3);
7380 	  }
7381       }
7382       break;
7383 
7384     case BUILTIN_PRINT:
7385     case BUILTIN_PRINTLN:
7386       // Force all the arguments into temporary variables, so that we
7387       // don't try to evaluate something while holding the print lock.
7388       if (this->args() == NULL)
7389 	break;
7390       for (Expression_list::iterator pa = this->args()->begin();
7391 	   pa != this->args()->end();
7392 	   ++pa)
7393 	{
7394 	  if (!(*pa)->is_variable() && !(*pa)->is_constant())
7395 	    {
7396 	      Temporary_statement* temp =
7397 		Statement::make_temporary(NULL, *pa, loc);
7398 	      inserter->insert(temp);
7399 	      *pa = Expression::make_temporary_reference(temp, loc);
7400 	    }
7401 	}
7402       break;
7403     }
7404 
7405   return this;
7406 }
7407 
7408 // Flatten a builtin call expression.  This turns the arguments of copy and
7409 // append into temporary expressions.
7410 
7411 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7412 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7413                                     Statement_inserter* inserter)
7414 {
7415   Location loc = this->location();
7416 
7417   switch (this->code_)
7418     {
7419     default:
7420       break;
7421 
7422     case BUILTIN_APPEND:
7423       return this->flatten_append(gogo, function, inserter);
7424 
7425     case BUILTIN_COPY:
7426       {
7427 	Type* at = this->args()->front()->type();
7428 	for (Expression_list::iterator pa = this->args()->begin();
7429 	     pa != this->args()->end();
7430 	     ++pa)
7431 	  {
7432 	    if ((*pa)->is_nil_expression())
7433 	      {
7434 		Expression* nil = Expression::make_nil(loc);
7435 		Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7436 		*pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7437 	      }
7438 	    if (!(*pa)->is_variable())
7439 	      {
7440 		Temporary_statement* temp =
7441                   Statement::make_temporary(NULL, *pa, loc);
7442 		inserter->insert(temp);
7443 		*pa = Expression::make_temporary_reference(temp, loc);
7444 	      }
7445 	  }
7446       }
7447       break;
7448 
7449     case BUILTIN_PANIC:
7450       for (Expression_list::iterator pa = this->args()->begin();
7451 	   pa != this->args()->end();
7452 	   ++pa)
7453 	{
7454 	  if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7455 	    {
7456 	      Temporary_statement* temp =
7457 		Statement::make_temporary(NULL, *pa, loc);
7458 	      inserter->insert(temp);
7459 	      *pa = Expression::make_temporary_reference(temp, loc);
7460 	    }
7461 	}
7462       break;
7463 
7464     case BUILTIN_LEN:
7465     case BUILTIN_CAP:
7466       {
7467 	Expression_list::iterator pa = this->args()->begin();
7468 	if (!(*pa)->is_variable()
7469 	    && ((*pa)->type()->map_type() != NULL
7470 		|| (*pa)->type()->channel_type() != NULL))
7471 	  {
7472 	    Temporary_statement* temp =
7473 	      Statement::make_temporary(NULL, *pa, loc);
7474 	    inserter->insert(temp);
7475 	    *pa = Expression::make_temporary_reference(temp, loc);
7476 	  }
7477       }
7478       break;
7479     }
7480 
7481   return this;
7482 }
7483 
7484 // Lower a make expression.
7485 
7486 Expression*
lower_make(Statement_inserter * inserter)7487 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7488 {
7489   Location loc = this->location();
7490 
7491   const Expression_list* args = this->args();
7492   if (args == NULL || args->size() < 1)
7493     {
7494       this->report_error(_("not enough arguments"));
7495       return Expression::make_error(this->location());
7496     }
7497 
7498   Expression_list::const_iterator parg = args->begin();
7499 
7500   Expression* first_arg = *parg;
7501   if (!first_arg->is_type_expression())
7502     {
7503       go_error_at(first_arg->location(), "expected type");
7504       this->set_is_error();
7505       return Expression::make_error(this->location());
7506     }
7507   Type* type = first_arg->type();
7508 
7509   if (!type->in_heap())
7510     go_error_at(first_arg->location(),
7511 		"can't make slice of go:notinheap type");
7512 
7513   bool is_slice = false;
7514   bool is_map = false;
7515   bool is_chan = false;
7516   if (type->is_slice_type())
7517     is_slice = true;
7518   else if (type->map_type() != NULL)
7519     is_map = true;
7520   else if (type->channel_type() != NULL)
7521     is_chan = true;
7522   else
7523     {
7524       this->report_error(_("invalid type for make function"));
7525       return Expression::make_error(this->location());
7526     }
7527 
7528   Type_context int_context(Type::lookup_integer_type("int"), false);
7529 
7530   ++parg;
7531   Expression* len_arg;
7532   bool len_small = false;
7533   if (parg == args->end())
7534     {
7535       if (is_slice)
7536 	{
7537 	  this->report_error(_("length required when allocating a slice"));
7538 	  return Expression::make_error(this->location());
7539 	}
7540       len_arg = Expression::make_integer_ul(0, NULL, loc);
7541       len_small = true;
7542     }
7543   else
7544     {
7545       len_arg = *parg;
7546       len_arg->determine_type(&int_context);
7547       if (len_arg->type()->integer_type() == NULL)
7548 	{
7549 	  go_error_at(len_arg->location(), "non-integer len argument in make");
7550 	  return Expression::make_error(this->location());
7551 	}
7552       if (!this->check_int_value(len_arg, true, &len_small))
7553 	return Expression::make_error(this->location());
7554       ++parg;
7555     }
7556 
7557   Expression* cap_arg = NULL;
7558   bool cap_small = false;
7559   Numeric_constant nclen;
7560   Numeric_constant nccap;
7561   unsigned long vlen;
7562   unsigned long vcap;
7563   if (is_slice && parg != args->end())
7564     {
7565       cap_arg = *parg;
7566       cap_arg->determine_type(&int_context);
7567       if (cap_arg->type()->integer_type() == NULL)
7568 	{
7569 	  go_error_at(cap_arg->location(), "non-integer cap argument in make");
7570 	  return Expression::make_error(this->location());
7571 	}
7572       if (!this->check_int_value(cap_arg, false, &cap_small))
7573 	return Expression::make_error(this->location());
7574 
7575       if (len_arg->numeric_constant_value(&nclen)
7576 	  && cap_arg->numeric_constant_value(&nccap)
7577 	  && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7578 	  && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7579 	  && vlen > vcap)
7580 	{
7581 	  this->report_error(_("len larger than cap"));
7582 	  return Expression::make_error(this->location());
7583 	}
7584 
7585       ++parg;
7586     }
7587 
7588   if (parg != args->end())
7589     {
7590       this->report_error(_("too many arguments to make"));
7591       return Expression::make_error(this->location());
7592     }
7593 
7594   Location type_loc = first_arg->location();
7595 
7596   Expression* call;
7597   if (is_slice)
7598     {
7599       if (cap_arg == NULL)
7600 	{
7601           cap_small = len_small;
7602           if (len_arg->numeric_constant_value(&nclen)
7603               && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID)
7604             cap_arg = Expression::make_integer_ul(vlen, len_arg->type(), loc);
7605           else
7606             {
7607               Temporary_statement* temp = Statement::make_temporary(NULL,
7608                                                                     len_arg,
7609                                                                     loc);
7610               inserter->insert(temp);
7611               len_arg = Expression::make_temporary_reference(temp, loc);
7612               cap_arg = Expression::make_temporary_reference(temp, loc);
7613             }
7614 	}
7615 
7616       Type* et = type->array_type()->element_type();
7617       Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7618       Runtime::Function code = Runtime::MAKESLICE;
7619       if (!len_small || !cap_small)
7620 	code = Runtime::MAKESLICE64;
7621       call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
7622     }
7623   else if (is_map)
7624     {
7625       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7626       if (!len_small)
7627 	call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
7628 				  len_arg,
7629 				  Expression::make_nil(loc));
7630       else
7631 	{
7632 	  Numeric_constant nclen;
7633 	  unsigned long vlen;
7634 	  if (len_arg->numeric_constant_value(&nclen)
7635 	      && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7636 	      && vlen <= Map_type::bucket_size)
7637 	    call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
7638 	  else
7639 	    call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
7640 				      len_arg,
7641 				      Expression::make_nil(loc));
7642 	}
7643     }
7644   else if (is_chan)
7645     {
7646       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7647       Runtime::Function code = Runtime::MAKECHAN;
7648       if (!len_small)
7649 	code = Runtime::MAKECHAN64;
7650       call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
7651     }
7652   else
7653     go_unreachable();
7654 
7655   return Expression::make_unsafe_cast(type, call, loc);
7656 }
7657 
7658 // Flatten a call to the predeclared append function.  We do this in
7659 // the flatten phase, not the lowering phase, so that we run after
7660 // type checking and after order_evaluations.
7661 
7662 Expression*
flatten_append(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7663 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7664 					Statement_inserter* inserter)
7665 {
7666   if (this->is_error_expression())
7667     return this;
7668 
7669   Location loc = this->location();
7670 
7671   const Expression_list* args = this->args();
7672   go_assert(args != NULL && !args->empty());
7673 
7674   Type* slice_type = args->front()->type();
7675   go_assert(slice_type->is_slice_type());
7676   Type* element_type = slice_type->array_type()->element_type();
7677 
7678   if (args->size() == 1)
7679     {
7680       // append(s) evaluates to s.
7681       return args->front();
7682     }
7683 
7684   Type* int_type = Type::lookup_integer_type("int");
7685   Type* uint_type = Type::lookup_integer_type("uint");
7686 
7687   // Implementing
7688   //   append(s1, s2...)
7689   // or
7690   //   append(s1, a1, a2, a3, ...)
7691 
7692   // s1tmp := s1
7693   Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7694 							 loc);
7695   inserter->insert(s1tmp);
7696 
7697   // l1tmp := len(s1tmp)
7698   Named_object* lenfn = gogo->lookup_global("len");
7699   Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7700   Expression_list* call_args = new Expression_list();
7701   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7702   Expression* len = Expression::make_call(lenref, call_args, false, loc);
7703   gogo->lower_expression(function, inserter, &len);
7704   gogo->flatten_expression(function, inserter, &len);
7705   Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7706   inserter->insert(l1tmp);
7707 
7708   Temporary_statement* s2tmp = NULL;
7709   Temporary_statement* l2tmp = NULL;
7710   Expression_list* add = NULL;
7711   Expression* len2;
7712   if (this->is_varargs())
7713     {
7714       go_assert(args->size() == 2);
7715 
7716       // s2tmp := s2
7717       s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7718       inserter->insert(s2tmp);
7719 
7720       // l2tmp := len(s2tmp)
7721       lenref = Expression::make_func_reference(lenfn, NULL, loc);
7722       call_args = new Expression_list();
7723       call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7724       len = Expression::make_call(lenref, call_args, false, loc);
7725       gogo->lower_expression(function, inserter, &len);
7726       gogo->flatten_expression(function, inserter, &len);
7727       l2tmp = Statement::make_temporary(int_type, len, loc);
7728       inserter->insert(l2tmp);
7729 
7730       // len2 = l2tmp
7731       len2 = Expression::make_temporary_reference(l2tmp, loc);
7732     }
7733   else
7734     {
7735       // We have to ensure that all the arguments are in variables
7736       // now, because otherwise if one of them is an index expression
7737       // into the current slice we could overwrite it before we fetch
7738       // it.
7739       add = new Expression_list();
7740       Expression_list::const_iterator pa = args->begin();
7741       for (++pa; pa != args->end(); ++pa)
7742 	{
7743 	  if ((*pa)->is_variable())
7744 	    add->push_back(*pa);
7745 	  else
7746 	    {
7747 	      Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7748 								   loc);
7749 	      inserter->insert(tmp);
7750 	      add->push_back(Expression::make_temporary_reference(tmp, loc));
7751 	    }
7752 	}
7753 
7754       // len2 = len(add)
7755       len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7756     }
7757 
7758   // ntmp := l1tmp + len2
7759   Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7760   Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7761   gogo->lower_expression(function, inserter, &sum);
7762   gogo->flatten_expression(function, inserter, &sum);
7763   Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7764   inserter->insert(ntmp);
7765 
7766   // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7767   //   growslice(type, s1tmp, ntmp) :
7768   //   s1tmp[:ntmp]
7769   // Using uint here means that if the computation of ntmp overflowed,
7770   // we will call growslice which will panic.
7771 
7772   Expression* left = Expression::make_temporary_reference(ntmp, loc);
7773   left = Expression::make_cast(uint_type, left, loc);
7774 
7775   Named_object* capfn = gogo->lookup_global("cap");
7776   Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7777   call_args = new Expression_list();
7778   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7779   Expression* right = Expression::make_call(capref, call_args, false, loc);
7780   right = Expression::make_cast(uint_type, right, loc);
7781 
7782   Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7783 
7784   Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7785   Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7786   Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7787   Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7788 					a1, a2, a3);
7789   call = Expression::make_unsafe_cast(slice_type, call, loc);
7790 
7791   ref = Expression::make_temporary_reference(s1tmp, loc);
7792   Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7793   Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7794   // FIXME: Mark this index as not requiring bounds checks.
7795   ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7796 
7797   Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7798 
7799   gogo->lower_expression(function, inserter, &rhs);
7800   gogo->flatten_expression(function, inserter, &rhs);
7801 
7802   Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7803   Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7804   inserter->insert(assign);
7805 
7806   if (this->is_varargs())
7807     {
7808       // copy(s1tmp[l1tmp:], s2tmp)
7809       a1 = Expression::make_temporary_reference(s1tmp, loc);
7810       ref = Expression::make_temporary_reference(l1tmp, loc);
7811       Expression* nil = Expression::make_nil(loc);
7812       // FIXME: Mark this index as not requiring bounds checks.
7813       a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7814 
7815       a2 = Expression::make_temporary_reference(s2tmp, loc);
7816 
7817       Named_object* copyfn = gogo->lookup_global("copy");
7818       Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7819       call_args = new Expression_list();
7820       call_args->push_back(a1);
7821       call_args->push_back(a2);
7822       call = Expression::make_call(copyref, call_args, false, loc);
7823       gogo->lower_expression(function, inserter, &call);
7824       gogo->flatten_expression(function, inserter, &call);
7825       inserter->insert(Statement::make_statement(call, false));
7826     }
7827   else
7828     {
7829       // For each argument:
7830       //  s1tmp[l1tmp+i] = a
7831       unsigned long i = 0;
7832       for (Expression_list::const_iterator pa = add->begin();
7833 	   pa != add->end();
7834 	   ++pa, ++i)
7835 	{
7836 	  ref = Expression::make_temporary_reference(s1tmp, loc);
7837 	  ref2 = Expression::make_temporary_reference(l1tmp, loc);
7838 	  Expression* off = Expression::make_integer_ul(i, int_type, loc);
7839 	  ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7840 	  // FIXME: Mark this index as not requiring bounds checks.
7841 	  lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7842 	  gogo->lower_expression(function, inserter, &lhs);
7843 	  gogo->flatten_expression(function, inserter, &lhs);
7844 	  // The flatten pass runs after the write barrier pass, so we
7845 	  // need to insert a write barrier here if necessary.
7846 	  if (!gogo->assign_needs_write_barrier(lhs))
7847 	    assign = Statement::make_assignment(lhs, *pa, loc);
7848 	  else
7849 	    {
7850 	      Function* f = function == NULL ? NULL : function->func_value();
7851 	      assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7852 						       lhs, *pa, loc);
7853 	    }
7854 	  inserter->insert(assign);
7855 	}
7856     }
7857 
7858   return Expression::make_temporary_reference(s1tmp, loc);
7859 }
7860 
7861 // Return whether an expression has an integer value.  Report an error
7862 // if not.  This is used when handling calls to the predeclared make
7863 // function.  Set *SMALL if the value is known to fit in type "int".
7864 
7865 bool
check_int_value(Expression * e,bool is_length,bool * small)7866 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7867 					 bool *small)
7868 {
7869   *small = false;
7870 
7871   Numeric_constant nc;
7872   if (e->numeric_constant_value(&nc))
7873     {
7874       unsigned long v;
7875       switch (nc.to_unsigned_long(&v))
7876 	{
7877 	case Numeric_constant::NC_UL_VALID:
7878 	  break;
7879 	case Numeric_constant::NC_UL_NOTINT:
7880 	  go_error_at(e->location(), "non-integer %s argument to make",
7881 		      is_length ? "len" : "cap");
7882 	  return false;
7883 	case Numeric_constant::NC_UL_NEGATIVE:
7884 	  go_error_at(e->location(), "negative %s argument to make",
7885 		      is_length ? "len" : "cap");
7886 	  return false;
7887 	case Numeric_constant::NC_UL_BIG:
7888 	  // We don't want to give a compile-time error for a 64-bit
7889 	  // value on a 32-bit target.
7890 	  break;
7891 	}
7892 
7893       mpz_t val;
7894       if (!nc.to_int(&val))
7895 	go_unreachable();
7896       int bits = mpz_sizeinbase(val, 2);
7897       mpz_clear(val);
7898       Type* int_type = Type::lookup_integer_type("int");
7899       if (bits >= int_type->integer_type()->bits())
7900 	{
7901 	  go_error_at(e->location(), "%s argument too large for make",
7902 		      is_length ? "len" : "cap");
7903 	  return false;
7904 	}
7905 
7906       *small = true;
7907       return true;
7908     }
7909 
7910   if (e->type()->integer_type() != NULL)
7911     {
7912       int ebits = e->type()->integer_type()->bits();
7913       int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7914 
7915       // We can treat ebits == intbits as small even for an unsigned
7916       // integer type, because we will convert the value to int and
7917       // then reject it in the runtime if it is negative.
7918       *small = ebits <= intbits;
7919 
7920       return true;
7921     }
7922 
7923   go_error_at(e->location(), "non-integer %s argument to make",
7924 	      is_length ? "len" : "cap");
7925   return false;
7926 }
7927 
7928 // Return the type of the real or imag functions, given the type of
7929 // the argument.  We need to map complex64 to float32 and complex128
7930 // to float64, so it has to be done by name.  This returns NULL if it
7931 // can't figure out the type.
7932 
7933 Type*
real_imag_type(Type * arg_type)7934 Builtin_call_expression::real_imag_type(Type* arg_type)
7935 {
7936   if (arg_type == NULL || arg_type->is_abstract())
7937     return NULL;
7938   Named_type* nt = arg_type->named_type();
7939   if (nt == NULL)
7940     return NULL;
7941   while (nt->real_type()->named_type() != NULL)
7942     nt = nt->real_type()->named_type();
7943   if (nt->name() == "complex64")
7944     return Type::lookup_float_type("float32");
7945   else if (nt->name() == "complex128")
7946     return Type::lookup_float_type("float64");
7947   else
7948     return NULL;
7949 }
7950 
7951 // Return the type of the complex function, given the type of one of the
7952 // argments.  Like real_imag_type, we have to map by name.
7953 
7954 Type*
complex_type(Type * arg_type)7955 Builtin_call_expression::complex_type(Type* arg_type)
7956 {
7957   if (arg_type == NULL || arg_type->is_abstract())
7958     return NULL;
7959   Named_type* nt = arg_type->named_type();
7960   if (nt == NULL)
7961     return NULL;
7962   while (nt->real_type()->named_type() != NULL)
7963     nt = nt->real_type()->named_type();
7964   if (nt->name() == "float32")
7965     return Type::lookup_complex_type("complex64");
7966   else if (nt->name() == "float64")
7967     return Type::lookup_complex_type("complex128");
7968   else
7969     return NULL;
7970 }
7971 
7972 // Return a single argument, or NULL if there isn't one.
7973 
7974 Expression*
one_arg() const7975 Builtin_call_expression::one_arg() const
7976 {
7977   const Expression_list* args = this->args();
7978   if (args == NULL || args->size() != 1)
7979     return NULL;
7980   return args->front();
7981 }
7982 
7983 // A traversal class which looks for a call or receive expression.
7984 
7985 class Find_call_expression : public Traverse
7986 {
7987  public:
Find_call_expression()7988   Find_call_expression()
7989     : Traverse(traverse_expressions),
7990       found_(false)
7991   { }
7992 
7993   int
7994   expression(Expression**);
7995 
7996   bool
found()7997   found()
7998   { return this->found_; }
7999 
8000  private:
8001   bool found_;
8002 };
8003 
8004 int
expression(Expression ** pexpr)8005 Find_call_expression::expression(Expression** pexpr)
8006 {
8007   Expression* expr = *pexpr;
8008   if (!expr->is_constant()
8009       && (expr->call_expression() != NULL
8010 	  || expr->receive_expression() != NULL))
8011     {
8012       this->found_ = true;
8013       return TRAVERSE_EXIT;
8014     }
8015   return TRAVERSE_CONTINUE;
8016 }
8017 
8018 // Return whether calling len or cap on EXPR, of array type, is a
8019 // constant.  The language spec says "the expressions len(s) and
8020 // cap(s) are constants if the type of s is an array or pointer to an
8021 // array and the expression s does not contain channel receives or
8022 // (non-constant) function calls."
8023 
8024 bool
array_len_is_constant(Expression * expr)8025 Builtin_call_expression::array_len_is_constant(Expression* expr)
8026 {
8027   go_assert(expr->type()->deref()->array_type() != NULL
8028 	    && !expr->type()->deref()->is_slice_type());
8029   if (expr->is_constant())
8030     return true;
8031   Find_call_expression find_call;
8032   Expression::traverse(&expr, &find_call);
8033   return !find_call.found();
8034 }
8035 
8036 // Return whether this is constant: len of a string constant, or len
8037 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
8038 // unsafe.Alignof.
8039 
8040 bool
do_is_constant() const8041 Builtin_call_expression::do_is_constant() const
8042 {
8043   if (this->is_error_expression())
8044     return true;
8045   switch (this->code_)
8046     {
8047     case BUILTIN_LEN:
8048     case BUILTIN_CAP:
8049       {
8050 	if (this->seen_)
8051 	  return false;
8052 
8053 	Expression* arg = this->one_arg();
8054 	if (arg == NULL)
8055 	  return false;
8056 	Type* arg_type = arg->type();
8057 
8058 	if (arg_type->points_to() != NULL
8059 	    && arg_type->points_to()->array_type() != NULL
8060 	    && !arg_type->points_to()->is_slice_type())
8061 	  arg_type = arg_type->points_to();
8062 
8063 	if (arg_type->array_type() != NULL
8064 	    && arg_type->array_type()->length() != NULL
8065 	    && Builtin_call_expression::array_len_is_constant(arg))
8066 	  return true;
8067 
8068 	if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8069 	  {
8070 	    this->seen_ = true;
8071 	    bool ret = arg->is_constant();
8072 	    this->seen_ = false;
8073 	    return ret;
8074 	  }
8075       }
8076       break;
8077 
8078     case BUILTIN_SIZEOF:
8079     case BUILTIN_ALIGNOF:
8080       return this->one_arg() != NULL;
8081 
8082     case BUILTIN_OFFSETOF:
8083       {
8084 	Expression* arg = this->one_arg();
8085 	if (arg == NULL)
8086 	  return false;
8087 	return arg->field_reference_expression() != NULL;
8088       }
8089 
8090     case BUILTIN_COMPLEX:
8091       {
8092 	const Expression_list* args = this->args();
8093 	if (args != NULL && args->size() == 2)
8094 	  return args->front()->is_constant() && args->back()->is_constant();
8095       }
8096       break;
8097 
8098     case BUILTIN_REAL:
8099     case BUILTIN_IMAG:
8100       {
8101 	Expression* arg = this->one_arg();
8102 	return arg != NULL && arg->is_constant();
8103       }
8104 
8105     default:
8106       break;
8107     }
8108 
8109   return false;
8110 }
8111 
8112 // Return a numeric constant if possible.
8113 
8114 bool
do_numeric_constant_value(Numeric_constant * nc) const8115 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8116 {
8117   if (this->code_ == BUILTIN_LEN
8118       || this->code_ == BUILTIN_CAP)
8119     {
8120       Expression* arg = this->one_arg();
8121       if (arg == NULL)
8122 	return false;
8123       Type* arg_type = arg->type();
8124 
8125       if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8126 	{
8127 	  std::string sval;
8128 	  if (arg->string_constant_value(&sval))
8129 	    {
8130 	      nc->set_unsigned_long(Type::lookup_integer_type("int"),
8131 				    sval.length());
8132 	      return true;
8133 	    }
8134 	}
8135 
8136       if (arg_type->points_to() != NULL
8137 	  && arg_type->points_to()->array_type() != NULL
8138 	  && !arg_type->points_to()->is_slice_type())
8139 	arg_type = arg_type->points_to();
8140 
8141       if (arg_type->array_type() != NULL
8142 	  && arg_type->array_type()->length() != NULL)
8143 	{
8144 	  if (this->seen_)
8145 	    return false;
8146 	  Expression* e = arg_type->array_type()->length();
8147 	  this->seen_ = true;
8148 	  bool r = e->numeric_constant_value(nc);
8149 	  this->seen_ = false;
8150 	  if (r)
8151 	    {
8152 	      if (!nc->set_type(Type::lookup_integer_type("int"), false,
8153 				this->location()))
8154 		r = false;
8155 	    }
8156 	  return r;
8157 	}
8158     }
8159   else if (this->code_ == BUILTIN_SIZEOF
8160 	   || this->code_ == BUILTIN_ALIGNOF)
8161     {
8162       Expression* arg = this->one_arg();
8163       if (arg == NULL)
8164 	return false;
8165       Type* arg_type = arg->type();
8166       if (arg_type->is_error())
8167 	return false;
8168       if (arg_type->is_abstract())
8169 	arg_type = arg_type->make_non_abstract_type();
8170       if (this->seen_)
8171         return false;
8172 
8173       int64_t ret;
8174       if (this->code_ == BUILTIN_SIZEOF)
8175 	{
8176           this->seen_ = true;
8177 	  bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8178           this->seen_ = false;
8179 	  if (!ok)
8180 	    return false;
8181 	}
8182       else if (this->code_ == BUILTIN_ALIGNOF)
8183 	{
8184 	  bool ok;
8185           this->seen_ = true;
8186 	  if (arg->field_reference_expression() == NULL)
8187 	    ok = arg_type->backend_type_align(this->gogo_, &ret);
8188 	  else
8189 	    {
8190 	      // Calling unsafe.Alignof(s.f) returns the alignment of
8191 	      // the type of f when it is used as a field in a struct.
8192 	      ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8193 	    }
8194           this->seen_ = false;
8195 	  if (!ok)
8196 	    return false;
8197 	}
8198       else
8199 	go_unreachable();
8200 
8201       mpz_t zval;
8202       set_mpz_from_int64(&zval, ret);
8203       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8204       mpz_clear(zval);
8205       return true;
8206     }
8207   else if (this->code_ == BUILTIN_OFFSETOF)
8208     {
8209       Expression* arg = this->one_arg();
8210       if (arg == NULL)
8211 	return false;
8212       Field_reference_expression* farg = arg->field_reference_expression();
8213       if (farg == NULL)
8214 	return false;
8215       if (this->seen_)
8216         return false;
8217 
8218       int64_t total_offset = 0;
8219       while (true)
8220         {
8221           Expression* struct_expr = farg->expr();
8222           Type* st = struct_expr->type();
8223           if (st->struct_type() == NULL)
8224             return false;
8225           if (st->named_type() != NULL)
8226             st->named_type()->convert(this->gogo_);
8227           if (st->is_error_type())
8228             {
8229               go_assert(saw_errors());
8230               return false;
8231             }
8232           int64_t offset;
8233           this->seen_ = true;
8234           bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8235 							    farg->field_index(),
8236 							    &offset);
8237           this->seen_ = false;
8238 	  if (!ok)
8239 	    return false;
8240           total_offset += offset;
8241           if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8242             {
8243               // Go up until we reach the original base.
8244               farg = struct_expr->field_reference_expression();
8245               continue;
8246             }
8247           break;
8248         }
8249       mpz_t zval;
8250       set_mpz_from_int64(&zval, total_offset);
8251       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8252       mpz_clear(zval);
8253       return true;
8254     }
8255   else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8256     {
8257       Expression* arg = this->one_arg();
8258       if (arg == NULL)
8259 	return false;
8260 
8261       Numeric_constant argnc;
8262       if (!arg->numeric_constant_value(&argnc))
8263 	return false;
8264 
8265       mpc_t val;
8266       if (!argnc.to_complex(&val))
8267 	return false;
8268 
8269       Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8270       if (this->code_ == BUILTIN_REAL)
8271 	nc->set_float(type, mpc_realref(val));
8272       else
8273 	nc->set_float(type, mpc_imagref(val));
8274       mpc_clear(val);
8275       return true;
8276     }
8277   else if (this->code_ == BUILTIN_COMPLEX)
8278     {
8279       const Expression_list* args = this->args();
8280       if (args == NULL || args->size() != 2)
8281 	return false;
8282 
8283       Numeric_constant rnc;
8284       if (!args->front()->numeric_constant_value(&rnc))
8285 	return false;
8286       Numeric_constant inc;
8287       if (!args->back()->numeric_constant_value(&inc))
8288 	return false;
8289 
8290       if (rnc.type() != NULL
8291 	  && !rnc.type()->is_abstract()
8292 	  && inc.type() != NULL
8293 	  && !inc.type()->is_abstract()
8294 	  && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8295 	return false;
8296 
8297       mpfr_t r;
8298       if (!rnc.to_float(&r))
8299 	return false;
8300       mpfr_t i;
8301       if (!inc.to_float(&i))
8302 	{
8303 	  mpfr_clear(r);
8304 	  return false;
8305 	}
8306 
8307       Type* arg_type = rnc.type();
8308       if (arg_type == NULL || arg_type->is_abstract())
8309 	arg_type = inc.type();
8310 
8311       mpc_t val;
8312       mpc_init2(val, mpc_precision);
8313       mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8314       mpfr_clear(r);
8315       mpfr_clear(i);
8316 
8317       Type* type = Builtin_call_expression::complex_type(arg_type);
8318       nc->set_complex(type, val);
8319 
8320       mpc_clear(val);
8321 
8322       return true;
8323     }
8324 
8325   return false;
8326 }
8327 
8328 // Give an error if we are discarding the value of an expression which
8329 // should not normally be discarded.  We don't give an error for
8330 // discarding the value of an ordinary function call, but we do for
8331 // builtin functions, purely for consistency with the gc compiler.
8332 
8333 bool
do_discarding_value()8334 Builtin_call_expression::do_discarding_value()
8335 {
8336   switch (this->code_)
8337     {
8338     case BUILTIN_INVALID:
8339     default:
8340       go_unreachable();
8341 
8342     case BUILTIN_APPEND:
8343     case BUILTIN_CAP:
8344     case BUILTIN_COMPLEX:
8345     case BUILTIN_IMAG:
8346     case BUILTIN_LEN:
8347     case BUILTIN_MAKE:
8348     case BUILTIN_NEW:
8349     case BUILTIN_REAL:
8350     case BUILTIN_ALIGNOF:
8351     case BUILTIN_OFFSETOF:
8352     case BUILTIN_SIZEOF:
8353       this->unused_value_error();
8354       return false;
8355 
8356     case BUILTIN_CLOSE:
8357     case BUILTIN_COPY:
8358     case BUILTIN_DELETE:
8359     case BUILTIN_PANIC:
8360     case BUILTIN_PRINT:
8361     case BUILTIN_PRINTLN:
8362     case BUILTIN_RECOVER:
8363       return true;
8364     }
8365 }
8366 
8367 // Return the type.
8368 
8369 Type*
do_type()8370 Builtin_call_expression::do_type()
8371 {
8372   if (this->is_error_expression())
8373     return Type::make_error_type();
8374   switch (this->code_)
8375     {
8376     case BUILTIN_INVALID:
8377     default:
8378       return Type::make_error_type();
8379 
8380     case BUILTIN_NEW:
8381       {
8382 	const Expression_list* args = this->args();
8383 	if (args == NULL || args->empty())
8384 	  return Type::make_error_type();
8385 	return Type::make_pointer_type(args->front()->type());
8386       }
8387 
8388     case BUILTIN_MAKE:
8389       {
8390 	const Expression_list* args = this->args();
8391 	if (args == NULL || args->empty())
8392 	  return Type::make_error_type();
8393 	return args->front()->type();
8394       }
8395 
8396     case BUILTIN_CAP:
8397     case BUILTIN_COPY:
8398     case BUILTIN_LEN:
8399       return Type::lookup_integer_type("int");
8400 
8401     case BUILTIN_ALIGNOF:
8402     case BUILTIN_OFFSETOF:
8403     case BUILTIN_SIZEOF:
8404       return Type::lookup_integer_type("uintptr");
8405 
8406     case BUILTIN_CLOSE:
8407     case BUILTIN_DELETE:
8408     case BUILTIN_PANIC:
8409     case BUILTIN_PRINT:
8410     case BUILTIN_PRINTLN:
8411       return Type::make_void_type();
8412 
8413     case BUILTIN_RECOVER:
8414       return Type::make_empty_interface_type(Linemap::predeclared_location());
8415 
8416     case BUILTIN_APPEND:
8417       {
8418 	const Expression_list* args = this->args();
8419 	if (args == NULL || args->empty())
8420 	  return Type::make_error_type();
8421 	Type *ret = args->front()->type();
8422 	if (!ret->is_slice_type())
8423 	  return Type::make_error_type();
8424 	return ret;
8425       }
8426 
8427     case BUILTIN_REAL:
8428     case BUILTIN_IMAG:
8429       {
8430 	Expression* arg = this->one_arg();
8431 	if (arg == NULL)
8432 	  return Type::make_error_type();
8433 	Type* t = arg->type();
8434 	if (t->is_abstract())
8435 	  t = t->make_non_abstract_type();
8436 	t = Builtin_call_expression::real_imag_type(t);
8437 	if (t == NULL)
8438 	  t = Type::make_error_type();
8439 	return t;
8440       }
8441 
8442     case BUILTIN_COMPLEX:
8443       {
8444 	const Expression_list* args = this->args();
8445 	if (args == NULL || args->size() != 2)
8446 	  return Type::make_error_type();
8447 	Type* t = args->front()->type();
8448 	if (t->is_abstract())
8449 	  {
8450 	    t = args->back()->type();
8451 	    if (t->is_abstract())
8452 	      t = t->make_non_abstract_type();
8453 	  }
8454 	t = Builtin_call_expression::complex_type(t);
8455 	if (t == NULL)
8456 	  t = Type::make_error_type();
8457 	return t;
8458       }
8459     }
8460 }
8461 
8462 // Determine the type.
8463 
8464 void
do_determine_type(const Type_context * context)8465 Builtin_call_expression::do_determine_type(const Type_context* context)
8466 {
8467   if (!this->determining_types())
8468     return;
8469 
8470   this->fn()->determine_type_no_context();
8471 
8472   const Expression_list* args = this->args();
8473 
8474   bool is_print;
8475   Type* arg_type = NULL;
8476   Type* trailing_arg_types = NULL;
8477   switch (this->code_)
8478     {
8479     case BUILTIN_PRINT:
8480     case BUILTIN_PRINTLN:
8481       // Do not force a large integer constant to "int".
8482       is_print = true;
8483       break;
8484 
8485     case BUILTIN_REAL:
8486     case BUILTIN_IMAG:
8487       arg_type = Builtin_call_expression::complex_type(context->type);
8488       if (arg_type == NULL)
8489 	arg_type = Type::lookup_complex_type("complex128");
8490       is_print = false;
8491       break;
8492 
8493     case BUILTIN_COMPLEX:
8494       {
8495 	// For the complex function the type of one operand can
8496 	// determine the type of the other, as in a binary expression.
8497 	arg_type = Builtin_call_expression::real_imag_type(context->type);
8498 	if (arg_type == NULL)
8499 	  arg_type = Type::lookup_float_type("float64");
8500 	if (args != NULL && args->size() == 2)
8501 	  {
8502 	    Type* t1 = args->front()->type();
8503 	    Type* t2 = args->back()->type();
8504 	    if (!t1->is_abstract())
8505 	      arg_type = t1;
8506 	    else if (!t2->is_abstract())
8507 	      arg_type = t2;
8508 	  }
8509 	is_print = false;
8510       }
8511       break;
8512 
8513     case BUILTIN_APPEND:
8514       if (!this->is_varargs()
8515 	  && args != NULL
8516 	  && !args->empty()
8517 	  && args->front()->type()->is_slice_type())
8518 	trailing_arg_types =
8519 	  args->front()->type()->array_type()->element_type();
8520       is_print = false;
8521       break;
8522 
8523     default:
8524       is_print = false;
8525       break;
8526     }
8527 
8528   if (args != NULL)
8529     {
8530       for (Expression_list::const_iterator pa = args->begin();
8531 	   pa != args->end();
8532 	   ++pa)
8533 	{
8534 	  Type_context subcontext;
8535 	  subcontext.type = arg_type;
8536 
8537 	  if (is_print)
8538 	    {
8539 	      // We want to print large constants, we so can't just
8540 	      // use the appropriate nonabstract type.  Use uint64 for
8541 	      // an integer if we know it is nonnegative, otherwise
8542 	      // use int64 for a integer, otherwise use float64 for a
8543 	      // float or complex128 for a complex.
8544 	      Type* want_type = NULL;
8545 	      Type* atype = (*pa)->type();
8546 	      if (atype->is_abstract())
8547 		{
8548 		  if (atype->integer_type() != NULL)
8549 		    {
8550 		      Numeric_constant nc;
8551 		      if (this->numeric_constant_value(&nc))
8552 			{
8553 			  mpz_t val;
8554 			  if (nc.to_int(&val))
8555 			    {
8556 			      if (mpz_sgn(val) >= 0)
8557 				want_type = Type::lookup_integer_type("uint64");
8558 			      mpz_clear(val);
8559 			    }
8560 			}
8561 		      if (want_type == NULL)
8562 			want_type = Type::lookup_integer_type("int64");
8563 		    }
8564 		  else if (atype->float_type() != NULL)
8565 		    want_type = Type::lookup_float_type("float64");
8566 		  else if (atype->complex_type() != NULL)
8567 		    want_type = Type::lookup_complex_type("complex128");
8568 		  else if (atype->is_abstract_string_type())
8569 		    want_type = Type::lookup_string_type();
8570 		  else if (atype->is_abstract_boolean_type())
8571 		    want_type = Type::lookup_bool_type();
8572 		  else
8573 		    go_unreachable();
8574 		  subcontext.type = want_type;
8575 		}
8576 	    }
8577 
8578 	  (*pa)->determine_type(&subcontext);
8579 
8580 	  if (trailing_arg_types != NULL)
8581 	    {
8582 	      arg_type = trailing_arg_types;
8583 	      trailing_arg_types = NULL;
8584 	    }
8585 	}
8586     }
8587 }
8588 
8589 // If there is exactly one argument, return true.  Otherwise give an
8590 // error message and return false.
8591 
8592 bool
check_one_arg()8593 Builtin_call_expression::check_one_arg()
8594 {
8595   const Expression_list* args = this->args();
8596   if (args == NULL || args->size() < 1)
8597     {
8598       this->report_error(_("not enough arguments"));
8599       return false;
8600     }
8601   else if (args->size() > 1)
8602     {
8603       this->report_error(_("too many arguments"));
8604       return false;
8605     }
8606   if (args->front()->is_error_expression()
8607       || args->front()->type()->is_error())
8608     {
8609       this->set_is_error();
8610       return false;
8611     }
8612   return true;
8613 }
8614 
8615 // Check argument types for a builtin function.
8616 
8617 void
do_check_types(Gogo *)8618 Builtin_call_expression::do_check_types(Gogo*)
8619 {
8620   if (this->is_error_expression())
8621     return;
8622   switch (this->code_)
8623     {
8624     case BUILTIN_INVALID:
8625     case BUILTIN_NEW:
8626     case BUILTIN_MAKE:
8627     case BUILTIN_DELETE:
8628       return;
8629 
8630     case BUILTIN_LEN:
8631     case BUILTIN_CAP:
8632       {
8633 	// The single argument may be either a string or an array or a
8634 	// map or a channel, or a pointer to a closed array.
8635 	if (this->check_one_arg())
8636 	  {
8637 	    Type* arg_type = this->one_arg()->type();
8638 	    if (arg_type->points_to() != NULL
8639 		&& arg_type->points_to()->array_type() != NULL
8640 		&& !arg_type->points_to()->is_slice_type())
8641 	      arg_type = arg_type->points_to();
8642 	    if (this->code_ == BUILTIN_CAP)
8643 	      {
8644 		if (!arg_type->is_error()
8645 		    && arg_type->array_type() == NULL
8646 		    && arg_type->channel_type() == NULL)
8647 		  this->report_error(_("argument must be array or slice "
8648 				       "or channel"));
8649 	      }
8650 	    else
8651 	      {
8652 		if (!arg_type->is_error()
8653 		    && !arg_type->is_string_type()
8654 		    && arg_type->array_type() == NULL
8655 		    && arg_type->map_type() == NULL
8656 		    && arg_type->channel_type() == NULL)
8657 		  this->report_error(_("argument must be string or "
8658 				       "array or slice or map or channel"));
8659 	      }
8660 	  }
8661       }
8662       break;
8663 
8664     case BUILTIN_PRINT:
8665     case BUILTIN_PRINTLN:
8666       {
8667 	const Expression_list* args = this->args();
8668 	if (args == NULL)
8669 	  {
8670 	    if (this->code_ == BUILTIN_PRINT)
8671 	      go_warning_at(this->location(), 0,
8672 			 "no arguments for builtin function %<%s%>",
8673 			 (this->code_ == BUILTIN_PRINT
8674 			  ? "print"
8675 			  : "println"));
8676 	  }
8677 	else
8678 	  {
8679 	    for (Expression_list::const_iterator p = args->begin();
8680 		 p != args->end();
8681 		 ++p)
8682 	      {
8683 		Type* type = (*p)->type();
8684 		if (type->is_error()
8685 		    || type->is_string_type()
8686 		    || type->integer_type() != NULL
8687 		    || type->float_type() != NULL
8688 		    || type->complex_type() != NULL
8689 		    || type->is_boolean_type()
8690 		    || type->points_to() != NULL
8691 		    || type->interface_type() != NULL
8692 		    || type->channel_type() != NULL
8693 		    || type->map_type() != NULL
8694 		    || type->function_type() != NULL
8695 		    || type->is_slice_type())
8696 		  ;
8697 		else if ((*p)->is_type_expression())
8698 		  {
8699 		    // If this is a type expression it's going to give
8700 		    // an error anyhow, so we don't need one here.
8701 		  }
8702 		else
8703 		  this->report_error(_("unsupported argument type to "
8704 				       "builtin function"));
8705 	      }
8706 	  }
8707       }
8708       break;
8709 
8710     case BUILTIN_CLOSE:
8711       if (this->check_one_arg())
8712 	{
8713 	  if (this->one_arg()->type()->channel_type() == NULL)
8714 	    this->report_error(_("argument must be channel"));
8715 	  else if (!this->one_arg()->type()->channel_type()->may_send())
8716 	    this->report_error(_("cannot close receive-only channel"));
8717 	}
8718       break;
8719 
8720     case BUILTIN_PANIC:
8721     case BUILTIN_SIZEOF:
8722     case BUILTIN_ALIGNOF:
8723       this->check_one_arg();
8724       break;
8725 
8726     case BUILTIN_RECOVER:
8727       if (this->args() != NULL
8728 	  && !this->args()->empty()
8729 	  && !this->recover_arg_is_set_)
8730 	this->report_error(_("too many arguments"));
8731       break;
8732 
8733     case BUILTIN_OFFSETOF:
8734       if (this->check_one_arg())
8735 	{
8736 	  Expression* arg = this->one_arg();
8737 	  if (arg->field_reference_expression() == NULL)
8738 	    this->report_error(_("argument must be a field reference"));
8739 	}
8740       break;
8741 
8742     case BUILTIN_COPY:
8743       {
8744 	const Expression_list* args = this->args();
8745 	if (args == NULL || args->size() < 2)
8746 	  {
8747 	    this->report_error(_("not enough arguments"));
8748 	    break;
8749 	  }
8750 	else if (args->size() > 2)
8751 	  {
8752 	    this->report_error(_("too many arguments"));
8753 	    break;
8754 	  }
8755 	Type* arg1_type = args->front()->type();
8756 	Type* arg2_type = args->back()->type();
8757 	if (arg1_type->is_error() || arg2_type->is_error())
8758 	  {
8759 	    this->set_is_error();
8760 	    break;
8761 	  }
8762 
8763 	Type* e1;
8764 	if (arg1_type->is_slice_type())
8765 	  e1 = arg1_type->array_type()->element_type();
8766 	else
8767 	  {
8768 	    this->report_error(_("left argument must be a slice"));
8769 	    break;
8770 	  }
8771 
8772 	if (arg2_type->is_slice_type())
8773 	  {
8774 	    Type* e2 = arg2_type->array_type()->element_type();
8775 	    if (!Type::are_identical(e1, e2, true, NULL))
8776 	      this->report_error(_("element types must be the same"));
8777 	  }
8778 	else if (arg2_type->is_string_type())
8779 	  {
8780 	    if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8781 	      this->report_error(_("first argument must be []byte"));
8782 	  }
8783 	else
8784 	    this->report_error(_("second argument must be slice or string"));
8785       }
8786       break;
8787 
8788     case BUILTIN_APPEND:
8789       {
8790 	const Expression_list* args = this->args();
8791 	if (args == NULL || args->empty())
8792 	  {
8793 	    this->report_error(_("not enough arguments"));
8794 	    break;
8795 	  }
8796 
8797 	Type* slice_type = args->front()->type();
8798 	if (!slice_type->is_slice_type())
8799 	  {
8800 	    if (slice_type->is_error_type())
8801 	      break;
8802 	    if (slice_type->is_nil_type())
8803 	      go_error_at(args->front()->location(), "use of untyped nil");
8804 	    else
8805 	      go_error_at(args->front()->location(),
8806 			  "argument 1 must be a slice");
8807 	    this->set_is_error();
8808 	    break;
8809 	  }
8810 
8811 	Type* element_type = slice_type->array_type()->element_type();
8812 	if (!element_type->in_heap())
8813 	  go_error_at(args->front()->location(),
8814 		      "can't append to slice of go:notinheap type");
8815 	if (this->is_varargs())
8816 	  {
8817 	    if (!args->back()->type()->is_slice_type()
8818 		&& !args->back()->type()->is_string_type())
8819 	      {
8820 		go_error_at(args->back()->location(),
8821 			    "invalid use of %<...%> with non-slice/non-string");
8822 		this->set_is_error();
8823 		break;
8824 	      }
8825 
8826 	    if (args->size() < 2)
8827 	      {
8828 		this->report_error(_("not enough arguments"));
8829 		break;
8830 	      }
8831 	    if (args->size() > 2)
8832 	      {
8833 		this->report_error(_("too many arguments"));
8834 		break;
8835 	      }
8836 
8837 	    if (args->back()->type()->is_string_type()
8838 		&& element_type->integer_type() != NULL
8839 		&& element_type->integer_type()->is_byte())
8840 	      {
8841 		// Permit append(s1, s2...) when s1 is a slice of
8842 		// bytes and s2 is a string type.
8843 	      }
8844 	    else
8845 	      {
8846 		// We have to test for assignment compatibility to a
8847 		// slice of the element type, which is not necessarily
8848 		// the same as the type of the first argument: the
8849 		// first argument might have a named type.
8850 		Type* check_type = Type::make_array_type(element_type, NULL);
8851 		std::string reason;
8852 		if (!Type::are_assignable(check_type, args->back()->type(),
8853 					  &reason))
8854 		  {
8855 		    if (reason.empty())
8856 		      go_error_at(args->back()->location(),
8857 				  "argument 2 has invalid type");
8858 		    else
8859 		      go_error_at(args->back()->location(),
8860 				  "argument 2 has invalid type (%s)",
8861 				  reason.c_str());
8862 		    this->set_is_error();
8863 		    break;
8864 		  }
8865 	      }
8866 	  }
8867 	else
8868 	  {
8869 	    Expression_list::const_iterator pa = args->begin();
8870 	    int i = 2;
8871 	    for (++pa; pa != args->end(); ++pa, ++i)
8872 	      {
8873 		std::string reason;
8874 		if (!Type::are_assignable(element_type, (*pa)->type(),
8875 					  &reason))
8876 		  {
8877 		    if (reason.empty())
8878 		      go_error_at((*pa)->location(),
8879 				  "argument %d has incompatible type", i);
8880 		    else
8881 		      go_error_at((*pa)->location(),
8882 				  "argument %d has incompatible type (%s)",
8883 				  i, reason.c_str());
8884 		    this->set_is_error();
8885 		  }
8886 	      }
8887 	  }
8888       }
8889       break;
8890 
8891     case BUILTIN_REAL:
8892     case BUILTIN_IMAG:
8893       if (this->check_one_arg())
8894 	{
8895 	  if (this->one_arg()->type()->complex_type() == NULL)
8896 	    this->report_error(_("argument must have complex type"));
8897 	}
8898       break;
8899 
8900     case BUILTIN_COMPLEX:
8901       {
8902 	const Expression_list* args = this->args();
8903 	if (args == NULL || args->size() < 2)
8904 	  this->report_error(_("not enough arguments"));
8905 	else if (args->size() > 2)
8906 	  this->report_error(_("too many arguments"));
8907 	else if (args->front()->is_error_expression()
8908 		 || args->front()->type()->is_error()
8909 		 || args->back()->is_error_expression()
8910 		 || args->back()->type()->is_error())
8911 	  this->set_is_error();
8912 	else if (!Type::are_identical(args->front()->type(),
8913 				      args->back()->type(), true, NULL))
8914 	  this->report_error(_("complex arguments must have identical types"));
8915 	else if (args->front()->type()->float_type() == NULL)
8916 	  this->report_error(_("complex arguments must have "
8917 			       "floating-point type"));
8918       }
8919       break;
8920 
8921     default:
8922       go_unreachable();
8923     }
8924 }
8925 
8926 Expression*
do_copy()8927 Builtin_call_expression::do_copy()
8928 {
8929   Call_expression* bce =
8930     new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8931 				(this->args() == NULL
8932 				 ? NULL
8933 				 : this->args()->copy()),
8934 				this->is_varargs(),
8935 				this->location());
8936 
8937   if (this->varargs_are_lowered())
8938     bce->set_varargs_are_lowered();
8939   return bce;
8940 }
8941 
8942 // Return the backend representation for a builtin function.
8943 
8944 Bexpression*
do_get_backend(Translate_context * context)8945 Builtin_call_expression::do_get_backend(Translate_context* context)
8946 {
8947   Gogo* gogo = context->gogo();
8948   Location location = this->location();
8949 
8950   if (this->is_erroneous_call())
8951     {
8952       go_assert(saw_errors());
8953       return gogo->backend()->error_expression();
8954     }
8955 
8956   switch (this->code_)
8957     {
8958     case BUILTIN_INVALID:
8959     case BUILTIN_NEW:
8960     case BUILTIN_MAKE:
8961       go_unreachable();
8962 
8963     case BUILTIN_LEN:
8964     case BUILTIN_CAP:
8965       {
8966 	const Expression_list* args = this->args();
8967 	go_assert(args != NULL && args->size() == 1);
8968 	Expression* arg = args->front();
8969 	Type* arg_type = arg->type();
8970 
8971 	if (this->seen_)
8972 	  {
8973 	    go_assert(saw_errors());
8974 	    return context->backend()->error_expression();
8975 	  }
8976 	this->seen_ = true;
8977 	this->seen_ = false;
8978 	if (arg_type->points_to() != NULL)
8979 	  {
8980 	    arg_type = arg_type->points_to();
8981 	    go_assert(arg_type->array_type() != NULL
8982 		       && !arg_type->is_slice_type());
8983             arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
8984                                                location);
8985 	  }
8986 
8987 	Type* int_type = Type::lookup_integer_type("int");
8988         Expression* val;
8989 	if (this->code_ == BUILTIN_LEN)
8990 	  {
8991 	    if (arg_type->is_string_type())
8992 	      val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8993 						 location);
8994 	    else if (arg_type->array_type() != NULL)
8995 	      {
8996 		if (this->seen_)
8997 		  {
8998 		    go_assert(saw_errors());
8999 		    return context->backend()->error_expression();
9000 		  }
9001 		this->seen_ = true;
9002 	        val = arg_type->array_type()->get_length(gogo, arg);
9003 		this->seen_ = false;
9004 	      }
9005 	    else if (arg_type->map_type() != NULL
9006 		     || arg_type->channel_type() != NULL)
9007 	      {
9008 		// The first field is the length.  If the pointer is
9009 		// nil, the length is zero.
9010 		Type* pint_type = Type::make_pointer_type(int_type);
9011 		arg = Expression::make_unsafe_cast(pint_type, arg, location);
9012 		Expression* nil = Expression::make_nil(location);
9013 		nil = Expression::make_cast(pint_type, nil, location);
9014 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9015 							  arg, nil, location);
9016 		Expression* zero = Expression::make_integer_ul(0, int_type,
9017 							       location);
9018                 Expression* indir =
9019                     Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
9020                                                  location);
9021 		val = Expression::make_conditional(cmp, zero, indir, location);
9022 	      }
9023 	    else
9024 	      go_unreachable();
9025 	  }
9026 	else
9027 	  {
9028 	    if (arg_type->array_type() != NULL)
9029 	      {
9030 		if (this->seen_)
9031 		  {
9032 		    go_assert(saw_errors());
9033 		    return context->backend()->error_expression();
9034 		  }
9035 		this->seen_ = true;
9036                 val = arg_type->array_type()->get_capacity(gogo, arg);
9037 		this->seen_ = false;
9038 	      }
9039 	    else if (arg_type->channel_type() != NULL)
9040 	      {
9041 		// The second field is the capacity.  If the pointer
9042 		// is nil, the capacity is zero.
9043 		Type* uintptr_type = Type::lookup_integer_type("uintptr");
9044 		Type* pint_type = Type::make_pointer_type(int_type);
9045 		Expression* parg = Expression::make_unsafe_cast(uintptr_type,
9046 								arg,
9047 								location);
9048 		int off = int_type->integer_type()->bits() / 8;
9049 		Expression* eoff = Expression::make_integer_ul(off,
9050 							       uintptr_type,
9051 							       location);
9052 		parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
9053 					       location);
9054 		parg = Expression::make_unsafe_cast(pint_type, parg, location);
9055 		Expression* nil = Expression::make_nil(location);
9056 		nil = Expression::make_cast(pint_type, nil, location);
9057 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9058 							  arg, nil, location);
9059 		Expression* zero = Expression::make_integer_ul(0, int_type,
9060 							       location);
9061                 Expression* indir =
9062                     Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
9063                                                  location);
9064 		val = Expression::make_conditional(cmp, zero, indir, location);
9065 	      }
9066 	    else
9067 	      go_unreachable();
9068 	  }
9069 
9070 	return Expression::make_cast(int_type, val,
9071 				     location)->get_backend(context);
9072       }
9073 
9074     case BUILTIN_PRINT:
9075     case BUILTIN_PRINTLN:
9076       {
9077 	const bool is_ln = this->code_ == BUILTIN_PRINTLN;
9078 
9079 	Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
9080 						     location, 0);
9081 
9082 	const Expression_list* call_args = this->args();
9083 	if (call_args != NULL)
9084 	  {
9085 	    for (Expression_list::const_iterator p = call_args->begin();
9086 		 p != call_args->end();
9087 		 ++p)
9088 	      {
9089 		if (is_ln && p != call_args->begin())
9090 		  {
9091                     Expression* print_space =
9092 		      Runtime::make_call(Runtime::PRINTSP, location, 0);
9093 
9094                     print_stmts =
9095                         Expression::make_compound(print_stmts, print_space,
9096                                                   location);
9097 		  }
9098 
9099                 Expression* arg = *p;
9100 		Type* type = arg->type();
9101                 Runtime::Function code;
9102 		if (type->is_string_type())
9103                   code = Runtime::PRINTSTRING;
9104 		else if (type->integer_type() != NULL
9105 			 && type->integer_type()->is_unsigned())
9106 		  {
9107 		    Type* itype = Type::lookup_integer_type("uint64");
9108 		    arg = Expression::make_cast(itype, arg, location);
9109                     code = Runtime::PRINTUINT;
9110 		  }
9111 		else if (type->integer_type() != NULL)
9112 		  {
9113 		    Type* itype = Type::lookup_integer_type("int64");
9114 		    arg = Expression::make_cast(itype, arg, location);
9115                     code = Runtime::PRINTINT;
9116 		  }
9117 		else if (type->float_type() != NULL)
9118 		  {
9119                     Type* dtype = Type::lookup_float_type("float64");
9120                     arg = Expression::make_cast(dtype, arg, location);
9121                     code = Runtime::PRINTFLOAT;
9122 		  }
9123 		else if (type->complex_type() != NULL)
9124 		  {
9125                     Type* ctype = Type::lookup_complex_type("complex128");
9126                     arg = Expression::make_cast(ctype, arg, location);
9127                     code = Runtime::PRINTCOMPLEX;
9128 		  }
9129 		else if (type->is_boolean_type())
9130                   code = Runtime::PRINTBOOL;
9131 		else if (type->points_to() != NULL
9132 			 || type->channel_type() != NULL
9133 			 || type->map_type() != NULL
9134 			 || type->function_type() != NULL)
9135 		  {
9136                     arg = Expression::make_cast(type, arg, location);
9137                     code = Runtime::PRINTPOINTER;
9138 		  }
9139 		else if (type->interface_type() != NULL)
9140 		  {
9141 		    if (type->interface_type()->is_empty())
9142                       code = Runtime::PRINTEFACE;
9143 		    else
9144                       code = Runtime::PRINTIFACE;
9145 		  }
9146 		else if (type->is_slice_type())
9147                   code = Runtime::PRINTSLICE;
9148 		else
9149 		  {
9150 		    go_assert(saw_errors());
9151 		    return context->backend()->error_expression();
9152 		  }
9153 
9154                 Expression* call = Runtime::make_call(code, location, 1, arg);
9155 		print_stmts = Expression::make_compound(print_stmts, call,
9156 							location);
9157 	      }
9158 	  }
9159 
9160 	if (is_ln)
9161 	  {
9162             Expression* print_nl =
9163                 Runtime::make_call(Runtime::PRINTNL, location, 0);
9164 	    print_stmts = Expression::make_compound(print_stmts, print_nl,
9165 						    location);
9166 	  }
9167 
9168 	Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9169 						location, 0);
9170 	print_stmts = Expression::make_compound(print_stmts, unlock, location);
9171 
9172         return print_stmts->get_backend(context);
9173       }
9174 
9175     case BUILTIN_PANIC:
9176       {
9177 	const Expression_list* args = this->args();
9178 	go_assert(args != NULL && args->size() == 1);
9179 	Expression* arg = args->front();
9180 	Type *empty =
9181 	  Type::make_empty_interface_type(Linemap::predeclared_location());
9182         arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9183 
9184         Expression* panic =
9185             Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9186         return panic->get_backend(context);
9187       }
9188 
9189     case BUILTIN_RECOVER:
9190       {
9191 	// The argument is set when building recover thunks.  It's a
9192 	// boolean value which is true if we can recover a value now.
9193 	const Expression_list* args = this->args();
9194 	go_assert(args != NULL && args->size() == 1);
9195 	Expression* arg = args->front();
9196 	Type *empty =
9197 	  Type::make_empty_interface_type(Linemap::predeclared_location());
9198 
9199 	Expression* nil = Expression::make_nil(location);
9200 	nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9201 
9202 	// We need to handle a deferred call to recover specially,
9203 	// because it changes whether it can recover a panic or not.
9204 	// See test7 in test/recover1.go.
9205         Expression* recover = Runtime::make_call((this->is_deferred()
9206                                                   ? Runtime::DEFERREDRECOVER
9207                                                   : Runtime::GORECOVER),
9208                                                  location, 0);
9209         Expression* cond =
9210             Expression::make_conditional(arg, recover, nil, location);
9211         return cond->get_backend(context);
9212       }
9213 
9214     case BUILTIN_CLOSE:
9215       {
9216 	const Expression_list* args = this->args();
9217 	go_assert(args != NULL && args->size() == 1);
9218 	Expression* arg = args->front();
9219         Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9220 					       1, arg);
9221         return close->get_backend(context);
9222       }
9223 
9224     case BUILTIN_SIZEOF:
9225     case BUILTIN_OFFSETOF:
9226     case BUILTIN_ALIGNOF:
9227       {
9228 	Numeric_constant nc;
9229 	unsigned long val;
9230 	if (!this->numeric_constant_value(&nc)
9231 	    || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9232 	  {
9233 	    go_assert(saw_errors());
9234 	    return context->backend()->error_expression();
9235 	  }
9236 	Type* uintptr_type = Type::lookup_integer_type("uintptr");
9237         mpz_t ival;
9238         nc.get_int(&ival);
9239         Expression* int_cst =
9240             Expression::make_integer_z(&ival, uintptr_type, location);
9241         mpz_clear(ival);
9242         return int_cst->get_backend(context);
9243       }
9244 
9245     case BUILTIN_COPY:
9246       {
9247 	const Expression_list* args = this->args();
9248 	go_assert(args != NULL && args->size() == 2);
9249 	Expression* arg1 = args->front();
9250 	Expression* arg2 = args->back();
9251 
9252 	Type* arg1_type = arg1->type();
9253 	Array_type* at = arg1_type->array_type();
9254 	go_assert(arg1->is_variable());
9255 
9256 	Expression* call;
9257 
9258 	Type* arg2_type = arg2->type();
9259         go_assert(arg2->is_variable());
9260 	if (arg2_type->is_string_type())
9261 	  call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9262 				    2, arg1, arg2);
9263 	else
9264 	  {
9265 	    Type* et = at->element_type();
9266 	    if (et->has_pointer())
9267 	      {
9268 		Expression* td = Expression::make_type_descriptor(et,
9269 								  location);
9270 		call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9271 					  3, td, arg1, arg2);
9272 	      }
9273 	    else
9274 	      {
9275 		Expression* sz = Expression::make_type_info(et,
9276 							    TYPE_INFO_SIZE);
9277 		call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9278 					  arg1, arg2, sz);
9279 	      }
9280 	  }
9281 
9282 	return call->get_backend(context);
9283       }
9284 
9285     case BUILTIN_APPEND:
9286       // Handled in Builtin_call_expression::flatten_append.
9287       go_unreachable();
9288 
9289     case BUILTIN_REAL:
9290     case BUILTIN_IMAG:
9291       {
9292 	const Expression_list* args = this->args();
9293 	go_assert(args != NULL && args->size() == 1);
9294 
9295         Bexpression* ret;
9296         Bexpression* bcomplex = args->front()->get_backend(context);
9297         if (this->code_ == BUILTIN_REAL)
9298           ret = gogo->backend()->real_part_expression(bcomplex, location);
9299         else
9300           ret = gogo->backend()->imag_part_expression(bcomplex, location);
9301         return ret;
9302       }
9303 
9304     case BUILTIN_COMPLEX:
9305       {
9306 	const Expression_list* args = this->args();
9307 	go_assert(args != NULL && args->size() == 2);
9308 	Bexpression* breal = args->front()->get_backend(context);
9309 	Bexpression* bimag = args->back()->get_backend(context);
9310 	return gogo->backend()->complex_expression(breal, bimag, location);
9311       }
9312 
9313     default:
9314       go_unreachable();
9315     }
9316 }
9317 
9318 // We have to support exporting a builtin call expression, because
9319 // code can set a constant to the result of a builtin expression.
9320 
9321 void
do_export(Export * exp) const9322 Builtin_call_expression::do_export(Export* exp) const
9323 {
9324   Numeric_constant nc;
9325   if (!this->numeric_constant_value(&nc))
9326     {
9327       go_error_at(this->location(), "value is not constant");
9328       return;
9329     }
9330 
9331   if (nc.is_int())
9332     {
9333       mpz_t val;
9334       nc.get_int(&val);
9335       Integer_expression::export_integer(exp, val);
9336       mpz_clear(val);
9337     }
9338   else if (nc.is_float())
9339     {
9340       mpfr_t fval;
9341       nc.get_float(&fval);
9342       Float_expression::export_float(exp, fval);
9343       mpfr_clear(fval);
9344     }
9345   else if (nc.is_complex())
9346     {
9347       mpc_t cval;
9348       nc.get_complex(&cval);
9349       Complex_expression::export_complex(exp, cval);
9350       mpc_clear(cval);
9351     }
9352   else
9353     go_unreachable();
9354 
9355   // A trailing space lets us reliably identify the end of the number.
9356   exp->write_c_string(" ");
9357 }
9358 
9359 // Class Call_expression.
9360 
9361 // A Go function can be viewed in a couple of different ways.  The
9362 // code of a Go function becomes a backend function with parameters
9363 // whose types are simply the backend representation of the Go types.
9364 // If there are multiple results, they are returned as a backend
9365 // struct.
9366 
9367 // However, when Go code refers to a function other than simply
9368 // calling it, the backend type of that function is actually a struct.
9369 // The first field of the struct points to the Go function code
9370 // (sometimes a wrapper as described below).  The remaining fields
9371 // hold addresses of closed-over variables.  This struct is called a
9372 // closure.
9373 
9374 // There are a few cases to consider.
9375 
9376 // A direct function call of a known function in package scope.  In
9377 // this case there are no closed-over variables, and we know the name
9378 // of the function code.  We can simply produce a backend call to the
9379 // function directly, and not worry about the closure.
9380 
9381 // A direct function call of a known function literal.  In this case
9382 // we know the function code and we know the closure.  We generate the
9383 // function code such that it expects an additional final argument of
9384 // the closure type.  We pass the closure as the last argument, after
9385 // the other arguments.
9386 
9387 // An indirect function call.  In this case we have a closure.  We
9388 // load the pointer to the function code from the first field of the
9389 // closure.  We pass the address of the closure as the last argument.
9390 
9391 // A call to a method of an interface.  Type methods are always at
9392 // package scope, so we call the function directly, and don't worry
9393 // about the closure.
9394 
9395 // This means that for a function at package scope we have two cases.
9396 // One is the direct call, which has no closure.  The other is the
9397 // indirect call, which does have a closure.  We can't simply ignore
9398 // the closure, even though it is the last argument, because that will
9399 // fail on targets where the function pops its arguments.  So when
9400 // generating a closure for a package-scope function we set the
9401 // function code pointer in the closure to point to a wrapper
9402 // function.  This wrapper function accepts a final argument that
9403 // points to the closure, ignores it, and calls the real function as a
9404 // direct function call.  This wrapper will normally be efficient, and
9405 // can often simply be a tail call to the real function.
9406 
9407 // We don't use GCC's static chain pointer because 1) we don't need
9408 // it; 2) GCC only permits using a static chain to call a known
9409 // function, so we can't use it for an indirect call anyhow.  Since we
9410 // can't use it for an indirect call, we may as well not worry about
9411 // using it for a direct call either.
9412 
9413 // We pass the closure last rather than first because it means that
9414 // the function wrapper we put into a closure for a package-scope
9415 // function can normally just be a tail call to the real function.
9416 
9417 // For method expressions we generate a wrapper that loads the
9418 // receiver from the closure and then calls the method.  This
9419 // unfortunately forces reshuffling the arguments, since there is a
9420 // new first argument, but we can't avoid reshuffling either for
9421 // method expressions or for indirect calls of package-scope
9422 // functions, and since the latter are more common we reshuffle for
9423 // method expressions.
9424 
9425 // Note that the Go code retains the Go types.  The extra final
9426 // argument only appears when we convert to the backend
9427 // representation.
9428 
9429 // Traversal.
9430 
9431 int
do_traverse(Traverse * traverse)9432 Call_expression::do_traverse(Traverse* traverse)
9433 {
9434   // If we are calling a function in a different package that returns
9435   // an unnamed type, this may be the only chance we get to traverse
9436   // that type.  We don't traverse this->type_ because it may be a
9437   // Call_multiple_result_type that will just lead back here.
9438   if (this->type_ != NULL && !this->type_->is_error_type())
9439     {
9440       Function_type *fntype = this->get_function_type();
9441       if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9442 	return TRAVERSE_EXIT;
9443     }
9444   if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9445     return TRAVERSE_EXIT;
9446   if (this->args_ != NULL)
9447     {
9448       if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9449 	return TRAVERSE_EXIT;
9450     }
9451   return TRAVERSE_CONTINUE;
9452 }
9453 
9454 // Lower a call statement.
9455 
9456 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)9457 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9458 			  Statement_inserter* inserter, int)
9459 {
9460   Location loc = this->location();
9461 
9462   // A type cast can look like a function call.
9463   if (this->fn_->is_type_expression()
9464       && this->args_ != NULL
9465       && this->args_->size() == 1)
9466     return Expression::make_cast(this->fn_->type(), this->args_->front(),
9467 				 loc);
9468 
9469   // Because do_type will return an error type and thus prevent future
9470   // errors, check for that case now to ensure that the error gets
9471   // reported.
9472   Function_type* fntype = this->get_function_type();
9473   if (fntype == NULL)
9474     {
9475       if (!this->fn_->type()->is_error())
9476 	this->report_error(_("expected function"));
9477       this->set_is_error();
9478       return this;
9479     }
9480 
9481   // Handle an argument which is a call to a function which returns
9482   // multiple results.
9483   if (this->args_ != NULL
9484       && this->args_->size() == 1
9485       && this->args_->front()->call_expression() != NULL)
9486     {
9487       size_t rc = this->args_->front()->call_expression()->result_count();
9488       if (rc > 1
9489 	  && ((fntype->parameters() != NULL
9490                && (fntype->parameters()->size() == rc
9491                    || (fntype->is_varargs()
9492                        && fntype->parameters()->size() - 1 <= rc)))
9493               || fntype->is_builtin()))
9494 	{
9495 	  Call_expression* call = this->args_->front()->call_expression();
9496 	  call->set_is_multi_value_arg();
9497 	  if (this->is_varargs_)
9498 	    {
9499 	      // It is not clear which result of a multiple result call
9500 	      // the ellipsis operator should be applied to.  If we unpack the
9501 	      // the call into its individual results here, the ellipsis will be
9502 	      // applied to the last result.
9503 	      go_error_at(call->location(),
9504 			  _("multiple-value argument in single-value context"));
9505 	      return Expression::make_error(call->location());
9506 	    }
9507 
9508 	  Expression_list* args = new Expression_list;
9509 	  for (size_t i = 0; i < rc; ++i)
9510 	    args->push_back(Expression::make_call_result(call, i));
9511 	  // We can't return a new call expression here, because this
9512 	  // one may be referenced by Call_result expressions.  We
9513 	  // also can't delete the old arguments, because we may still
9514 	  // traverse them somewhere up the call stack.  FIXME.
9515 	  this->args_ = args;
9516 	}
9517     }
9518 
9519   // Recognize a call to a builtin function.
9520   if (fntype->is_builtin())
9521     return new Builtin_call_expression(gogo, this->fn_, this->args_,
9522 				       this->is_varargs_, loc);
9523 
9524   // If this call returns multiple results, create a temporary
9525   // variable to hold them.
9526   if (this->result_count() > 1 && this->call_temp_ == NULL)
9527     {
9528       Struct_field_list* sfl = new Struct_field_list();
9529       Function_type* fntype = this->get_function_type();
9530       const Typed_identifier_list* results = fntype->results();
9531       Location loc = this->location();
9532 
9533       int i = 0;
9534       char buf[20];
9535       for (Typed_identifier_list::const_iterator p = results->begin();
9536            p != results->end();
9537            ++p, ++i)
9538         {
9539           snprintf(buf, sizeof buf, "res%d", i);
9540           sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9541         }
9542 
9543       Struct_type* st = Type::make_struct_type(sfl, loc);
9544       st->set_is_struct_incomparable();
9545       this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9546       inserter->insert(this->call_temp_);
9547     }
9548 
9549   // Handle a call to a varargs function by packaging up the extra
9550   // parameters.
9551   if (fntype->is_varargs())
9552     {
9553       const Typed_identifier_list* parameters = fntype->parameters();
9554       go_assert(parameters != NULL && !parameters->empty());
9555       Type* varargs_type = parameters->back().type();
9556       this->lower_varargs(gogo, function, inserter, varargs_type,
9557 			  parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9558     }
9559 
9560   // If this is call to a method, call the method directly passing the
9561   // object as the first parameter.
9562   Bound_method_expression* bme = this->fn_->bound_method_expression();
9563   if (bme != NULL)
9564     {
9565       Named_object* methodfn = bme->function();
9566       Expression* first_arg = bme->first_argument();
9567 
9568       // We always pass a pointer when calling a method.
9569       if (first_arg->type()->points_to() == NULL
9570 	  && !first_arg->type()->is_error())
9571 	{
9572 	  first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9573 	  // We may need to create a temporary variable so that we can
9574 	  // take the address.  We can't do that here because it will
9575 	  // mess up the order of evaluation.
9576 	  Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9577 	  ue->set_create_temp();
9578 	}
9579 
9580       // If we are calling a method which was inherited from an
9581       // embedded struct, and the method did not get a stub, then the
9582       // first type may be wrong.
9583       Type* fatype = bme->first_argument_type();
9584       if (fatype != NULL)
9585 	{
9586 	  if (fatype->points_to() == NULL)
9587 	    fatype = Type::make_pointer_type(fatype);
9588 	  first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9589 	}
9590 
9591       Expression_list* new_args = new Expression_list();
9592       new_args->push_back(first_arg);
9593       if (this->args_ != NULL)
9594 	{
9595 	  for (Expression_list::const_iterator p = this->args_->begin();
9596 	       p != this->args_->end();
9597 	       ++p)
9598 	    new_args->push_back(*p);
9599 	}
9600 
9601       // We have to change in place because this structure may be
9602       // referenced by Call_result_expressions.  We can't delete the
9603       // old arguments, because we may be traversing them up in some
9604       // caller.  FIXME.
9605       this->args_ = new_args;
9606       this->fn_ = Expression::make_func_reference(methodfn, NULL,
9607 						  bme->location());
9608     }
9609 
9610   // Handle a couple of special runtime functions.  In the runtime
9611   // package, getcallerpc returns the PC of the caller, and
9612   // getcallersp returns the frame pointer of the caller.  Implement
9613   // these by turning them into calls to GCC builtin functions.  We
9614   // could implement them in normal code, but then we would have to
9615   // explicitly unwind the stack.  These functions are intended to be
9616   // efficient.  Note that this technique obviously only works for
9617   // direct calls, but that is the only way they are used.
9618   if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9619     {
9620       Func_expression* fe = this->fn_->func_expression();
9621       if (fe != NULL
9622 	  && fe->named_object()->is_function_declaration()
9623 	  && fe->named_object()->package() == NULL)
9624 	{
9625 	  std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9626 	  if ((this->args_ == NULL || this->args_->size() == 0)
9627 	      && n == "getcallerpc")
9628 	    {
9629 	      static Named_object* builtin_return_address;
9630 	      return this->lower_to_builtin(&builtin_return_address,
9631 					    "__builtin_return_address",
9632 					    0);
9633 	    }
9634 	  else if (this->args_ != NULL
9635 		   && this->args_->size() == 1
9636 		   && n == "getcallersp")
9637 	    {
9638 	      // The actual argument to getcallersp is always the
9639 	      // address of a parameter; we don't need that for the
9640 	      // GCC builtin function, so we just ignore it.
9641 	      static Named_object* builtin_frame_address;
9642 	      return this->lower_to_builtin(&builtin_frame_address,
9643 					    "__builtin_frame_address",
9644 					    1);
9645 	    }
9646 	}
9647     }
9648 
9649   return this;
9650 }
9651 
9652 // Lower a call to a varargs function.  FUNCTION is the function in
9653 // which the call occurs--it's not the function we are calling.
9654 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9655 // PARAM_COUNT is the number of parameters of the function we are
9656 // calling; the last of these parameters will be the varargs
9657 // parameter.
9658 
9659 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count,Slice_storage_escape_disp escape_disp)9660 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9661 			       Statement_inserter* inserter,
9662 			       Type* varargs_type, size_t param_count,
9663                                Slice_storage_escape_disp escape_disp)
9664 {
9665   if (this->varargs_are_lowered_)
9666     return;
9667 
9668   Location loc = this->location();
9669 
9670   go_assert(param_count > 0);
9671   go_assert(varargs_type->is_slice_type());
9672 
9673   size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9674   if (arg_count < param_count - 1)
9675     {
9676       // Not enough arguments; will be caught in check_types.
9677       return;
9678     }
9679 
9680   Expression_list* old_args = this->args_;
9681   Expression_list* new_args = new Expression_list();
9682   bool push_empty_arg = false;
9683   if (old_args == NULL || old_args->empty())
9684     {
9685       go_assert(param_count == 1);
9686       push_empty_arg = true;
9687     }
9688   else
9689     {
9690       Expression_list::const_iterator pa;
9691       int i = 1;
9692       for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9693 	{
9694 	  if (static_cast<size_t>(i) == param_count)
9695 	    break;
9696 	  new_args->push_back(*pa);
9697 	}
9698 
9699       // We have reached the varargs parameter.
9700 
9701       bool issued_error = false;
9702       if (pa == old_args->end())
9703 	push_empty_arg = true;
9704       else if (pa + 1 == old_args->end() && this->is_varargs_)
9705 	new_args->push_back(*pa);
9706       else if (this->is_varargs_)
9707 	{
9708 	  if ((*pa)->type()->is_slice_type())
9709 	    this->report_error(_("too many arguments"));
9710 	  else
9711 	    {
9712 	      go_error_at(this->location(),
9713 			  _("invalid use of %<...%> with non-slice"));
9714 	      this->set_is_error();
9715 	    }
9716 	  return;
9717 	}
9718       else
9719 	{
9720 	  Type* element_type = varargs_type->array_type()->element_type();
9721 	  Expression_list* vals = new Expression_list;
9722 	  for (; pa != old_args->end(); ++pa, ++i)
9723 	    {
9724 	      // Check types here so that we get a better message.
9725 	      Type* patype = (*pa)->type();
9726 	      Location paloc = (*pa)->location();
9727 	      if (!this->check_argument_type(i, element_type, patype,
9728 					     paloc, issued_error))
9729 		continue;
9730 	      vals->push_back(*pa);
9731 	    }
9732 	  Slice_construction_expression* sce =
9733 	    Expression::make_slice_composite_literal(varargs_type, vals, loc);
9734 	  if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9735 	      sce->set_storage_does_not_escape();
9736           Expression* val = sce;
9737 	  gogo->lower_expression(function, inserter, &val);
9738 	  new_args->push_back(val);
9739 	}
9740     }
9741 
9742   if (push_empty_arg)
9743     new_args->push_back(Expression::make_nil(loc));
9744 
9745   // We can't return a new call expression here, because this one may
9746   // be referenced by Call_result expressions.  FIXME.  We can't
9747   // delete OLD_ARGS because we may have both a Call_expression and a
9748   // Builtin_call_expression which refer to them.  FIXME.
9749   this->args_ = new_args;
9750   this->varargs_are_lowered_ = true;
9751 }
9752 
9753 // Return a call to __builtin_return_address or __builtin_frame_address.
9754 
9755 Expression*
lower_to_builtin(Named_object ** pno,const char * name,int arg)9756 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9757 				  int arg)
9758 {
9759   if (*pno == NULL)
9760     *pno = Gogo::declare_builtin_rf_address(name);
9761 
9762   Location loc = this->location();
9763 
9764   Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9765   Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9766   Expression_list *args = new Expression_list();
9767   args->push_back(a);
9768   Expression* call = Expression::make_call(fn, args, false, loc);
9769 
9770   // The builtin functions return void*, but the Go functions return uintptr.
9771   Type* uintptr_type = Type::lookup_integer_type("uintptr");
9772   return Expression::make_cast(uintptr_type, call, loc);
9773 }
9774 
9775 // Flatten a call with multiple results into a temporary.
9776 
9777 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)9778 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9779 			    Statement_inserter* inserter)
9780 {
9781   if (this->is_erroneous_call())
9782     {
9783       go_assert(saw_errors());
9784       return Expression::make_error(this->location());
9785     }
9786 
9787   if (this->is_flattened_)
9788     return this;
9789   this->is_flattened_ = true;
9790 
9791   // Add temporary variables for all arguments that require type
9792   // conversion.
9793   Function_type* fntype = this->get_function_type();
9794   if (fntype == NULL)
9795     {
9796       go_assert(saw_errors());
9797       return this;
9798     }
9799   if (this->args_ != NULL && !this->args_->empty()
9800       && fntype->parameters() != NULL && !fntype->parameters()->empty())
9801     {
9802       bool is_interface_method =
9803 	this->fn_->interface_field_reference_expression() != NULL;
9804 
9805       Expression_list *args = new Expression_list();
9806       Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9807       Expression_list::const_iterator pa = this->args_->begin();
9808       if (!is_interface_method && fntype->is_method())
9809 	{
9810 	  // The receiver argument.
9811 	  args->push_back(*pa);
9812 	  ++pa;
9813 	}
9814       for (; pa != this->args_->end(); ++pa, ++pp)
9815 	{
9816 	  go_assert(pp != fntype->parameters()->end());
9817 	  if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9818 	    args->push_back(*pa);
9819 	  else
9820 	    {
9821 	      Location loc = (*pa)->location();
9822 	      Expression* arg = *pa;
9823 	      if (!arg->is_variable())
9824 		{
9825 		  Temporary_statement *temp =
9826 		    Statement::make_temporary(NULL, arg, loc);
9827 		  inserter->insert(temp);
9828 		  arg = Expression::make_temporary_reference(temp, loc);
9829 		}
9830 	      arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9831 						       loc);
9832 	      args->push_back(arg);
9833 	    }
9834 	}
9835       delete this->args_;
9836       this->args_ = args;
9837     }
9838 
9839   return this;
9840 }
9841 
9842 // Get the function type.  This can return NULL in error cases.
9843 
9844 Function_type*
get_function_type() const9845 Call_expression::get_function_type() const
9846 {
9847   return this->fn_->type()->function_type();
9848 }
9849 
9850 // Return the number of values which this call will return.
9851 
9852 size_t
result_count() const9853 Call_expression::result_count() const
9854 {
9855   const Function_type* fntype = this->get_function_type();
9856   if (fntype == NULL)
9857     return 0;
9858   if (fntype->results() == NULL)
9859     return 0;
9860   return fntype->results()->size();
9861 }
9862 
9863 // Return the temporary that holds the result for a call with multiple
9864 // results.
9865 
9866 Temporary_statement*
results() const9867 Call_expression::results() const
9868 {
9869   if (this->call_temp_ == NULL)
9870     {
9871       go_assert(saw_errors());
9872       return NULL;
9873     }
9874   return this->call_temp_;
9875 }
9876 
9877 // Set the number of results expected from a call expression.
9878 
9879 void
set_expected_result_count(size_t count)9880 Call_expression::set_expected_result_count(size_t count)
9881 {
9882   go_assert(this->expected_result_count_ == 0);
9883   this->expected_result_count_ = count;
9884 }
9885 
9886 // Return whether this is a call to the predeclared function recover.
9887 
9888 bool
is_recover_call() const9889 Call_expression::is_recover_call() const
9890 {
9891   return this->do_is_recover_call();
9892 }
9893 
9894 // Set the argument to the recover function.
9895 
9896 void
set_recover_arg(Expression * arg)9897 Call_expression::set_recover_arg(Expression* arg)
9898 {
9899   this->do_set_recover_arg(arg);
9900 }
9901 
9902 // Virtual functions also implemented by Builtin_call_expression.
9903 
9904 bool
do_is_recover_call() const9905 Call_expression::do_is_recover_call() const
9906 {
9907   return false;
9908 }
9909 
9910 void
do_set_recover_arg(Expression *)9911 Call_expression::do_set_recover_arg(Expression*)
9912 {
9913   go_unreachable();
9914 }
9915 
9916 // We have found an error with this call expression; return true if
9917 // we should report it.
9918 
9919 bool
issue_error()9920 Call_expression::issue_error()
9921 {
9922   if (this->issued_error_)
9923     return false;
9924   else
9925     {
9926       this->issued_error_ = true;
9927       return true;
9928     }
9929 }
9930 
9931 // Whether or not this call contains errors, either in the call or the
9932 // arguments to the call.
9933 
9934 bool
is_erroneous_call()9935 Call_expression::is_erroneous_call()
9936 {
9937   if (this->is_error_expression() || this->fn()->is_error_expression())
9938     return true;
9939 
9940   if (this->args() == NULL)
9941     return false;
9942   for (Expression_list::iterator pa = this->args()->begin();
9943        pa != this->args()->end();
9944        ++pa)
9945     {
9946       if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9947         return true;
9948     }
9949   return false;
9950 }
9951 
9952 // Get the type.
9953 
9954 Type*
do_type()9955 Call_expression::do_type()
9956 {
9957   if (this->type_ != NULL)
9958     return this->type_;
9959 
9960   Type* ret;
9961   Function_type* fntype = this->get_function_type();
9962   if (fntype == NULL)
9963     return Type::make_error_type();
9964 
9965   const Typed_identifier_list* results = fntype->results();
9966   if (results == NULL)
9967     ret = Type::make_void_type();
9968   else if (results->size() == 1)
9969     ret = results->begin()->type();
9970   else
9971     ret = Type::make_call_multiple_result_type(this);
9972 
9973   this->type_ = ret;
9974 
9975   return this->type_;
9976 }
9977 
9978 // Determine types for a call expression.  We can use the function
9979 // parameter types to set the types of the arguments.
9980 
9981 void
do_determine_type(const Type_context *)9982 Call_expression::do_determine_type(const Type_context*)
9983 {
9984   if (!this->determining_types())
9985     return;
9986 
9987   this->fn_->determine_type_no_context();
9988   Function_type* fntype = this->get_function_type();
9989   const Typed_identifier_list* parameters = NULL;
9990   if (fntype != NULL)
9991     parameters = fntype->parameters();
9992   if (this->args_ != NULL)
9993     {
9994       Typed_identifier_list::const_iterator pt;
9995       if (parameters != NULL)
9996 	pt = parameters->begin();
9997       bool first = true;
9998       for (Expression_list::const_iterator pa = this->args_->begin();
9999 	   pa != this->args_->end();
10000 	   ++pa)
10001 	{
10002 	  if (first)
10003 	    {
10004 	      first = false;
10005 	      // If this is a method, the first argument is the
10006 	      // receiver.
10007 	      if (fntype != NULL && fntype->is_method())
10008 		{
10009 		  Type* rtype = fntype->receiver()->type();
10010 		  // The receiver is always passed as a pointer.
10011 		  if (rtype->points_to() == NULL)
10012 		    rtype = Type::make_pointer_type(rtype);
10013 		  Type_context subcontext(rtype, false);
10014 		  (*pa)->determine_type(&subcontext);
10015 		  continue;
10016 		}
10017 	    }
10018 
10019 	  if (parameters != NULL && pt != parameters->end())
10020 	    {
10021 	      Type_context subcontext(pt->type(), false);
10022 	      (*pa)->determine_type(&subcontext);
10023 	      ++pt;
10024 	    }
10025 	  else
10026 	    (*pa)->determine_type_no_context();
10027 	}
10028     }
10029 }
10030 
10031 // Called when determining types for a Call_expression.  Return true
10032 // if we should go ahead, false if they have already been determined.
10033 
10034 bool
determining_types()10035 Call_expression::determining_types()
10036 {
10037   if (this->types_are_determined_)
10038     return false;
10039   else
10040     {
10041       this->types_are_determined_ = true;
10042       return true;
10043     }
10044 }
10045 
10046 // Check types for parameter I.
10047 
10048 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)10049 Call_expression::check_argument_type(int i, const Type* parameter_type,
10050 				     const Type* argument_type,
10051 				     Location argument_location,
10052 				     bool issued_error)
10053 {
10054   std::string reason;
10055   if (!Type::are_assignable(parameter_type, argument_type, &reason))
10056     {
10057       if (!issued_error)
10058 	{
10059 	  if (reason.empty())
10060 	    go_error_at(argument_location, "argument %d has incompatible type", i);
10061 	  else
10062 	    go_error_at(argument_location,
10063 			"argument %d has incompatible type (%s)",
10064 			i, reason.c_str());
10065 	}
10066       this->set_is_error();
10067       return false;
10068     }
10069   return true;
10070 }
10071 
10072 // Check types.
10073 
10074 void
do_check_types(Gogo *)10075 Call_expression::do_check_types(Gogo*)
10076 {
10077   if (this->classification() == EXPRESSION_ERROR)
10078     return;
10079 
10080   Function_type* fntype = this->get_function_type();
10081   if (fntype == NULL)
10082     {
10083       if (!this->fn_->type()->is_error())
10084 	this->report_error(_("expected function"));
10085       return;
10086     }
10087 
10088   if (this->expected_result_count_ != 0
10089       && this->expected_result_count_ != this->result_count())
10090     {
10091       if (this->issue_error())
10092 	this->report_error(_("function result count mismatch"));
10093       this->set_is_error();
10094       return;
10095     }
10096 
10097   bool is_method = fntype->is_method();
10098   if (is_method)
10099     {
10100       go_assert(this->args_ != NULL && !this->args_->empty());
10101       Type* rtype = fntype->receiver()->type();
10102       Expression* first_arg = this->args_->front();
10103       // We dereference the values since receivers are always passed
10104       // as pointers.
10105       std::string reason;
10106       if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10107 				&reason))
10108 	{
10109 	  if (reason.empty())
10110 	    this->report_error(_("incompatible type for receiver"));
10111 	  else
10112 	    {
10113 	      go_error_at(this->location(),
10114                           "incompatible type for receiver (%s)",
10115                           reason.c_str());
10116 	      this->set_is_error();
10117 	    }
10118 	}
10119     }
10120 
10121   // Note that varargs was handled by the lower_varargs() method, so
10122   // we don't have to worry about it here unless something is wrong.
10123   if (this->is_varargs_ && !this->varargs_are_lowered_)
10124     {
10125       if (!fntype->is_varargs())
10126 	{
10127 	  go_error_at(this->location(),
10128                       _("invalid use of %<...%> calling non-variadic function"));
10129 	  this->set_is_error();
10130 	  return;
10131 	}
10132     }
10133 
10134   const Typed_identifier_list* parameters = fntype->parameters();
10135   if (this->args_ == NULL || this->args_->size() == 0)
10136     {
10137       if (parameters != NULL && !parameters->empty())
10138 	this->report_error(_("not enough arguments"));
10139     }
10140   else if (parameters == NULL)
10141     {
10142       if (!is_method || this->args_->size() > 1)
10143 	this->report_error(_("too many arguments"));
10144     }
10145   else if (this->args_->size() == 1
10146 	   && this->args_->front()->call_expression() != NULL
10147 	   && this->args_->front()->call_expression()->result_count() > 1)
10148     {
10149       // This is F(G()) when G returns more than one result.  If the
10150       // results can be matched to parameters, it would have been
10151       // lowered in do_lower.  If we get here we know there is a
10152       // mismatch.
10153       if (this->args_->front()->call_expression()->result_count()
10154 	  < parameters->size())
10155 	this->report_error(_("not enough arguments"));
10156       else
10157 	this->report_error(_("too many arguments"));
10158     }
10159   else
10160     {
10161       int i = 0;
10162       Expression_list::const_iterator pa = this->args_->begin();
10163       if (is_method)
10164 	++pa;
10165       for (Typed_identifier_list::const_iterator pt = parameters->begin();
10166 	   pt != parameters->end();
10167 	   ++pt, ++pa, ++i)
10168 	{
10169 	  if (pa == this->args_->end())
10170 	    {
10171 	      this->report_error(_("not enough arguments"));
10172 	      return;
10173 	    }
10174 	  this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10175 				    (*pa)->location(), false);
10176 	}
10177       if (pa != this->args_->end())
10178 	this->report_error(_("too many arguments"));
10179     }
10180 }
10181 
10182 Expression*
do_copy()10183 Call_expression::do_copy()
10184 {
10185   Call_expression* call =
10186     Expression::make_call(this->fn_->copy(),
10187 			  (this->args_ == NULL
10188 			   ? NULL
10189 			   : this->args_->copy()),
10190 			  this->is_varargs_, this->location());
10191 
10192   if (this->varargs_are_lowered_)
10193     call->set_varargs_are_lowered();
10194   return call;
10195 }
10196 
10197 // Return whether we have to use a temporary variable to ensure that
10198 // we evaluate this call expression in order.  If the call returns no
10199 // results then it will inevitably be executed last.
10200 
10201 bool
do_must_eval_in_order() const10202 Call_expression::do_must_eval_in_order() const
10203 {
10204   return this->result_count() > 0;
10205 }
10206 
10207 // Get the function and the first argument to use when calling an
10208 // interface method.
10209 
10210 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr,Location location)10211 Call_expression::interface_method_function(
10212     Interface_field_reference_expression* interface_method,
10213     Expression** first_arg_ptr,
10214     Location location)
10215 {
10216   Expression* object = interface_method->get_underlying_object();
10217   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10218   *first_arg_ptr =
10219       Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10220   return interface_method->get_function();
10221 }
10222 
10223 // Build the call expression.
10224 
10225 Bexpression*
do_get_backend(Translate_context * context)10226 Call_expression::do_get_backend(Translate_context* context)
10227 {
10228   Location location = this->location();
10229 
10230   if (this->call_ != NULL)
10231     {
10232       // If the call returns multiple results, make a new reference to
10233       // the temporary.
10234       if (this->call_temp_ != NULL)
10235 	{
10236 	  Expression* ref =
10237 	    Expression::make_temporary_reference(this->call_temp_, location);
10238 	  return ref->get_backend(context);
10239 	}
10240 
10241       return this->call_;
10242     }
10243 
10244   Function_type* fntype = this->get_function_type();
10245   if (fntype == NULL)
10246     return context->backend()->error_expression();
10247 
10248   if (this->fn_->is_error_expression())
10249     return context->backend()->error_expression();
10250 
10251   Gogo* gogo = context->gogo();
10252 
10253   Func_expression* func = this->fn_->func_expression();
10254   Interface_field_reference_expression* interface_method =
10255     this->fn_->interface_field_reference_expression();
10256   const bool has_closure = func != NULL && func->closure() != NULL;
10257   const bool is_interface_method = interface_method != NULL;
10258 
10259   bool has_closure_arg;
10260   if (has_closure)
10261     has_closure_arg = true;
10262   else if (func != NULL)
10263     has_closure_arg = false;
10264   else if (is_interface_method)
10265     has_closure_arg = false;
10266   else
10267     has_closure_arg = true;
10268 
10269   int nargs;
10270   std::vector<Bexpression*> fn_args;
10271   if (this->args_ == NULL || this->args_->empty())
10272     {
10273       nargs = is_interface_method ? 1 : 0;
10274       if (nargs > 0)
10275         fn_args.resize(1);
10276     }
10277   else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10278     {
10279       // Passing a receiver parameter.
10280       go_assert(!is_interface_method
10281 		&& fntype->is_method()
10282 		&& this->args_->size() == 1);
10283       nargs = 1;
10284       fn_args.resize(1);
10285       fn_args[0] = this->args_->front()->get_backend(context);
10286     }
10287   else
10288     {
10289       const Typed_identifier_list* params = fntype->parameters();
10290 
10291       nargs = this->args_->size();
10292       int i = is_interface_method ? 1 : 0;
10293       nargs += i;
10294       fn_args.resize(nargs);
10295 
10296       Typed_identifier_list::const_iterator pp = params->begin();
10297       Expression_list::const_iterator pe = this->args_->begin();
10298       if (!is_interface_method && fntype->is_method())
10299 	{
10300           fn_args[i] = (*pe)->get_backend(context);
10301 	  ++pe;
10302 	  ++i;
10303 	}
10304       for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10305 	{
10306 	  go_assert(pp != params->end());
10307           Expression* arg =
10308               Expression::convert_for_assignment(gogo, pp->type(), *pe,
10309                                                  location);
10310           fn_args[i] = arg->get_backend(context);
10311 	}
10312       go_assert(pp == params->end());
10313       go_assert(i == nargs);
10314     }
10315 
10316   Expression* fn;
10317   Expression* closure = NULL;
10318   if (func != NULL)
10319     {
10320       Named_object* no = func->named_object();
10321       fn = Expression::make_func_code_reference(no, location);
10322       if (has_closure)
10323         closure = func->closure();
10324     }
10325   else if (!is_interface_method)
10326     {
10327       closure = this->fn_;
10328 
10329       // The backend representation of this function type is a pointer
10330       // to a struct whose first field is the actual function to call.
10331       Type* pfntype =
10332           Type::make_pointer_type(
10333               Type::make_pointer_type(Type::make_void_type()));
10334       fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10335       fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
10336     }
10337   else
10338     {
10339       Expression* first_arg;
10340       fn = this->interface_method_function(interface_method, &first_arg,
10341                                            location);
10342       fn_args[0] = first_arg->get_backend(context);
10343     }
10344 
10345   Bexpression* bclosure = NULL;
10346   if (has_closure_arg)
10347     bclosure = closure->get_backend(context);
10348   else
10349     go_assert(closure == NULL);
10350 
10351   Bexpression* bfn = fn->get_backend(context);
10352 
10353   // When not calling a named function directly, use a type conversion
10354   // in case the type of the function is a recursive type which refers
10355   // to itself.  We don't do this for an interface method because 1)
10356   // an interface method never refers to itself, so we always have a
10357   // function type here; 2) we pass an extra first argument to an
10358   // interface method, so fntype is not correct.
10359   if (func == NULL && !is_interface_method)
10360     {
10361       Btype* bft = fntype->get_backend_fntype(gogo);
10362       bfn = gogo->backend()->convert_expression(bft, bfn, location);
10363     }
10364 
10365   Bfunction* bfunction = NULL;
10366   if (context->function())
10367     bfunction = context->function()->func_value()->get_decl();
10368   Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10369                                                        fn_args, bclosure,
10370                                                        location);
10371 
10372   if (this->call_temp_ != NULL)
10373     {
10374       // This case occurs when the call returns multiple results.
10375 
10376       Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10377 							     location);
10378       Bexpression* bref = ref->get_backend(context);
10379       Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10380 								bref, call,
10381 								location);
10382 
10383       ref = Expression::make_temporary_reference(this->call_temp_, location);
10384       this->call_ = ref->get_backend(context);
10385 
10386       return gogo->backend()->compound_expression(bassn, this->call_,
10387 						  location);
10388     }
10389 
10390   this->call_ = call;
10391   return this->call_;
10392 }
10393 
10394 // Dump ast representation for a call expressin.
10395 
10396 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10397 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10398 {
10399   this->fn_->dump_expression(ast_dump_context);
10400   ast_dump_context->ostream() << "(";
10401   if (args_ != NULL)
10402     ast_dump_context->dump_expression_list(this->args_);
10403 
10404   ast_dump_context->ostream() << ") ";
10405 }
10406 
10407 // Make a call expression.
10408 
10409 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)10410 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10411 		      Location location)
10412 {
10413   return new Call_expression(fn, args, is_varargs, location);
10414 }
10415 
10416 // Class Call_result_expression.
10417 
10418 // Traverse a call result.
10419 
10420 int
do_traverse(Traverse * traverse)10421 Call_result_expression::do_traverse(Traverse* traverse)
10422 {
10423   if (traverse->remember_expression(this->call_))
10424     {
10425       // We have already traversed the call expression.
10426       return TRAVERSE_CONTINUE;
10427     }
10428   return Expression::traverse(&this->call_, traverse);
10429 }
10430 
10431 // Get the type.
10432 
10433 Type*
do_type()10434 Call_result_expression::do_type()
10435 {
10436   if (this->classification() == EXPRESSION_ERROR)
10437     return Type::make_error_type();
10438 
10439   // THIS->CALL_ can be replaced with a temporary reference due to
10440   // Call_expression::do_must_eval_in_order when there is an error.
10441   Call_expression* ce = this->call_->call_expression();
10442   if (ce == NULL)
10443     {
10444       this->set_is_error();
10445       return Type::make_error_type();
10446     }
10447   Function_type* fntype = ce->get_function_type();
10448   if (fntype == NULL)
10449     {
10450       if (ce->issue_error())
10451 	{
10452 	  if (!ce->fn()->type()->is_error())
10453 	    this->report_error(_("expected function"));
10454 	}
10455       this->set_is_error();
10456       return Type::make_error_type();
10457     }
10458   const Typed_identifier_list* results = fntype->results();
10459   if (results == NULL || results->size() < 2)
10460     {
10461       if (ce->issue_error())
10462 	this->report_error(_("number of results does not match "
10463 			     "number of values"));
10464       return Type::make_error_type();
10465     }
10466   Typed_identifier_list::const_iterator pr = results->begin();
10467   for (unsigned int i = 0; i < this->index_; ++i)
10468     {
10469       if (pr == results->end())
10470 	break;
10471       ++pr;
10472     }
10473   if (pr == results->end())
10474     {
10475       if (ce->issue_error())
10476 	this->report_error(_("number of results does not match "
10477 			     "number of values"));
10478       return Type::make_error_type();
10479     }
10480   return pr->type();
10481 }
10482 
10483 // Check the type.  Just make sure that we trigger the warning in
10484 // do_type.
10485 
10486 void
do_check_types(Gogo *)10487 Call_result_expression::do_check_types(Gogo*)
10488 {
10489   this->type();
10490 }
10491 
10492 // Determine the type.  We have nothing to do here, but the 0 result
10493 // needs to pass down to the caller.
10494 
10495 void
do_determine_type(const Type_context *)10496 Call_result_expression::do_determine_type(const Type_context*)
10497 {
10498   this->call_->determine_type_no_context();
10499 }
10500 
10501 // Return the backend representation.  We just refer to the temporary set by the
10502 // call expression.  We don't do this at lowering time because it makes it
10503 // hard to evaluate the call at the right time.
10504 
10505 Bexpression*
do_get_backend(Translate_context * context)10506 Call_result_expression::do_get_backend(Translate_context* context)
10507 {
10508   Call_expression* ce = this->call_->call_expression();
10509   if (ce == NULL)
10510     {
10511       go_assert(this->call_->is_error_expression());
10512       return context->backend()->error_expression();
10513     }
10514   Temporary_statement* ts = ce->results();
10515   if (ts == NULL)
10516     {
10517       go_assert(saw_errors());
10518       return context->backend()->error_expression();
10519     }
10520   Expression* ref = Expression::make_temporary_reference(ts, this->location());
10521   ref = Expression::make_field_reference(ref, this->index_, this->location());
10522   return ref->get_backend(context);
10523 }
10524 
10525 // Dump ast representation for a call result expression.
10526 
10527 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10528 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10529     const
10530 {
10531   // FIXME: Wouldn't it be better if the call is assigned to a temporary
10532   // (struct) and the fields are referenced instead.
10533   ast_dump_context->ostream() << this->index_ << "@(";
10534   ast_dump_context->dump_expression(this->call_);
10535   ast_dump_context->ostream() << ")";
10536 }
10537 
10538 // Make a reference to a single result of a call which returns
10539 // multiple results.
10540 
10541 Expression*
make_call_result(Call_expression * call,unsigned int index)10542 Expression::make_call_result(Call_expression* call, unsigned int index)
10543 {
10544   return new Call_result_expression(call, index);
10545 }
10546 
10547 // Class Index_expression.
10548 
10549 // Traversal.
10550 
10551 int
do_traverse(Traverse * traverse)10552 Index_expression::do_traverse(Traverse* traverse)
10553 {
10554   if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10555       || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10556       || (this->end_ != NULL
10557 	  && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10558       || (this->cap_ != NULL
10559           && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10560     return TRAVERSE_EXIT;
10561   return TRAVERSE_CONTINUE;
10562 }
10563 
10564 // Lower an index expression.  This converts the generic index
10565 // expression into an array index, a string index, or a map index.
10566 
10567 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)10568 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10569 {
10570   Location location = this->location();
10571   Expression* left = this->left_;
10572   Expression* start = this->start_;
10573   Expression* end = this->end_;
10574   Expression* cap = this->cap_;
10575 
10576   Type* type = left->type();
10577   if (type->is_error())
10578     {
10579       go_assert(saw_errors());
10580       return Expression::make_error(location);
10581     }
10582   else if (left->is_type_expression())
10583     {
10584       go_error_at(location, "attempt to index type expression");
10585       return Expression::make_error(location);
10586     }
10587   else if (type->array_type() != NULL)
10588     return Expression::make_array_index(left, start, end, cap, location);
10589   else if (type->points_to() != NULL
10590 	   && type->points_to()->array_type() != NULL
10591 	   && !type->points_to()->is_slice_type())
10592     {
10593       Expression* deref =
10594           Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
10595 
10596       // For an ordinary index into the array, the pointer will be
10597       // dereferenced.  For a slice it will not--the resulting slice
10598       // will simply reuse the pointer, which is incorrect if that
10599       // pointer is nil.
10600       if (end != NULL || cap != NULL)
10601 	deref->issue_nil_check();
10602 
10603       return Expression::make_array_index(deref, start, end, cap, location);
10604     }
10605   else if (type->is_string_type())
10606     {
10607       if (cap != NULL)
10608         {
10609           go_error_at(location, "invalid 3-index slice of string");
10610           return Expression::make_error(location);
10611         }
10612       return Expression::make_string_index(left, start, end, location);
10613     }
10614   else if (type->map_type() != NULL)
10615     {
10616       if (end != NULL || cap != NULL)
10617 	{
10618 	  go_error_at(location, "invalid slice of map");
10619 	  return Expression::make_error(location);
10620 	}
10621       return Expression::make_map_index(left, start, location);
10622     }
10623   else if (cap != NULL)
10624     {
10625       go_error_at(location,
10626 		  "invalid 3-index slice of object that is not a slice");
10627       return Expression::make_error(location);
10628     }
10629   else if (end != NULL)
10630     {
10631       go_error_at(location,
10632 		  ("attempt to slice object that is not "
10633 		   "array, slice, or string"));
10634       return Expression::make_error(location);
10635     }
10636   else
10637     {
10638       go_error_at(location,
10639                   ("attempt to index object that is not "
10640 		   "array, slice, string, or map"));
10641       return Expression::make_error(location);
10642     }
10643 }
10644 
10645 // Write an indexed expression
10646 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10647 
10648 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)10649 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10650 					const Expression* expr,
10651 					const Expression* start,
10652 					const Expression* end,
10653 					const Expression* cap)
10654 {
10655   expr->dump_expression(ast_dump_context);
10656   ast_dump_context->ostream() << "[";
10657   start->dump_expression(ast_dump_context);
10658   if (end != NULL)
10659     {
10660       ast_dump_context->ostream() << ":";
10661       end->dump_expression(ast_dump_context);
10662     }
10663   if (cap != NULL)
10664     {
10665       ast_dump_context->ostream() << ":";
10666       cap->dump_expression(ast_dump_context);
10667     }
10668   ast_dump_context->ostream() << "]";
10669 }
10670 
10671 // Dump ast representation for an index expression.
10672 
10673 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10674 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10675     const
10676 {
10677   Index_expression::dump_index_expression(ast_dump_context, this->left_,
10678                                           this->start_, this->end_, this->cap_);
10679 }
10680 
10681 // Make an index expression.
10682 
10683 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)10684 Expression::make_index(Expression* left, Expression* start, Expression* end,
10685 		       Expression* cap, Location location)
10686 {
10687   return new Index_expression(left, start, end, cap, location);
10688 }
10689 
10690 // Class Array_index_expression.
10691 
10692 // Array index traversal.
10693 
10694 int
do_traverse(Traverse * traverse)10695 Array_index_expression::do_traverse(Traverse* traverse)
10696 {
10697   if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10698     return TRAVERSE_EXIT;
10699   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10700     return TRAVERSE_EXIT;
10701   if (this->end_ != NULL)
10702     {
10703       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10704 	return TRAVERSE_EXIT;
10705     }
10706   if (this->cap_ != NULL)
10707     {
10708       if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10709         return TRAVERSE_EXIT;
10710     }
10711   return TRAVERSE_CONTINUE;
10712 }
10713 
10714 // Return the type of an array index.
10715 
10716 Type*
do_type()10717 Array_index_expression::do_type()
10718 {
10719   if (this->type_ == NULL)
10720     {
10721      Array_type* type = this->array_->type()->array_type();
10722       if (type == NULL)
10723 	this->type_ = Type::make_error_type();
10724       else if (this->end_ == NULL)
10725 	this->type_ = type->element_type();
10726       else if (type->is_slice_type())
10727 	{
10728 	  // A slice of a slice has the same type as the original
10729 	  // slice.
10730 	  this->type_ = this->array_->type()->deref();
10731 	}
10732       else
10733 	{
10734 	  // A slice of an array is a slice.
10735 	  this->type_ = Type::make_array_type(type->element_type(), NULL);
10736 	}
10737     }
10738   return this->type_;
10739 }
10740 
10741 // Set the type of an array index.
10742 
10743 void
do_determine_type(const Type_context *)10744 Array_index_expression::do_determine_type(const Type_context*)
10745 {
10746   this->array_->determine_type_no_context();
10747 
10748   Type_context index_context(Type::lookup_integer_type("int"), false);
10749   if (this->start_->is_constant())
10750     this->start_->determine_type(&index_context);
10751   else
10752     this->start_->determine_type_no_context();
10753   if (this->end_ != NULL)
10754     {
10755       if (this->end_->is_constant())
10756         this->end_->determine_type(&index_context);
10757       else
10758         this->end_->determine_type_no_context();
10759     }
10760   if (this->cap_ != NULL)
10761     {
10762       if (this->cap_->is_constant())
10763         this->cap_->determine_type(&index_context);
10764       else
10765         this->cap_->determine_type_no_context();
10766     }
10767 }
10768 
10769 // Check types of an array index.
10770 
10771 void
do_check_types(Gogo *)10772 Array_index_expression::do_check_types(Gogo*)
10773 {
10774   Numeric_constant nc;
10775   unsigned long v;
10776   if (this->start_->type()->integer_type() == NULL
10777       && !this->start_->type()->is_error()
10778       && (!this->start_->numeric_constant_value(&nc)
10779 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10780     this->report_error(_("index must be integer"));
10781   if (this->end_ != NULL
10782       && this->end_->type()->integer_type() == NULL
10783       && !this->end_->type()->is_error()
10784       && !this->end_->is_nil_expression()
10785       && !this->end_->is_error_expression()
10786       && (!this->end_->numeric_constant_value(&nc)
10787 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10788     this->report_error(_("slice end must be integer"));
10789   if (this->cap_ != NULL
10790       && this->cap_->type()->integer_type() == NULL
10791       && !this->cap_->type()->is_error()
10792       && !this->cap_->is_nil_expression()
10793       && !this->cap_->is_error_expression()
10794       && (!this->cap_->numeric_constant_value(&nc)
10795 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10796     this->report_error(_("slice capacity must be integer"));
10797 
10798   Array_type* array_type = this->array_->type()->array_type();
10799   if (array_type == NULL)
10800     {
10801       go_assert(this->array_->type()->is_error());
10802       return;
10803     }
10804 
10805   unsigned int int_bits =
10806     Type::lookup_integer_type("int")->integer_type()->bits();
10807 
10808   Numeric_constant lvalnc;
10809   mpz_t lval;
10810   bool lval_valid = (array_type->length() != NULL
10811 		     && array_type->length()->numeric_constant_value(&lvalnc)
10812 		     && lvalnc.to_int(&lval));
10813   Numeric_constant inc;
10814   mpz_t ival;
10815   bool ival_valid = false;
10816   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10817     {
10818       ival_valid = true;
10819       if (mpz_sgn(ival) < 0
10820 	  || mpz_sizeinbase(ival, 2) >= int_bits
10821 	  || (lval_valid
10822 	      && (this->end_ == NULL
10823 		  ? mpz_cmp(ival, lval) >= 0
10824 		  : mpz_cmp(ival, lval) > 0)))
10825 	{
10826 	  go_error_at(this->start_->location(), "array index out of bounds");
10827 	  this->set_is_error();
10828 	}
10829     }
10830   if (this->end_ != NULL && !this->end_->is_nil_expression())
10831     {
10832       Numeric_constant enc;
10833       mpz_t eval;
10834       bool eval_valid = false;
10835       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10836 	{
10837 	  eval_valid = true;
10838 	  if (mpz_sgn(eval) < 0
10839 	      || mpz_sizeinbase(eval, 2) >= int_bits
10840 	      || (lval_valid && mpz_cmp(eval, lval) > 0))
10841 	    {
10842 	      go_error_at(this->end_->location(), "array index out of bounds");
10843 	      this->set_is_error();
10844 	    }
10845 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
10846 	    this->report_error(_("inverted slice range"));
10847 	}
10848 
10849       Numeric_constant cnc;
10850       mpz_t cval;
10851       if (this->cap_ != NULL
10852           && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10853         {
10854           if (mpz_sgn(cval) < 0
10855               || mpz_sizeinbase(cval, 2) >= int_bits
10856               || (lval_valid && mpz_cmp(cval, lval) > 0))
10857             {
10858               go_error_at(this->cap_->location(), "array index out of bounds");
10859               this->set_is_error();
10860             }
10861 	  else if (ival_valid && mpz_cmp(ival, cval) > 0)
10862 	    {
10863 	      go_error_at(this->cap_->location(),
10864                           "invalid slice index: capacity less than start");
10865 	      this->set_is_error();
10866 	    }
10867           else if (eval_valid && mpz_cmp(eval, cval) > 0)
10868             {
10869               go_error_at(this->cap_->location(),
10870                           "invalid slice index: capacity less than length");
10871               this->set_is_error();
10872             }
10873           mpz_clear(cval);
10874         }
10875 
10876       if (eval_valid)
10877         mpz_clear(eval);
10878     }
10879   if (ival_valid)
10880     mpz_clear(ival);
10881   if (lval_valid)
10882     mpz_clear(lval);
10883 
10884   // A slice of an array requires an addressable array.  A slice of a
10885   // slice is always possible.
10886   if (this->end_ != NULL && !array_type->is_slice_type())
10887     {
10888       if (!this->array_->is_addressable())
10889 	this->report_error(_("slice of unaddressable value"));
10890       else
10891         // Set the array address taken but not escape. The escape
10892         // analysis will make it escape to heap when needed.
10893         this->array_->address_taken(false);
10894     }
10895 }
10896 
10897 // Flatten array indexing by using temporary variables for slices and indexes.
10898 
10899 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)10900 Array_index_expression::do_flatten(Gogo*, Named_object*,
10901                                    Statement_inserter* inserter)
10902 {
10903   Location loc = this->location();
10904   Expression* array = this->array_;
10905   Expression* start = this->start_;
10906   Expression* end = this->end_;
10907   Expression* cap = this->cap_;
10908   if (array->is_error_expression()
10909       || array->type()->is_error_type()
10910       || start->is_error_expression()
10911       || start->type()->is_error_type()
10912       || (end != NULL
10913           && (end->is_error_expression() || end->type()->is_error_type()))
10914       || (cap != NULL
10915           && (cap->is_error_expression() || cap->type()->is_error_type())))
10916     {
10917       go_assert(saw_errors());
10918       return Expression::make_error(loc);
10919     }
10920 
10921   Temporary_statement* temp;
10922   if (array->type()->is_slice_type() && !array->is_variable())
10923     {
10924       temp = Statement::make_temporary(NULL, array, loc);
10925       inserter->insert(temp);
10926       this->array_ = Expression::make_temporary_reference(temp, loc);
10927     }
10928   if (!start->is_variable())
10929     {
10930       temp = Statement::make_temporary(NULL, start, loc);
10931       inserter->insert(temp);
10932       this->start_ = Expression::make_temporary_reference(temp, loc);
10933     }
10934   if (end != NULL
10935       && !end->is_nil_expression()
10936       && !end->is_variable())
10937     {
10938       temp = Statement::make_temporary(NULL, end, loc);
10939       inserter->insert(temp);
10940       this->end_ = Expression::make_temporary_reference(temp, loc);
10941     }
10942   if (cap != NULL && !cap->is_variable())
10943     {
10944       temp = Statement::make_temporary(NULL, cap, loc);
10945       inserter->insert(temp);
10946       this->cap_ = Expression::make_temporary_reference(temp, loc);
10947     }
10948 
10949   return this;
10950 }
10951 
10952 // Return whether this expression is addressable.
10953 
10954 bool
do_is_addressable() const10955 Array_index_expression::do_is_addressable() const
10956 {
10957   // A slice expression is not addressable.
10958   if (this->end_ != NULL)
10959     return false;
10960 
10961   // An index into a slice is addressable.
10962   if (this->array_->type()->is_slice_type())
10963     return true;
10964 
10965   // An index into an array is addressable if the array is
10966   // addressable.
10967   return this->array_->is_addressable();
10968 }
10969 
10970 void
do_address_taken(bool escapes)10971 Array_index_expression::do_address_taken(bool escapes)
10972 {
10973   // In &x[0], if x is a slice, then x's address is not taken.
10974   if (!this->array_->type()->is_slice_type())
10975     this->array_->address_taken(escapes);
10976 }
10977 
10978 // Get the backend representation for an array index.
10979 
10980 Bexpression*
do_get_backend(Translate_context * context)10981 Array_index_expression::do_get_backend(Translate_context* context)
10982 {
10983   Array_type* array_type = this->array_->type()->array_type();
10984   if (array_type == NULL)
10985     {
10986       go_assert(this->array_->type()->is_error());
10987       return context->backend()->error_expression();
10988     }
10989   go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10990 
10991   Location loc = this->location();
10992   Gogo* gogo = context->gogo();
10993 
10994   Type* int_type = Type::lookup_integer_type("int");
10995   Btype* int_btype = int_type->get_backend(gogo);
10996 
10997   // We need to convert the length and capacity to the Go "int" type here
10998   // because the length of a fixed-length array could be of type "uintptr"
10999   // and gimple disallows binary operations between "uintptr" and other
11000   // integer types. FIXME.
11001   Bexpression* length = NULL;
11002   if (this->end_ == NULL || this->end_->is_nil_expression())
11003     {
11004       Expression* len = array_type->get_length(gogo, this->array_);
11005       length = len->get_backend(context);
11006       length = gogo->backend()->convert_expression(int_btype, length, loc);
11007     }
11008 
11009   Bexpression* capacity = NULL;
11010   if (this->end_ != NULL)
11011     {
11012       Expression* cap = array_type->get_capacity(gogo, this->array_);
11013       capacity = cap->get_backend(context);
11014       capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
11015     }
11016 
11017   Bexpression* cap_arg = capacity;
11018   if (this->cap_ != NULL)
11019     {
11020       cap_arg = this->cap_->get_backend(context);
11021       cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11022     }
11023 
11024   if (length == NULL)
11025     length = cap_arg;
11026 
11027   int code = (array_type->length() != NULL
11028 	      ? (this->end_ == NULL
11029 		 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
11030 		 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
11031 	      : (this->end_ == NULL
11032 		 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
11033 		 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
11034   Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11035 
11036   if (this->start_->type()->integer_type() == NULL
11037       && !Type::are_convertible(int_type, this->start_->type(), NULL))
11038     {
11039       go_assert(saw_errors());
11040       return context->backend()->error_expression();
11041     }
11042 
11043   Bexpression* bad_index =
11044     Expression::check_bounds(this->start_, loc)->get_backend(context);
11045 
11046   Bexpression* start = this->start_->get_backend(context);
11047   start = gogo->backend()->convert_expression(int_btype, start, loc);
11048   Bexpression* start_too_large =
11049     gogo->backend()->binary_expression((this->end_ == NULL
11050 					? OPERATOR_GE
11051 					: OPERATOR_GT),
11052                                        start,
11053 				       (this->end_ == NULL
11054 					? length
11055 					: capacity),
11056                                        loc);
11057   bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
11058 						 bad_index, loc);
11059 
11060   Bfunction* bfn = context->function()->func_value()->get_decl();
11061   if (this->end_ == NULL)
11062     {
11063       // Simple array indexing.  This has to return an l-value, so
11064       // wrap the index check into START.
11065       start =
11066         gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
11067 						crash, start, loc);
11068 
11069       Bexpression* ret;
11070       if (array_type->length() != NULL)
11071 	{
11072 	  Bexpression* array = this->array_->get_backend(context);
11073 	  ret = gogo->backend()->array_index_expression(array, start, loc);
11074 	}
11075       else
11076 	{
11077 	  // Slice.
11078 	  Expression* valptr =
11079               array_type->get_value_pointer(gogo, this->array_,
11080                                             this->is_lvalue_);
11081 	  Bexpression* ptr = valptr->get_backend(context);
11082           ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11083 
11084 	  Type* ele_type = this->array_->type()->array_type()->element_type();
11085 	  Btype* ele_btype = ele_type->get_backend(gogo);
11086 	  ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11087 	}
11088       return ret;
11089     }
11090 
11091   // Array slice.
11092 
11093   if (this->cap_ != NULL)
11094     {
11095       Bexpression* bounds_bcheck =
11096 	Expression::check_bounds(this->cap_, loc)->get_backend(context);
11097       bad_index =
11098 	gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11099 					   bad_index, loc);
11100       cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11101 
11102       Bexpression* cap_too_small =
11103 	gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11104       Bexpression* cap_too_large =
11105 	gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11106       Bexpression* bad_cap =
11107 	gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11108 					   cap_too_large, loc);
11109       bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11110 						     bad_index, loc);
11111     }
11112 
11113   Bexpression* end;
11114   if (this->end_->is_nil_expression())
11115     end = length;
11116   else
11117     {
11118       Bexpression* bounds_bcheck =
11119 	Expression::check_bounds(this->end_, loc)->get_backend(context);
11120 
11121       bad_index =
11122 	gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11123 					   bad_index, loc);
11124 
11125       end = this->end_->get_backend(context);
11126       end = gogo->backend()->convert_expression(int_btype, end, loc);
11127       Bexpression* end_too_small =
11128 	gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11129       Bexpression* end_too_large =
11130 	gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11131       Bexpression* bad_end =
11132 	gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11133 					   end_too_large, loc);
11134       bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11135 						     bad_index, loc);
11136     }
11137 
11138   Bexpression* result_length =
11139     gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11140 
11141   Bexpression* result_capacity =
11142     gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11143 
11144   // If the new capacity is zero, don't change val.  Otherwise we can
11145   // get a pointer to the next object in memory, keeping it live
11146   // unnecessarily.  When the capacity is zero, the actual pointer
11147   // value doesn't matter.
11148   Bexpression* zero =
11149     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11150   Bexpression* cond =
11151     gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11152 				       loc);
11153   Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11154 								cond, zero,
11155 								start, loc);
11156   Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11157                                                      this->is_lvalue_);
11158   Bexpression* val = valptr->get_backend(context);
11159   val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11160 
11161   Btype* struct_btype = this->type()->get_backend(gogo);
11162   std::vector<Bexpression*> init;
11163   init.push_back(val);
11164   init.push_back(result_length);
11165   init.push_back(result_capacity);
11166 
11167   Bexpression* ctor =
11168     gogo->backend()->constructor_expression(struct_btype, init, loc);
11169   return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11170 						 crash, ctor, loc);
11171 }
11172 
11173 // Dump ast representation for an array index expression.
11174 
11175 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11176 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11177     const
11178 {
11179   Index_expression::dump_index_expression(ast_dump_context, this->array_,
11180                                           this->start_, this->end_, this->cap_);
11181 }
11182 
11183 // Make an array index expression.  END and CAP may be NULL.
11184 
11185 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)11186 Expression::make_array_index(Expression* array, Expression* start,
11187                              Expression* end, Expression* cap,
11188                              Location location)
11189 {
11190   return new Array_index_expression(array, start, end, cap, location);
11191 }
11192 
11193 // Class String_index_expression.
11194 
11195 // String index traversal.
11196 
11197 int
do_traverse(Traverse * traverse)11198 String_index_expression::do_traverse(Traverse* traverse)
11199 {
11200   if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11201     return TRAVERSE_EXIT;
11202   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11203     return TRAVERSE_EXIT;
11204   if (this->end_ != NULL)
11205     {
11206       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11207 	return TRAVERSE_EXIT;
11208     }
11209   return TRAVERSE_CONTINUE;
11210 }
11211 
11212 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)11213 String_index_expression::do_flatten(Gogo*, Named_object*,
11214                                     Statement_inserter* inserter)
11215 {
11216   Location loc = this->location();
11217   Expression* string = this->string_;
11218   Expression* start = this->start_;
11219   Expression* end = this->end_;
11220   if (string->is_error_expression()
11221       || string->type()->is_error_type()
11222       || start->is_error_expression()
11223       || start->type()->is_error_type()
11224       || (end != NULL
11225           && (end->is_error_expression() || end->type()->is_error_type())))
11226     {
11227       go_assert(saw_errors());
11228       return Expression::make_error(loc);
11229     }
11230 
11231   Temporary_statement* temp;
11232   if (!this->string_->is_variable())
11233     {
11234       temp = Statement::make_temporary(NULL, this->string_, loc);
11235       inserter->insert(temp);
11236       this->string_ = Expression::make_temporary_reference(temp, loc);
11237     }
11238   if (!this->start_->is_variable())
11239     {
11240       temp = Statement::make_temporary(NULL, this->start_, loc);
11241       inserter->insert(temp);
11242       this->start_ = Expression::make_temporary_reference(temp, loc);
11243     }
11244   if (this->end_ != NULL
11245       && !this->end_->is_nil_expression()
11246       && !this->end_->is_variable())
11247     {
11248       temp = Statement::make_temporary(NULL, this->end_, loc);
11249       inserter->insert(temp);
11250       this->end_ = Expression::make_temporary_reference(temp, loc);
11251     }
11252 
11253   return this;
11254 }
11255 
11256 // Return the type of a string index.
11257 
11258 Type*
do_type()11259 String_index_expression::do_type()
11260 {
11261   if (this->end_ == NULL)
11262     return Type::lookup_integer_type("uint8");
11263   else
11264     return this->string_->type();
11265 }
11266 
11267 // Determine the type of a string index.
11268 
11269 void
do_determine_type(const Type_context *)11270 String_index_expression::do_determine_type(const Type_context*)
11271 {
11272   this->string_->determine_type_no_context();
11273 
11274   Type_context index_context(Type::lookup_integer_type("int"), false);
11275   if (this->start_->is_constant())
11276     this->start_->determine_type(&index_context);
11277   else
11278     this->start_->determine_type_no_context();
11279   if (this->end_ != NULL)
11280     {
11281       if (this->end_->is_constant())
11282         this->end_->determine_type(&index_context);
11283       else
11284         this->end_->determine_type_no_context();
11285     }
11286 }
11287 
11288 // Check types of a string index.
11289 
11290 void
do_check_types(Gogo *)11291 String_index_expression::do_check_types(Gogo*)
11292 {
11293   Numeric_constant nc;
11294   unsigned long v;
11295   if (this->start_->type()->integer_type() == NULL
11296       && !this->start_->type()->is_error()
11297       && (!this->start_->numeric_constant_value(&nc)
11298 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11299     this->report_error(_("index must be integer"));
11300   if (this->end_ != NULL
11301       && this->end_->type()->integer_type() == NULL
11302       && !this->end_->type()->is_error()
11303       && !this->end_->is_nil_expression()
11304       && !this->end_->is_error_expression()
11305       && (!this->end_->numeric_constant_value(&nc)
11306 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11307     this->report_error(_("slice end must be integer"));
11308 
11309   std::string sval;
11310   bool sval_valid = this->string_->string_constant_value(&sval);
11311 
11312   Numeric_constant inc;
11313   mpz_t ival;
11314   bool ival_valid = false;
11315   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11316     {
11317       ival_valid = true;
11318       if (mpz_sgn(ival) < 0
11319 	  || (sval_valid
11320 	      && (this->end_ == NULL
11321 		  ? mpz_cmp_ui(ival, sval.length()) >= 0
11322 		  : mpz_cmp_ui(ival, sval.length()) > 0)))
11323 	{
11324 	  go_error_at(this->start_->location(), "string index out of bounds");
11325 	  this->set_is_error();
11326 	}
11327     }
11328   if (this->end_ != NULL && !this->end_->is_nil_expression())
11329     {
11330       Numeric_constant enc;
11331       mpz_t eval;
11332       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11333 	{
11334 	  if (mpz_sgn(eval) < 0
11335 	      || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11336 	    {
11337 	      go_error_at(this->end_->location(), "string index out of bounds");
11338 	      this->set_is_error();
11339 	    }
11340 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
11341 	    this->report_error(_("inverted slice range"));
11342 	  mpz_clear(eval);
11343 	}
11344     }
11345   if (ival_valid)
11346     mpz_clear(ival);
11347 }
11348 
11349 // Get the backend representation for a string index.
11350 
11351 Bexpression*
do_get_backend(Translate_context * context)11352 String_index_expression::do_get_backend(Translate_context* context)
11353 {
11354   Location loc = this->location();
11355   Expression* string_arg = this->string_;
11356   if (this->string_->type()->points_to() != NULL)
11357     string_arg = Expression::make_dereference(this->string_,
11358                                               NIL_CHECK_NOT_NEEDED, loc);
11359 
11360   Expression* bad_index = Expression::check_bounds(this->start_, loc);
11361 
11362   int code = (this->end_ == NULL
11363 	      ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11364 	      : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11365 
11366   Gogo* gogo = context->gogo();
11367   Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11368 
11369   Type* int_type = Type::lookup_integer_type("int");
11370 
11371   // It is possible that an error occurred earlier because the start index
11372   // cannot be represented as an integer type.  In this case, we shouldn't
11373   // try casting the starting index into an integer since
11374   // Type_conversion_expression will fail to get the backend representation.
11375   // FIXME.
11376   if (this->start_->type()->integer_type() == NULL
11377       && !Type::are_convertible(int_type, this->start_->type(), NULL))
11378     {
11379       go_assert(saw_errors());
11380       return context->backend()->error_expression();
11381     }
11382 
11383   Expression* start = Expression::make_cast(int_type, this->start_, loc);
11384   Bfunction* bfn = context->function()->func_value()->get_decl();
11385 
11386   if (this->end_ == NULL)
11387     {
11388       Expression* length =
11389           Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11390 
11391       Expression* start_too_large =
11392           Expression::make_binary(OPERATOR_GE, start, length, loc);
11393       bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11394                                           bad_index, loc);
11395       Expression* bytes =
11396 	Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11397 
11398       Bexpression* bstart = start->get_backend(context);
11399       Bexpression* ptr = bytes->get_backend(context);
11400       ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11401       Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11402       Bexpression* index =
11403 	gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11404 
11405       Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11406       Bexpression* index_error = bad_index->get_backend(context);
11407       return gogo->backend()->conditional_expression(bfn, byte_btype,
11408                                                      index_error, crash,
11409                                                      index, loc);
11410     }
11411 
11412   Expression* end = NULL;
11413   if (this->end_->is_nil_expression())
11414     end = Expression::make_integer_sl(-1, int_type, loc);
11415   else
11416     {
11417       Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11418       bad_index =
11419           Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11420       end = Expression::make_cast(int_type, this->end_, loc);
11421     }
11422 
11423   Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11424                                             string_arg, start, end);
11425   Bexpression* bstrslice = strslice->get_backend(context);
11426 
11427   Btype* str_btype = strslice->type()->get_backend(gogo);
11428   Bexpression* index_error = bad_index->get_backend(context);
11429   return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11430 						 crash, bstrslice, loc);
11431 }
11432 
11433 // Dump ast representation for a string index expression.
11434 
11435 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11436 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11437     const
11438 {
11439   Index_expression::dump_index_expression(ast_dump_context, this->string_,
11440                                           this->start_, this->end_, NULL);
11441 }
11442 
11443 // Make a string index expression.  END may be NULL.
11444 
11445 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)11446 Expression::make_string_index(Expression* string, Expression* start,
11447 			      Expression* end, Location location)
11448 {
11449   return new String_index_expression(string, start, end, location);
11450 }
11451 
11452 // Class Map_index.
11453 
11454 // Get the type of the map.
11455 
11456 Map_type*
get_map_type() const11457 Map_index_expression::get_map_type() const
11458 {
11459   Map_type* mt = this->map_->type()->map_type();
11460   if (mt == NULL)
11461     go_assert(saw_errors());
11462   return mt;
11463 }
11464 
11465 // Map index traversal.
11466 
11467 int
do_traverse(Traverse * traverse)11468 Map_index_expression::do_traverse(Traverse* traverse)
11469 {
11470   if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11471     return TRAVERSE_EXIT;
11472   return Expression::traverse(&this->index_, traverse);
11473 }
11474 
11475 // We need to pass in a pointer to the key, so flatten the index into a
11476 // temporary variable if it isn't already.  The value pointer will be
11477 // dereferenced and checked for nil, so flatten into a temporary to avoid
11478 // recomputation.
11479 
11480 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)11481 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11482 				 Statement_inserter* inserter)
11483 {
11484   Location loc = this->location();
11485   Map_type* mt = this->get_map_type();
11486   if (this->index()->is_error_expression()
11487       || this->index()->type()->is_error_type()
11488       || mt->is_error_type())
11489     {
11490       go_assert(saw_errors());
11491       return Expression::make_error(loc);
11492     }
11493 
11494   if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11495     {
11496       if (this->index_->type()->interface_type() != NULL
11497 	  && !this->index_->is_variable())
11498 	{
11499 	  Temporary_statement* temp =
11500 	    Statement::make_temporary(NULL, this->index_, loc);
11501 	  inserter->insert(temp);
11502 	  this->index_ = Expression::make_temporary_reference(temp, loc);
11503 	}
11504       this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11505 							this->index_, loc);
11506     }
11507 
11508   if (!this->index_->is_variable())
11509     {
11510       Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11511                                                             loc);
11512       inserter->insert(temp);
11513       this->index_ = Expression::make_temporary_reference(temp, loc);
11514     }
11515 
11516   if (this->value_pointer_ == NULL)
11517     this->get_value_pointer(gogo);
11518   if (this->value_pointer_->is_error_expression()
11519       || this->value_pointer_->type()->is_error_type())
11520     return Expression::make_error(loc);
11521   if (!this->value_pointer_->is_variable())
11522     {
11523       Temporary_statement* temp =
11524 	Statement::make_temporary(NULL, this->value_pointer_, loc);
11525       inserter->insert(temp);
11526       this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11527     }
11528 
11529   return this;
11530 }
11531 
11532 // Return the type of a map index.
11533 
11534 Type*
do_type()11535 Map_index_expression::do_type()
11536 {
11537   Map_type* mt = this->get_map_type();
11538   if (mt == NULL)
11539     return Type::make_error_type();
11540   return mt->val_type();
11541 }
11542 
11543 // Fix the type of a map index.
11544 
11545 void
do_determine_type(const Type_context *)11546 Map_index_expression::do_determine_type(const Type_context*)
11547 {
11548   this->map_->determine_type_no_context();
11549   Map_type* mt = this->get_map_type();
11550   Type* key_type = mt == NULL ? NULL : mt->key_type();
11551   Type_context subcontext(key_type, false);
11552   this->index_->determine_type(&subcontext);
11553 }
11554 
11555 // Check types of a map index.
11556 
11557 void
do_check_types(Gogo *)11558 Map_index_expression::do_check_types(Gogo*)
11559 {
11560   std::string reason;
11561   Map_type* mt = this->get_map_type();
11562   if (mt == NULL)
11563     return;
11564   if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11565     {
11566       if (reason.empty())
11567 	this->report_error(_("incompatible type for map index"));
11568       else
11569 	{
11570 	  go_error_at(this->location(), "incompatible type for map index (%s)",
11571                       reason.c_str());
11572 	  this->set_is_error();
11573 	}
11574     }
11575 }
11576 
11577 // Get the backend representation for a map index.
11578 
11579 Bexpression*
do_get_backend(Translate_context * context)11580 Map_index_expression::do_get_backend(Translate_context* context)
11581 {
11582   Map_type* type = this->get_map_type();
11583   if (type == NULL)
11584     {
11585       go_assert(saw_errors());
11586       return context->backend()->error_expression();
11587     }
11588 
11589   go_assert(this->value_pointer_ != NULL
11590             && this->value_pointer_->is_variable());
11591 
11592   Expression* val = Expression::make_dereference(this->value_pointer_,
11593                                                  NIL_CHECK_NOT_NEEDED,
11594                                                  this->location());
11595   return val->get_backend(context);
11596 }
11597 
11598 // Get an expression for the map index.  This returns an expression
11599 // that evaluates to a pointer to a value.  If the key is not in the
11600 // map, the pointer will point to a zero value.
11601 
11602 Expression*
get_value_pointer(Gogo * gogo)11603 Map_index_expression::get_value_pointer(Gogo* gogo)
11604 {
11605   if (this->value_pointer_ == NULL)
11606     {
11607       Map_type* type = this->get_map_type();
11608       if (type == NULL)
11609 	{
11610 	  go_assert(saw_errors());
11611 	  return Expression::make_error(this->location());
11612 	}
11613 
11614       Location loc = this->location();
11615       Expression* map_ref = this->map_;
11616 
11617       Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11618 						     this->index_,
11619                                                      loc);
11620 
11621       Expression* zero = type->fat_zero_value(gogo);
11622 
11623       Expression* map_index;
11624 
11625       if (zero == NULL)
11626 	map_index =
11627           Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11628 			     Expression::make_type_descriptor(type, loc),
11629                              map_ref, index_ptr);
11630       else
11631 	map_index =
11632 	  Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11633 			     Expression::make_type_descriptor(type, loc),
11634 			     map_ref, index_ptr, zero);
11635 
11636       Type* val_type = type->val_type();
11637       this->value_pointer_ =
11638           Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11639                                        map_index, this->location());
11640     }
11641 
11642   return this->value_pointer_;
11643 }
11644 
11645 // Dump ast representation for a map index expression
11646 
11647 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11648 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11649     const
11650 {
11651   Index_expression::dump_index_expression(ast_dump_context, this->map_,
11652                                           this->index_, NULL, NULL);
11653 }
11654 
11655 // Make a map index expression.
11656 
11657 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)11658 Expression::make_map_index(Expression* map, Expression* index,
11659 			   Location location)
11660 {
11661   return new Map_index_expression(map, index, location);
11662 }
11663 
11664 // Class Field_reference_expression.
11665 
11666 // Lower a field reference expression.  There is nothing to lower, but
11667 // this is where we generate the tracking information for fields with
11668 // the magic go:"track" tag.
11669 
11670 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)11671 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11672 				     Statement_inserter* inserter, int)
11673 {
11674   Struct_type* struct_type = this->expr_->type()->struct_type();
11675   if (struct_type == NULL)
11676     {
11677       // Error will be reported elsewhere.
11678       return this;
11679     }
11680   const Struct_field* field = struct_type->field(this->field_index_);
11681   if (field == NULL)
11682     return this;
11683   if (!field->has_tag())
11684     return this;
11685   if (field->tag().find("go:\"track\"") == std::string::npos)
11686     return this;
11687 
11688   // References from functions generated by the compiler don't count.
11689   if (function != NULL && function->func_value()->is_type_specific_function())
11690     return this;
11691 
11692   // We have found a reference to a tracked field.  Build a call to
11693   // the runtime function __go_fieldtrack with a string that describes
11694   // the field.  FIXME: We should only call this once per referenced
11695   // field per function, not once for each reference to the field.
11696 
11697   if (this->called_fieldtrack_)
11698     return this;
11699   this->called_fieldtrack_ = true;
11700 
11701   Location loc = this->location();
11702 
11703   std::string s = "fieldtrack \"";
11704   Named_type* nt = this->expr_->type()->unalias()->named_type();
11705   if (nt == NULL || nt->named_object()->package() == NULL)
11706     s.append(gogo->pkgpath());
11707   else
11708     s.append(nt->named_object()->package()->pkgpath());
11709   s.push_back('.');
11710   if (nt != NULL)
11711     s.append(Gogo::unpack_hidden_name(nt->name()));
11712   s.push_back('.');
11713   s.append(field->field_name());
11714   s.push_back('"');
11715 
11716   // We can't use a string here, because internally a string holds a
11717   // pointer to the actual bytes; when the linker garbage collects the
11718   // string, it won't garbage collect the bytes.  So we use a
11719   // [...]byte.
11720 
11721   Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11722 
11723   Type* byte_type = gogo->lookup_global("byte")->type_value();
11724   Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11725   array_type->set_is_array_incomparable();
11726 
11727   Expression_list* bytes = new Expression_list();
11728   for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11729     {
11730       unsigned char c = static_cast<unsigned char>(*p);
11731       bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11732     }
11733 
11734   Expression* e = Expression::make_composite_literal(array_type, 0, false,
11735 						     bytes, false, loc);
11736 
11737   Variable* var = new Variable(array_type, e, true, false, false, loc);
11738 
11739   static int count;
11740   char buf[50];
11741   snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11742   ++count;
11743 
11744   Named_object* no = gogo->add_variable(buf, var);
11745   e = Expression::make_var_reference(no, loc);
11746   e = Expression::make_unary(OPERATOR_AND, e, loc);
11747 
11748   Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11749   gogo->lower_expression(function, inserter, &call);
11750   inserter->insert(Statement::make_statement(call, false));
11751 
11752   // Put this function, and the global variable we just created, into
11753   // unique sections.  This will permit the linker to garbage collect
11754   // them if they are not referenced.  The effect is that the only
11755   // strings, indicating field references, that will wind up in the
11756   // executable will be those for functions that are actually needed.
11757   if (function != NULL)
11758     function->func_value()->set_in_unique_section();
11759   var->set_in_unique_section();
11760 
11761   return this;
11762 }
11763 
11764 // Return the type of a field reference.
11765 
11766 Type*
do_type()11767 Field_reference_expression::do_type()
11768 {
11769   Type* type = this->expr_->type();
11770   if (type->is_error())
11771     return type;
11772   Struct_type* struct_type = type->struct_type();
11773   go_assert(struct_type != NULL);
11774   return struct_type->field(this->field_index_)->type();
11775 }
11776 
11777 // Check the types for a field reference.
11778 
11779 void
do_check_types(Gogo *)11780 Field_reference_expression::do_check_types(Gogo*)
11781 {
11782   Type* type = this->expr_->type();
11783   if (type->is_error())
11784     return;
11785   Struct_type* struct_type = type->struct_type();
11786   go_assert(struct_type != NULL);
11787   go_assert(struct_type->field(this->field_index_) != NULL);
11788 }
11789 
11790 // Get the backend representation for a field reference.
11791 
11792 Bexpression*
do_get_backend(Translate_context * context)11793 Field_reference_expression::do_get_backend(Translate_context* context)
11794 {
11795   Bexpression* bstruct = this->expr_->get_backend(context);
11796   return context->gogo()->backend()->struct_field_expression(bstruct,
11797 							     this->field_index_,
11798 							     this->location());
11799 }
11800 
11801 // Dump ast representation for a field reference expression.
11802 
11803 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11804 Field_reference_expression::do_dump_expression(
11805     Ast_dump_context* ast_dump_context) const
11806 {
11807   this->expr_->dump_expression(ast_dump_context);
11808   ast_dump_context->ostream() << "." <<  this->field_index_;
11809 }
11810 
11811 // Make a reference to a qualified identifier in an expression.
11812 
11813 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)11814 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11815 				 Location location)
11816 {
11817   return new Field_reference_expression(expr, field_index, location);
11818 }
11819 
11820 // Class Interface_field_reference_expression.
11821 
11822 // Return an expression for the pointer to the function to call.
11823 
11824 Expression*
get_function()11825 Interface_field_reference_expression::get_function()
11826 {
11827   Expression* ref = this->expr_;
11828   Location loc = this->location();
11829   if (ref->type()->points_to() != NULL)
11830     ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
11831 
11832   Expression* mtable =
11833       Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11834   Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11835 
11836   std::string name = Gogo::unpack_hidden_name(this->name_);
11837   unsigned int index;
11838   const Struct_field* field = mtable_type->find_local_field(name, &index);
11839   go_assert(field != NULL);
11840 
11841   mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
11842   return Expression::make_field_reference(mtable, index, loc);
11843 }
11844 
11845 // Return an expression for the first argument to pass to the interface
11846 // function.
11847 
11848 Expression*
get_underlying_object()11849 Interface_field_reference_expression::get_underlying_object()
11850 {
11851   Expression* expr = this->expr_;
11852   if (expr->type()->points_to() != NULL)
11853     expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
11854                                         this->location());
11855   return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11856                                          this->location());
11857 }
11858 
11859 // Traversal.
11860 
11861 int
do_traverse(Traverse * traverse)11862 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11863 {
11864   return Expression::traverse(&this->expr_, traverse);
11865 }
11866 
11867 // Lower the expression.  If this expression is not called, we need to
11868 // evaluate the expression twice when converting to the backend
11869 // interface.  So introduce a temporary variable if necessary.
11870 
11871 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)11872 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11873 						 Statement_inserter* inserter)
11874 {
11875   if (this->expr_->is_error_expression()
11876       || this->expr_->type()->is_error_type())
11877     {
11878       go_assert(saw_errors());
11879       return Expression::make_error(this->location());
11880     }
11881 
11882   if (!this->expr_->is_variable())
11883     {
11884       Temporary_statement* temp =
11885 	Statement::make_temporary(this->expr_->type(), NULL, this->location());
11886       inserter->insert(temp);
11887       this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11888 							   this->location());
11889     }
11890   return this;
11891 }
11892 
11893 // Return the type of an interface field reference.
11894 
11895 Type*
do_type()11896 Interface_field_reference_expression::do_type()
11897 {
11898   Type* expr_type = this->expr_->type();
11899 
11900   Type* points_to = expr_type->points_to();
11901   if (points_to != NULL)
11902     expr_type = points_to;
11903 
11904   Interface_type* interface_type = expr_type->interface_type();
11905   if (interface_type == NULL)
11906     return Type::make_error_type();
11907 
11908   const Typed_identifier* method = interface_type->find_method(this->name_);
11909   if (method == NULL)
11910     return Type::make_error_type();
11911 
11912   return method->type();
11913 }
11914 
11915 // Determine types.
11916 
11917 void
do_determine_type(const Type_context *)11918 Interface_field_reference_expression::do_determine_type(const Type_context*)
11919 {
11920   this->expr_->determine_type_no_context();
11921 }
11922 
11923 // Check the types for an interface field reference.
11924 
11925 void
do_check_types(Gogo *)11926 Interface_field_reference_expression::do_check_types(Gogo*)
11927 {
11928   Type* type = this->expr_->type();
11929 
11930   Type* points_to = type->points_to();
11931   if (points_to != NULL)
11932     type = points_to;
11933 
11934   Interface_type* interface_type = type->interface_type();
11935   if (interface_type == NULL)
11936     {
11937       if (!type->is_error_type())
11938 	this->report_error(_("expected interface or pointer to interface"));
11939     }
11940   else
11941     {
11942       const Typed_identifier* method =
11943 	interface_type->find_method(this->name_);
11944       if (method == NULL)
11945 	{
11946 	  go_error_at(this->location(), "method %qs not in interface",
11947                       Gogo::message_name(this->name_).c_str());
11948 	  this->set_is_error();
11949 	}
11950     }
11951 }
11952 
11953 // If an interface field reference is not simply called, then it is
11954 // represented as a closure.  The closure will hold a single variable,
11955 // the value of the interface on which the method should be called.
11956 // The function will be a simple thunk that pulls the value from the
11957 // closure and calls the method with the remaining arguments.
11958 
11959 // Because method values are not common, we don't build all thunks for
11960 // all possible interface methods, but instead only build them as we
11961 // need them.  In particular, we even build them on demand for
11962 // interface methods defined in other packages.
11963 
11964 Interface_field_reference_expression::Interface_method_thunks
11965   Interface_field_reference_expression::interface_method_thunks;
11966 
11967 // Find or create the thunk to call method NAME on TYPE.
11968 
11969 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)11970 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11971 						   Interface_type* type,
11972 						   const std::string& name)
11973 {
11974   std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11975   std::pair<Interface_method_thunks::iterator, bool> ins =
11976     Interface_field_reference_expression::interface_method_thunks.insert(val);
11977   if (ins.second)
11978     {
11979       // This is the first time we have seen this interface.
11980       ins.first->second = new Method_thunks();
11981     }
11982 
11983   for (Method_thunks::const_iterator p = ins.first->second->begin();
11984        p != ins.first->second->end();
11985        p++)
11986     if (p->first == name)
11987       return p->second;
11988 
11989   Location loc = type->location();
11990 
11991   const Typed_identifier* method_id = type->find_method(name);
11992   if (method_id == NULL)
11993     return Named_object::make_erroneous_name(gogo->thunk_name());
11994 
11995   Function_type* orig_fntype = method_id->type()->function_type();
11996   if (orig_fntype == NULL)
11997     return Named_object::make_erroneous_name(gogo->thunk_name());
11998 
11999   Struct_field_list* sfl = new Struct_field_list();
12000   // The type here is wrong--it should be the C function type.  But it
12001   // doesn't really matter.
12002   Type* vt = Type::make_pointer_type(Type::make_void_type());
12003   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
12004   sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
12005   Struct_type* st = Type::make_struct_type(sfl, loc);
12006   st->set_is_struct_incomparable();
12007   Type* closure_type = Type::make_pointer_type(st);
12008 
12009   Function_type* new_fntype = orig_fntype->copy_with_names();
12010 
12011   std::string thunk_name = gogo->thunk_name();
12012   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
12013 					      false, loc);
12014 
12015   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
12016   cvar->set_is_used();
12017   cvar->set_is_closure();
12018   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
12019 						 NULL, cvar);
12020   new_no->func_value()->set_closure_var(cp);
12021 
12022   gogo->start_block(loc);
12023 
12024   // Field 0 of the closure is the function code pointer, field 1 is
12025   // the value on which to invoke the method.
12026   Expression* arg = Expression::make_var_reference(cp, loc);
12027   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
12028   arg = Expression::make_field_reference(arg, 1, loc);
12029 
12030   Expression *ifre = Expression::make_interface_field_reference(arg, name,
12031 								loc);
12032 
12033   const Typed_identifier_list* orig_params = orig_fntype->parameters();
12034   Expression_list* args;
12035   if (orig_params == NULL || orig_params->empty())
12036     args = NULL;
12037   else
12038     {
12039       const Typed_identifier_list* new_params = new_fntype->parameters();
12040       args = new Expression_list();
12041       for (Typed_identifier_list::const_iterator p = new_params->begin();
12042 	   p != new_params->end();
12043 	   ++p)
12044 	{
12045 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
12046 	  go_assert(p_no != NULL
12047 		    && p_no->is_variable()
12048 		    && p_no->var_value()->is_parameter());
12049 	  args->push_back(Expression::make_var_reference(p_no, loc));
12050 	}
12051     }
12052 
12053   Call_expression* call = Expression::make_call(ifre, args,
12054 						orig_fntype->is_varargs(),
12055 						loc);
12056   call->set_varargs_are_lowered();
12057 
12058   Statement* s = Statement::make_return_from_call(call, loc);
12059   gogo->add_statement(s);
12060   Block* b = gogo->finish_block(loc);
12061   gogo->add_block(b, loc);
12062   gogo->lower_block(new_no, b);
12063   gogo->flatten_block(new_no, b);
12064   gogo->finish_function(loc);
12065 
12066   ins.first->second->push_back(std::make_pair(name, new_no));
12067   return new_no;
12068 }
12069 
12070 // Get the backend representation for a method value.
12071 
12072 Bexpression*
do_get_backend(Translate_context * context)12073 Interface_field_reference_expression::do_get_backend(Translate_context* context)
12074 {
12075   Interface_type* type = this->expr_->type()->interface_type();
12076   if (type == NULL)
12077     {
12078       go_assert(saw_errors());
12079       return context->backend()->error_expression();
12080     }
12081 
12082   Named_object* thunk =
12083     Interface_field_reference_expression::create_thunk(context->gogo(),
12084 						       type, this->name_);
12085   if (thunk->is_erroneous())
12086     {
12087       go_assert(saw_errors());
12088       return context->backend()->error_expression();
12089     }
12090 
12091   // FIXME: We should lower this earlier, but we can't it lower it in
12092   // the lowering pass because at that point we don't know whether we
12093   // need to create the thunk or not.  If the expression is called, we
12094   // don't need the thunk.
12095 
12096   Location loc = this->location();
12097 
12098   Struct_field_list* fields = new Struct_field_list();
12099   fields->push_back(Struct_field(Typed_identifier("fn",
12100 						  thunk->func_value()->type(),
12101 						  loc)));
12102   fields->push_back(Struct_field(Typed_identifier("val",
12103 						  this->expr_->type(),
12104 						  loc)));
12105   Struct_type* st = Type::make_struct_type(fields, loc);
12106   st->set_is_struct_incomparable();
12107 
12108   Expression_list* vals = new Expression_list();
12109   vals->push_back(Expression::make_func_code_reference(thunk, loc));
12110   vals->push_back(this->expr_);
12111 
12112   Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12113   Bexpression* bclosure =
12114     Expression::make_heap_expression(expr, loc)->get_backend(context);
12115 
12116   Gogo* gogo = context->gogo();
12117   Btype* btype = this->type()->get_backend(gogo);
12118   bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12119 
12120   Expression* nil_check =
12121       Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12122                               Expression::make_nil(loc), loc);
12123   Bexpression* bnil_check = nil_check->get_backend(context);
12124 
12125   Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12126 					    loc)->get_backend(context);
12127 
12128   Bfunction* bfn = context->function()->func_value()->get_decl();
12129   Bexpression* bcond =
12130       gogo->backend()->conditional_expression(bfn, NULL,
12131                                               bnil_check, bcrash, NULL, loc);
12132   Bfunction* bfunction = context->function()->func_value()->get_decl();
12133   Bstatement* cond_statement =
12134       gogo->backend()->expression_statement(bfunction, bcond);
12135   return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12136 }
12137 
12138 // Dump ast representation for an interface field reference.
12139 
12140 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12141 Interface_field_reference_expression::do_dump_expression(
12142     Ast_dump_context* ast_dump_context) const
12143 {
12144   this->expr_->dump_expression(ast_dump_context);
12145   ast_dump_context->ostream() << "." << this->name_;
12146 }
12147 
12148 // Make a reference to a field in an interface.
12149 
12150 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)12151 Expression::make_interface_field_reference(Expression* expr,
12152 					   const std::string& field,
12153 					   Location location)
12154 {
12155   return new Interface_field_reference_expression(expr, field, location);
12156 }
12157 
12158 // A general selector.  This is a Parser_expression for LEFT.NAME.  It
12159 // is lowered after we know the type of the left hand side.
12160 
12161 class Selector_expression : public Parser_expression
12162 {
12163  public:
Selector_expression(Expression * left,const std::string & name,Location location)12164   Selector_expression(Expression* left, const std::string& name,
12165 		      Location location)
12166     : Parser_expression(EXPRESSION_SELECTOR, location),
12167       left_(left), name_(name)
12168   { }
12169 
12170  protected:
12171   int
do_traverse(Traverse * traverse)12172   do_traverse(Traverse* traverse)
12173   { return Expression::traverse(&this->left_, traverse); }
12174 
12175   Expression*
12176   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12177 
12178   Expression*
do_copy()12179   do_copy()
12180   {
12181     return new Selector_expression(this->left_->copy(), this->name_,
12182 				   this->location());
12183   }
12184 
12185   void
12186   do_dump_expression(Ast_dump_context* ast_dump_context) const;
12187 
12188  private:
12189   Expression*
12190   lower_method_expression(Gogo*);
12191 
12192   // The expression on the left hand side.
12193   Expression* left_;
12194   // The name on the right hand side.
12195   std::string name_;
12196 };
12197 
12198 // Lower a selector expression once we know the real type of the left
12199 // hand side.
12200 
12201 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)12202 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12203 			      int)
12204 {
12205   Expression* left = this->left_;
12206   if (left->is_type_expression())
12207     return this->lower_method_expression(gogo);
12208   return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12209 				    this->location());
12210 }
12211 
12212 // Lower a method expression T.M or (*T).M.  We turn this into a
12213 // function literal.
12214 
12215 Expression*
lower_method_expression(Gogo * gogo)12216 Selector_expression::lower_method_expression(Gogo* gogo)
12217 {
12218   Location location = this->location();
12219   Type* left_type = this->left_->type();
12220   Type* type = left_type;
12221   const std::string& name(this->name_);
12222 
12223   bool is_pointer;
12224   if (type->points_to() == NULL)
12225     is_pointer = false;
12226   else
12227     {
12228       is_pointer = true;
12229       type = type->points_to();
12230     }
12231   Named_type* nt = type->named_type();
12232   if (nt == NULL)
12233     {
12234       go_error_at(location,
12235                   ("method expression requires named type or "
12236                    "pointer to named type"));
12237       return Expression::make_error(location);
12238     }
12239 
12240   bool is_ambiguous;
12241   Method* method = nt->method_function(name, &is_ambiguous);
12242   const Typed_identifier* imethod = NULL;
12243   if (method == NULL && !is_pointer)
12244     {
12245       Interface_type* it = nt->interface_type();
12246       if (it != NULL)
12247 	imethod = it->find_method(name);
12248     }
12249 
12250   if ((method == NULL && imethod == NULL)
12251       || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12252     {
12253       if (!is_ambiguous)
12254 	go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12255                     is_pointer ? "*" : "",
12256                     nt->message_name().c_str(),
12257                     Gogo::message_name(name).c_str());
12258       else
12259 	go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12260                     Gogo::message_name(name).c_str(),
12261                     is_pointer ? "*" : "",
12262                     nt->message_name().c_str());
12263       return Expression::make_error(location);
12264     }
12265 
12266   if (method != NULL && !is_pointer && !method->is_value_method())
12267     {
12268       go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12269                   nt->message_name().c_str(),
12270                   Gogo::message_name(name).c_str());
12271       return Expression::make_error(location);
12272     }
12273 
12274   // Build a new function type in which the receiver becomes the first
12275   // argument.
12276   Function_type* method_type;
12277   if (method != NULL)
12278     {
12279       method_type = method->type();
12280       go_assert(method_type->is_method());
12281     }
12282   else
12283     {
12284       method_type = imethod->type()->function_type();
12285       go_assert(method_type != NULL && !method_type->is_method());
12286     }
12287 
12288   const char* const receiver_name = "$this";
12289   Typed_identifier_list* parameters = new Typed_identifier_list();
12290   parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12291 					 location));
12292 
12293   const Typed_identifier_list* method_parameters = method_type->parameters();
12294   if (method_parameters != NULL)
12295     {
12296       int i = 0;
12297       for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12298 	   p != method_parameters->end();
12299 	   ++p, ++i)
12300 	{
12301 	  if (!p->name().empty())
12302 	    parameters->push_back(*p);
12303 	  else
12304 	    {
12305 	      char buf[20];
12306 	      snprintf(buf, sizeof buf, "$param%d", i);
12307 	      parameters->push_back(Typed_identifier(buf, p->type(),
12308 						     p->location()));
12309 	    }
12310 	}
12311     }
12312 
12313   const Typed_identifier_list* method_results = method_type->results();
12314   Typed_identifier_list* results;
12315   if (method_results == NULL)
12316     results = NULL;
12317   else
12318     {
12319       results = new Typed_identifier_list();
12320       for (Typed_identifier_list::const_iterator p = method_results->begin();
12321 	   p != method_results->end();
12322 	   ++p)
12323 	results->push_back(*p);
12324     }
12325 
12326   Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12327 						   location);
12328   if (method_type->is_varargs())
12329     fntype->set_is_varargs();
12330 
12331   // We generate methods which always takes a pointer to the receiver
12332   // as their first argument.  If this is for a pointer type, we can
12333   // simply reuse the existing function.  We use an internal hack to
12334   // get the right type.
12335   // FIXME: This optimization is disabled because it doesn't yet work
12336   // with function descriptors when the method expression is not
12337   // directly called.
12338   if (method != NULL && is_pointer && false)
12339     {
12340       Named_object* mno = (method->needs_stub_method()
12341 			   ? method->stub_object()
12342 			   : method->named_object());
12343       Expression* f = Expression::make_func_reference(mno, NULL, location);
12344       f = Expression::make_cast(fntype, f, location);
12345       Type_conversion_expression* tce =
12346 	static_cast<Type_conversion_expression*>(f);
12347       tce->set_may_convert_function_types();
12348       return f;
12349     }
12350 
12351   Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
12352 					  location);
12353 
12354   Named_object* vno = gogo->lookup(receiver_name, NULL);
12355   go_assert(vno != NULL);
12356   Expression* ve = Expression::make_var_reference(vno, location);
12357   Expression* bm;
12358   if (method != NULL)
12359     bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12360   else
12361     bm = Expression::make_interface_field_reference(ve, name, location);
12362 
12363   // Even though we found the method above, if it has an error type we
12364   // may see an error here.
12365   if (bm->is_error_expression())
12366     {
12367       gogo->finish_function(location);
12368       return bm;
12369     }
12370 
12371   Expression_list* args;
12372   if (parameters->size() <= 1)
12373     args = NULL;
12374   else
12375     {
12376       args = new Expression_list();
12377       Typed_identifier_list::const_iterator p = parameters->begin();
12378       ++p;
12379       for (; p != parameters->end(); ++p)
12380 	{
12381 	  vno = gogo->lookup(p->name(), NULL);
12382 	  go_assert(vno != NULL);
12383 	  args->push_back(Expression::make_var_reference(vno, location));
12384 	}
12385     }
12386 
12387   gogo->start_block(location);
12388 
12389   Call_expression* call = Expression::make_call(bm, args,
12390 						method_type->is_varargs(),
12391 						location);
12392 
12393   Statement* s = Statement::make_return_from_call(call, location);
12394   gogo->add_statement(s);
12395 
12396   Block* b = gogo->finish_block(location);
12397 
12398   gogo->add_block(b, location);
12399 
12400   // Lower the call in case there are multiple results.
12401   gogo->lower_block(no, b);
12402   gogo->flatten_block(no, b);
12403 
12404   gogo->finish_function(location);
12405 
12406   return Expression::make_func_reference(no, NULL, location);
12407 }
12408 
12409 // Dump the ast for a selector expression.
12410 
12411 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12412 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12413     const
12414 {
12415   ast_dump_context->dump_expression(this->left_);
12416   ast_dump_context->ostream() << ".";
12417   ast_dump_context->ostream() << this->name_;
12418 }
12419 
12420 // Make a selector expression.
12421 
12422 Expression*
make_selector(Expression * left,const std::string & name,Location location)12423 Expression::make_selector(Expression* left, const std::string& name,
12424 			  Location location)
12425 {
12426   return new Selector_expression(left, name, location);
12427 }
12428 
12429 // Class Allocation_expression.
12430 
12431 int
do_traverse(Traverse * traverse)12432 Allocation_expression::do_traverse(Traverse* traverse)
12433 {
12434   return Type::traverse(this->type_, traverse);
12435 }
12436 
12437 Type*
do_type()12438 Allocation_expression::do_type()
12439 {
12440   return Type::make_pointer_type(this->type_);
12441 }
12442 
12443 void
do_check_types(Gogo *)12444 Allocation_expression::do_check_types(Gogo*)
12445 {
12446   if (!this->type_->in_heap())
12447     go_error_at(this->location(), "can't heap allocate go:notinheap type");
12448 }
12449 
12450 // Make a copy of an allocation expression.
12451 
12452 Expression*
do_copy()12453 Allocation_expression::do_copy()
12454 {
12455   Allocation_expression* alloc =
12456     new Allocation_expression(this->type_->copy_expressions(),
12457 			      this->location());
12458   if (this->allocate_on_stack_)
12459     alloc->set_allocate_on_stack();
12460   return alloc;
12461 }
12462 
12463 // Return the backend representation for an allocation expression.
12464 
12465 Bexpression*
do_get_backend(Translate_context * context)12466 Allocation_expression::do_get_backend(Translate_context* context)
12467 {
12468   Gogo* gogo = context->gogo();
12469   Location loc = this->location();
12470   Btype* btype = this->type_->get_backend(gogo);
12471 
12472   if (this->allocate_on_stack_)
12473     {
12474       int64_t size;
12475       bool ok = this->type_->backend_type_size(gogo, &size);
12476       if (!ok)
12477         {
12478           go_assert(saw_errors());
12479           return gogo->backend()->error_expression();
12480         }
12481       Bstatement* decl;
12482       Named_object* fn = context->function();
12483       go_assert(fn != NULL);
12484       Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
12485       Bexpression* zero = gogo->backend()->zero_expression(btype);
12486       Bvariable* temp =
12487         gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
12488                                             zero, true, loc, &decl);
12489       Bexpression* ret = gogo->backend()->var_expression(temp, loc);
12490       ret = gogo->backend()->address_expression(ret, loc);
12491       ret = gogo->backend()->compound_expression(decl, ret, loc);
12492       return ret;
12493     }
12494 
12495   Bexpression* space =
12496     gogo->allocate_memory(this->type_, loc)->get_backend(context);
12497   Btype* pbtype = gogo->backend()->pointer_type(btype);
12498   return gogo->backend()->convert_expression(pbtype, space, loc);
12499 }
12500 
12501 // Dump ast representation for an allocation expression.
12502 
12503 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12504 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12505     const
12506 {
12507   ast_dump_context->ostream() << "new(";
12508   ast_dump_context->dump_type(this->type_);
12509   ast_dump_context->ostream() << ")";
12510 }
12511 
12512 // Make an allocation expression.
12513 
12514 Expression*
make_allocation(Type * type,Location location)12515 Expression::make_allocation(Type* type, Location location)
12516 {
12517   return new Allocation_expression(type, location);
12518 }
12519 
12520 // Class Ordered_value_list.
12521 
12522 int
traverse_vals(Traverse * traverse)12523 Ordered_value_list::traverse_vals(Traverse* traverse)
12524 {
12525   if (this->vals_ != NULL)
12526     {
12527       if (this->traverse_order_ == NULL)
12528 	{
12529 	  if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12530 	    return TRAVERSE_EXIT;
12531 	}
12532       else
12533 	{
12534 	  for (std::vector<unsigned long>::const_iterator p =
12535 		   this->traverse_order_->begin();
12536 	       p != this->traverse_order_->end();
12537 	       ++p)
12538 	    {
12539 	      if (Expression::traverse(&this->vals_->at(*p), traverse)
12540 		  == TRAVERSE_EXIT)
12541 		return TRAVERSE_EXIT;
12542 	    }
12543 	}
12544     }
12545   return TRAVERSE_CONTINUE;
12546 }
12547 
12548 // Class Struct_construction_expression.
12549 
12550 // Traversal.
12551 
12552 int
do_traverse(Traverse * traverse)12553 Struct_construction_expression::do_traverse(Traverse* traverse)
12554 {
12555   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12556     return TRAVERSE_EXIT;
12557   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12558     return TRAVERSE_EXIT;
12559   return TRAVERSE_CONTINUE;
12560 }
12561 
12562 // Return whether this is a constant initializer.
12563 
12564 bool
is_constant_struct() const12565 Struct_construction_expression::is_constant_struct() const
12566 {
12567   if (this->vals() == NULL)
12568     return true;
12569   for (Expression_list::const_iterator pv = this->vals()->begin();
12570        pv != this->vals()->end();
12571        ++pv)
12572     {
12573       if (*pv != NULL
12574 	  && !(*pv)->is_constant()
12575 	  && (!(*pv)->is_composite_literal()
12576 	      || (*pv)->is_nonconstant_composite_literal()))
12577 	return false;
12578     }
12579 
12580   const Struct_field_list* fields = this->type_->struct_type()->fields();
12581   for (Struct_field_list::const_iterator pf = fields->begin();
12582        pf != fields->end();
12583        ++pf)
12584     {
12585       // There are no constant constructors for interfaces.
12586       if (pf->type()->interface_type() != NULL)
12587 	return false;
12588     }
12589 
12590   return true;
12591 }
12592 
12593 // Return whether this struct can be used as a constant initializer.
12594 
12595 bool
do_is_static_initializer() const12596 Struct_construction_expression::do_is_static_initializer() const
12597 {
12598   if (this->vals() == NULL)
12599     return true;
12600   for (Expression_list::const_iterator pv = this->vals()->begin();
12601        pv != this->vals()->end();
12602        ++pv)
12603     {
12604       if (*pv != NULL && !(*pv)->is_static_initializer())
12605 	return false;
12606     }
12607 
12608   const Struct_field_list* fields = this->type_->struct_type()->fields();
12609   for (Struct_field_list::const_iterator pf = fields->begin();
12610        pf != fields->end();
12611        ++pf)
12612     {
12613       // There are no constant constructors for interfaces.
12614       if (pf->type()->interface_type() != NULL)
12615 	return false;
12616     }
12617 
12618   return true;
12619 }
12620 
12621 // Final type determination.
12622 
12623 void
do_determine_type(const Type_context *)12624 Struct_construction_expression::do_determine_type(const Type_context*)
12625 {
12626   if (this->vals() == NULL)
12627     return;
12628   const Struct_field_list* fields = this->type_->struct_type()->fields();
12629   Expression_list::const_iterator pv = this->vals()->begin();
12630   for (Struct_field_list::const_iterator pf = fields->begin();
12631        pf != fields->end();
12632        ++pf, ++pv)
12633     {
12634       if (pv == this->vals()->end())
12635 	return;
12636       if (*pv != NULL)
12637 	{
12638 	  Type_context subcontext(pf->type(), false);
12639 	  (*pv)->determine_type(&subcontext);
12640 	}
12641     }
12642   // Extra values are an error we will report elsewhere; we still want
12643   // to determine the type to avoid knockon errors.
12644   for (; pv != this->vals()->end(); ++pv)
12645     (*pv)->determine_type_no_context();
12646 }
12647 
12648 // Check types.
12649 
12650 void
do_check_types(Gogo *)12651 Struct_construction_expression::do_check_types(Gogo*)
12652 {
12653   if (this->vals() == NULL)
12654     return;
12655 
12656   Struct_type* st = this->type_->struct_type();
12657   if (this->vals()->size() > st->field_count())
12658     {
12659       this->report_error(_("too many expressions for struct"));
12660       return;
12661     }
12662 
12663   const Struct_field_list* fields = st->fields();
12664   Expression_list::const_iterator pv = this->vals()->begin();
12665   int i = 0;
12666   for (Struct_field_list::const_iterator pf = fields->begin();
12667        pf != fields->end();
12668        ++pf, ++pv, ++i)
12669     {
12670       if (pv == this->vals()->end())
12671 	{
12672 	  this->report_error(_("too few expressions for struct"));
12673 	  break;
12674 	}
12675 
12676       if (*pv == NULL)
12677 	continue;
12678 
12679       std::string reason;
12680       if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12681 	{
12682 	  if (reason.empty())
12683 	    go_error_at((*pv)->location(),
12684                         "incompatible type for field %d in struct construction",
12685                         i + 1);
12686 	  else
12687 	    go_error_at((*pv)->location(),
12688                         ("incompatible type for field %d in "
12689                          "struct construction (%s)"),
12690                         i + 1, reason.c_str());
12691 	  this->set_is_error();
12692 	}
12693     }
12694   go_assert(pv == this->vals()->end());
12695 }
12696 
12697 // Copy.
12698 
12699 Expression*
do_copy()12700 Struct_construction_expression::do_copy()
12701 {
12702   Struct_construction_expression* ret =
12703     new Struct_construction_expression(this->type_->copy_expressions(),
12704 				       (this->vals() == NULL
12705 					? NULL
12706 					: this->vals()->copy()),
12707 				       this->location());
12708   if (this->traverse_order() != NULL)
12709     ret->set_traverse_order(this->traverse_order());
12710   return ret;
12711 }
12712 
12713 // Flatten a struct construction expression.  Store the values into
12714 // temporaries in case they need interface conversion.
12715 
12716 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)12717 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12718 					   Statement_inserter* inserter)
12719 {
12720   if (this->vals() == NULL)
12721     return this;
12722 
12723   // If this is a constant struct, we don't need temporaries.
12724   if (this->is_constant_struct() || this->is_static_initializer())
12725     return this;
12726 
12727   Location loc = this->location();
12728   for (Expression_list::iterator pv = this->vals()->begin();
12729        pv != this->vals()->end();
12730        ++pv)
12731     {
12732       if (*pv != NULL)
12733 	{
12734           if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12735             {
12736               go_assert(saw_errors());
12737               return Expression::make_error(loc);
12738             }
12739 	  if (!(*pv)->is_variable())
12740 	    {
12741 	      Temporary_statement* temp =
12742 		Statement::make_temporary(NULL, *pv, loc);
12743 	      inserter->insert(temp);
12744 	      *pv = Expression::make_temporary_reference(temp, loc);
12745 	    }
12746 	}
12747     }
12748   return this;
12749 }
12750 
12751 // Return the backend representation for constructing a struct.
12752 
12753 Bexpression*
do_get_backend(Translate_context * context)12754 Struct_construction_expression::do_get_backend(Translate_context* context)
12755 {
12756   Gogo* gogo = context->gogo();
12757 
12758   Btype* btype = this->type_->get_backend(gogo);
12759   if (this->vals() == NULL)
12760     return gogo->backend()->zero_expression(btype);
12761 
12762   const Struct_field_list* fields = this->type_->struct_type()->fields();
12763   Expression_list::const_iterator pv = this->vals()->begin();
12764   std::vector<Bexpression*> init;
12765   for (Struct_field_list::const_iterator pf = fields->begin();
12766        pf != fields->end();
12767        ++pf)
12768     {
12769       Btype* fbtype = pf->type()->get_backend(gogo);
12770       if (pv == this->vals()->end())
12771         init.push_back(gogo->backend()->zero_expression(fbtype));
12772       else if (*pv == NULL)
12773 	{
12774           init.push_back(gogo->backend()->zero_expression(fbtype));
12775 	  ++pv;
12776 	}
12777       else
12778 	{
12779           Expression* val =
12780               Expression::convert_for_assignment(gogo, pf->type(),
12781                                                  *pv, this->location());
12782           init.push_back(val->get_backend(context));
12783 	  ++pv;
12784 	}
12785     }
12786   return gogo->backend()->constructor_expression(btype, init, this->location());
12787 }
12788 
12789 // Export a struct construction.
12790 
12791 void
do_export(Export * exp) const12792 Struct_construction_expression::do_export(Export* exp) const
12793 {
12794   exp->write_c_string("convert(");
12795   exp->write_type(this->type_);
12796   for (Expression_list::const_iterator pv = this->vals()->begin();
12797        pv != this->vals()->end();
12798        ++pv)
12799     {
12800       exp->write_c_string(", ");
12801       if (*pv != NULL)
12802 	(*pv)->export_expression(exp);
12803     }
12804   exp->write_c_string(")");
12805 }
12806 
12807 // Dump ast representation of a struct construction expression.
12808 
12809 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12810 Struct_construction_expression::do_dump_expression(
12811     Ast_dump_context* ast_dump_context) const
12812 {
12813   ast_dump_context->dump_type(this->type_);
12814   ast_dump_context->ostream() << "{";
12815   ast_dump_context->dump_expression_list(this->vals());
12816   ast_dump_context->ostream() << "}";
12817 }
12818 
12819 // Make a struct composite literal.  This used by the thunk code.
12820 
12821 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)12822 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12823 					  Location location)
12824 {
12825   go_assert(type->struct_type() != NULL);
12826   return new Struct_construction_expression(type, vals, location);
12827 }
12828 
12829 // Class Array_construction_expression.
12830 
12831 // Traversal.
12832 
12833 int
do_traverse(Traverse * traverse)12834 Array_construction_expression::do_traverse(Traverse* traverse)
12835 {
12836   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12837     return TRAVERSE_EXIT;
12838   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12839     return TRAVERSE_EXIT;
12840   return TRAVERSE_CONTINUE;
12841 }
12842 
12843 // Return whether this is a constant initializer.
12844 
12845 bool
is_constant_array() const12846 Array_construction_expression::is_constant_array() const
12847 {
12848   if (this->vals() == NULL)
12849     return true;
12850 
12851   // There are no constant constructors for interfaces.
12852   if (this->type_->array_type()->element_type()->interface_type() != NULL)
12853     return false;
12854 
12855   for (Expression_list::const_iterator pv = this->vals()->begin();
12856        pv != this->vals()->end();
12857        ++pv)
12858     {
12859       if (*pv != NULL
12860 	  && !(*pv)->is_constant()
12861 	  && (!(*pv)->is_composite_literal()
12862 	      || (*pv)->is_nonconstant_composite_literal()))
12863 	return false;
12864     }
12865   return true;
12866 }
12867 
12868 // Return whether this can be used a constant initializer.
12869 
12870 bool
do_is_static_initializer() const12871 Array_construction_expression::do_is_static_initializer() const
12872 {
12873   if (this->vals() == NULL)
12874     return true;
12875 
12876   // There are no constant constructors for interfaces.
12877   if (this->type_->array_type()->element_type()->interface_type() != NULL)
12878     return false;
12879 
12880   for (Expression_list::const_iterator pv = this->vals()->begin();
12881        pv != this->vals()->end();
12882        ++pv)
12883     {
12884       if (*pv != NULL && !(*pv)->is_static_initializer())
12885 	return false;
12886     }
12887   return true;
12888 }
12889 
12890 // Final type determination.
12891 
12892 void
do_determine_type(const Type_context *)12893 Array_construction_expression::do_determine_type(const Type_context*)
12894 {
12895   if (this->vals() == NULL)
12896     return;
12897   Type_context subcontext(this->type_->array_type()->element_type(), false);
12898   for (Expression_list::const_iterator pv = this->vals()->begin();
12899        pv != this->vals()->end();
12900        ++pv)
12901     {
12902       if (*pv != NULL)
12903 	(*pv)->determine_type(&subcontext);
12904     }
12905 }
12906 
12907 // Check types.
12908 
12909 void
do_check_types(Gogo *)12910 Array_construction_expression::do_check_types(Gogo*)
12911 {
12912   if (this->vals() == NULL)
12913     return;
12914 
12915   Array_type* at = this->type_->array_type();
12916   int i = 0;
12917   Type* element_type = at->element_type();
12918   for (Expression_list::const_iterator pv = this->vals()->begin();
12919        pv != this->vals()->end();
12920        ++pv, ++i)
12921     {
12922       if (*pv != NULL
12923 	  && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12924 	{
12925 	  go_error_at((*pv)->location(),
12926                       "incompatible type for element %d in composite literal",
12927                       i + 1);
12928 	  this->set_is_error();
12929 	}
12930     }
12931 }
12932 
12933 // Flatten an array construction expression.  Store the values into
12934 // temporaries in case they need interface conversion.
12935 
12936 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)12937 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12938 					   Statement_inserter* inserter)
12939 {
12940   if (this->vals() == NULL)
12941     return this;
12942 
12943   // If this is a constant array, we don't need temporaries.
12944   if (this->is_constant_array() || this->is_static_initializer())
12945     return this;
12946 
12947   Location loc = this->location();
12948   for (Expression_list::iterator pv = this->vals()->begin();
12949        pv != this->vals()->end();
12950        ++pv)
12951     {
12952       if (*pv != NULL)
12953 	{
12954           if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12955             {
12956               go_assert(saw_errors());
12957               return Expression::make_error(loc);
12958             }
12959 	  if (!(*pv)->is_variable())
12960 	    {
12961 	      Temporary_statement* temp =
12962 		Statement::make_temporary(NULL, *pv, loc);
12963 	      inserter->insert(temp);
12964 	      *pv = Expression::make_temporary_reference(temp, loc);
12965 	    }
12966 	}
12967     }
12968   return this;
12969 }
12970 
12971 // Get a constructor expression for the array values.
12972 
12973 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)12974 Array_construction_expression::get_constructor(Translate_context* context,
12975                                                Btype* array_btype)
12976 {
12977   Type* element_type = this->type_->array_type()->element_type();
12978 
12979   std::vector<unsigned long> indexes;
12980   std::vector<Bexpression*> vals;
12981   Gogo* gogo = context->gogo();
12982   if (this->vals() != NULL)
12983     {
12984       size_t i = 0;
12985       std::vector<unsigned long>::const_iterator pi;
12986       if (this->indexes_ != NULL)
12987 	pi = this->indexes_->begin();
12988       for (Expression_list::const_iterator pv = this->vals()->begin();
12989 	   pv != this->vals()->end();
12990 	   ++pv, ++i)
12991 	{
12992 	  if (this->indexes_ != NULL)
12993 	    go_assert(pi != this->indexes_->end());
12994 
12995 	  if (this->indexes_ == NULL)
12996 	    indexes.push_back(i);
12997 	  else
12998 	    indexes.push_back(*pi);
12999 	  if (*pv == NULL)
13000 	    {
13001 	      Btype* ebtype = element_type->get_backend(gogo);
13002 	      Bexpression *zv = gogo->backend()->zero_expression(ebtype);
13003 	      vals.push_back(zv);
13004 	    }
13005 	  else
13006 	    {
13007               Expression* val_expr =
13008                   Expression::convert_for_assignment(gogo, element_type, *pv,
13009                                                      this->location());
13010 	      vals.push_back(val_expr->get_backend(context));
13011 	    }
13012 	  if (this->indexes_ != NULL)
13013 	    ++pi;
13014 	}
13015       if (this->indexes_ != NULL)
13016 	go_assert(pi == this->indexes_->end());
13017     }
13018   return gogo->backend()->array_constructor_expression(array_btype, indexes,
13019                                                        vals, this->location());
13020 }
13021 
13022 // Export an array construction.
13023 
13024 void
do_export(Export * exp) const13025 Array_construction_expression::do_export(Export* exp) const
13026 {
13027   exp->write_c_string("convert(");
13028   exp->write_type(this->type_);
13029   if (this->vals() != NULL)
13030     {
13031       std::vector<unsigned long>::const_iterator pi;
13032       if (this->indexes_ != NULL)
13033 	pi = this->indexes_->begin();
13034       for (Expression_list::const_iterator pv = this->vals()->begin();
13035 	   pv != this->vals()->end();
13036 	   ++pv)
13037 	{
13038 	  exp->write_c_string(", ");
13039 
13040 	  if (this->indexes_ != NULL)
13041 	    {
13042 	      char buf[100];
13043 	      snprintf(buf, sizeof buf, "%lu", *pi);
13044 	      exp->write_c_string(buf);
13045 	      exp->write_c_string(":");
13046 	    }
13047 
13048 	  if (*pv != NULL)
13049 	    (*pv)->export_expression(exp);
13050 
13051 	  if (this->indexes_ != NULL)
13052 	    ++pi;
13053 	}
13054     }
13055   exp->write_c_string(")");
13056 }
13057 
13058 // Dump ast representation of an array construction expression.
13059 
13060 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13061 Array_construction_expression::do_dump_expression(
13062     Ast_dump_context* ast_dump_context) const
13063 {
13064   Expression* length = this->type_->array_type()->length();
13065 
13066   ast_dump_context->ostream() << "[" ;
13067   if (length != NULL)
13068     {
13069       ast_dump_context->dump_expression(length);
13070     }
13071   ast_dump_context->ostream() << "]" ;
13072   ast_dump_context->dump_type(this->type_);
13073   this->dump_slice_storage_expression(ast_dump_context);
13074   ast_dump_context->ostream() << "{" ;
13075   if (this->indexes_ == NULL)
13076     ast_dump_context->dump_expression_list(this->vals());
13077   else
13078     {
13079       Expression_list::const_iterator pv = this->vals()->begin();
13080       for (std::vector<unsigned long>::const_iterator pi =
13081 	     this->indexes_->begin();
13082 	   pi != this->indexes_->end();
13083 	   ++pi, ++pv)
13084 	{
13085 	  if (pi != this->indexes_->begin())
13086 	    ast_dump_context->ostream() << ", ";
13087 	  ast_dump_context->ostream() << *pi << ':';
13088 	  ast_dump_context->dump_expression(*pv);
13089 	}
13090     }
13091   ast_dump_context->ostream() << "}" ;
13092 
13093 }
13094 
13095 // Class Fixed_array_construction_expression.
13096 
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)13097 Fixed_array_construction_expression::Fixed_array_construction_expression(
13098     Type* type, const std::vector<unsigned long>* indexes,
13099     Expression_list* vals, Location location)
13100   : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13101 				  type, indexes, vals, location)
13102 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
13103 
13104 
13105 // Copy.
13106 
13107 Expression*
do_copy()13108 Fixed_array_construction_expression::do_copy()
13109 {
13110   Type* t = this->type()->copy_expressions();
13111   return new Fixed_array_construction_expression(t, this->indexes(),
13112 						 (this->vals() == NULL
13113 						  ? NULL
13114 						  : this->vals()->copy()),
13115 						 this->location());
13116 }
13117 
13118 // Return the backend representation for constructing a fixed array.
13119 
13120 Bexpression*
do_get_backend(Translate_context * context)13121 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
13122 {
13123   Type* type = this->type();
13124   Btype* btype = type->get_backend(context->gogo());
13125   return this->get_constructor(context, btype);
13126 }
13127 
13128 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)13129 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13130                                          Location location)
13131 {
13132   go_assert(type->array_type() != NULL && !type->is_slice_type());
13133   return new Fixed_array_construction_expression(type, NULL, vals, location);
13134 }
13135 
13136 // Class Slice_construction_expression.
13137 
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)13138 Slice_construction_expression::Slice_construction_expression(
13139   Type* type, const std::vector<unsigned long>* indexes,
13140   Expression_list* vals, Location location)
13141   : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13142 				  type, indexes, vals, location),
13143     valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13144     storage_escapes_(true)
13145 {
13146   go_assert(type->is_slice_type());
13147 
13148   unsigned long lenval;
13149   Expression* length;
13150   if (vals == NULL || vals->empty())
13151     lenval = 0;
13152   else
13153     {
13154       if (this->indexes() == NULL)
13155 	lenval = vals->size();
13156       else
13157 	lenval = indexes->back() + 1;
13158     }
13159   Type* int_type = Type::lookup_integer_type("int");
13160   length = Expression::make_integer_ul(lenval, int_type, location);
13161   Type* element_type = type->array_type()->element_type();
13162   Array_type* array_type = Type::make_array_type(element_type, length);
13163   array_type->set_is_array_incomparable();
13164   this->valtype_ = array_type;
13165 }
13166 
13167 // Traversal.
13168 
13169 int
do_traverse(Traverse * traverse)13170 Slice_construction_expression::do_traverse(Traverse* traverse)
13171 {
13172   if (this->Array_construction_expression::do_traverse(traverse)
13173       == TRAVERSE_EXIT)
13174     return TRAVERSE_EXIT;
13175   if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13176     return TRAVERSE_EXIT;
13177   if (this->array_val_ != NULL
13178       && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13179     return TRAVERSE_EXIT;
13180   if (this->slice_storage_ != NULL
13181       && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13182     return TRAVERSE_EXIT;
13183   return TRAVERSE_CONTINUE;
13184 }
13185 
13186 // Helper routine to create fixed array value underlying the slice literal.
13187 // May be called during flattening, or later during do_get_backend().
13188 
13189 Expression*
create_array_val()13190 Slice_construction_expression::create_array_val()
13191 {
13192   Array_type* array_type = this->type()->array_type();
13193   if (array_type == NULL)
13194     {
13195       go_assert(this->type()->is_error());
13196       return NULL;
13197     }
13198 
13199   Location loc = this->location();
13200   go_assert(this->valtype_ != NULL);
13201 
13202   Expression_list* vals = this->vals();
13203   return new Fixed_array_construction_expression(
13204       this->valtype_, this->indexes(), vals, loc);
13205 }
13206 
13207 // If we're previous established that the slice storage does not
13208 // escape, then create a separate array temp val here for it. We
13209 // need to do this as part of flattening so as to be able to insert
13210 // the new temp statement.
13211 
13212 Expression*
do_flatten(Gogo * gogo,Named_object * no,Statement_inserter * inserter)13213 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13214                                           Statement_inserter* inserter)
13215 {
13216   if (this->type()->array_type() == NULL)
13217     return NULL;
13218 
13219   // Base class flattening first
13220   this->Array_construction_expression::do_flatten(gogo, no, inserter);
13221 
13222   // Create a stack-allocated storage temp if storage won't escape
13223   if (!this->storage_escapes_
13224       && this->slice_storage_ == NULL
13225       && this->element_count() > 0)
13226     {
13227       Location loc = this->location();
13228       this->array_val_ = this->create_array_val();
13229       go_assert(this->array_val_);
13230       Temporary_statement* temp =
13231           Statement::make_temporary(this->valtype_, this->array_val_, loc);
13232       inserter->insert(temp);
13233       this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13234     }
13235   return this;
13236 }
13237 
13238 // When dumping a slice construction expression that has an explicit
13239 // storeage temp, emit the temp here (if we don't do this the storage
13240 // temp appears unused in the AST dump).
13241 
13242 void
13243 Slice_construction_expression::
dump_slice_storage_expression(Ast_dump_context * ast_dump_context) const13244 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13245 {
13246   if (this->slice_storage_ == NULL)
13247     return;
13248   ast_dump_context->ostream() << "storage=" ;
13249   ast_dump_context->dump_expression(this->slice_storage_);
13250 }
13251 
13252 // Copy.
13253 
13254 Expression*
do_copy()13255 Slice_construction_expression::do_copy()
13256 {
13257   return new Slice_construction_expression(this->type()->copy_expressions(),
13258 					   this->indexes(),
13259 					   (this->vals() == NULL
13260 					    ? NULL
13261 					    : this->vals()->copy()),
13262 					   this->location());
13263 }
13264 
13265 // Return the backend representation for constructing a slice.
13266 
13267 Bexpression*
do_get_backend(Translate_context * context)13268 Slice_construction_expression::do_get_backend(Translate_context* context)
13269 {
13270   if (this->array_val_ == NULL)
13271     this->array_val_ = this->create_array_val();
13272   if (this->array_val_ == NULL)
13273     {
13274       go_assert(this->type()->is_error());
13275       return context->backend()->error_expression();
13276     }
13277 
13278   Location loc = this->location();
13279 
13280   bool is_static_initializer = this->array_val_->is_static_initializer();
13281 
13282   // We have to copy the initial values into heap memory if we are in
13283   // a function or if the values are not constants.
13284   bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13285 
13286   Expression* space;
13287 
13288   if (this->slice_storage_ != NULL)
13289     {
13290       go_assert(!this->storage_escapes_);
13291       space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13292     }
13293   else if (!copy_to_heap)
13294     {
13295       // The initializer will only run once.
13296       space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13297       space->unary_expression()->set_is_slice_init();
13298     }
13299   else
13300     {
13301       go_assert(this->storage_escapes_ || this->element_count() == 0);
13302       space = Expression::make_heap_expression(this->array_val_, loc);
13303     }
13304 
13305   // Build a constructor for the slice.
13306   Expression* len = this->valtype_->array_type()->length();
13307   Expression* slice_val =
13308     Expression::make_slice_value(this->type(), space, len, len, loc);
13309   return slice_val->get_backend(context);
13310 }
13311 
13312 // Make a slice composite literal.  This is used by the type
13313 // descriptor code.
13314 
13315 Slice_construction_expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)13316 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13317 					 Location location)
13318 {
13319   go_assert(type->is_slice_type());
13320   return new Slice_construction_expression(type, NULL, vals, location);
13321 }
13322 
13323 // Class Map_construction_expression.
13324 
13325 // Traversal.
13326 
13327 int
do_traverse(Traverse * traverse)13328 Map_construction_expression::do_traverse(Traverse* traverse)
13329 {
13330   if (this->vals_ != NULL
13331       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13332     return TRAVERSE_EXIT;
13333   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13334     return TRAVERSE_EXIT;
13335   return TRAVERSE_CONTINUE;
13336 }
13337 
13338 // Flatten constructor initializer into a temporary variable since
13339 // we need to take its address for __go_construct_map.
13340 
13341 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13342 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13343                                         Statement_inserter* inserter)
13344 {
13345   if (!this->is_error_expression()
13346       && this->vals_ != NULL
13347       && !this->vals_->empty()
13348       && this->constructor_temp_ == NULL)
13349     {
13350       Map_type* mt = this->type_->map_type();
13351       Type* key_type = mt->key_type();
13352       Type* val_type = mt->val_type();
13353       this->element_type_ = Type::make_builtin_struct_type(2,
13354                                                            "__key", key_type,
13355                                                            "__val", val_type);
13356 
13357       Expression_list* value_pairs = new Expression_list();
13358       Location loc = this->location();
13359 
13360       size_t i = 0;
13361       for (Expression_list::const_iterator pv = this->vals_->begin();
13362            pv != this->vals_->end();
13363            ++pv, ++i)
13364         {
13365           Expression_list* key_value_pair = new Expression_list();
13366           Expression* key = *pv;
13367           if (key->is_error_expression() || key->type()->is_error_type())
13368             {
13369               go_assert(saw_errors());
13370               return Expression::make_error(loc);
13371             }
13372 	  if (key->type()->interface_type() != NULL && !key->is_variable())
13373 	    {
13374 	      Temporary_statement* temp =
13375 		Statement::make_temporary(NULL, key, loc);
13376 	      inserter->insert(temp);
13377 	      key = Expression::make_temporary_reference(temp, loc);
13378 	    }
13379 	  key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13380 
13381           ++pv;
13382           Expression* val = *pv;
13383           if (val->is_error_expression() || val->type()->is_error_type())
13384             {
13385               go_assert(saw_errors());
13386               return Expression::make_error(loc);
13387             }
13388 	  if (val->type()->interface_type() != NULL && !val->is_variable())
13389 	    {
13390 	      Temporary_statement* temp =
13391 		Statement::make_temporary(NULL, val, loc);
13392 	      inserter->insert(temp);
13393 	      val = Expression::make_temporary_reference(temp, loc);
13394 	    }
13395 	  val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13396 
13397           key_value_pair->push_back(key);
13398           key_value_pair->push_back(val);
13399           value_pairs->push_back(
13400               Expression::make_struct_composite_literal(this->element_type_,
13401                                                         key_value_pair, loc));
13402         }
13403 
13404       Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13405       Array_type* ctor_type =
13406           Type::make_array_type(this->element_type_, element_count);
13407       ctor_type->set_is_array_incomparable();
13408       Expression* constructor =
13409           new Fixed_array_construction_expression(ctor_type, NULL,
13410                                                   value_pairs, loc);
13411 
13412       this->constructor_temp_ =
13413           Statement::make_temporary(NULL, constructor, loc);
13414       constructor->issue_nil_check();
13415       this->constructor_temp_->set_is_address_taken();
13416       inserter->insert(this->constructor_temp_);
13417     }
13418 
13419   return this;
13420 }
13421 
13422 // Final type determination.
13423 
13424 void
do_determine_type(const Type_context *)13425 Map_construction_expression::do_determine_type(const Type_context*)
13426 {
13427   if (this->vals_ == NULL)
13428     return;
13429 
13430   Map_type* mt = this->type_->map_type();
13431   Type_context key_context(mt->key_type(), false);
13432   Type_context val_context(mt->val_type(), false);
13433   for (Expression_list::const_iterator pv = this->vals_->begin();
13434        pv != this->vals_->end();
13435        ++pv)
13436     {
13437       (*pv)->determine_type(&key_context);
13438       ++pv;
13439       (*pv)->determine_type(&val_context);
13440     }
13441 }
13442 
13443 // Check types.
13444 
13445 void
do_check_types(Gogo *)13446 Map_construction_expression::do_check_types(Gogo*)
13447 {
13448   if (this->vals_ == NULL)
13449     return;
13450 
13451   Map_type* mt = this->type_->map_type();
13452   int i = 0;
13453   Type* key_type = mt->key_type();
13454   Type* val_type = mt->val_type();
13455   for (Expression_list::const_iterator pv = this->vals_->begin();
13456        pv != this->vals_->end();
13457        ++pv, ++i)
13458     {
13459       if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13460 	{
13461 	  go_error_at((*pv)->location(),
13462                       "incompatible type for element %d key in map construction",
13463                       i + 1);
13464 	  this->set_is_error();
13465 	}
13466       ++pv;
13467       if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13468 	{
13469 	  go_error_at((*pv)->location(),
13470                       ("incompatible type for element %d value "
13471                        "in map construction"),
13472 		   i + 1);
13473 	  this->set_is_error();
13474 	}
13475     }
13476 }
13477 
13478 // Copy.
13479 
13480 Expression*
do_copy()13481 Map_construction_expression::do_copy()
13482 {
13483   return new Map_construction_expression(this->type_->copy_expressions(),
13484 					 (this->vals_ == NULL
13485 					  ? NULL
13486 					  : this->vals_->copy()),
13487 					 this->location());
13488 }
13489 
13490 // Return the backend representation for constructing a map.
13491 
13492 Bexpression*
do_get_backend(Translate_context * context)13493 Map_construction_expression::do_get_backend(Translate_context* context)
13494 {
13495   if (this->is_error_expression())
13496     return context->backend()->error_expression();
13497   Location loc = this->location();
13498 
13499   size_t i = 0;
13500   Expression* ventries;
13501   if (this->vals_ == NULL || this->vals_->empty())
13502     ventries = Expression::make_nil(loc);
13503   else
13504     {
13505       go_assert(this->constructor_temp_ != NULL);
13506       i = this->vals_->size() / 2;
13507 
13508       Expression* ctor_ref =
13509           Expression::make_temporary_reference(this->constructor_temp_, loc);
13510       ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13511     }
13512 
13513   Map_type* mt = this->type_->map_type();
13514   if (this->element_type_ == NULL)
13515       this->element_type_ =
13516           Type::make_builtin_struct_type(2,
13517                                          "__key", mt->key_type(),
13518                                          "__val", mt->val_type());
13519   Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13520 
13521   Type* uintptr_t = Type::lookup_integer_type("uintptr");
13522   Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13523 
13524   Expression* entry_size =
13525       Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13526 
13527   unsigned int field_index;
13528   const Struct_field* valfield =
13529       this->element_type_->find_local_field("__val", &field_index);
13530   Expression* val_offset =
13531       Expression::make_struct_field_offset(this->element_type_, valfield);
13532 
13533   Expression* map_ctor =
13534       Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13535                          entry_size, val_offset, ventries);
13536   return map_ctor->get_backend(context);
13537 }
13538 
13539 // Export an array construction.
13540 
13541 void
do_export(Export * exp) const13542 Map_construction_expression::do_export(Export* exp) const
13543 {
13544   exp->write_c_string("convert(");
13545   exp->write_type(this->type_);
13546   for (Expression_list::const_iterator pv = this->vals_->begin();
13547        pv != this->vals_->end();
13548        ++pv)
13549     {
13550       exp->write_c_string(", ");
13551       (*pv)->export_expression(exp);
13552     }
13553   exp->write_c_string(")");
13554 }
13555 
13556 // Dump ast representation for a map construction expression.
13557 
13558 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13559 Map_construction_expression::do_dump_expression(
13560     Ast_dump_context* ast_dump_context) const
13561 {
13562   ast_dump_context->ostream() << "{" ;
13563   ast_dump_context->dump_expression_list(this->vals_, true);
13564   ast_dump_context->ostream() << "}";
13565 }
13566 
13567 // Class Composite_literal_expression.
13568 
13569 // Traversal.
13570 
13571 int
do_traverse(Traverse * traverse)13572 Composite_literal_expression::do_traverse(Traverse* traverse)
13573 {
13574   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13575     return TRAVERSE_EXIT;
13576 
13577   // If this is a struct composite literal with keys, then the keys
13578   // are field names, not expressions.  We don't want to traverse them
13579   // in that case.  If we do, we can give an erroneous error "variable
13580   // initializer refers to itself."  See bug482.go in the testsuite.
13581   if (this->has_keys_ && this->vals_ != NULL)
13582     {
13583       // The type may not be resolvable at this point.
13584       Type* type = this->type_;
13585 
13586       for (int depth = 0; depth < this->depth_; ++depth)
13587         {
13588           if (type->array_type() != NULL)
13589             type = type->array_type()->element_type();
13590           else if (type->map_type() != NULL)
13591             {
13592               if (this->key_path_[depth])
13593                 type = type->map_type()->key_type();
13594               else
13595                 type = type->map_type()->val_type();
13596             }
13597           else
13598             {
13599               // This error will be reported during lowering.
13600               return TRAVERSE_CONTINUE;
13601             }
13602         }
13603 
13604       while (true)
13605 	{
13606 	  if (type->classification() == Type::TYPE_NAMED)
13607 	    type = type->named_type()->real_type();
13608 	  else if (type->classification() == Type::TYPE_FORWARD)
13609 	    {
13610 	      Type* t = type->forwarded();
13611 	      if (t == type)
13612 		break;
13613 	      type = t;
13614 	    }
13615 	  else
13616 	    break;
13617 	}
13618 
13619       if (type->classification() == Type::TYPE_STRUCT)
13620 	{
13621 	  Expression_list::iterator p = this->vals_->begin();
13622 	  while (p != this->vals_->end())
13623 	    {
13624 	      // Skip key.
13625 	      ++p;
13626 	      go_assert(p != this->vals_->end());
13627 	      if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13628 		return TRAVERSE_EXIT;
13629 	      ++p;
13630 	    }
13631 	  return TRAVERSE_CONTINUE;
13632 	}
13633     }
13634 
13635   if (this->vals_ != NULL)
13636     return this->vals_->traverse(traverse);
13637 
13638   return TRAVERSE_CONTINUE;
13639 }
13640 
13641 // Lower a generic composite literal into a specific version based on
13642 // the type.
13643 
13644 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)13645 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13646 				       Statement_inserter* inserter, int)
13647 {
13648   Type* type = this->type_;
13649 
13650   for (int depth = 0; depth < this->depth_; ++depth)
13651     {
13652       if (type->array_type() != NULL)
13653 	type = type->array_type()->element_type();
13654       else if (type->map_type() != NULL)
13655         {
13656           if (this->key_path_[depth])
13657             type = type->map_type()->key_type();
13658           else
13659             type = type->map_type()->val_type();
13660         }
13661       else
13662 	{
13663 	  if (!type->is_error())
13664 	    go_error_at(this->location(),
13665                         ("may only omit types within composite literals "
13666                          "of slice, array, or map type"));
13667 	  return Expression::make_error(this->location());
13668 	}
13669     }
13670 
13671   Type *pt = type->points_to();
13672   bool is_pointer = false;
13673   if (pt != NULL)
13674     {
13675       is_pointer = true;
13676       type = pt;
13677     }
13678 
13679   Expression* ret;
13680   if (type->is_error())
13681     return Expression::make_error(this->location());
13682   else if (type->struct_type() != NULL)
13683     ret = this->lower_struct(gogo, type);
13684   else if (type->array_type() != NULL)
13685     ret = this->lower_array(type);
13686   else if (type->map_type() != NULL)
13687     ret = this->lower_map(gogo, function, inserter, type);
13688   else
13689     {
13690       go_error_at(this->location(),
13691                   ("expected struct, slice, array, or map type "
13692                    "for composite literal"));
13693       return Expression::make_error(this->location());
13694     }
13695 
13696   if (is_pointer)
13697     ret = Expression::make_heap_expression(ret, this->location());
13698 
13699   return ret;
13700 }
13701 
13702 // Lower a struct composite literal.
13703 
13704 Expression*
lower_struct(Gogo * gogo,Type * type)13705 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13706 {
13707   Location location = this->location();
13708   Struct_type* st = type->struct_type();
13709   if (this->vals_ == NULL || !this->has_keys_)
13710     {
13711       if (this->vals_ != NULL
13712 	  && !this->vals_->empty()
13713 	  && type->named_type() != NULL
13714 	  && type->named_type()->named_object()->package() != NULL)
13715 	{
13716 	  for (Struct_field_list::const_iterator pf = st->fields()->begin();
13717 	       pf != st->fields()->end();
13718 	       ++pf)
13719 	    {
13720 	      if (Gogo::is_hidden_name(pf->field_name())
13721 		  || pf->is_embedded_builtin(gogo))
13722 		go_error_at(this->location(),
13723                             "assignment of unexported field %qs in %qs literal",
13724                             Gogo::message_name(pf->field_name()).c_str(),
13725                             type->named_type()->message_name().c_str());
13726 	    }
13727 	}
13728 
13729       return new Struct_construction_expression(type, this->vals_, location);
13730     }
13731 
13732   size_t field_count = st->field_count();
13733   std::vector<Expression*> vals(field_count);
13734   std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13735   Expression_list::const_iterator p = this->vals_->begin();
13736   Expression* external_expr = NULL;
13737   const Named_object* external_no = NULL;
13738   while (p != this->vals_->end())
13739     {
13740       Expression* name_expr = *p;
13741 
13742       ++p;
13743       go_assert(p != this->vals_->end());
13744       Expression* val = *p;
13745 
13746       ++p;
13747 
13748       if (name_expr == NULL)
13749 	{
13750 	  go_error_at(val->location(),
13751                       "mixture of field and value initializers");
13752 	  return Expression::make_error(location);
13753 	}
13754 
13755       bool bad_key = false;
13756       std::string name;
13757       const Named_object* no = NULL;
13758       switch (name_expr->classification())
13759 	{
13760 	case EXPRESSION_UNKNOWN_REFERENCE:
13761 	  name = name_expr->unknown_expression()->name();
13762 	  if (type->named_type() != NULL)
13763 	    {
13764 	      // If the named object found for this field name comes from a
13765 	      // different package than the struct it is a part of, do not count
13766 	      // this incorrect lookup as a usage of the object's package.
13767 	      no = name_expr->unknown_expression()->named_object();
13768 	      if (no->package() != NULL
13769 		  && no->package() != type->named_type()->named_object()->package())
13770 		no->package()->forget_usage(name_expr);
13771 	    }
13772 	  break;
13773 
13774 	case EXPRESSION_CONST_REFERENCE:
13775 	  no = static_cast<Const_expression*>(name_expr)->named_object();
13776 	  break;
13777 
13778 	case EXPRESSION_TYPE:
13779 	  {
13780 	    Type* t = name_expr->type();
13781 	    Named_type* nt = t->named_type();
13782 	    if (nt == NULL)
13783 	      bad_key = true;
13784 	    else
13785 	      no = nt->named_object();
13786 	  }
13787 	  break;
13788 
13789 	case EXPRESSION_VAR_REFERENCE:
13790 	  no = name_expr->var_expression()->named_object();
13791 	  break;
13792 
13793 	case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13794 	  no = name_expr->enclosed_var_expression()->variable();
13795 	  break;
13796 
13797 	case EXPRESSION_FUNC_REFERENCE:
13798 	  no = name_expr->func_expression()->named_object();
13799 	  break;
13800 
13801 	default:
13802 	  bad_key = true;
13803 	  break;
13804 	}
13805       if (bad_key)
13806 	{
13807 	  go_error_at(name_expr->location(), "expected struct field name");
13808 	  return Expression::make_error(location);
13809 	}
13810 
13811       if (no != NULL)
13812 	{
13813 	  if (no->package() != NULL && external_expr == NULL)
13814 	    {
13815 	      external_expr = name_expr;
13816 	      external_no = no;
13817 	    }
13818 
13819 	  name = no->name();
13820 
13821 	  // A predefined name won't be packed.  If it starts with a
13822 	  // lower case letter we need to check for that case, because
13823 	  // the field name will be packed.  FIXME.
13824 	  if (!Gogo::is_hidden_name(name)
13825 	      && name[0] >= 'a'
13826 	      && name[0] <= 'z')
13827 	    {
13828 	      Named_object* gno = gogo->lookup_global(name.c_str());
13829 	      if (gno == no)
13830 		name = gogo->pack_hidden_name(name, false);
13831 	    }
13832 	}
13833 
13834       unsigned int index;
13835       const Struct_field* sf = st->find_local_field(name, &index);
13836       if (sf == NULL)
13837 	{
13838 	  go_error_at(name_expr->location(), "unknown field %qs in %qs",
13839                       Gogo::message_name(name).c_str(),
13840                       (type->named_type() != NULL
13841                        ? type->named_type()->message_name().c_str()
13842                        : "unnamed struct"));
13843 	  return Expression::make_error(location);
13844 	}
13845       if (vals[index] != NULL)
13846 	{
13847 	  go_error_at(name_expr->location(),
13848                       "duplicate value for field %qs in %qs",
13849                       Gogo::message_name(name).c_str(),
13850                       (type->named_type() != NULL
13851                        ? type->named_type()->message_name().c_str()
13852                        : "unnamed struct"));
13853 	  return Expression::make_error(location);
13854 	}
13855 
13856       if (type->named_type() != NULL
13857 	  && type->named_type()->named_object()->package() != NULL
13858 	  && (Gogo::is_hidden_name(sf->field_name())
13859 	      || sf->is_embedded_builtin(gogo)))
13860 	go_error_at(name_expr->location(),
13861                     "assignment of unexported field %qs in %qs literal",
13862                     Gogo::message_name(sf->field_name()).c_str(),
13863                     type->named_type()->message_name().c_str());
13864 
13865       vals[index] = val;
13866       traverse_order->push_back(static_cast<unsigned long>(index));
13867     }
13868 
13869   if (!this->all_are_names_)
13870     {
13871       // This is a weird case like bug462 in the testsuite.
13872       if (external_expr == NULL)
13873 	go_error_at(this->location(), "unknown field in %qs literal",
13874                     (type->named_type() != NULL
13875                      ? type->named_type()->message_name().c_str()
13876                      : "unnamed struct"));
13877       else
13878 	go_error_at(external_expr->location(), "unknown field %qs in %qs",
13879                     external_no->message_name().c_str(),
13880                     (type->named_type() != NULL
13881                      ? type->named_type()->message_name().c_str()
13882                      : "unnamed struct"));
13883       return Expression::make_error(location);
13884     }
13885 
13886   Expression_list* list = new Expression_list;
13887   list->reserve(field_count);
13888   for (size_t i = 0; i < field_count; ++i)
13889     list->push_back(vals[i]);
13890 
13891   Struct_construction_expression* ret =
13892     new Struct_construction_expression(type, list, location);
13893   ret->set_traverse_order(traverse_order);
13894   return ret;
13895 }
13896 
13897 // Index/value/traversal-order triple.
13898 
13899 struct IVT_triple {
13900   unsigned long index;
13901   unsigned long traversal_order;
13902   Expression* expr;
IVT_tripleIVT_triple13903   IVT_triple(unsigned long i, unsigned long to, Expression *e)
13904       : index(i), traversal_order(to), expr(e) { }
operator <IVT_triple13905   bool operator<(const IVT_triple& other) const
13906   { return this->index < other.index; }
13907 };
13908 
13909 // Lower an array composite literal.
13910 
13911 Expression*
lower_array(Type * type)13912 Composite_literal_expression::lower_array(Type* type)
13913 {
13914   Location location = this->location();
13915   if (this->vals_ == NULL || !this->has_keys_)
13916     return this->make_array(type, NULL, this->vals_);
13917 
13918   std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13919   indexes->reserve(this->vals_->size());
13920   bool indexes_out_of_order = false;
13921   Expression_list* vals = new Expression_list();
13922   vals->reserve(this->vals_->size());
13923   unsigned long index = 0;
13924   Expression_list::const_iterator p = this->vals_->begin();
13925   while (p != this->vals_->end())
13926     {
13927       Expression* index_expr = *p;
13928 
13929       ++p;
13930       go_assert(p != this->vals_->end());
13931       Expression* val = *p;
13932 
13933       ++p;
13934 
13935       if (index_expr == NULL)
13936 	{
13937 	  if (!indexes->empty())
13938 	    indexes->push_back(index);
13939 	}
13940       else
13941 	{
13942 	  if (indexes->empty() && !vals->empty())
13943 	    {
13944 	      for (size_t i = 0; i < vals->size(); ++i)
13945 		indexes->push_back(i);
13946 	    }
13947 
13948 	  Numeric_constant nc;
13949 	  if (!index_expr->numeric_constant_value(&nc))
13950 	    {
13951 	      go_error_at(index_expr->location(),
13952                           "index expression is not integer constant");
13953 	      return Expression::make_error(location);
13954 	    }
13955 
13956 	  switch (nc.to_unsigned_long(&index))
13957 	    {
13958 	    case Numeric_constant::NC_UL_VALID:
13959 	      break;
13960 	    case Numeric_constant::NC_UL_NOTINT:
13961 	      go_error_at(index_expr->location(),
13962                           "index expression is not integer constant");
13963 	      return Expression::make_error(location);
13964 	    case Numeric_constant::NC_UL_NEGATIVE:
13965 	      go_error_at(index_expr->location(),
13966                           "index expression is negative");
13967 	      return Expression::make_error(location);
13968 	    case Numeric_constant::NC_UL_BIG:
13969 	      go_error_at(index_expr->location(), "index value overflow");
13970 	      return Expression::make_error(location);
13971 	    default:
13972 	      go_unreachable();
13973 	    }
13974 
13975 	  Named_type* ntype = Type::lookup_integer_type("int");
13976 	  Integer_type* inttype = ntype->integer_type();
13977 	  if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13978 	      && index >> (inttype->bits() - 1) != 0)
13979 	    {
13980 	      go_error_at(index_expr->location(), "index value overflow");
13981 	      return Expression::make_error(location);
13982 	    }
13983 
13984 	  if (std::find(indexes->begin(), indexes->end(), index)
13985 	      != indexes->end())
13986 	    {
13987 	      go_error_at(index_expr->location(),
13988                           "duplicate value for index %lu",
13989                           index);
13990 	      return Expression::make_error(location);
13991 	    }
13992 
13993 	  if (!indexes->empty() && index < indexes->back())
13994 	    indexes_out_of_order = true;
13995 
13996 	  indexes->push_back(index);
13997 	}
13998 
13999       vals->push_back(val);
14000 
14001       ++index;
14002     }
14003 
14004   if (indexes->empty())
14005     {
14006       delete indexes;
14007       indexes = NULL;
14008     }
14009 
14010   std::vector<unsigned long>* traverse_order = NULL;
14011   if (indexes_out_of_order)
14012     {
14013       typedef std::vector<IVT_triple> V;
14014 
14015       V v;
14016       v.reserve(indexes->size());
14017       std::vector<unsigned long>::const_iterator pi = indexes->begin();
14018       unsigned long torder = 0;
14019       for (Expression_list::const_iterator pe = vals->begin();
14020 	   pe != vals->end();
14021 	   ++pe, ++pi, ++torder)
14022 	v.push_back(IVT_triple(*pi, torder, *pe));
14023 
14024       std::sort(v.begin(), v.end());
14025 
14026       delete indexes;
14027       delete vals;
14028 
14029       indexes = new std::vector<unsigned long>();
14030       indexes->reserve(v.size());
14031       vals = new Expression_list();
14032       vals->reserve(v.size());
14033       traverse_order = new std::vector<unsigned long>();
14034       traverse_order->reserve(v.size());
14035 
14036       for (V::const_iterator p = v.begin(); p != v.end(); ++p)
14037 	{
14038 	  indexes->push_back(p->index);
14039 	  vals->push_back(p->expr);
14040 	  traverse_order->push_back(p->traversal_order);
14041 	}
14042     }
14043 
14044   Expression* ret = this->make_array(type, indexes, vals);
14045   Array_construction_expression* ace = ret->array_literal();
14046   if (ace != NULL && traverse_order != NULL)
14047     ace->set_traverse_order(traverse_order);
14048   return ret;
14049 }
14050 
14051 // Actually build the array composite literal. This handles
14052 // [...]{...}.
14053 
14054 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)14055 Composite_literal_expression::make_array(
14056     Type* type,
14057     const std::vector<unsigned long>* indexes,
14058     Expression_list* vals)
14059 {
14060   Location location = this->location();
14061   Array_type* at = type->array_type();
14062 
14063   if (at->length() != NULL && at->length()->is_nil_expression())
14064     {
14065       size_t size;
14066       if (vals == NULL)
14067 	size = 0;
14068       else if (indexes != NULL)
14069 	size = indexes->back() + 1;
14070       else
14071 	{
14072 	  size = vals->size();
14073 	  Integer_type* it = Type::lookup_integer_type("int")->integer_type();
14074 	  if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
14075 	      && size >> (it->bits() - 1) != 0)
14076 	    {
14077 	      go_error_at(location, "too many elements in composite literal");
14078 	      return Expression::make_error(location);
14079 	    }
14080 	}
14081 
14082       Expression* elen = Expression::make_integer_ul(size, NULL, location);
14083       at = Type::make_array_type(at->element_type(), elen);
14084       type = at;
14085     }
14086   else if (at->length() != NULL
14087 	   && !at->length()->is_error_expression()
14088 	   && this->vals_ != NULL)
14089     {
14090       Numeric_constant nc;
14091       unsigned long val;
14092       if (at->length()->numeric_constant_value(&nc)
14093 	  && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
14094 	{
14095 	  if (indexes == NULL)
14096 	    {
14097 	      if (this->vals_->size() > val)
14098 		{
14099 		  go_error_at(location,
14100                               "too many elements in composite literal");
14101 		  return Expression::make_error(location);
14102 		}
14103 	    }
14104 	  else
14105 	    {
14106 	      unsigned long max = indexes->back();
14107 	      if (max >= val)
14108 		{
14109 		  go_error_at(location,
14110                               ("some element keys in composite literal "
14111                                "are out of range"));
14112 		  return Expression::make_error(location);
14113 		}
14114 	    }
14115 	}
14116     }
14117 
14118   if (at->length() != NULL)
14119     return new Fixed_array_construction_expression(type, indexes, vals,
14120 						   location);
14121   else
14122     return new Slice_construction_expression(type, indexes, vals, location);
14123 }
14124 
14125 // Lower a map composite literal.
14126 
14127 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)14128 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
14129 					Statement_inserter* inserter,
14130 					Type* type)
14131 {
14132   Location location = this->location();
14133   if (this->vals_ != NULL)
14134     {
14135       if (!this->has_keys_)
14136 	{
14137 	  go_error_at(location, "map composite literal must have keys");
14138 	  return Expression::make_error(location);
14139 	}
14140 
14141       for (Expression_list::iterator p = this->vals_->begin();
14142 	   p != this->vals_->end();
14143 	   p += 2)
14144 	{
14145 	  if (*p == NULL)
14146 	    {
14147 	      ++p;
14148 	      go_error_at((*p)->location(),
14149                           ("map composite literal must "
14150                            "have keys for every value"));
14151 	      return Expression::make_error(location);
14152 	    }
14153 	  // Make sure we have lowered the key; it may not have been
14154 	  // lowered in order to handle keys for struct composite
14155 	  // literals.  Lower it now to get the right error message.
14156 	  if ((*p)->unknown_expression() != NULL)
14157 	    {
14158 	      (*p)->unknown_expression()->clear_is_composite_literal_key();
14159 	      gogo->lower_expression(function, inserter, &*p);
14160 	      go_assert((*p)->is_error_expression());
14161 	      return Expression::make_error(location);
14162 	    }
14163 	}
14164     }
14165 
14166   return new Map_construction_expression(type, this->vals_, location);
14167 }
14168 
14169 // Copy.
14170 
14171 Expression*
do_copy()14172 Composite_literal_expression::do_copy()
14173 {
14174   Composite_literal_expression* ret =
14175     new Composite_literal_expression(this->type_->copy_expressions(),
14176 				     this->depth_, this->has_keys_,
14177 				     (this->vals_ == NULL
14178 				      ? NULL
14179 				      : this->vals_->copy()),
14180 				     this->all_are_names_,
14181 				     this->location());
14182   ret->key_path_ = this->key_path_;
14183   return ret;
14184 }
14185 
14186 // Dump ast representation for a composite literal expression.
14187 
14188 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14189 Composite_literal_expression::do_dump_expression(
14190                                Ast_dump_context* ast_dump_context) const
14191 {
14192   ast_dump_context->ostream() << "composite(";
14193   ast_dump_context->dump_type(this->type_);
14194   ast_dump_context->ostream() << ", {";
14195   ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14196   ast_dump_context->ostream() << "})";
14197 }
14198 
14199 // Make a composite literal expression.
14200 
14201 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)14202 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14203 				   Expression_list* vals, bool all_are_names,
14204 				   Location location)
14205 {
14206   return new Composite_literal_expression(type, depth, has_keys, vals,
14207 					  all_are_names, location);
14208 }
14209 
14210 // Return whether this expression is a composite literal.
14211 
14212 bool
is_composite_literal() const14213 Expression::is_composite_literal() const
14214 {
14215   switch (this->classification_)
14216     {
14217     case EXPRESSION_COMPOSITE_LITERAL:
14218     case EXPRESSION_STRUCT_CONSTRUCTION:
14219     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14220     case EXPRESSION_SLICE_CONSTRUCTION:
14221     case EXPRESSION_MAP_CONSTRUCTION:
14222       return true;
14223     default:
14224       return false;
14225     }
14226 }
14227 
14228 // Return whether this expression is a composite literal which is not
14229 // constant.
14230 
14231 bool
is_nonconstant_composite_literal() const14232 Expression::is_nonconstant_composite_literal() const
14233 {
14234   switch (this->classification_)
14235     {
14236     case EXPRESSION_STRUCT_CONSTRUCTION:
14237       {
14238 	const Struct_construction_expression *psce =
14239 	  static_cast<const Struct_construction_expression*>(this);
14240 	return !psce->is_constant_struct();
14241       }
14242     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14243       {
14244 	const Fixed_array_construction_expression *pace =
14245 	  static_cast<const Fixed_array_construction_expression*>(this);
14246 	return !pace->is_constant_array();
14247       }
14248     case EXPRESSION_SLICE_CONSTRUCTION:
14249       {
14250 	const Slice_construction_expression *pace =
14251 	  static_cast<const Slice_construction_expression*>(this);
14252 	return !pace->is_constant_array();
14253       }
14254     case EXPRESSION_MAP_CONSTRUCTION:
14255       return true;
14256     default:
14257       return false;
14258     }
14259 }
14260 
14261 // Return true if this is a variable or temporary_variable.
14262 
14263 bool
is_variable() const14264 Expression::is_variable() const
14265 {
14266   switch (this->classification_)
14267     {
14268     case EXPRESSION_VAR_REFERENCE:
14269     case EXPRESSION_TEMPORARY_REFERENCE:
14270     case EXPRESSION_SET_AND_USE_TEMPORARY:
14271     case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14272       return true;
14273     default:
14274       return false;
14275     }
14276 }
14277 
14278 // Return true if this is a reference to a local variable.
14279 
14280 bool
is_local_variable() const14281 Expression::is_local_variable() const
14282 {
14283   const Var_expression* ve = this->var_expression();
14284   if (ve == NULL)
14285     return false;
14286   const Named_object* no = ve->named_object();
14287   return (no->is_result_variable()
14288 	  || (no->is_variable() && !no->var_value()->is_global()));
14289 }
14290 
14291 // Class Type_guard_expression.
14292 
14293 // Traversal.
14294 
14295 int
do_traverse(Traverse * traverse)14296 Type_guard_expression::do_traverse(Traverse* traverse)
14297 {
14298   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14299       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14300     return TRAVERSE_EXIT;
14301   return TRAVERSE_CONTINUE;
14302 }
14303 
14304 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14305 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14306                                   Statement_inserter* inserter)
14307 {
14308   if (this->expr_->is_error_expression()
14309       || this->expr_->type()->is_error_type())
14310     {
14311       go_assert(saw_errors());
14312       return Expression::make_error(this->location());
14313     }
14314 
14315   if (!this->expr_->is_variable())
14316     {
14317       Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14318                                                             this->location());
14319       inserter->insert(temp);
14320       this->expr_ =
14321           Expression::make_temporary_reference(temp, this->location());
14322     }
14323   return this;
14324 }
14325 
14326 // Check types of a type guard expression.  The expression must have
14327 // an interface type, but the actual type conversion is checked at run
14328 // time.
14329 
14330 void
do_check_types(Gogo *)14331 Type_guard_expression::do_check_types(Gogo*)
14332 {
14333   Type* expr_type = this->expr_->type();
14334   if (expr_type->interface_type() == NULL)
14335     {
14336       if (!expr_type->is_error() && !this->type_->is_error())
14337 	this->report_error(_("type assertion only valid for interface types"));
14338       this->set_is_error();
14339     }
14340   else if (this->type_->interface_type() == NULL)
14341     {
14342       std::string reason;
14343       if (!expr_type->interface_type()->implements_interface(this->type_,
14344 							     &reason))
14345 	{
14346 	  if (!this->type_->is_error())
14347 	    {
14348 	      if (reason.empty())
14349 		this->report_error(_("impossible type assertion: "
14350 				     "type does not implement interface"));
14351 	      else
14352 		go_error_at(this->location(),
14353                             ("impossible type assertion: "
14354                              "type does not implement interface (%s)"),
14355                             reason.c_str());
14356 	    }
14357 	  this->set_is_error();
14358 	}
14359     }
14360 }
14361 
14362 // Copy.
14363 
14364 Expression*
do_copy()14365 Type_guard_expression::do_copy()
14366 {
14367   return new Type_guard_expression(this->expr_->copy(),
14368 				   this->type_->copy_expressions(),
14369 				   this->location());
14370 }
14371 
14372 // Return the backend representation for a type guard expression.
14373 
14374 Bexpression*
do_get_backend(Translate_context * context)14375 Type_guard_expression::do_get_backend(Translate_context* context)
14376 {
14377   Expression* conversion;
14378   if (this->type_->interface_type() != NULL)
14379     conversion =
14380         Expression::convert_interface_to_interface(this->type_, this->expr_,
14381                                                    true, this->location());
14382   else
14383     conversion =
14384         Expression::convert_for_assignment(context->gogo(), this->type_,
14385                                            this->expr_, this->location());
14386 
14387   Gogo* gogo = context->gogo();
14388   Btype* bt = this->type_->get_backend(gogo);
14389   Bexpression* bexpr = conversion->get_backend(context);
14390   return gogo->backend()->convert_expression(bt, bexpr, this->location());
14391 }
14392 
14393 // Dump ast representation for a type guard expression.
14394 
14395 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14396 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14397     const
14398 {
14399   this->expr_->dump_expression(ast_dump_context);
14400   ast_dump_context->ostream() <<  ".";
14401   ast_dump_context->dump_type(this->type_);
14402 }
14403 
14404 // Make a type guard expression.
14405 
14406 Expression*
make_type_guard(Expression * expr,Type * type,Location location)14407 Expression::make_type_guard(Expression* expr, Type* type,
14408 			    Location location)
14409 {
14410   return new Type_guard_expression(expr, type, location);
14411 }
14412 
14413 // Class Heap_expression.
14414 
14415 // Return the type of the expression stored on the heap.
14416 
14417 Type*
do_type()14418 Heap_expression::do_type()
14419 { return Type::make_pointer_type(this->expr_->type()); }
14420 
14421 // Return the backend representation for allocating an expression on the heap.
14422 
14423 Bexpression*
do_get_backend(Translate_context * context)14424 Heap_expression::do_get_backend(Translate_context* context)
14425 {
14426   Type* etype = this->expr_->type();
14427   if (this->expr_->is_error_expression() || etype->is_error())
14428     return context->backend()->error_expression();
14429 
14430   Location loc = this->location();
14431   Gogo* gogo = context->gogo();
14432   Btype* btype = this->type()->get_backend(gogo);
14433 
14434   Expression* alloc = Expression::make_allocation(etype, loc);
14435   if (this->allocate_on_stack_)
14436     alloc->allocation_expression()->set_allocate_on_stack();
14437   Bexpression* space = alloc->get_backend(context);
14438 
14439   Bstatement* decl;
14440   Named_object* fn = context->function();
14441   go_assert(fn != NULL);
14442   Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14443   Bvariable* space_temp =
14444     gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14445 					space, true, loc, &decl);
14446   Btype* expr_btype = etype->get_backend(gogo);
14447 
14448   Bexpression* bexpr = this->expr_->get_backend(context);
14449 
14450   // If this assignment needs a write barrier, call typedmemmove.  We
14451   // don't do this in the write barrier pass because in some cases
14452   // backend conversion can introduce new Heap_expression values.
14453   Bstatement* assn;
14454   if (!etype->has_pointer() || this->allocate_on_stack_)
14455     {
14456       space = gogo->backend()->var_expression(space_temp, loc);
14457       Bexpression* ref =
14458 	gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14459       assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14460     }
14461   else
14462     {
14463       Bstatement* edecl;
14464       Bvariable* btemp =
14465 	gogo->backend()->temporary_variable(fndecl, context->bblock(),
14466 					    expr_btype, bexpr, true, loc,
14467 					    &edecl);
14468       Bexpression* btempref = gogo->backend()->var_expression(btemp,
14469 							      loc);
14470       Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14471 
14472       Expression* td = Expression::make_type_descriptor(etype, loc);
14473       Type* etype_ptr = Type::make_pointer_type(etype);
14474       space = gogo->backend()->var_expression(space_temp, loc);
14475       Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14476       Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14477       Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14478 					    td, elhs, erhs);
14479       Bexpression* bcall = call->get_backend(context);
14480       Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14481       assn = gogo->backend()->compound_statement(edecl, s);
14482     }
14483   decl = gogo->backend()->compound_statement(decl, assn);
14484   space = gogo->backend()->var_expression(space_temp, loc);
14485   return gogo->backend()->compound_expression(decl, space, loc);
14486 }
14487 
14488 // Dump ast representation for a heap expression.
14489 
14490 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14491 Heap_expression::do_dump_expression(
14492     Ast_dump_context* ast_dump_context) const
14493 {
14494   ast_dump_context->ostream() << "&(";
14495   ast_dump_context->dump_expression(this->expr_);
14496   ast_dump_context->ostream() << ")";
14497 }
14498 
14499 // Allocate an expression on the heap.
14500 
14501 Expression*
make_heap_expression(Expression * expr,Location location)14502 Expression::make_heap_expression(Expression* expr, Location location)
14503 {
14504   return new Heap_expression(expr, location);
14505 }
14506 
14507 // Class Receive_expression.
14508 
14509 // Return the type of a receive expression.
14510 
14511 Type*
do_type()14512 Receive_expression::do_type()
14513 {
14514   if (this->is_error_expression())
14515     return Type::make_error_type();
14516   Channel_type* channel_type = this->channel_->type()->channel_type();
14517   if (channel_type == NULL)
14518     {
14519       this->report_error(_("expected channel"));
14520       return Type::make_error_type();
14521     }
14522   return channel_type->element_type();
14523 }
14524 
14525 // Check types for a receive expression.
14526 
14527 void
do_check_types(Gogo *)14528 Receive_expression::do_check_types(Gogo*)
14529 {
14530   Type* type = this->channel_->type();
14531   if (type->is_error())
14532     {
14533       go_assert(saw_errors());
14534       this->set_is_error();
14535       return;
14536     }
14537   if (type->channel_type() == NULL)
14538     {
14539       this->report_error(_("expected channel"));
14540       return;
14541     }
14542   if (!type->channel_type()->may_receive())
14543     {
14544       this->report_error(_("invalid receive on send-only channel"));
14545       return;
14546     }
14547 }
14548 
14549 // Flattening for receive expressions creates a temporary variable to store
14550 // received data in for receives.
14551 
14552 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14553 Receive_expression::do_flatten(Gogo*, Named_object*,
14554                                Statement_inserter* inserter)
14555 {
14556   Channel_type* channel_type = this->channel_->type()->channel_type();
14557   if (channel_type == NULL)
14558     {
14559       go_assert(saw_errors());
14560       return this;
14561     }
14562   else if (this->channel_->is_error_expression())
14563    {
14564      go_assert(saw_errors());
14565      return Expression::make_error(this->location());
14566    }
14567 
14568   Type* element_type = channel_type->element_type();
14569   if (this->temp_receiver_ == NULL)
14570     {
14571       this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14572 						       this->location());
14573       this->temp_receiver_->set_is_address_taken();
14574       inserter->insert(this->temp_receiver_);
14575     }
14576 
14577   return this;
14578 }
14579 
14580 // Get the backend representation for a receive expression.
14581 
14582 Bexpression*
do_get_backend(Translate_context * context)14583 Receive_expression::do_get_backend(Translate_context* context)
14584 {
14585   Location loc = this->location();
14586 
14587   Channel_type* channel_type = this->channel_->type()->channel_type();
14588   if (channel_type == NULL)
14589     {
14590       go_assert(this->channel_->type()->is_error());
14591       return context->backend()->error_expression();
14592     }
14593 
14594   Expression* recv_ref =
14595     Expression::make_temporary_reference(this->temp_receiver_, loc);
14596   Expression* recv_addr =
14597     Expression::make_temporary_reference(this->temp_receiver_, loc);
14598   recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14599   Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
14600 					this->channel_, recv_addr);
14601   return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14602 }
14603 
14604 // Dump ast representation for a receive expression.
14605 
14606 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14607 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14608 {
14609   ast_dump_context->ostream() << " <- " ;
14610   ast_dump_context->dump_expression(channel_);
14611 }
14612 
14613 // Make a receive expression.
14614 
14615 Receive_expression*
make_receive(Expression * channel,Location location)14616 Expression::make_receive(Expression* channel, Location location)
14617 {
14618   return new Receive_expression(channel, location);
14619 }
14620 
14621 // An expression which evaluates to a pointer to the type descriptor
14622 // of a type.
14623 
14624 class Type_descriptor_expression : public Expression
14625 {
14626  public:
Type_descriptor_expression(Type * type,Location location)14627   Type_descriptor_expression(Type* type, Location location)
14628     : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14629       type_(type)
14630   { }
14631 
14632  protected:
14633   int
14634   do_traverse(Traverse*);
14635 
14636   Type*
do_type()14637   do_type()
14638   { return Type::make_type_descriptor_ptr_type(); }
14639 
14640   bool
do_is_static_initializer() const14641   do_is_static_initializer() const
14642   { return true; }
14643 
14644   void
do_determine_type(const Type_context *)14645   do_determine_type(const Type_context*)
14646   { }
14647 
14648   Expression*
do_copy()14649   do_copy()
14650   { return this; }
14651 
14652   Bexpression*
do_get_backend(Translate_context * context)14653   do_get_backend(Translate_context* context)
14654   {
14655     return this->type_->type_descriptor_pointer(context->gogo(),
14656 						this->location());
14657   }
14658 
14659   void
14660   do_dump_expression(Ast_dump_context*) const;
14661 
14662  private:
14663   // The type for which this is the descriptor.
14664   Type* type_;
14665 };
14666 
14667 int
do_traverse(Traverse * traverse)14668 Type_descriptor_expression::do_traverse(Traverse* traverse)
14669 {
14670   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14671     return TRAVERSE_EXIT;
14672   return TRAVERSE_CONTINUE;
14673 }
14674 
14675 // Dump ast representation for a type descriptor expression.
14676 
14677 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14678 Type_descriptor_expression::do_dump_expression(
14679     Ast_dump_context* ast_dump_context) const
14680 {
14681   ast_dump_context->dump_type(this->type_);
14682 }
14683 
14684 // Make a type descriptor expression.
14685 
14686 Expression*
make_type_descriptor(Type * type,Location location)14687 Expression::make_type_descriptor(Type* type, Location location)
14688 {
14689   return new Type_descriptor_expression(type, location);
14690 }
14691 
14692 // An expression which evaluates to a pointer to the Garbage Collection symbol
14693 // of a type.
14694 
14695 class GC_symbol_expression : public Expression
14696 {
14697  public:
GC_symbol_expression(Type * type)14698   GC_symbol_expression(Type* type)
14699     : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14700       type_(type)
14701   {}
14702 
14703  protected:
14704   Type*
do_type()14705   do_type()
14706   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14707 
14708   bool
do_is_static_initializer() const14709   do_is_static_initializer() const
14710   { return true; }
14711 
14712   void
do_determine_type(const Type_context *)14713   do_determine_type(const Type_context*)
14714   { }
14715 
14716   Expression*
do_copy()14717   do_copy()
14718   { return this; }
14719 
14720   Bexpression*
do_get_backend(Translate_context * context)14721   do_get_backend(Translate_context* context)
14722   { return this->type_->gc_symbol_pointer(context->gogo()); }
14723 
14724   void
14725   do_dump_expression(Ast_dump_context*) const;
14726 
14727  private:
14728   // The type which this gc symbol describes.
14729   Type* type_;
14730 };
14731 
14732 // Dump ast representation for a gc symbol expression.
14733 
14734 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14735 GC_symbol_expression::do_dump_expression(
14736     Ast_dump_context* ast_dump_context) const
14737 {
14738   ast_dump_context->ostream() << "gcdata(";
14739   ast_dump_context->dump_type(this->type_);
14740   ast_dump_context->ostream() << ")";
14741 }
14742 
14743 // Make a gc symbol expression.
14744 
14745 Expression*
make_gc_symbol(Type * type)14746 Expression::make_gc_symbol(Type* type)
14747 {
14748   return new GC_symbol_expression(type);
14749 }
14750 
14751 // An expression that evaluates to a pointer to a symbol holding the
14752 // ptrmask data of a type.
14753 
14754 class Ptrmask_symbol_expression : public Expression
14755 {
14756  public:
Ptrmask_symbol_expression(Type * type)14757   Ptrmask_symbol_expression(Type* type)
14758     : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14759       type_(type)
14760   {}
14761 
14762  protected:
14763   Type*
do_type()14764   do_type()
14765   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14766 
14767   bool
do_is_static_initializer() const14768   do_is_static_initializer() const
14769   { return true; }
14770 
14771   void
do_determine_type(const Type_context *)14772   do_determine_type(const Type_context*)
14773   { }
14774 
14775   Expression*
do_copy()14776   do_copy()
14777   { return this; }
14778 
14779   Bexpression*
14780   do_get_backend(Translate_context*);
14781 
14782   void
14783   do_dump_expression(Ast_dump_context*) const;
14784 
14785  private:
14786   // The type that this ptrmask symbol describes.
14787   Type* type_;
14788 };
14789 
14790 // Return the ptrmask variable.
14791 
14792 Bexpression*
do_get_backend(Translate_context * context)14793 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14794 {
14795   Gogo* gogo = context->gogo();
14796 
14797   // If this type does not need a gcprog, then we can use the standard
14798   // GC symbol.
14799   int64_t ptrsize, ptrdata;
14800   if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14801     return this->type_->gc_symbol_pointer(gogo);
14802 
14803   // Otherwise we have to build a ptrmask variable, and return a
14804   // pointer to it.
14805 
14806   Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14807   Location bloc = Linemap::predeclared_location();
14808   Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
14809   Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14810 
14811   Type* uint8_type = Type::lookup_integer_type("uint8");
14812   Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14813   Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14814   return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14815 }
14816 
14817 // Dump AST for a ptrmask symbol expression.
14818 
14819 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14820 Ptrmask_symbol_expression::do_dump_expression(
14821     Ast_dump_context* ast_dump_context) const
14822 {
14823   ast_dump_context->ostream() << "ptrmask(";
14824   ast_dump_context->dump_type(this->type_);
14825   ast_dump_context->ostream() << ")";
14826 }
14827 
14828 // Make a ptrmask symbol expression.
14829 
14830 Expression*
make_ptrmask_symbol(Type * type)14831 Expression::make_ptrmask_symbol(Type* type)
14832 {
14833   return new Ptrmask_symbol_expression(type);
14834 }
14835 
14836 // An expression which evaluates to some characteristic of a type.
14837 // This is only used to initialize fields of a type descriptor.  Using
14838 // a new expression class is slightly inefficient but gives us a good
14839 // separation between the frontend and the middle-end with regard to
14840 // how types are laid out.
14841 
14842 class Type_info_expression : public Expression
14843 {
14844  public:
Type_info_expression(Type * type,Type_info type_info)14845   Type_info_expression(Type* type, Type_info type_info)
14846     : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14847       type_(type), type_info_(type_info)
14848   { }
14849 
14850  protected:
14851   bool
do_is_static_initializer() const14852   do_is_static_initializer() const
14853   { return true; }
14854 
14855   Type*
14856   do_type();
14857 
14858   void
do_determine_type(const Type_context *)14859   do_determine_type(const Type_context*)
14860   { }
14861 
14862   Expression*
do_copy()14863   do_copy()
14864   { return this; }
14865 
14866   Bexpression*
14867   do_get_backend(Translate_context* context);
14868 
14869   void
14870   do_dump_expression(Ast_dump_context*) const;
14871 
14872  private:
14873   // The type for which we are getting information.
14874   Type* type_;
14875   // What information we want.
14876   Type_info type_info_;
14877 };
14878 
14879 // The type is chosen to match what the type descriptor struct
14880 // expects.
14881 
14882 Type*
do_type()14883 Type_info_expression::do_type()
14884 {
14885   switch (this->type_info_)
14886     {
14887     case TYPE_INFO_SIZE:
14888     case TYPE_INFO_BACKEND_PTRDATA:
14889     case TYPE_INFO_DESCRIPTOR_PTRDATA:
14890       return Type::lookup_integer_type("uintptr");
14891     case TYPE_INFO_ALIGNMENT:
14892     case TYPE_INFO_FIELD_ALIGNMENT:
14893       return Type::lookup_integer_type("uint8");
14894     default:
14895       go_unreachable();
14896     }
14897 }
14898 
14899 // Return the backend representation for type information.
14900 
14901 Bexpression*
do_get_backend(Translate_context * context)14902 Type_info_expression::do_get_backend(Translate_context* context)
14903 {
14904   Gogo* gogo = context->gogo();
14905   bool ok = true;
14906   int64_t val;
14907   switch (this->type_info_)
14908     {
14909     case TYPE_INFO_SIZE:
14910       ok = this->type_->backend_type_size(gogo, &val);
14911       break;
14912     case TYPE_INFO_ALIGNMENT:
14913       ok = this->type_->backend_type_align(gogo, &val);
14914       break;
14915     case TYPE_INFO_FIELD_ALIGNMENT:
14916       ok = this->type_->backend_type_field_align(gogo, &val);
14917       break;
14918     case TYPE_INFO_BACKEND_PTRDATA:
14919       ok = this->type_->backend_type_ptrdata(gogo, &val);
14920       break;
14921     case TYPE_INFO_DESCRIPTOR_PTRDATA:
14922       ok = this->type_->descriptor_ptrdata(gogo, &val);
14923       break;
14924     default:
14925       go_unreachable();
14926     }
14927   if (!ok)
14928     {
14929       go_assert(saw_errors());
14930       return gogo->backend()->error_expression();
14931     }
14932   Expression* e = Expression::make_integer_int64(val, this->type(),
14933 						 this->location());
14934   return e->get_backend(context);
14935 }
14936 
14937 // Dump ast representation for a type info expression.
14938 
14939 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14940 Type_info_expression::do_dump_expression(
14941     Ast_dump_context* ast_dump_context) const
14942 {
14943   ast_dump_context->ostream() << "typeinfo(";
14944   ast_dump_context->dump_type(this->type_);
14945   ast_dump_context->ostream() << ",";
14946   ast_dump_context->ostream() <<
14947     (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14948     : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14949     : this->type_info_ == TYPE_INFO_SIZE ? "size"
14950     : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14951     : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
14952     : "unknown");
14953   ast_dump_context->ostream() << ")";
14954 }
14955 
14956 // Make a type info expression.
14957 
14958 Expression*
make_type_info(Type * type,Type_info type_info)14959 Expression::make_type_info(Type* type, Type_info type_info)
14960 {
14961   return new Type_info_expression(type, type_info);
14962 }
14963 
14964 // An expression that evaluates to some characteristic of a slice.
14965 // This is used when indexing, bound-checking, or nil checking a slice.
14966 
14967 class Slice_info_expression : public Expression
14968 {
14969  public:
Slice_info_expression(Expression * slice,Slice_info slice_info,Location location)14970   Slice_info_expression(Expression* slice, Slice_info slice_info,
14971                         Location location)
14972     : Expression(EXPRESSION_SLICE_INFO, location),
14973       slice_(slice), slice_info_(slice_info)
14974   { }
14975 
14976  protected:
14977   Type*
14978   do_type();
14979 
14980   void
do_determine_type(const Type_context *)14981   do_determine_type(const Type_context*)
14982   { }
14983 
14984   Expression*
do_copy()14985   do_copy()
14986   {
14987     return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14988                                      this->location());
14989   }
14990 
14991   Bexpression*
14992   do_get_backend(Translate_context* context);
14993 
14994   void
14995   do_dump_expression(Ast_dump_context*) const;
14996 
14997   void
do_issue_nil_check()14998   do_issue_nil_check()
14999   { this->slice_->issue_nil_check(); }
15000 
15001  private:
15002   // The slice for which we are getting information.
15003   Expression* slice_;
15004   // What information we want.
15005   Slice_info slice_info_;
15006 };
15007 
15008 // Return the type of the slice info.
15009 
15010 Type*
do_type()15011 Slice_info_expression::do_type()
15012 {
15013   switch (this->slice_info_)
15014     {
15015     case SLICE_INFO_VALUE_POINTER:
15016       return Type::make_pointer_type(
15017           this->slice_->type()->array_type()->element_type());
15018     case SLICE_INFO_LENGTH:
15019     case SLICE_INFO_CAPACITY:
15020         return Type::lookup_integer_type("int");
15021     default:
15022       go_unreachable();
15023     }
15024 }
15025 
15026 // Return the backend information for slice information.
15027 
15028 Bexpression*
do_get_backend(Translate_context * context)15029 Slice_info_expression::do_get_backend(Translate_context* context)
15030 {
15031   Gogo* gogo = context->gogo();
15032   Bexpression* bslice = this->slice_->get_backend(context);
15033   switch (this->slice_info_)
15034     {
15035     case SLICE_INFO_VALUE_POINTER:
15036     case SLICE_INFO_LENGTH:
15037     case SLICE_INFO_CAPACITY:
15038       return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
15039 						      this->location());
15040       break;
15041     default:
15042       go_unreachable();
15043     }
15044 }
15045 
15046 // Dump ast representation for a type info expression.
15047 
15048 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15049 Slice_info_expression::do_dump_expression(
15050     Ast_dump_context* ast_dump_context) const
15051 {
15052   ast_dump_context->ostream() << "sliceinfo(";
15053   this->slice_->dump_expression(ast_dump_context);
15054   ast_dump_context->ostream() << ",";
15055   ast_dump_context->ostream() <<
15056       (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
15057     : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
15058     : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
15059     : "unknown");
15060   ast_dump_context->ostream() << ")";
15061 }
15062 
15063 // Make a slice info expression.
15064 
15065 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)15066 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
15067                             Location location)
15068 {
15069   return new Slice_info_expression(slice, slice_info, location);
15070 }
15071 
15072 // An expression that represents a slice value: a struct with value pointer,
15073 // length, and capacity fields.
15074 
15075 class Slice_value_expression : public Expression
15076 {
15077  public:
Slice_value_expression(Type * type,Expression * valptr,Expression * len,Expression * cap,Location location)15078   Slice_value_expression(Type* type, Expression* valptr, Expression* len,
15079                          Expression* cap, Location location)
15080       : Expression(EXPRESSION_SLICE_VALUE, location),
15081         type_(type), valptr_(valptr), len_(len), cap_(cap)
15082   { }
15083 
15084  protected:
15085   int
15086   do_traverse(Traverse*);
15087 
15088   Type*
do_type()15089   do_type()
15090   { return this->type_; }
15091 
15092   void
do_determine_type(const Type_context *)15093   do_determine_type(const Type_context*)
15094   { go_unreachable(); }
15095 
15096   Expression*
do_copy()15097   do_copy()
15098   {
15099     return new Slice_value_expression(this->type_->copy_expressions(),
15100 				      this->valptr_->copy(),
15101                                       this->len_->copy(), this->cap_->copy(),
15102                                       this->location());
15103   }
15104 
15105   Bexpression*
15106   do_get_backend(Translate_context* context);
15107 
15108   void
15109   do_dump_expression(Ast_dump_context*) const;
15110 
15111  private:
15112   // The type of the slice value.
15113   Type* type_;
15114   // The pointer to the values in the slice.
15115   Expression* valptr_;
15116   // The length of the slice.
15117   Expression* len_;
15118   // The capacity of the slice.
15119   Expression* cap_;
15120 };
15121 
15122 int
do_traverse(Traverse * traverse)15123 Slice_value_expression::do_traverse(Traverse* traverse)
15124 {
15125   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
15126       || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
15127       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
15128       || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
15129     return TRAVERSE_EXIT;
15130   return TRAVERSE_CONTINUE;
15131 }
15132 
15133 Bexpression*
do_get_backend(Translate_context * context)15134 Slice_value_expression::do_get_backend(Translate_context* context)
15135 {
15136   std::vector<Bexpression*> vals(3);
15137   vals[0] = this->valptr_->get_backend(context);
15138   vals[1] = this->len_->get_backend(context);
15139   vals[2] = this->cap_->get_backend(context);
15140 
15141   Gogo* gogo = context->gogo();
15142   Btype* btype = this->type_->get_backend(gogo);
15143   return gogo->backend()->constructor_expression(btype, vals, this->location());
15144 }
15145 
15146 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15147 Slice_value_expression::do_dump_expression(
15148     Ast_dump_context* ast_dump_context) const
15149 {
15150   ast_dump_context->ostream() << "slicevalue(";
15151   ast_dump_context->ostream() << "values: ";
15152   this->valptr_->dump_expression(ast_dump_context);
15153   ast_dump_context->ostream() << ", length: ";
15154   this->len_->dump_expression(ast_dump_context);
15155   ast_dump_context->ostream() << ", capacity: ";
15156   this->cap_->dump_expression(ast_dump_context);
15157   ast_dump_context->ostream() << ")";
15158 }
15159 
15160 Expression*
make_slice_value(Type * at,Expression * valptr,Expression * len,Expression * cap,Location location)15161 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
15162                              Expression* cap, Location location)
15163 {
15164   go_assert(at->is_slice_type());
15165   return new Slice_value_expression(at, valptr, len, cap, location);
15166 }
15167 
15168 // An expression that evaluates to some characteristic of a non-empty interface.
15169 // This is used to access the method table or underlying object of an interface.
15170 
15171 class Interface_info_expression : public Expression
15172 {
15173  public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)15174   Interface_info_expression(Expression* iface, Interface_info iface_info,
15175                             Location location)
15176     : Expression(EXPRESSION_INTERFACE_INFO, location),
15177       iface_(iface), iface_info_(iface_info)
15178   { }
15179 
15180  protected:
15181   Type*
15182   do_type();
15183 
15184   void
do_determine_type(const Type_context *)15185   do_determine_type(const Type_context*)
15186   { }
15187 
15188   Expression*
do_copy()15189   do_copy()
15190   {
15191     return new Interface_info_expression(this->iface_->copy(),
15192                                          this->iface_info_, this->location());
15193   }
15194 
15195   Bexpression*
15196   do_get_backend(Translate_context* context);
15197 
15198   void
15199   do_dump_expression(Ast_dump_context*) const;
15200 
15201   void
do_issue_nil_check()15202   do_issue_nil_check()
15203   { this->iface_->issue_nil_check(); }
15204 
15205  private:
15206   // The interface for which we are getting information.
15207   Expression* iface_;
15208   // What information we want.
15209   Interface_info iface_info_;
15210 };
15211 
15212 // Return the type of the interface info.
15213 
15214 Type*
do_type()15215 Interface_info_expression::do_type()
15216 {
15217   switch (this->iface_info_)
15218     {
15219     case INTERFACE_INFO_METHODS:
15220       {
15221         typedef Unordered_map(Interface_type*, Type*) Hashtable;
15222         static Hashtable result_types;
15223 
15224         Interface_type* itype = this->iface_->type()->interface_type();
15225 
15226         Hashtable::const_iterator p = result_types.find(itype);
15227         if (p != result_types.end())
15228           return p->second;
15229 
15230         Type* pdt = Type::make_type_descriptor_ptr_type();
15231         if (itype->is_empty())
15232           {
15233             result_types[itype] = pdt;
15234             return pdt;
15235           }
15236 
15237         Location loc = this->location();
15238         Struct_field_list* sfl = new Struct_field_list();
15239         sfl->push_back(
15240             Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15241 
15242         for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15243              p != itype->methods()->end();
15244              ++p)
15245           {
15246             Function_type* ft = p->type()->function_type();
15247             go_assert(ft->receiver() == NULL);
15248 
15249             const Typed_identifier_list* params = ft->parameters();
15250             Typed_identifier_list* mparams = new Typed_identifier_list();
15251             if (params != NULL)
15252               mparams->reserve(params->size() + 1);
15253             Type* vt = Type::make_pointer_type(Type::make_void_type());
15254             mparams->push_back(Typed_identifier("", vt, ft->location()));
15255             if (params != NULL)
15256               {
15257                 for (Typed_identifier_list::const_iterator pp = params->begin();
15258                      pp != params->end();
15259                      ++pp)
15260                   mparams->push_back(*pp);
15261               }
15262 
15263             Typed_identifier_list* mresults = (ft->results() == NULL
15264                                                ? NULL
15265                                                : ft->results()->copy());
15266             Backend_function_type* mft =
15267                 Type::make_backend_function_type(NULL, mparams, mresults,
15268                                                  ft->location());
15269 
15270             std::string fname = Gogo::unpack_hidden_name(p->name());
15271             sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15272           }
15273 
15274 	Struct_type* st = Type::make_struct_type(sfl, loc);
15275 	st->set_is_struct_incomparable();
15276 	Pointer_type *pt = Type::make_pointer_type(st);
15277         result_types[itype] = pt;
15278         return pt;
15279       }
15280     case INTERFACE_INFO_OBJECT:
15281       return Type::make_pointer_type(Type::make_void_type());
15282     default:
15283       go_unreachable();
15284     }
15285 }
15286 
15287 // Return the backend representation for interface information.
15288 
15289 Bexpression*
do_get_backend(Translate_context * context)15290 Interface_info_expression::do_get_backend(Translate_context* context)
15291 {
15292   Gogo* gogo = context->gogo();
15293   Bexpression* biface = this->iface_->get_backend(context);
15294   switch (this->iface_info_)
15295     {
15296     case INTERFACE_INFO_METHODS:
15297     case INTERFACE_INFO_OBJECT:
15298       return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15299 						      this->location());
15300       break;
15301     default:
15302       go_unreachable();
15303     }
15304 }
15305 
15306 // Dump ast representation for an interface info expression.
15307 
15308 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15309 Interface_info_expression::do_dump_expression(
15310     Ast_dump_context* ast_dump_context) const
15311 {
15312   bool is_empty = this->iface_->type()->interface_type()->is_empty();
15313   ast_dump_context->ostream() << "interfaceinfo(";
15314   this->iface_->dump_expression(ast_dump_context);
15315   ast_dump_context->ostream() << ",";
15316   ast_dump_context->ostream() <<
15317       (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15318     : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15319     : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15320     : "unknown");
15321   ast_dump_context->ostream() << ")";
15322 }
15323 
15324 // Make an interface info expression.
15325 
15326 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)15327 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15328                                 Location location)
15329 {
15330   return new Interface_info_expression(iface, iface_info, location);
15331 }
15332 
15333 // An expression that represents an interface value.  The first field is either
15334 // a type descriptor for an empty interface or a pointer to the interface method
15335 // table for a non-empty interface.  The second field is always the object.
15336 
15337 class Interface_value_expression : public Expression
15338 {
15339  public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)15340   Interface_value_expression(Type* type, Expression* first_field,
15341                              Expression* obj, Location location)
15342       : Expression(EXPRESSION_INTERFACE_VALUE, location),
15343         type_(type), first_field_(first_field), obj_(obj)
15344   { }
15345 
15346  protected:
15347   int
15348   do_traverse(Traverse*);
15349 
15350   Type*
do_type()15351   do_type()
15352   { return this->type_; }
15353 
15354   void
do_determine_type(const Type_context *)15355   do_determine_type(const Type_context*)
15356   { go_unreachable(); }
15357 
15358   Expression*
do_copy()15359   do_copy()
15360   {
15361     return new Interface_value_expression(this->type_->copy_expressions(),
15362                                           this->first_field_->copy(),
15363                                           this->obj_->copy(), this->location());
15364   }
15365 
15366   Bexpression*
15367   do_get_backend(Translate_context* context);
15368 
15369   void
15370   do_dump_expression(Ast_dump_context*) const;
15371 
15372  private:
15373   // The type of the interface value.
15374   Type* type_;
15375   // The first field of the interface (either a type descriptor or a pointer
15376   // to the method table.
15377   Expression* first_field_;
15378   // The underlying object of the interface.
15379   Expression* obj_;
15380 };
15381 
15382 int
do_traverse(Traverse * traverse)15383 Interface_value_expression::do_traverse(Traverse* traverse)
15384 {
15385   if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15386       || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15387     return TRAVERSE_EXIT;
15388   return TRAVERSE_CONTINUE;
15389 }
15390 
15391 Bexpression*
do_get_backend(Translate_context * context)15392 Interface_value_expression::do_get_backend(Translate_context* context)
15393 {
15394   std::vector<Bexpression*> vals(2);
15395   vals[0] = this->first_field_->get_backend(context);
15396   vals[1] = this->obj_->get_backend(context);
15397 
15398   Gogo* gogo = context->gogo();
15399   Btype* btype = this->type_->get_backend(gogo);
15400   return gogo->backend()->constructor_expression(btype, vals, this->location());
15401 }
15402 
15403 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15404 Interface_value_expression::do_dump_expression(
15405     Ast_dump_context* ast_dump_context) const
15406 {
15407   ast_dump_context->ostream() << "interfacevalue(";
15408   ast_dump_context->ostream() <<
15409       (this->type_->interface_type()->is_empty()
15410        ? "type_descriptor: "
15411        : "methods: ");
15412   this->first_field_->dump_expression(ast_dump_context);
15413   ast_dump_context->ostream() << ", object: ";
15414   this->obj_->dump_expression(ast_dump_context);
15415   ast_dump_context->ostream() << ")";
15416 }
15417 
15418 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)15419 Expression::make_interface_value(Type* type, Expression* first_value,
15420                                  Expression* object, Location location)
15421 {
15422   return new Interface_value_expression(type, first_value, object, location);
15423 }
15424 
15425 // An interface method table for a pair of types: an interface type and a type
15426 // that implements that interface.
15427 
15428 class Interface_mtable_expression : public Expression
15429 {
15430  public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)15431   Interface_mtable_expression(Interface_type* itype, Type* type,
15432                               bool is_pointer, Location location)
15433       : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15434         itype_(itype), type_(type), is_pointer_(is_pointer),
15435 	method_table_type_(NULL), bvar_(NULL)
15436   { }
15437 
15438  protected:
15439   int
15440   do_traverse(Traverse*);
15441 
15442   Type*
15443   do_type();
15444 
15445   bool
do_is_static_initializer() const15446   do_is_static_initializer() const
15447   { return true; }
15448 
15449   void
do_determine_type(const Type_context *)15450   do_determine_type(const Type_context*)
15451   { go_unreachable(); }
15452 
15453   Expression*
do_copy()15454   do_copy()
15455   {
15456     Interface_type* itype = this->itype_->copy_expressions()->interface_type();
15457     return new Interface_mtable_expression(itype,
15458 					   this->type_->copy_expressions(),
15459                                            this->is_pointer_, this->location());
15460   }
15461 
15462   bool
do_is_addressable() const15463   do_is_addressable() const
15464   { return true; }
15465 
15466   Bexpression*
15467   do_get_backend(Translate_context* context);
15468 
15469   void
15470   do_dump_expression(Ast_dump_context*) const;
15471 
15472  private:
15473   // The interface type for which the methods are defined.
15474   Interface_type* itype_;
15475   // The type to construct the interface method table for.
15476   Type* type_;
15477   // Whether this table contains the method set for the receiver type or the
15478   // pointer receiver type.
15479   bool is_pointer_;
15480   // The type of the method table.
15481   Type* method_table_type_;
15482   // The backend variable that refers to the interface method table.
15483   Bvariable* bvar_;
15484 };
15485 
15486 int
do_traverse(Traverse * traverse)15487 Interface_mtable_expression::do_traverse(Traverse* traverse)
15488 {
15489   if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15490       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15491     return TRAVERSE_EXIT;
15492   return TRAVERSE_CONTINUE;
15493 }
15494 
15495 Type*
do_type()15496 Interface_mtable_expression::do_type()
15497 {
15498   if (this->method_table_type_ != NULL)
15499     return this->method_table_type_;
15500 
15501   const Typed_identifier_list* interface_methods = this->itype_->methods();
15502   go_assert(!interface_methods->empty());
15503 
15504   Struct_field_list* sfl = new Struct_field_list;
15505   Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15506                        this->location());
15507   sfl->push_back(Struct_field(tid));
15508   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15509   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15510        p != interface_methods->end();
15511        ++p)
15512     {
15513       // We want C function pointers here, not func descriptors; model
15514       // using void* pointers.
15515       Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15516       sfl->push_back(Struct_field(method));
15517     }
15518   Struct_type* st = Type::make_struct_type(sfl, this->location());
15519   st->set_is_struct_incomparable();
15520   this->method_table_type_ = st;
15521   return this->method_table_type_;
15522 }
15523 
15524 Bexpression*
do_get_backend(Translate_context * context)15525 Interface_mtable_expression::do_get_backend(Translate_context* context)
15526 {
15527   Gogo* gogo = context->gogo();
15528   Location loc = Linemap::predeclared_location();
15529   if (this->bvar_ != NULL)
15530     return gogo->backend()->var_expression(this->bvar_, this->location());
15531 
15532   const Typed_identifier_list* interface_methods = this->itype_->methods();
15533   go_assert(!interface_methods->empty());
15534 
15535   std::string mangled_name =
15536     gogo->interface_method_table_name(this->itype_, this->type_,
15537 				      this->is_pointer_);
15538 
15539   // Set is_public if we are converting a named type to an interface
15540   // type that is defined in the same package as the named type, and
15541   // the interface has hidden methods.  In that case the interface
15542   // method table will be defined by the package that defines the
15543   // types.
15544   bool is_public = false;
15545   if (this->type_->named_type() != NULL
15546       && (this->type_->named_type()->named_object()->package()
15547 	  == this->itype_->package()))
15548     {
15549       for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15550 	   p != interface_methods->end();
15551 	   ++p)
15552 	{
15553 	  if (Gogo::is_hidden_name(p->name()))
15554 	    {
15555 	      is_public = true;
15556 	      break;
15557 	    }
15558 	}
15559     }
15560 
15561   if (is_public
15562       && this->type_->named_type()->named_object()->package() != NULL)
15563     {
15564       // The interface conversion table is defined elsewhere.
15565       Btype* btype = this->type()->get_backend(gogo);
15566       std::string asm_name(go_selectively_encode_id(mangled_name));
15567       this->bvar_ =
15568           gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15569                                                       btype, loc);
15570       return gogo->backend()->var_expression(this->bvar_, this->location());
15571     }
15572 
15573   // The first element is the type descriptor.
15574   Type* td_type;
15575   if (!this->is_pointer_)
15576     td_type = this->type_;
15577   else
15578     td_type = Type::make_pointer_type(this->type_);
15579 
15580   std::vector<Backend::Btyped_identifier> bstructfields;
15581 
15582   // Build an interface method table for a type: a type descriptor followed by a
15583   // list of function pointers, one for each interface method.  This is used for
15584   // interfaces.
15585   Expression_list* svals = new Expression_list();
15586   Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15587   svals->push_back(tdescriptor);
15588 
15589   Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15590   Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15591   bstructfields.push_back(btd);
15592 
15593   Named_type* nt = this->type_->named_type();
15594   Struct_type* st = this->type_->struct_type();
15595   go_assert(nt != NULL || st != NULL);
15596 
15597   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15598        p != interface_methods->end();
15599        ++p)
15600     {
15601       bool is_ambiguous;
15602       Method* m;
15603       if (nt != NULL)
15604 	m = nt->method_function(p->name(), &is_ambiguous);
15605       else
15606 	m = st->method_function(p->name(), &is_ambiguous);
15607       go_assert(m != NULL);
15608       Named_object* no = m->named_object();
15609 
15610       go_assert(no->is_function() || no->is_function_declaration());
15611 
15612       Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15613       Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15614       bstructfields.push_back(bmtype);
15615 
15616       svals->push_back(Expression::make_func_code_reference(no, loc));
15617     }
15618 
15619   Btype *btype = gogo->backend()->struct_type(bstructfields);
15620   std::vector<Bexpression*> ctor_bexprs;
15621   for (Expression_list::const_iterator pe = svals->begin();
15622        pe != svals->end();
15623        ++pe)
15624     {
15625       ctor_bexprs.push_back((*pe)->get_backend(context));
15626     }
15627   Bexpression* ctor =
15628       gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
15629 
15630   std::string asm_name(go_selectively_encode_id(mangled_name));
15631   this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15632 						  !is_public, btype, loc);
15633   gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15634                                              !is_public, btype, loc, ctor);
15635   return gogo->backend()->var_expression(this->bvar_, loc);
15636 }
15637 
15638 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15639 Interface_mtable_expression::do_dump_expression(
15640     Ast_dump_context* ast_dump_context) const
15641 {
15642   ast_dump_context->ostream() << "__go_"
15643                               << (this->is_pointer_ ? "pimt__" : "imt_");
15644   ast_dump_context->dump_type(this->itype_);
15645   ast_dump_context->ostream() << "__";
15646   ast_dump_context->dump_type(this->type_);
15647 }
15648 
15649 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)15650 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15651                                       bool is_pointer, Location location)
15652 {
15653   return new Interface_mtable_expression(itype, type, is_pointer, location);
15654 }
15655 
15656 // An expression which evaluates to the offset of a field within a
15657 // struct.  This, like Type_info_expression, q.v., is only used to
15658 // initialize fields of a type descriptor.
15659 
15660 class Struct_field_offset_expression : public Expression
15661 {
15662  public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)15663   Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15664     : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15665 		 Linemap::predeclared_location()),
15666       type_(type), field_(field)
15667   { }
15668 
15669  protected:
15670   bool
do_is_static_initializer() const15671   do_is_static_initializer() const
15672   { return true; }
15673 
15674   Type*
do_type()15675   do_type()
15676   { return Type::lookup_integer_type("uintptr"); }
15677 
15678   void
do_determine_type(const Type_context *)15679   do_determine_type(const Type_context*)
15680   { }
15681 
15682   Expression*
do_copy()15683   do_copy()
15684   { return this; }
15685 
15686   Bexpression*
15687   do_get_backend(Translate_context* context);
15688 
15689   void
15690   do_dump_expression(Ast_dump_context*) const;
15691 
15692  private:
15693   // The type of the struct.
15694   Struct_type* type_;
15695   // The field.
15696   const Struct_field* field_;
15697 };
15698 
15699 // Return the backend representation for a struct field offset.
15700 
15701 Bexpression*
do_get_backend(Translate_context * context)15702 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15703 {
15704   const Struct_field_list* fields = this->type_->fields();
15705   Struct_field_list::const_iterator p;
15706   unsigned i = 0;
15707   for (p = fields->begin();
15708        p != fields->end();
15709        ++p, ++i)
15710     if (&*p == this->field_)
15711       break;
15712   go_assert(&*p == this->field_);
15713 
15714   Gogo* gogo = context->gogo();
15715   Btype* btype = this->type_->get_backend(gogo);
15716 
15717   int64_t offset = gogo->backend()->type_field_offset(btype, i);
15718   Type* uptr_type = Type::lookup_integer_type("uintptr");
15719   Expression* ret =
15720     Expression::make_integer_int64(offset, uptr_type,
15721 				   Linemap::predeclared_location());
15722   return ret->get_backend(context);
15723 }
15724 
15725 // Dump ast representation for a struct field offset expression.
15726 
15727 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15728 Struct_field_offset_expression::do_dump_expression(
15729     Ast_dump_context* ast_dump_context) const
15730 {
15731   ast_dump_context->ostream() <<  "unsafe.Offsetof(";
15732   ast_dump_context->dump_type(this->type_);
15733   ast_dump_context->ostream() << '.';
15734   ast_dump_context->ostream() <<
15735     Gogo::message_name(this->field_->field_name());
15736   ast_dump_context->ostream() << ")";
15737 }
15738 
15739 // Make an expression for a struct field offset.
15740 
15741 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)15742 Expression::make_struct_field_offset(Struct_type* type,
15743 				     const Struct_field* field)
15744 {
15745   return new Struct_field_offset_expression(type, field);
15746 }
15747 
15748 // An expression which evaluates to the address of an unnamed label.
15749 
15750 class Label_addr_expression : public Expression
15751 {
15752  public:
Label_addr_expression(Label * label,Location location)15753   Label_addr_expression(Label* label, Location location)
15754     : Expression(EXPRESSION_LABEL_ADDR, location),
15755       label_(label)
15756   { }
15757 
15758  protected:
15759   Type*
do_type()15760   do_type()
15761   { return Type::make_pointer_type(Type::make_void_type()); }
15762 
15763   void
do_determine_type(const Type_context *)15764   do_determine_type(const Type_context*)
15765   { }
15766 
15767   Expression*
do_copy()15768   do_copy()
15769   { return new Label_addr_expression(this->label_, this->location()); }
15770 
15771   Bexpression*
do_get_backend(Translate_context * context)15772   do_get_backend(Translate_context* context)
15773   { return this->label_->get_addr(context, this->location()); }
15774 
15775   void
do_dump_expression(Ast_dump_context * ast_dump_context) const15776   do_dump_expression(Ast_dump_context* ast_dump_context) const
15777   { ast_dump_context->ostream() << this->label_->name(); }
15778 
15779  private:
15780   // The label whose address we are taking.
15781   Label* label_;
15782 };
15783 
15784 // Make an expression for the address of an unnamed label.
15785 
15786 Expression*
make_label_addr(Label * label,Location location)15787 Expression::make_label_addr(Label* label, Location location)
15788 {
15789   return new Label_addr_expression(label, location);
15790 }
15791 
15792 // Class Conditional_expression.
15793 
15794 // Traversal.
15795 
15796 int
do_traverse(Traverse * traverse)15797 Conditional_expression::do_traverse(Traverse* traverse)
15798 {
15799   if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15800       || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15801       || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15802     return TRAVERSE_EXIT;
15803   return TRAVERSE_CONTINUE;
15804 }
15805 
15806 // Return the type of the conditional expression.
15807 
15808 Type*
do_type()15809 Conditional_expression::do_type()
15810 {
15811   Type* result_type = Type::make_void_type();
15812   if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15813                           NULL))
15814     result_type = this->then_->type();
15815   else if (this->then_->is_nil_expression()
15816            || this->else_->is_nil_expression())
15817     result_type = (!this->then_->is_nil_expression()
15818                    ? this->then_->type()
15819                    : this->else_->type());
15820   return result_type;
15821 }
15822 
15823 // Determine type for a conditional expression.
15824 
15825 void
do_determine_type(const Type_context * context)15826 Conditional_expression::do_determine_type(const Type_context* context)
15827 {
15828   this->cond_->determine_type_no_context();
15829   this->then_->determine_type(context);
15830   this->else_->determine_type(context);
15831 }
15832 
15833 // Get the backend representation of a conditional expression.
15834 
15835 Bexpression*
do_get_backend(Translate_context * context)15836 Conditional_expression::do_get_backend(Translate_context* context)
15837 {
15838   Gogo* gogo = context->gogo();
15839   Btype* result_btype = this->type()->get_backend(gogo);
15840   Bexpression* cond = this->cond_->get_backend(context);
15841   Bexpression* then = this->then_->get_backend(context);
15842   Bexpression* belse = this->else_->get_backend(context);
15843   Bfunction* bfn = context->function()->func_value()->get_decl();
15844   return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
15845 						 belse, this->location());
15846 }
15847 
15848 // Dump ast representation of a conditional expression.
15849 
15850 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15851 Conditional_expression::do_dump_expression(
15852     Ast_dump_context* ast_dump_context) const
15853 {
15854   ast_dump_context->ostream() << "(";
15855   ast_dump_context->dump_expression(this->cond_);
15856   ast_dump_context->ostream() << " ? ";
15857   ast_dump_context->dump_expression(this->then_);
15858   ast_dump_context->ostream() << " : ";
15859   ast_dump_context->dump_expression(this->else_);
15860   ast_dump_context->ostream() << ") ";
15861 }
15862 
15863 // Make a conditional expression.
15864 
15865 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)15866 Expression::make_conditional(Expression* cond, Expression* then,
15867                              Expression* else_expr, Location location)
15868 {
15869   return new Conditional_expression(cond, then, else_expr, location);
15870 }
15871 
15872 // Class Compound_expression.
15873 
15874 // Traversal.
15875 
15876 int
do_traverse(Traverse * traverse)15877 Compound_expression::do_traverse(Traverse* traverse)
15878 {
15879   if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15880       || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15881     return TRAVERSE_EXIT;
15882   return TRAVERSE_CONTINUE;
15883 }
15884 
15885 // Return the type of the compound expression.
15886 
15887 Type*
do_type()15888 Compound_expression::do_type()
15889 {
15890   return this->expr_->type();
15891 }
15892 
15893 // Determine type for a compound expression.
15894 
15895 void
do_determine_type(const Type_context * context)15896 Compound_expression::do_determine_type(const Type_context* context)
15897 {
15898   this->init_->determine_type_no_context();
15899   this->expr_->determine_type(context);
15900 }
15901 
15902 // Get the backend representation of a compound expression.
15903 
15904 Bexpression*
do_get_backend(Translate_context * context)15905 Compound_expression::do_get_backend(Translate_context* context)
15906 {
15907   Gogo* gogo = context->gogo();
15908   Bexpression* binit = this->init_->get_backend(context);
15909   Bfunction* bfunction = context->function()->func_value()->get_decl();
15910   Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15911                                                                 binit);
15912   Bexpression* bexpr = this->expr_->get_backend(context);
15913   return gogo->backend()->compound_expression(init_stmt, bexpr,
15914 					      this->location());
15915 }
15916 
15917 // Dump ast representation of a conditional expression.
15918 
15919 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15920 Compound_expression::do_dump_expression(
15921     Ast_dump_context* ast_dump_context) const
15922 {
15923   ast_dump_context->ostream() << "(";
15924   ast_dump_context->dump_expression(this->init_);
15925   ast_dump_context->ostream() << ",";
15926   ast_dump_context->dump_expression(this->expr_);
15927   ast_dump_context->ostream() << ") ";
15928 }
15929 
15930 // Make a compound expression.
15931 
15932 Expression*
make_compound(Expression * init,Expression * expr,Location location)15933 Expression::make_compound(Expression* init, Expression* expr, Location location)
15934 {
15935   return new Compound_expression(init, expr, location);
15936 }
15937 
15938 // Class Backend_expression.
15939 
15940 int
do_traverse(Traverse *)15941 Backend_expression::do_traverse(Traverse*)
15942 {
15943   return TRAVERSE_CONTINUE;
15944 }
15945 
15946 Expression*
do_copy()15947 Backend_expression::do_copy()
15948 {
15949   return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
15950 				this->location());
15951 }
15952 
15953 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15954 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15955 {
15956   ast_dump_context->ostream() << "backend_expression<";
15957   ast_dump_context->dump_type(this->type_);
15958   ast_dump_context->ostream() << ">";
15959 }
15960 
15961 Expression*
make_backend(Bexpression * bexpr,Type * type,Location location)15962 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15963 {
15964   return new Backend_expression(bexpr, type, location);
15965 }
15966 
15967 // Import an expression.  This comes at the end in order to see the
15968 // various class definitions.
15969 
15970 Expression*
import_expression(Import * imp)15971 Expression::import_expression(Import* imp)
15972 {
15973   int c = imp->peek_char();
15974   if (imp->match_c_string("- ")
15975       || imp->match_c_string("! ")
15976       || imp->match_c_string("^ "))
15977     return Unary_expression::do_import(imp);
15978   else if (c == '(')
15979     return Binary_expression::do_import(imp);
15980   else if (imp->match_c_string("true")
15981 	   || imp->match_c_string("false"))
15982     return Boolean_expression::do_import(imp);
15983   else if (c == '"')
15984     return String_expression::do_import(imp);
15985   else if (c == '-' || (c >= '0' && c <= '9'))
15986     {
15987       // This handles integers, floats and complex constants.
15988       return Integer_expression::do_import(imp);
15989     }
15990   else if (imp->match_c_string("nil"))
15991     return Nil_expression::do_import(imp);
15992   else if (imp->match_c_string("convert"))
15993     return Type_conversion_expression::do_import(imp);
15994   else
15995     {
15996       go_error_at(imp->location(), "import error: expected expression");
15997       return Expression::make_error(imp->location());
15998     }
15999 }
16000 
16001 // Class Expression_list.
16002 
16003 // Traverse the list.
16004 
16005 int
traverse(Traverse * traverse)16006 Expression_list::traverse(Traverse* traverse)
16007 {
16008   for (Expression_list::iterator p = this->begin();
16009        p != this->end();
16010        ++p)
16011     {
16012       if (*p != NULL)
16013 	{
16014 	  if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16015 	    return TRAVERSE_EXIT;
16016 	}
16017     }
16018   return TRAVERSE_CONTINUE;
16019 }
16020 
16021 // Copy the list.
16022 
16023 Expression_list*
copy()16024 Expression_list::copy()
16025 {
16026   Expression_list* ret = new Expression_list();
16027   for (Expression_list::iterator p = this->begin();
16028        p != this->end();
16029        ++p)
16030     {
16031       if (*p == NULL)
16032 	ret->push_back(NULL);
16033       else
16034 	ret->push_back((*p)->copy());
16035     }
16036   return ret;
16037 }
16038 
16039 // Return whether an expression list has an error expression.
16040 
16041 bool
contains_error() const16042 Expression_list::contains_error() const
16043 {
16044   for (Expression_list::const_iterator p = this->begin();
16045        p != this->end();
16046        ++p)
16047     if (*p != NULL && (*p)->is_error_expression())
16048       return true;
16049   return false;
16050 }
16051 
16052 // Class Numeric_constant.
16053 
16054 // Destructor.
16055 
~Numeric_constant()16056 Numeric_constant::~Numeric_constant()
16057 {
16058   this->clear();
16059 }
16060 
16061 // Copy constructor.
16062 
Numeric_constant(const Numeric_constant & a)16063 Numeric_constant::Numeric_constant(const Numeric_constant& a)
16064   : classification_(a.classification_), type_(a.type_)
16065 {
16066   switch (a.classification_)
16067     {
16068     case NC_INVALID:
16069       break;
16070     case NC_INT:
16071     case NC_RUNE:
16072       mpz_init_set(this->u_.int_val, a.u_.int_val);
16073       break;
16074     case NC_FLOAT:
16075       mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16076       break;
16077     case NC_COMPLEX:
16078       mpc_init2(this->u_.complex_val, mpc_precision);
16079       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16080       break;
16081     default:
16082       go_unreachable();
16083     }
16084 }
16085 
16086 // Assignment operator.
16087 
16088 Numeric_constant&
operator =(const Numeric_constant & a)16089 Numeric_constant::operator=(const Numeric_constant& a)
16090 {
16091   this->clear();
16092   this->classification_ = a.classification_;
16093   this->type_ = a.type_;
16094   switch (a.classification_)
16095     {
16096     case NC_INVALID:
16097       break;
16098     case NC_INT:
16099     case NC_RUNE:
16100       mpz_init_set(this->u_.int_val, a.u_.int_val);
16101       break;
16102     case NC_FLOAT:
16103       mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16104       break;
16105     case NC_COMPLEX:
16106       mpc_init2(this->u_.complex_val, mpc_precision);
16107       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16108       break;
16109     default:
16110       go_unreachable();
16111     }
16112   return *this;
16113 }
16114 
16115 // Clear the contents.
16116 
16117 void
clear()16118 Numeric_constant::clear()
16119 {
16120   switch (this->classification_)
16121     {
16122     case NC_INVALID:
16123       break;
16124     case NC_INT:
16125     case NC_RUNE:
16126       mpz_clear(this->u_.int_val);
16127       break;
16128     case NC_FLOAT:
16129       mpfr_clear(this->u_.float_val);
16130       break;
16131     case NC_COMPLEX:
16132       mpc_clear(this->u_.complex_val);
16133       break;
16134     default:
16135       go_unreachable();
16136     }
16137   this->classification_ = NC_INVALID;
16138 }
16139 
16140 // Set to an unsigned long value.
16141 
16142 void
set_unsigned_long(Type * type,unsigned long val)16143 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
16144 {
16145   this->clear();
16146   this->classification_ = NC_INT;
16147   this->type_ = type;
16148   mpz_init_set_ui(this->u_.int_val, val);
16149 }
16150 
16151 // Set to an integer value.
16152 
16153 void
set_int(Type * type,const mpz_t val)16154 Numeric_constant::set_int(Type* type, const mpz_t val)
16155 {
16156   this->clear();
16157   this->classification_ = NC_INT;
16158   this->type_ = type;
16159   mpz_init_set(this->u_.int_val, val);
16160 }
16161 
16162 // Set to a rune value.
16163 
16164 void
set_rune(Type * type,const mpz_t val)16165 Numeric_constant::set_rune(Type* type, const mpz_t val)
16166 {
16167   this->clear();
16168   this->classification_ = NC_RUNE;
16169   this->type_ = type;
16170   mpz_init_set(this->u_.int_val, val);
16171 }
16172 
16173 // Set to a floating point value.
16174 
16175 void
set_float(Type * type,const mpfr_t val)16176 Numeric_constant::set_float(Type* type, const mpfr_t val)
16177 {
16178   this->clear();
16179   this->classification_ = NC_FLOAT;
16180   this->type_ = type;
16181 
16182   // Numeric constants do not have negative zero values, so remove
16183   // them here.  They also don't have infinity or NaN values, but we
16184   // should never see them here.
16185   int bits = 0;
16186   if (type != NULL
16187       && type->float_type() != NULL
16188       && !type->float_type()->is_abstract())
16189     bits = type->float_type()->bits();
16190   if (Numeric_constant::is_float_neg_zero(val, bits))
16191     mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16192   else
16193     mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16194 }
16195 
16196 // Set to a complex value.
16197 
16198 void
set_complex(Type * type,const mpc_t val)16199 Numeric_constant::set_complex(Type* type, const mpc_t val)
16200 {
16201   this->clear();
16202   this->classification_ = NC_COMPLEX;
16203   this->type_ = type;
16204 
16205   // Avoid negative zero as in set_float.
16206   int bits = 0;
16207   if (type != NULL
16208       && type->complex_type() != NULL
16209       && !type->complex_type()->is_abstract())
16210     bits = type->complex_type()->bits() / 2;
16211 
16212   mpfr_t real;
16213   mpfr_init_set(real, mpc_realref(val), GMP_RNDN);
16214   if (Numeric_constant::is_float_neg_zero(real, bits))
16215     mpfr_set_ui(real, 0, GMP_RNDN);
16216 
16217   mpfr_t imag;
16218   mpfr_init_set(imag, mpc_imagref(val), GMP_RNDN);
16219   if (Numeric_constant::is_float_neg_zero(imag, bits))
16220     mpfr_set_ui(imag, 0, GMP_RNDN);
16221 
16222   mpc_init2(this->u_.complex_val, mpc_precision);
16223   mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
16224 
16225   mpfr_clear(real);
16226   mpfr_clear(imag);
16227 }
16228 
16229 // Return whether VAL, at a precision of BITS, is a negative zero.
16230 // BITS may be zero in which case it is ignored.
16231 
16232 bool
is_float_neg_zero(const mpfr_t val,int bits)16233 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
16234 {
16235   if (!mpfr_signbit(val))
16236     return false;
16237   if (mpfr_zero_p(val))
16238     return true;
16239   mp_exp_t min_exp;
16240   switch (bits)
16241     {
16242     case 0:
16243       return false;
16244     case 32:
16245       // In a denormalized float32 the exponent is -126, and there are
16246       // 24 bits of which at least the last must be 1, so the smallest
16247       // representable non-zero exponent is -126 - (24 - 1) == -149.
16248       min_exp = -149;
16249       break;
16250     case 64:
16251       // Minimum exponent is -1022, there are 53 bits.
16252       min_exp = -1074;
16253       break;
16254     default:
16255       go_unreachable();
16256     }
16257   return mpfr_get_exp(val) < min_exp;
16258 }
16259 
16260 // Get an int value.
16261 
16262 void
get_int(mpz_t * val) const16263 Numeric_constant::get_int(mpz_t* val) const
16264 {
16265   go_assert(this->is_int());
16266   mpz_init_set(*val, this->u_.int_val);
16267 }
16268 
16269 // Get a rune value.
16270 
16271 void
get_rune(mpz_t * val) const16272 Numeric_constant::get_rune(mpz_t* val) const
16273 {
16274   go_assert(this->is_rune());
16275   mpz_init_set(*val, this->u_.int_val);
16276 }
16277 
16278 // Get a floating point value.
16279 
16280 void
get_float(mpfr_t * val) const16281 Numeric_constant::get_float(mpfr_t* val) const
16282 {
16283   go_assert(this->is_float());
16284   mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16285 }
16286 
16287 // Get a complex value.
16288 
16289 void
get_complex(mpc_t * val) const16290 Numeric_constant::get_complex(mpc_t* val) const
16291 {
16292   go_assert(this->is_complex());
16293   mpc_init2(*val, mpc_precision);
16294   mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16295 }
16296 
16297 // Express value as unsigned long if possible.
16298 
16299 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const16300 Numeric_constant::to_unsigned_long(unsigned long* val) const
16301 {
16302   switch (this->classification_)
16303     {
16304     case NC_INT:
16305     case NC_RUNE:
16306       return this->mpz_to_unsigned_long(this->u_.int_val, val);
16307     case NC_FLOAT:
16308       return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16309     case NC_COMPLEX:
16310       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16311 	return NC_UL_NOTINT;
16312       return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16313 					 val);
16314     default:
16315       go_unreachable();
16316     }
16317 }
16318 
16319 // Express integer value as unsigned long if possible.
16320 
16321 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const16322 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16323 				       unsigned long *val) const
16324 {
16325   if (mpz_sgn(ival) < 0)
16326     return NC_UL_NEGATIVE;
16327   unsigned long ui = mpz_get_ui(ival);
16328   if (mpz_cmp_ui(ival, ui) != 0)
16329     return NC_UL_BIG;
16330   *val = ui;
16331   return NC_UL_VALID;
16332 }
16333 
16334 // Express floating point value as unsigned long if possible.
16335 
16336 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const16337 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16338 					unsigned long *val) const
16339 {
16340   if (!mpfr_integer_p(fval))
16341     return NC_UL_NOTINT;
16342   mpz_t ival;
16343   mpz_init(ival);
16344   mpfr_get_z(ival, fval, GMP_RNDN);
16345   To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16346   mpz_clear(ival);
16347   return ret;
16348 }
16349 
16350 // Express value as memory size if possible.
16351 
16352 bool
to_memory_size(int64_t * val) const16353 Numeric_constant::to_memory_size(int64_t* val) const
16354 {
16355   switch (this->classification_)
16356     {
16357     case NC_INT:
16358     case NC_RUNE:
16359       return this->mpz_to_memory_size(this->u_.int_val, val);
16360     case NC_FLOAT:
16361       return this->mpfr_to_memory_size(this->u_.float_val, val);
16362     case NC_COMPLEX:
16363       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16364 	return false;
16365       return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16366     default:
16367       go_unreachable();
16368     }
16369 }
16370 
16371 // Express integer as memory size if possible.
16372 
16373 bool
mpz_to_memory_size(const mpz_t ival,int64_t * val) const16374 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16375 {
16376   if (mpz_sgn(ival) < 0)
16377     return false;
16378   if (mpz_fits_slong_p(ival))
16379     {
16380       *val = static_cast<int64_t>(mpz_get_si(ival));
16381       return true;
16382     }
16383 
16384   // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16385   // positive value.
16386   if (mpz_sizeinbase(ival, 2) >= 64)
16387     return false;
16388 
16389   mpz_t q, r;
16390   mpz_init(q);
16391   mpz_init(r);
16392   mpz_tdiv_q_2exp(q, ival, 32);
16393   mpz_tdiv_r_2exp(r, ival, 32);
16394   go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16395   *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16396 	  + static_cast<int64_t>(mpz_get_ui(r)));
16397   mpz_clear(r);
16398   mpz_clear(q);
16399   return true;
16400 }
16401 
16402 // Express floating point value as memory size if possible.
16403 
16404 bool
mpfr_to_memory_size(const mpfr_t fval,int64_t * val) const16405 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16406 {
16407   if (!mpfr_integer_p(fval))
16408     return false;
16409   mpz_t ival;
16410   mpz_init(ival);
16411   mpfr_get_z(ival, fval, GMP_RNDN);
16412   bool ret = this->mpz_to_memory_size(ival, val);
16413   mpz_clear(ival);
16414   return ret;
16415 }
16416 
16417 // Convert value to integer if possible.
16418 
16419 bool
to_int(mpz_t * val) const16420 Numeric_constant::to_int(mpz_t* val) const
16421 {
16422   switch (this->classification_)
16423     {
16424     case NC_INT:
16425     case NC_RUNE:
16426       mpz_init_set(*val, this->u_.int_val);
16427       return true;
16428     case NC_FLOAT:
16429       if (!mpfr_integer_p(this->u_.float_val))
16430 	return false;
16431       mpz_init(*val);
16432       mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16433       return true;
16434     case NC_COMPLEX:
16435       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16436 	  || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16437 	return false;
16438       mpz_init(*val);
16439       mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16440       return true;
16441     default:
16442       go_unreachable();
16443     }
16444 }
16445 
16446 // Convert value to floating point if possible.
16447 
16448 bool
to_float(mpfr_t * val) const16449 Numeric_constant::to_float(mpfr_t* val) const
16450 {
16451   switch (this->classification_)
16452     {
16453     case NC_INT:
16454     case NC_RUNE:
16455       mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16456       return true;
16457     case NC_FLOAT:
16458       mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16459       return true;
16460     case NC_COMPLEX:
16461       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16462 	return false;
16463       mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16464       return true;
16465     default:
16466       go_unreachable();
16467     }
16468 }
16469 
16470 // Convert value to complex.
16471 
16472 bool
to_complex(mpc_t * val) const16473 Numeric_constant::to_complex(mpc_t* val) const
16474 {
16475   mpc_init2(*val, mpc_precision);
16476   switch (this->classification_)
16477     {
16478     case NC_INT:
16479     case NC_RUNE:
16480       mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16481       return true;
16482     case NC_FLOAT:
16483       mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16484       return true;
16485     case NC_COMPLEX:
16486       mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16487       return true;
16488     default:
16489       go_unreachable();
16490     }
16491 }
16492 
16493 // Get the type.
16494 
16495 Type*
type() const16496 Numeric_constant::type() const
16497 {
16498   if (this->type_ != NULL)
16499     return this->type_;
16500   switch (this->classification_)
16501     {
16502     case NC_INT:
16503       return Type::make_abstract_integer_type();
16504     case NC_RUNE:
16505       return Type::make_abstract_character_type();
16506     case NC_FLOAT:
16507       return Type::make_abstract_float_type();
16508     case NC_COMPLEX:
16509       return Type::make_abstract_complex_type();
16510     default:
16511       go_unreachable();
16512     }
16513 }
16514 
16515 // If the constant can be expressed in TYPE, then set the type of the
16516 // constant to TYPE and return true.  Otherwise return false, and, if
16517 // ISSUE_ERROR is true, report an appropriate error message.
16518 
16519 bool
set_type(Type * type,bool issue_error,Location loc)16520 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16521 {
16522   bool ret;
16523   if (type == NULL || type->is_error())
16524     ret = true;
16525   else if (type->integer_type() != NULL)
16526     ret = this->check_int_type(type->integer_type(), issue_error, loc);
16527   else if (type->float_type() != NULL)
16528     ret = this->check_float_type(type->float_type(), issue_error, loc);
16529   else if (type->complex_type() != NULL)
16530     ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16531   else
16532     {
16533       ret = false;
16534       if (issue_error)
16535         go_assert(saw_errors());
16536     }
16537   if (ret)
16538     this->type_ = type;
16539   return ret;
16540 }
16541 
16542 // Check whether the constant can be expressed in an integer type.
16543 
16544 bool
check_int_type(Integer_type * type,bool issue_error,Location location)16545 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
16546 				 Location location)
16547 {
16548   mpz_t val;
16549   switch (this->classification_)
16550     {
16551     case NC_INT:
16552     case NC_RUNE:
16553       mpz_init_set(val, this->u_.int_val);
16554       break;
16555 
16556     case NC_FLOAT:
16557       if (!mpfr_integer_p(this->u_.float_val))
16558 	{
16559 	  if (issue_error)
16560             {
16561               go_error_at(location,
16562                           "floating point constant truncated to integer");
16563               this->set_invalid();
16564             }
16565 	  return false;
16566 	}
16567       mpz_init(val);
16568       mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16569       break;
16570 
16571     case NC_COMPLEX:
16572       if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16573 	  || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16574 	{
16575 	  if (issue_error)
16576             {
16577               go_error_at(location, "complex constant truncated to integer");
16578               this->set_invalid();
16579             }
16580 	  return false;
16581 	}
16582       mpz_init(val);
16583       mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16584       break;
16585 
16586     default:
16587       go_unreachable();
16588     }
16589 
16590   bool ret;
16591   if (type->is_abstract())
16592     ret = true;
16593   else
16594     {
16595       int bits = mpz_sizeinbase(val, 2);
16596       if (type->is_unsigned())
16597 	{
16598 	  // For an unsigned type we can only accept a nonnegative
16599 	  // number, and we must be able to represents at least BITS.
16600 	  ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16601 	}
16602       else
16603 	{
16604 	  // For a signed type we need an extra bit to indicate the
16605 	  // sign.  We have to handle the most negative integer
16606 	  // specially.
16607 	  ret = (bits + 1 <= type->bits()
16608 		 || (bits <= type->bits()
16609 		     && mpz_sgn(val) < 0
16610 		     && (mpz_scan1(val, 0)
16611 			 == static_cast<unsigned long>(type->bits() - 1))
16612 		     && mpz_scan0(val, type->bits()) == ULONG_MAX));
16613 	}
16614     }
16615 
16616   if (!ret && issue_error)
16617     {
16618       go_error_at(location, "integer constant overflow");
16619       this->set_invalid();
16620     }
16621 
16622   return ret;
16623 }
16624 
16625 // Check whether the constant can be expressed in a floating point
16626 // type.
16627 
16628 bool
check_float_type(Float_type * type,bool issue_error,Location location)16629 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
16630 				   Location location)
16631 {
16632   mpfr_t val;
16633   switch (this->classification_)
16634     {
16635     case NC_INT:
16636     case NC_RUNE:
16637       mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16638       break;
16639 
16640     case NC_FLOAT:
16641       mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16642       break;
16643 
16644     case NC_COMPLEX:
16645       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16646 	{
16647 	  if (issue_error)
16648             {
16649               this->set_invalid();
16650               go_error_at(location, "complex constant truncated to float");
16651             }
16652 	  return false;
16653 	}
16654       mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16655       break;
16656 
16657     default:
16658       go_unreachable();
16659     }
16660 
16661   bool ret;
16662   if (type->is_abstract())
16663     ret = true;
16664   else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16665     {
16666       // A NaN or Infinity always fits in the range of the type.
16667       ret = true;
16668     }
16669   else
16670     {
16671       mp_exp_t exp = mpfr_get_exp(val);
16672       mp_exp_t max_exp;
16673       switch (type->bits())
16674 	{
16675 	case 32:
16676 	  max_exp = 128;
16677 	  break;
16678 	case 64:
16679 	  max_exp = 1024;
16680 	  break;
16681 	default:
16682 	  go_unreachable();
16683 	}
16684 
16685       ret = exp <= max_exp;
16686 
16687       if (ret)
16688 	{
16689 	  // Round the constant to the desired type.
16690 	  mpfr_t t;
16691 	  mpfr_init(t);
16692 	  switch (type->bits())
16693 	    {
16694 	    case 32:
16695 	      mpfr_set_prec(t, 24);
16696 	      break;
16697 	    case 64:
16698 	      mpfr_set_prec(t, 53);
16699 	      break;
16700 	    default:
16701 	      go_unreachable();
16702 	    }
16703 	  mpfr_set(t, val, GMP_RNDN);
16704 	  mpfr_set(val, t, GMP_RNDN);
16705 	  mpfr_clear(t);
16706 
16707 	  this->set_float(type, val);
16708 	}
16709     }
16710 
16711   mpfr_clear(val);
16712 
16713   if (!ret && issue_error)
16714     {
16715       go_error_at(location, "floating point constant overflow");
16716       this->set_invalid();
16717     }
16718 
16719   return ret;
16720 }
16721 
16722 // Check whether the constant can be expressed in a complex type.
16723 
16724 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)16725 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16726 				     Location location)
16727 {
16728   if (type->is_abstract())
16729     return true;
16730 
16731   mp_exp_t max_exp;
16732   switch (type->bits())
16733     {
16734     case 64:
16735       max_exp = 128;
16736       break;
16737     case 128:
16738       max_exp = 1024;
16739       break;
16740     default:
16741       go_unreachable();
16742     }
16743 
16744   mpc_t val;
16745   mpc_init2(val, mpc_precision);
16746   switch (this->classification_)
16747     {
16748     case NC_INT:
16749     case NC_RUNE:
16750       mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16751       break;
16752 
16753     case NC_FLOAT:
16754       mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16755       break;
16756 
16757     case NC_COMPLEX:
16758       mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16759       break;
16760 
16761     default:
16762       go_unreachable();
16763     }
16764 
16765   bool ret = true;
16766   if (!mpfr_nan_p(mpc_realref(val))
16767       && !mpfr_inf_p(mpc_realref(val))
16768       && !mpfr_zero_p(mpc_realref(val))
16769       && mpfr_get_exp(mpc_realref(val)) > max_exp)
16770     {
16771       if (issue_error)
16772         {
16773           go_error_at(location, "complex real part overflow");
16774           this->set_invalid();
16775         }
16776       ret = false;
16777     }
16778 
16779   if (!mpfr_nan_p(mpc_imagref(val))
16780       && !mpfr_inf_p(mpc_imagref(val))
16781       && !mpfr_zero_p(mpc_imagref(val))
16782       && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16783     {
16784       if (issue_error)
16785         {
16786           go_error_at(location, "complex imaginary part overflow");
16787           this->set_invalid();
16788         }
16789       ret = false;
16790     }
16791 
16792   if (ret)
16793     {
16794       // Round the constant to the desired type.
16795       mpc_t t;
16796       switch (type->bits())
16797 	{
16798 	case 64:
16799 	  mpc_init2(t, 24);
16800 	  break;
16801 	case 128:
16802 	  mpc_init2(t, 53);
16803 	  break;
16804 	default:
16805 	  go_unreachable();
16806 	}
16807       mpc_set(t, val, MPC_RNDNN);
16808       mpc_set(val, t, MPC_RNDNN);
16809       mpc_clear(t);
16810 
16811       this->set_complex(type, val);
16812     }
16813 
16814   mpc_clear(val);
16815 
16816   return ret;
16817 }
16818 
16819 // Return an Expression for this value.
16820 
16821 Expression*
expression(Location loc) const16822 Numeric_constant::expression(Location loc) const
16823 {
16824   switch (this->classification_)
16825     {
16826     case NC_INT:
16827       return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16828     case NC_RUNE:
16829       return Expression::make_character(&this->u_.int_val, this->type_, loc);
16830     case NC_FLOAT:
16831       return Expression::make_float(&this->u_.float_val, this->type_, loc);
16832     case NC_COMPLEX:
16833       return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16834     case NC_INVALID:
16835       go_assert(saw_errors());
16836       return Expression::make_error(loc);
16837     default:
16838       go_unreachable();
16839     }
16840 }
16841