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_function_body *) const85 Expression::do_export(Export_function_body*) const
86 {
87   go_unreachable();
88 }
89 
90 // Write a name to the export data.
91 
92 void
export_name(Export_function_body * efb,const Named_object * no)93 Expression::export_name(Export_function_body* efb, const Named_object* no)
94 {
95   if (no->package() != NULL)
96     {
97       char buf[50];
98       snprintf(buf, sizeof buf, "<p%d>", efb->package_index(no->package()));
99       efb->write_c_string(buf);
100     }
101 
102   if (!Gogo::is_hidden_name(no->name()))
103     efb->write_string(no->name());
104   else
105     {
106       efb->write_c_string(".");
107       efb->write_string(Gogo::unpack_hidden_name(no->name()));
108     }
109 }
110 
111 // Give an error saying that the value of the expression is not used.
112 
113 void
unused_value_error()114 Expression::unused_value_error()
115 {
116   this->report_error(_("value computed is not used"));
117 }
118 
119 // Note that this expression is an error.  This is called by children
120 // when they discover an error.
121 
122 void
set_is_error()123 Expression::set_is_error()
124 {
125   this->classification_ = EXPRESSION_ERROR;
126 }
127 
128 // For children to call to report an error conveniently.
129 
130 void
report_error(const char * msg)131 Expression::report_error(const char* msg)
132 {
133   go_error_at(this->location_, "%s", msg);
134   this->set_is_error();
135 }
136 
137 // Set types of variables and constants.  This is implemented by the
138 // child class.
139 
140 void
determine_type(const Type_context * context)141 Expression::determine_type(const Type_context* context)
142 {
143   this->do_determine_type(context);
144 }
145 
146 // Set types when there is no context.
147 
148 void
determine_type_no_context()149 Expression::determine_type_no_context()
150 {
151   Type_context context;
152   this->do_determine_type(&context);
153 }
154 
155 // Return true if two expressions refer to the same variable or struct
156 // field.  This can only be true when there are no side effects.
157 
158 bool
is_same_variable(Expression * a,Expression * b)159 Expression::is_same_variable(Expression* a, Expression* b)
160 {
161   if (a->classification() != b->classification())
162     return false;
163 
164   Var_expression* av = a->var_expression();
165   if (av != NULL)
166     return av->named_object() == b->var_expression()->named_object();
167 
168   Field_reference_expression* af = a->field_reference_expression();
169   if (af != NULL)
170     {
171       Field_reference_expression* bf = b->field_reference_expression();
172       return (af->field_index() == bf->field_index()
173 	      && Expression::is_same_variable(af->expr(), bf->expr()));
174     }
175 
176   Unary_expression* au = a->unary_expression();
177   if (au != NULL)
178     {
179       Unary_expression* bu = b->unary_expression();
180       return (au->op() == OPERATOR_MULT
181 	      && bu->op() == OPERATOR_MULT
182 	      && Expression::is_same_variable(au->operand(),
183 					      bu->operand()));
184     }
185 
186   Array_index_expression* aie = a->array_index_expression();
187   if (aie != NULL)
188     {
189       Array_index_expression* bie = b->array_index_expression();
190       return (aie->end() == NULL
191 	      && bie->end() == NULL
192 	      && Expression::is_same_variable(aie->array(), bie->array())
193 	      && Expression::is_same_variable(aie->start(), bie->start()));
194     }
195 
196   Numeric_constant aval;
197   if (a->numeric_constant_value(&aval))
198     {
199       Numeric_constant bval;
200       if (b->numeric_constant_value(&bval))
201 	return aval.equals(bval);
202     }
203 
204   return false;
205 }
206 
207 // Return an expression handling any conversions which must be done during
208 // assignment.
209 
210 Expression*
convert_for_assignment(Gogo *,Type * lhs_type,Expression * rhs,Location location)211 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
212 				   Expression* rhs, Location location)
213 {
214   Type* rhs_type = rhs->type();
215   if (lhs_type->is_error()
216       || rhs_type->is_error()
217       || rhs->is_error_expression())
218     return Expression::make_error(location);
219 
220   bool are_identical = Type::are_identical(lhs_type, rhs_type,
221 					   (Type::COMPARE_ERRORS
222 					    | Type::COMPARE_TAGS),
223 					   NULL);
224   if (!are_identical && lhs_type->interface_type() != NULL)
225     {
226       // Type to interface conversions have been made explicit early.
227       go_assert(rhs_type->interface_type() != NULL);
228       return Expression::convert_interface_to_interface(lhs_type, rhs, false,
229                                                         location);
230     }
231   else if (!are_identical && rhs_type->interface_type() != NULL)
232     return Expression::convert_interface_to_type(lhs_type, rhs, location);
233   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
234     {
235       // Assigning nil to a slice.
236       Expression* nil = Expression::make_nil(location);
237       Expression* zero = Expression::make_integer_ul(0, NULL, location);
238       return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
239     }
240   else if (rhs_type->is_nil_type())
241     return Expression::make_nil(location);
242   else if (are_identical)
243     {
244       if (lhs_type->forwarded() != rhs_type->forwarded())
245 	{
246 	  // Different but identical types require an explicit
247 	  // conversion.  This happens with type aliases.
248 	  return Expression::make_cast(lhs_type, rhs, location);
249 	}
250 
251       // No conversion is needed.
252       return rhs;
253     }
254   else if (lhs_type->points_to() != NULL)
255     return Expression::make_unsafe_cast(lhs_type, rhs, location);
256   else if (lhs_type->is_numeric_type())
257     return Expression::make_cast(lhs_type, rhs, location);
258   else if ((lhs_type->struct_type() != NULL
259             && rhs_type->struct_type() != NULL)
260            || (lhs_type->array_type() != NULL
261                && rhs_type->array_type() != NULL))
262     {
263       // This conversion must be permitted by Go, or we wouldn't have
264       // gotten here.
265       return Expression::make_unsafe_cast(lhs_type, rhs, location);
266     }
267   else
268     return rhs;
269 }
270 
271 // Return an expression for a conversion from a non-interface type to an
272 // interface type.  If ON_STACK is true, it can allocate the storage on
273 // stack.
274 
275 Expression*
convert_type_to_interface(Type * lhs_type,Expression * rhs,bool on_stack,Location location)276 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
277                                       bool on_stack, Location location)
278 {
279   Interface_type* lhs_interface_type = lhs_type->interface_type();
280   bool lhs_is_empty = lhs_interface_type->is_empty();
281 
282   // Since RHS_TYPE is a static type, we can create the interface
283   // method table at compile time.
284 
285   // When setting an interface to nil, we just set both fields to
286   // NULL.
287   Type* rhs_type = rhs->type();
288   if (rhs_type->is_nil_type())
289     {
290       Expression* nil = Expression::make_nil(location);
291       return Expression::make_interface_value(lhs_type, nil, nil, location);
292     }
293 
294   // This should have been checked already.
295   if (!lhs_interface_type->implements_interface(rhs_type, NULL))
296     {
297       go_assert(saw_errors());
298       return Expression::make_error(location);
299     }
300 
301   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
302   // then the first field is the type descriptor for RHS_TYPE.
303   // Otherwise it is the interface method table for RHS_TYPE.
304   Expression* first_field;
305   if (lhs_is_empty)
306     first_field = Expression::make_type_descriptor(rhs_type, location);
307   else
308     {
309       // Build the interface method table for this interface and this
310       // object type: a list of function pointers for each interface
311       // method.
312       Named_type* rhs_named_type = rhs_type->named_type();
313       Struct_type* rhs_struct_type = rhs_type->struct_type();
314       bool is_pointer = false;
315       if (rhs_named_type == NULL && rhs_struct_type == NULL)
316 	{
317 	  rhs_named_type = rhs_type->deref()->named_type();
318 	  rhs_struct_type = rhs_type->deref()->struct_type();
319 	  is_pointer = true;
320 	}
321       if (rhs_named_type != NULL)
322 	first_field =
323 	  rhs_named_type->interface_method_table(lhs_interface_type,
324                                                  is_pointer);
325       else if (rhs_struct_type != NULL)
326 	first_field =
327 	  rhs_struct_type->interface_method_table(lhs_interface_type,
328                                                   is_pointer);
329       else
330 	first_field = Expression::make_nil(location);
331     }
332 
333   Expression* obj;
334   if (rhs_type->is_direct_iface_type())
335     {
336       // We are assigning a pointer to the interface; the interface
337       // holds the pointer itself.
338       obj = unpack_direct_iface(rhs, location);
339     }
340   else
341     {
342       // We are assigning a non-pointer value to the interface; the
343       // interface gets a copy of the value in the heap if it escapes.
344       if (rhs->is_constant())
345         obj = Expression::make_unary(OPERATOR_AND, rhs, location);
346       else
347         {
348           obj = Expression::make_heap_expression(rhs, location);
349           if (on_stack)
350             obj->heap_expression()->set_allocate_on_stack();
351         }
352     }
353 
354   return Expression::make_interface_value(lhs_type, first_field, obj, location);
355 }
356 
357 // Return an expression for the pointer-typed value of a direct interface
358 // type.  Specifically, for single field struct or array, get the single
359 // field, and do this recursively.  The reason for this is that we don't
360 // want to assign a struct or an array to a pointer-typed field.  The
361 // backend may not like that.
362 
363 Expression*
unpack_direct_iface(Expression * rhs,Location loc)364 Expression::unpack_direct_iface(Expression* rhs, Location loc)
365 {
366   Struct_type* st = rhs->type()->struct_type();
367   if (st != NULL)
368     {
369       go_assert(st->field_count() == 1);
370       Expression* field = Expression::make_field_reference(rhs, 0, loc);
371       return unpack_direct_iface(field, loc);
372     }
373   Array_type* at = rhs->type()->array_type();
374   if (at != NULL)
375     {
376       int64_t len;
377       bool ok = at->int_length(&len);
378       go_assert(ok && len == 1);
379       Type* int_type = Type::lookup_integer_type("int");
380       Expression* index = Expression::make_integer_ul(0, int_type, loc);
381       Expression* elem = Expression::make_array_index(rhs, index, NULL, NULL, loc);
382       return unpack_direct_iface(elem, loc);
383     }
384   return rhs;
385 }
386 
387 // The opposite of unpack_direct_iface.
388 
389 Expression*
pack_direct_iface(Type * t,Expression * rhs,Location loc)390 Expression::pack_direct_iface(Type* t, Expression* rhs, Location loc)
391 {
392   if (rhs->type() == t)
393     return rhs;
394   Struct_type* st = t->struct_type();
395   if (st != NULL)
396     {
397       Expression_list* vals = new Expression_list();
398       vals->push_back(pack_direct_iface(st->field(0)->type(), rhs, loc));
399       return Expression::make_struct_composite_literal(t, vals, loc);
400     }
401   Array_type* at = t->array_type();
402   if (at != NULL)
403     {
404       Expression_list* vals = new Expression_list();
405       vals->push_back(pack_direct_iface(at->element_type(), rhs, loc));
406       return Expression::make_array_composite_literal(t, vals, loc);
407     }
408   return Expression::make_unsafe_cast(t, rhs, loc);
409 }
410 
411 // Return an expression for the type descriptor of RHS.
412 
413 Expression*
get_interface_type_descriptor(Expression * rhs)414 Expression::get_interface_type_descriptor(Expression* rhs)
415 {
416   go_assert(rhs->type()->interface_type() != NULL);
417   Location location = rhs->location();
418 
419   // The type descriptor is the first field of an empty interface.
420   if (rhs->type()->interface_type()->is_empty())
421     return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
422                                            location);
423 
424   Expression* mtable =
425       Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
426 
427   Expression* descriptor =
428       Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
429   descriptor = Expression::make_field_reference(descriptor, 0, location);
430   Expression* nil = Expression::make_nil(location);
431 
432   Expression* eq =
433       Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
434   return Expression::make_conditional(eq, nil, descriptor, location);
435 }
436 
437 // Return an expression for the conversion of an interface type to an
438 // interface type.
439 
440 Expression*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)441 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
442                                            bool for_type_guard,
443                                            Location location)
444 {
445   if (Type::are_identical(lhs_type, rhs->type(),
446 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
447 			  NULL))
448     return rhs;
449 
450   Interface_type* lhs_interface_type = lhs_type->interface_type();
451   bool lhs_is_empty = lhs_interface_type->is_empty();
452 
453   // In the general case this requires runtime examination of the type
454   // method table to match it up with the interface methods.
455 
456   // FIXME: If all of the methods in the right hand side interface
457   // also appear in the left hand side interface, then we don't need
458   // to do a runtime check, although we still need to build a new
459   // method table.
460 
461   // We are going to evaluate RHS multiple times.
462   go_assert(rhs->is_variable());
463 
464   // Get the type descriptor for the right hand side.  This will be
465   // NULL for a nil interface.
466   Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
467   Expression* lhs_type_expr =
468       Expression::make_type_descriptor(lhs_type, location);
469 
470   Expression* first_field;
471   if (for_type_guard)
472     {
473       // A type assertion fails when converting a nil interface.
474       first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
475 				       lhs_type_expr, rhs_type_expr);
476     }
477   else if (lhs_is_empty)
478     {
479       // A conversion to an empty interface always succeeds, and the
480       // first field is just the type descriptor of the object.
481       first_field = rhs_type_expr;
482     }
483   else
484     {
485       // A conversion to a non-empty interface may fail, but unlike a
486       // type assertion converting nil will always succeed.
487       first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
488 				       lhs_type_expr, rhs_type_expr);
489     }
490 
491   // The second field is simply the object pointer.
492   Expression* obj =
493       Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
494   return Expression::make_interface_value(lhs_type, first_field, obj, location);
495 }
496 
497 // Return an expression for the conversion of an interface type to a
498 // non-interface type.
499 
500 Expression*
convert_interface_to_type(Type * lhs_type,Expression * rhs,Location location)501 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
502                                       Location location)
503 {
504   // We are going to evaluate RHS multiple times.
505   go_assert(rhs->is_variable());
506 
507   // Build an expression to check that the type is valid.  It will
508   // panic with an appropriate runtime type error if the type is not
509   // valid.
510   // (lhs_type != rhs_type ? panicdottype(lhs_type, rhs_type, inter_type) :
511   //    nil /*dummy*/)
512   Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
513                                                                 location);
514   Expression* rhs_descriptor =
515       Expression::get_interface_type_descriptor(rhs);
516 
517   Type* rhs_type = rhs->type();
518   Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
519                                                                 location);
520 
521   Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, lhs_type_expr,
522                                              rhs_descriptor, location);
523   rhs_descriptor = Expression::get_interface_type_descriptor(rhs);
524   Expression* panic = Runtime::make_call(Runtime::PANICDOTTYPE, location,
525                                          3, lhs_type_expr->copy(),
526                                          rhs_descriptor,
527                                          rhs_inter_expr);
528   Expression* nil = Expression::make_nil(location);
529   Expression* check = Expression::make_conditional(cond, panic, nil,
530                                                    location);
531 
532   // If the conversion succeeds, pull out the value.
533   Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
534                                                     location);
535 
536   // If the value is a direct interface, then it is the value we want.
537   // Otherwise it points to the value.
538   if (lhs_type->is_direct_iface_type())
539     obj = Expression::pack_direct_iface(lhs_type, obj, location);
540   else
541     {
542       obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
543                                          location);
544       obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
545                                          location);
546     }
547   return Expression::make_compound(check, obj, location);
548 }
549 
550 // Convert an expression to its backend representation.  This is implemented by
551 // the child class.  Not that it is not in general safe to call this multiple
552 // times for a single expression, but that we don't catch such errors.
553 
554 Bexpression*
get_backend(Translate_context * context)555 Expression::get_backend(Translate_context* context)
556 {
557   // The child may have marked this expression as having an error.
558   if (this->classification_ == EXPRESSION_ERROR)
559     return context->backend()->error_expression();
560 
561   return this->do_get_backend(context);
562 }
563 
564 // Return a backend expression for VAL.
565 Bexpression*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)566 Expression::backend_numeric_constant_expression(Translate_context* context,
567                                                 Numeric_constant* val)
568 {
569   Gogo* gogo = context->gogo();
570   Type* type = val->type();
571   if (type == NULL)
572     return gogo->backend()->error_expression();
573 
574   Btype* btype = type->get_backend(gogo);
575   Bexpression* ret;
576   if (type->integer_type() != NULL)
577     {
578       mpz_t ival;
579       if (!val->to_int(&ival))
580         {
581           go_assert(saw_errors());
582           return gogo->backend()->error_expression();
583         }
584       ret = gogo->backend()->integer_constant_expression(btype, ival);
585       mpz_clear(ival);
586     }
587   else if (type->float_type() != NULL)
588     {
589       mpfr_t fval;
590       if (!val->to_float(&fval))
591         {
592           go_assert(saw_errors());
593           return gogo->backend()->error_expression();
594         }
595       ret = gogo->backend()->float_constant_expression(btype, fval);
596       mpfr_clear(fval);
597     }
598   else if (type->complex_type() != NULL)
599     {
600       mpc_t cval;
601       if (!val->to_complex(&cval))
602         {
603           go_assert(saw_errors());
604           return gogo->backend()->error_expression();
605         }
606       ret = gogo->backend()->complex_constant_expression(btype, cval);
607       mpc_clear(cval);
608     }
609   else
610     go_unreachable();
611 
612   return ret;
613 }
614 
615 // Insert bounds checks for an index expression.  Check that that VAL
616 // >= 0 and that it fits in an int.  Then check that VAL OP BOUND is
617 // true.  If any condition is false, call one of the CODE runtime
618 // functions, which will panic.
619 
620 void
check_bounds(Expression * val,Operator op,Expression * bound,Runtime::Function code,Runtime::Function code_u,Runtime::Function code_extend,Runtime::Function code_extend_u,Statement_inserter * inserter,Location loc)621 Expression::check_bounds(Expression* val, Operator op, Expression* bound,
622 			 Runtime::Function code,
623 			 Runtime::Function code_u,
624 			 Runtime::Function code_extend,
625 			 Runtime::Function code_extend_u,
626 			 Statement_inserter* inserter,
627 			 Location loc)
628 {
629   go_assert(val->is_variable() || val->is_constant());
630   go_assert(bound->is_variable() || bound->is_constant());
631 
632   Type* int_type = Type::lookup_integer_type("int");
633   int int_type_size = int_type->integer_type()->bits();
634 
635   Type* val_type = val->type();
636   if (val_type->integer_type() == NULL)
637     {
638       go_assert(saw_errors());
639       return;
640     }
641   int val_type_size = val_type->integer_type()->bits();
642   bool val_is_unsigned = val_type->integer_type()->is_unsigned();
643 
644   // Check that VAL >= 0.
645   Expression* check = NULL;
646   if (!val_is_unsigned)
647     {
648       Expression* zero = Expression::make_integer_ul(0, val_type, loc);
649       check = Expression::make_binary(OPERATOR_GE, val->copy(), zero, loc);
650     }
651 
652   // If VAL's type is larger than int, check that VAL fits in an int.
653   if (val_type_size > int_type_size
654       || (val_type_size == int_type_size
655 	  && val_is_unsigned))
656     {
657       mpz_t one;
658       mpz_init_set_ui(one, 1UL);
659 
660       // maxval = 2^(int_type_size - 1) - 1
661       mpz_t maxval;
662       mpz_init(maxval);
663       mpz_mul_2exp(maxval, one, int_type_size - 1);
664       mpz_sub_ui(maxval, maxval, 1);
665       Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
666       mpz_clear(one);
667       mpz_clear(maxval);
668 
669       Expression* cmp = Expression::make_binary(OPERATOR_LE, val->copy(),
670 						max, loc);
671       if (check == NULL)
672 	check = cmp;
673       else
674 	check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
675     }
676 
677   // For the final check we can assume that VAL fits in an int.
678   Expression* ival;
679   if (val_type == int_type)
680     ival = val->copy();
681   else
682     ival = Expression::make_cast(int_type, val->copy(), loc);
683 
684   // BOUND is assumed to fit in an int.  Either it comes from len or
685   // cap, or it was checked by an earlier call.
686   Expression* ibound;
687   if (bound->type() == int_type)
688     ibound = bound->copy();
689   else
690     ibound = Expression::make_cast(int_type, bound->copy(), loc);
691 
692   Expression* cmp = Expression::make_binary(op, ival, ibound, loc);
693   if (check == NULL)
694     check = cmp;
695   else
696     check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
697 
698   Runtime::Function c;
699   if (val_type_size > int_type_size)
700     {
701       if (val_is_unsigned)
702 	c = code_extend_u;
703       else
704 	c = code_extend;
705     }
706   else
707     {
708       if (val_is_unsigned)
709 	c = code_u;
710       else
711 	c = code;
712     }
713 
714   Expression* ignore = Expression::make_boolean(true, loc);
715   Expression* crash = Runtime::make_call(c, loc, 2,
716 					 val->copy(), bound->copy());
717   Expression* cond = Expression::make_conditional(check, ignore, crash, loc);
718   inserter->insert(Statement::make_statement(cond, true));
719 }
720 
721 void
dump_expression(Ast_dump_context * ast_dump_context) const722 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
723 {
724   this->do_dump_expression(ast_dump_context);
725 }
726 
727 // Error expressions.  This are used to avoid cascading errors.
728 
729 class Error_expression : public Expression
730 {
731  public:
Error_expression(Location location)732   Error_expression(Location location)
733     : Expression(EXPRESSION_ERROR, location)
734   { }
735 
736  protected:
737   bool
do_is_constant() const738   do_is_constant() const
739   { return true; }
740 
741   bool
do_numeric_constant_value(Numeric_constant * nc) const742   do_numeric_constant_value(Numeric_constant* nc) const
743   {
744     nc->set_unsigned_long(NULL, 0);
745     return true;
746   }
747 
748   bool
do_discarding_value()749   do_discarding_value()
750   { return true; }
751 
752   Type*
do_type()753   do_type()
754   { return Type::make_error_type(); }
755 
756   void
do_determine_type(const Type_context *)757   do_determine_type(const Type_context*)
758   { }
759 
760   Expression*
do_copy()761   do_copy()
762   { return this; }
763 
764   bool
do_is_addressable() const765   do_is_addressable() const
766   { return true; }
767 
768   Bexpression*
do_get_backend(Translate_context * context)769   do_get_backend(Translate_context* context)
770   { return context->backend()->error_expression(); }
771 
772   void
773   do_dump_expression(Ast_dump_context*) const;
774 };
775 
776 // Dump the ast representation for an error expression to a dump context.
777 
778 void
do_dump_expression(Ast_dump_context * ast_dump_context) const779 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
780 {
781   ast_dump_context->ostream() << "_Error_" ;
782 }
783 
784 Expression*
make_error(Location location)785 Expression::make_error(Location location)
786 {
787   return new Error_expression(location);
788 }
789 
790 // An expression which is really a type.  This is used during parsing.
791 // It is an error if these survive after lowering.
792 
793 class
794 Type_expression : public Expression
795 {
796  public:
Type_expression(Type * type,Location location)797   Type_expression(Type* type, Location location)
798     : Expression(EXPRESSION_TYPE, location),
799       type_(type)
800   { }
801 
802  protected:
803   int
do_traverse(Traverse * traverse)804   do_traverse(Traverse* traverse)
805   { return Type::traverse(this->type_, traverse); }
806 
807   Type*
do_type()808   do_type()
809   { return this->type_; }
810 
811   void
do_determine_type(const Type_context *)812   do_determine_type(const Type_context*)
813   { }
814 
815   void
do_check_types(Gogo *)816   do_check_types(Gogo*)
817   { this->report_error(_("invalid use of type")); }
818 
819   Expression*
do_copy()820   do_copy()
821   { return this; }
822 
823   Bexpression*
do_get_backend(Translate_context *)824   do_get_backend(Translate_context*)
825   { go_unreachable(); }
826 
827   void do_dump_expression(Ast_dump_context*) const;
828 
829  private:
830   // The type which we are representing as an expression.
831   Type* type_;
832 };
833 
834 void
do_dump_expression(Ast_dump_context * ast_dump_context) const835 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
836 {
837   ast_dump_context->dump_type(this->type_);
838 }
839 
840 Expression*
make_type(Type * type,Location location)841 Expression::make_type(Type* type, Location location)
842 {
843   return new Type_expression(type, location);
844 }
845 
846 // Class Parser_expression.
847 
848 Type*
do_type()849 Parser_expression::do_type()
850 {
851   // We should never really ask for the type of a Parser_expression.
852   // However, it can happen, at least when we have an invalid const
853   // whose initializer refers to the const itself.  In that case we
854   // may ask for the type when lowering the const itself.
855   go_assert(saw_errors());
856   return Type::make_error_type();
857 }
858 
859 // Class Var_expression.
860 
861 // Lower a variable expression.  Here we just make sure that the
862 // initialization expression of the variable has been lowered.  This
863 // ensures that we will be able to determine the type of the variable
864 // if necessary.
865 
866 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)867 Var_expression::do_lower(Gogo* gogo, Named_object* function,
868 			 Statement_inserter* inserter, int)
869 {
870   if (this->variable_->is_variable())
871     {
872       Variable* var = this->variable_->var_value();
873       // This is either a local variable or a global variable.  A
874       // reference to a variable which is local to an enclosing
875       // function will be a reference to a field in a closure.
876       if (var->is_global())
877 	{
878 	  function = NULL;
879 	  inserter = NULL;
880 	}
881       var->lower_init_expression(gogo, function, inserter);
882     }
883   return this;
884 }
885 
886 // Return the type of a reference to a variable.
887 
888 Type*
do_type()889 Var_expression::do_type()
890 {
891   if (this->variable_->is_variable())
892     return this->variable_->var_value()->type();
893   else if (this->variable_->is_result_variable())
894     return this->variable_->result_var_value()->type();
895   else
896     go_unreachable();
897 }
898 
899 // Determine the type of a reference to a variable.
900 
901 void
do_determine_type(const Type_context *)902 Var_expression::do_determine_type(const Type_context*)
903 {
904   if (this->variable_->is_variable())
905     this->variable_->var_value()->determine_type();
906 }
907 
908 // Something takes the address of this variable.  This means that we
909 // may want to move the variable onto the heap.
910 
911 void
do_address_taken(bool escapes)912 Var_expression::do_address_taken(bool escapes)
913 {
914   if (!escapes)
915     {
916       if (this->variable_->is_variable())
917 	this->variable_->var_value()->set_non_escaping_address_taken();
918       else if (this->variable_->is_result_variable())
919 	this->variable_->result_var_value()->set_non_escaping_address_taken();
920       else
921 	go_unreachable();
922     }
923   else
924     {
925       if (this->variable_->is_variable())
926 	this->variable_->var_value()->set_address_taken();
927       else if (this->variable_->is_result_variable())
928 	this->variable_->result_var_value()->set_address_taken();
929       else
930 	go_unreachable();
931     }
932 
933   if (this->variable_->is_variable()
934       && this->variable_->var_value()->is_in_heap())
935     {
936       Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
937       Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
938     }
939 }
940 
941 // Export a reference to a variable.
942 
943 void
do_export(Export_function_body * efb) const944 Var_expression::do_export(Export_function_body* efb) const
945 {
946   Named_object* no = this->variable_;
947   if (no->is_result_variable() || !no->var_value()->is_global())
948     efb->write_string(Gogo::unpack_hidden_name(no->name()));
949   else
950     Expression::export_name(efb, no);
951 }
952 
953 // Get the backend representation for a reference to a variable.
954 
955 Bexpression*
do_get_backend(Translate_context * context)956 Var_expression::do_get_backend(Translate_context* context)
957 {
958   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
959 							  context->function());
960   bool is_in_heap;
961   Location loc = this->location();
962   Btype* btype;
963   Gogo* gogo = context->gogo();
964   if (this->variable_->is_variable())
965     {
966       is_in_heap = this->variable_->var_value()->is_in_heap();
967       btype = this->variable_->var_value()->type()->get_backend(gogo);
968     }
969   else if (this->variable_->is_result_variable())
970     {
971       is_in_heap = this->variable_->result_var_value()->is_in_heap();
972       btype = this->variable_->result_var_value()->type()->get_backend(gogo);
973     }
974   else
975     go_unreachable();
976 
977   Bexpression* ret =
978       context->backend()->var_expression(bvar, loc);
979   if (is_in_heap)
980     ret = context->backend()->indirect_expression(btype, ret, true, loc);
981   return ret;
982 }
983 
984 // Ast dump for variable expression.
985 
986 void
do_dump_expression(Ast_dump_context * ast_dump_context) const987 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
988 {
989   ast_dump_context->ostream() << this->variable_->message_name() ;
990 }
991 
992 // Make a reference to a variable in an expression.
993 
994 Expression*
make_var_reference(Named_object * var,Location location)995 Expression::make_var_reference(Named_object* var, Location location)
996 {
997   if (var->is_sink())
998     return Expression::make_sink(location);
999 
1000   // FIXME: Creating a new object for each reference to a variable is
1001   // wasteful.
1002   return new Var_expression(var, location);
1003 }
1004 
1005 // Class Enclosed_var_expression.
1006 
1007 int
do_traverse(Traverse *)1008 Enclosed_var_expression::do_traverse(Traverse*)
1009 {
1010   return TRAVERSE_CONTINUE;
1011 }
1012 
1013 // Lower the reference to the enclosed variable.
1014 
1015 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)1016 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
1017 				  Statement_inserter* inserter, int)
1018 {
1019   gogo->lower_expression(function, inserter, &this->reference_);
1020   return this;
1021 }
1022 
1023 // Flatten the reference to the enclosed variable.
1024 
1025 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)1026 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
1027 				    Statement_inserter* inserter)
1028 {
1029   gogo->flatten_expression(function, inserter, &this->reference_);
1030   return this;
1031 }
1032 
1033 void
do_address_taken(bool escapes)1034 Enclosed_var_expression::do_address_taken(bool escapes)
1035 {
1036   if (!escapes)
1037     {
1038       if (this->variable_->is_variable())
1039 	this->variable_->var_value()->set_non_escaping_address_taken();
1040       else if (this->variable_->is_result_variable())
1041 	this->variable_->result_var_value()->set_non_escaping_address_taken();
1042       else
1043 	go_unreachable();
1044     }
1045   else
1046     {
1047       if (this->variable_->is_variable())
1048 	this->variable_->var_value()->set_address_taken();
1049       else if (this->variable_->is_result_variable())
1050 	this->variable_->result_var_value()->set_address_taken();
1051       else
1052 	go_unreachable();
1053     }
1054 
1055   if (this->variable_->is_variable()
1056       && this->variable_->var_value()->is_in_heap())
1057     Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1058 }
1059 
1060 // Ast dump for enclosed variable expression.
1061 
1062 void
do_dump_expression(Ast_dump_context * adc) const1063 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
1064 {
1065   adc->ostream() << this->variable_->message_name();
1066 }
1067 
1068 // Make a reference to a variable within an enclosing function.
1069 
1070 Expression*
make_enclosing_var_reference(Expression * reference,Named_object * var,Location location)1071 Expression::make_enclosing_var_reference(Expression* reference,
1072 					 Named_object* var, Location location)
1073 {
1074   return new Enclosed_var_expression(reference, var, location);
1075 }
1076 
1077 // Class Temporary_reference_expression.
1078 
1079 // The type.
1080 
1081 Type*
do_type()1082 Temporary_reference_expression::do_type()
1083 {
1084   return this->statement_->type();
1085 }
1086 
1087 // Called if something takes the address of this temporary variable.
1088 // We never have to move temporary variables to the heap, but we do
1089 // need to know that they must live in the stack rather than in a
1090 // register.
1091 
1092 void
do_address_taken(bool)1093 Temporary_reference_expression::do_address_taken(bool)
1094 {
1095   this->statement_->set_is_address_taken();
1096 }
1097 
1098 // Export a reference to a temporary.
1099 
1100 void
do_export(Export_function_body * efb) const1101 Temporary_reference_expression::do_export(Export_function_body* efb) const
1102 {
1103   unsigned int idx = efb->temporary_index(this->statement_);
1104   char buf[50];
1105   snprintf(buf, sizeof buf, "$t%u", idx);
1106   efb->write_c_string(buf);
1107 }
1108 
1109 // Import a reference to a temporary.
1110 
1111 Expression*
do_import(Import_function_body * ifb,Location loc)1112 Temporary_reference_expression::do_import(Import_function_body* ifb,
1113 					  Location loc)
1114 {
1115   std::string id = ifb->read_identifier();
1116   go_assert(id[0] == '$' && id[1] == 't');
1117   const char *p = id.c_str();
1118   char *end;
1119   long idx = strtol(p + 2, &end, 10);
1120   if (*end != '\0' || idx > 0x7fffffff)
1121     {
1122       if (!ifb->saw_error())
1123 	go_error_at(loc,
1124 		    ("invalid export data for %qs: "
1125 		     "invalid temporary reference index at %lu"),
1126 		    ifb->name().c_str(),
1127 		    static_cast<unsigned long>(ifb->off()));
1128       ifb->set_saw_error();
1129       return Expression::make_error(loc);
1130     }
1131 
1132   Temporary_statement* temp =
1133     ifb->temporary_statement(static_cast<unsigned int>(idx));
1134   if (temp == NULL)
1135     {
1136       if (!ifb->saw_error())
1137 	go_error_at(loc,
1138 		    ("invalid export data for %qs: "
1139 		     "undefined temporary reference index at %lu"),
1140 		    ifb->name().c_str(),
1141 		    static_cast<unsigned long>(ifb->off()));
1142       ifb->set_saw_error();
1143       return Expression::make_error(loc);
1144     }
1145 
1146   return Expression::make_temporary_reference(temp, loc);
1147 }
1148 
1149 // Get a backend expression referring to the variable.
1150 
1151 Bexpression*
do_get_backend(Translate_context * context)1152 Temporary_reference_expression::do_get_backend(Translate_context* context)
1153 {
1154   Gogo* gogo = context->gogo();
1155   Bvariable* bvar = this->statement_->get_backend_variable(context);
1156   Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
1157 
1158   // The backend can't always represent the same set of recursive types
1159   // that the Go frontend can.  In some cases this means that a
1160   // temporary variable won't have the right backend type.  Correct
1161   // that here by adding a type cast.  We need to use base() to push
1162   // the circularity down one level.
1163   Type* stype = this->statement_->type();
1164   if (!this->is_lvalue_
1165       && stype->points_to() != NULL
1166       && stype->points_to()->is_void_type())
1167     {
1168       Btype* btype = this->type()->base()->get_backend(gogo);
1169       ret = gogo->backend()->convert_expression(btype, ret, this->location());
1170     }
1171   return ret;
1172 }
1173 
1174 // Ast dump for temporary reference.
1175 
1176 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1177 Temporary_reference_expression::do_dump_expression(
1178                                 Ast_dump_context* ast_dump_context) const
1179 {
1180   ast_dump_context->dump_temp_variable_name(this->statement_);
1181 }
1182 
1183 // Make a reference to a temporary variable.
1184 
1185 Temporary_reference_expression*
make_temporary_reference(Temporary_statement * statement,Location location)1186 Expression::make_temporary_reference(Temporary_statement* statement,
1187 				     Location location)
1188 {
1189   statement->add_use();
1190   return new Temporary_reference_expression(statement, location);
1191 }
1192 
1193 // Class Set_and_use_temporary_expression.
1194 
1195 // Return the type.
1196 
1197 Type*
do_type()1198 Set_and_use_temporary_expression::do_type()
1199 {
1200   return this->statement_->type();
1201 }
1202 
1203 // Determine the type of the expression.
1204 
1205 void
do_determine_type(const Type_context * context)1206 Set_and_use_temporary_expression::do_determine_type(
1207     const Type_context* context)
1208 {
1209   this->expr_->determine_type(context);
1210 }
1211 
1212 // Take the address.
1213 
1214 void
do_address_taken(bool)1215 Set_and_use_temporary_expression::do_address_taken(bool)
1216 {
1217   this->statement_->set_is_address_taken();
1218 }
1219 
1220 // Return the backend representation.
1221 
1222 Bexpression*
do_get_backend(Translate_context * context)1223 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
1224 {
1225   Location loc = this->location();
1226   Gogo* gogo = context->gogo();
1227   Bvariable* bvar = this->statement_->get_backend_variable(context);
1228   Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
1229 
1230   Named_object* fn = context->function();
1231   go_assert(fn != NULL);
1232   Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
1233   Bexpression* bexpr = this->expr_->get_backend(context);
1234   Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
1235                                                           bexpr, loc);
1236   Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
1237   Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
1238   return ret;
1239 }
1240 
1241 // Dump.
1242 
1243 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1244 Set_and_use_temporary_expression::do_dump_expression(
1245     Ast_dump_context* ast_dump_context) const
1246 {
1247   ast_dump_context->ostream() << '(';
1248   ast_dump_context->dump_temp_variable_name(this->statement_);
1249   ast_dump_context->ostream() << " = ";
1250   this->expr_->dump_expression(ast_dump_context);
1251   ast_dump_context->ostream() << ')';
1252 }
1253 
1254 // Make a set-and-use temporary.
1255 
1256 Set_and_use_temporary_expression*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)1257 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1258 				       Expression* expr, Location location)
1259 {
1260   return new Set_and_use_temporary_expression(statement, expr, location);
1261 }
1262 
1263 // A sink expression--a use of the blank identifier _.
1264 
1265 class Sink_expression : public Expression
1266 {
1267  public:
Sink_expression(Location location)1268   Sink_expression(Location location)
1269     : Expression(EXPRESSION_SINK, location),
1270       type_(NULL), bvar_(NULL)
1271   { }
1272 
1273  protected:
1274   bool
do_discarding_value()1275   do_discarding_value()
1276   { return true; }
1277 
1278   Type*
1279   do_type();
1280 
1281   void
1282   do_determine_type(const Type_context*);
1283 
1284   Expression*
do_copy()1285   do_copy()
1286   { return new Sink_expression(this->location()); }
1287 
1288   Bexpression*
1289   do_get_backend(Translate_context*);
1290 
1291   void
1292   do_dump_expression(Ast_dump_context*) const;
1293 
1294  private:
1295   // The type of this sink variable.
1296   Type* type_;
1297   // The temporary variable we generate.
1298   Bvariable* bvar_;
1299 };
1300 
1301 // Return the type of a sink expression.
1302 
1303 Type*
do_type()1304 Sink_expression::do_type()
1305 {
1306   if (this->type_ == NULL)
1307     return Type::make_sink_type();
1308   return this->type_;
1309 }
1310 
1311 // Determine the type of a sink expression.
1312 
1313 void
do_determine_type(const Type_context * context)1314 Sink_expression::do_determine_type(const Type_context* context)
1315 {
1316   if (context->type != NULL)
1317     this->type_ = context->type;
1318 }
1319 
1320 // Return a temporary variable for a sink expression.  This will
1321 // presumably be a write-only variable which the middle-end will drop.
1322 
1323 Bexpression*
do_get_backend(Translate_context * context)1324 Sink_expression::do_get_backend(Translate_context* context)
1325 {
1326   Location loc = this->location();
1327   Gogo* gogo = context->gogo();
1328   if (this->bvar_ == NULL)
1329     {
1330       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1331       Named_object* fn = context->function();
1332       go_assert(fn != NULL);
1333       Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1334       Btype* bt = this->type_->get_backend(context->gogo());
1335       Bstatement* decl;
1336       this->bvar_ =
1337 	gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1338 					    false, loc, &decl);
1339       Bexpression* var_ref =
1340           gogo->backend()->var_expression(this->bvar_, loc);
1341       var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1342       return var_ref;
1343     }
1344   return gogo->backend()->var_expression(this->bvar_, loc);
1345 }
1346 
1347 // Ast dump for sink expression.
1348 
1349 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1350 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1351 {
1352   ast_dump_context->ostream() << "_" ;
1353 }
1354 
1355 // Make a sink expression.
1356 
1357 Expression*
make_sink(Location location)1358 Expression::make_sink(Location location)
1359 {
1360   return new Sink_expression(location);
1361 }
1362 
1363 // Class Func_expression.
1364 
1365 // FIXME: Can a function expression appear in a constant expression?
1366 // The value is unchanging.  Initializing a constant to the address of
1367 // a function seems like it could work, though there might be little
1368 // point to it.
1369 
1370 // Traversal.
1371 
1372 int
do_traverse(Traverse * traverse)1373 Func_expression::do_traverse(Traverse* traverse)
1374 {
1375   return (this->closure_ == NULL
1376 	  ? TRAVERSE_CONTINUE
1377 	  : Expression::traverse(&this->closure_, traverse));
1378 }
1379 
1380 // Return the type of a function expression.
1381 
1382 Type*
do_type()1383 Func_expression::do_type()
1384 {
1385   if (this->function_->is_function())
1386     return this->function_->func_value()->type();
1387   else if (this->function_->is_function_declaration())
1388     return this->function_->func_declaration_value()->type();
1389   else
1390     go_unreachable();
1391 }
1392 
1393 // Get the backend representation for the code of a function expression.
1394 
1395 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1396 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1397 {
1398   Function_type* fntype;
1399   if (no->is_function())
1400     fntype = no->func_value()->type();
1401   else if (no->is_function_declaration())
1402     fntype = no->func_declaration_value()->type();
1403   else
1404     go_unreachable();
1405 
1406   // Builtin functions are handled specially by Call_expression.  We
1407   // can't take their address.
1408   if (fntype->is_builtin())
1409     {
1410       go_error_at(loc,
1411 		  ("invalid use of special built-in function %qs; "
1412 		   "must be called"),
1413 		  no->message_name().c_str());
1414       return gogo->backend()->error_expression();
1415     }
1416 
1417   Bfunction* fndecl;
1418   if (no->is_function())
1419     fndecl = no->func_value()->get_or_make_decl(gogo, no);
1420   else if (no->is_function_declaration())
1421     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1422   else
1423     go_unreachable();
1424 
1425   return gogo->backend()->function_code_expression(fndecl, loc);
1426 }
1427 
1428 // Get the backend representation for a function expression.  This is used when
1429 // we take the address of a function rather than simply calling it.  A func
1430 // value is represented as a pointer to a block of memory.  The first
1431 // word of that memory is a pointer to the function code.  The
1432 // remaining parts of that memory are the addresses of variables that
1433 // the function closes over.
1434 
1435 Bexpression*
do_get_backend(Translate_context * context)1436 Func_expression::do_get_backend(Translate_context* context)
1437 {
1438   // If there is no closure, just use the function descriptor.
1439   if (this->closure_ == NULL)
1440     {
1441       Gogo* gogo = context->gogo();
1442       Named_object* no = this->function_;
1443       Expression* descriptor;
1444       if (no->is_function())
1445 	descriptor = no->func_value()->descriptor(gogo, no);
1446       else if (no->is_function_declaration())
1447 	{
1448 	  if (no->func_declaration_value()->type()->is_builtin())
1449 	    {
1450 	      go_error_at(this->location(),
1451 			  ("invalid use of special built-in function %qs; "
1452 			   "must be called"),
1453 			  no->message_name().c_str());
1454 	      return gogo->backend()->error_expression();
1455 	    }
1456 	  descriptor = no->func_declaration_value()->descriptor(gogo, no);
1457 	}
1458       else
1459 	go_unreachable();
1460 
1461       Bexpression* bdesc = descriptor->get_backend(context);
1462       return gogo->backend()->address_expression(bdesc, this->location());
1463     }
1464 
1465   go_assert(this->function_->func_value()->enclosing() != NULL);
1466 
1467   // If there is a closure, then the closure is itself the function
1468   // expression.  It is a pointer to a struct whose first field points
1469   // to the function code and whose remaining fields are the addresses
1470   // of the closed-over variables.
1471   Bexpression *bexpr = this->closure_->get_backend(context);
1472 
1473   // Introduce a backend type conversion, to account for any differences
1474   // between the argument type (function descriptor, struct with a
1475   // single field) and the closure (struct with multiple fields).
1476   Gogo* gogo = context->gogo();
1477   Btype *btype = this->type()->get_backend(gogo);
1478   return gogo->backend()->convert_expression(btype, bexpr, this->location());
1479 }
1480 
1481 // The cost of inlining a function reference.
1482 
1483 int
do_inlining_cost() const1484 Func_expression::do_inlining_cost() const
1485 {
1486   // FIXME: We don't inline references to nested functions.
1487   if (this->closure_ != NULL)
1488     return 0x100000;
1489   if (this->function_->is_function()
1490       && this->function_->func_value()->enclosing() != NULL)
1491     return 0x100000;
1492 
1493   return 1;
1494 }
1495 
1496 // Export a reference to a function.
1497 
1498 void
do_export(Export_function_body * efb) const1499 Func_expression::do_export(Export_function_body* efb) const
1500 {
1501   Expression::export_name(efb, this->function_);
1502 }
1503 
1504 // Ast dump for function.
1505 
1506 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1507 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1508 {
1509   ast_dump_context->ostream() << this->function_->name();
1510   if (this->closure_ != NULL)
1511     {
1512       ast_dump_context->ostream() << " {closure =  ";
1513       this->closure_->dump_expression(ast_dump_context);
1514       ast_dump_context->ostream() << "}";
1515     }
1516 }
1517 
1518 // Make a reference to a function in an expression.
1519 
1520 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1521 Expression::make_func_reference(Named_object* function, Expression* closure,
1522 				Location location)
1523 {
1524   Func_expression* fe = new Func_expression(function, closure, location);
1525 
1526   // Detect references to builtin functions and set the runtime code if
1527   // appropriate.
1528   if (function->is_function_declaration())
1529     fe->set_runtime_code(Runtime::name_to_code(function->name()));
1530   return fe;
1531 }
1532 
1533 // Class Func_descriptor_expression.
1534 
1535 // Constructor.
1536 
Func_descriptor_expression(Named_object * fn)1537 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1538   : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1539     fn_(fn), dvar_(NULL)
1540 {
1541   go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1542 }
1543 
1544 // Traversal.
1545 
1546 int
do_traverse(Traverse *)1547 Func_descriptor_expression::do_traverse(Traverse*)
1548 {
1549   return TRAVERSE_CONTINUE;
1550 }
1551 
1552 // All function descriptors have the same type.
1553 
1554 Type* Func_descriptor_expression::descriptor_type;
1555 
1556 void
make_func_descriptor_type()1557 Func_descriptor_expression::make_func_descriptor_type()
1558 {
1559   if (Func_descriptor_expression::descriptor_type != NULL)
1560     return;
1561   Type* uintptr_type = Type::lookup_integer_type("uintptr");
1562   Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1563   Func_descriptor_expression::descriptor_type =
1564     Type::make_builtin_named_type("functionDescriptor", struct_type);
1565 }
1566 
1567 Type*
do_type()1568 Func_descriptor_expression::do_type()
1569 {
1570   Func_descriptor_expression::make_func_descriptor_type();
1571   return Func_descriptor_expression::descriptor_type;
1572 }
1573 
1574 // The backend representation for a function descriptor.
1575 
1576 Bexpression*
do_get_backend(Translate_context * context)1577 Func_descriptor_expression::do_get_backend(Translate_context* context)
1578 {
1579   Named_object* no = this->fn_;
1580   Location loc = no->location();
1581   if (this->dvar_ != NULL)
1582     return context->backend()->var_expression(this->dvar_, loc);
1583 
1584   Gogo* gogo = context->gogo();
1585   std::string var_name(gogo->function_descriptor_name(no));
1586   bool is_descriptor = false;
1587   if (no->is_function_declaration()
1588       && !no->func_declaration_value()->asm_name().empty()
1589       && Linemap::is_predeclared_location(no->location()))
1590     is_descriptor = true;
1591 
1592   // The runtime package implements some functions defined in the
1593   // syscall package.  Let the syscall package define the descriptor
1594   // in this case.
1595   if (gogo->compiling_runtime()
1596       && gogo->package_name() == "runtime"
1597       && no->is_function()
1598       && !no->func_value()->asm_name().empty()
1599       && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1600     is_descriptor = true;
1601 
1602   Btype* btype = this->type()->get_backend(gogo);
1603 
1604   Bvariable* bvar;
1605   std::string asm_name(go_selectively_encode_id(var_name));
1606   if (no->package() != NULL || is_descriptor)
1607     bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1608                                                           btype, loc);
1609   else
1610     {
1611       Location bloc = Linemap::predeclared_location();
1612 
1613       // The runtime package has hash/equality functions that are
1614       // referenced by type descriptors outside of the runtime, so the
1615       // function descriptors must be visible even though they are not
1616       // exported.
1617       bool is_exported_runtime = false;
1618       if (gogo->compiling_runtime()
1619 	  && gogo->package_name() == "runtime"
1620 	  && (no->name().find("hash") != std::string::npos
1621 	      || no->name().find("equal") != std::string::npos))
1622 	is_exported_runtime = true;
1623 
1624       bool is_referenced_by_inline =
1625 	no->is_function() && no->func_value()->is_referenced_by_inline();
1626 
1627       bool is_hidden = ((no->is_function()
1628 			 && no->func_value()->enclosing() != NULL)
1629 			|| (Gogo::is_hidden_name(no->name())
1630 			    && !is_exported_runtime
1631 			    && !is_referenced_by_inline)
1632 			|| Gogo::is_thunk(no));
1633 
1634       bvar = context->backend()->immutable_struct(var_name, asm_name,
1635                                                   is_hidden, false,
1636 						  btype, bloc);
1637       Expression_list* vals = new Expression_list();
1638       vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1639       Expression* init =
1640 	Expression::make_struct_composite_literal(this->type(), vals, bloc);
1641       Translate_context bcontext(gogo, NULL, NULL, NULL);
1642       bcontext.set_is_const();
1643       Bexpression* binit = init->get_backend(&bcontext);
1644       context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1645 						    false, btype, bloc, binit);
1646     }
1647 
1648   this->dvar_ = bvar;
1649   return gogo->backend()->var_expression(bvar, loc);
1650 }
1651 
1652 // Print a function descriptor expression.
1653 
1654 void
do_dump_expression(Ast_dump_context * context) const1655 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1656 {
1657   context->ostream() << "[descriptor " << this->fn_->name() << "]";
1658 }
1659 
1660 // Make a function descriptor expression.
1661 
1662 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1663 Expression::make_func_descriptor(Named_object* fn)
1664 {
1665   return new Func_descriptor_expression(fn);
1666 }
1667 
1668 // Make the function descriptor type, so that it can be converted.
1669 
1670 void
make_func_descriptor_type()1671 Expression::make_func_descriptor_type()
1672 {
1673   Func_descriptor_expression::make_func_descriptor_type();
1674 }
1675 
1676 // A reference to just the code of a function.
1677 
1678 class Func_code_reference_expression : public Expression
1679 {
1680  public:
Func_code_reference_expression(Named_object * function,Location location)1681   Func_code_reference_expression(Named_object* function, Location location)
1682     : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1683       function_(function)
1684   { }
1685 
1686  protected:
1687   int
do_traverse(Traverse *)1688   do_traverse(Traverse*)
1689   { return TRAVERSE_CONTINUE; }
1690 
1691   bool
do_is_static_initializer() const1692   do_is_static_initializer() const
1693   { return true; }
1694 
1695   Type*
do_type()1696   do_type()
1697   { return Type::make_pointer_type(Type::make_void_type()); }
1698 
1699   void
do_determine_type(const Type_context *)1700   do_determine_type(const Type_context*)
1701   { }
1702 
1703   Expression*
do_copy()1704   do_copy()
1705   {
1706     return Expression::make_func_code_reference(this->function_,
1707 						this->location());
1708   }
1709 
1710   Bexpression*
1711   do_get_backend(Translate_context*);
1712 
1713   void
do_dump_expression(Ast_dump_context * context) const1714   do_dump_expression(Ast_dump_context* context) const
1715   { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1716 
1717  private:
1718   // The function.
1719   Named_object* function_;
1720 };
1721 
1722 // Get the backend representation for a reference to function code.
1723 
1724 Bexpression*
do_get_backend(Translate_context * context)1725 Func_code_reference_expression::do_get_backend(Translate_context* context)
1726 {
1727   return Func_expression::get_code_pointer(context->gogo(), this->function_,
1728 					   this->location());
1729 }
1730 
1731 // Make a reference to the code of a function.
1732 
1733 Expression*
make_func_code_reference(Named_object * function,Location location)1734 Expression::make_func_code_reference(Named_object* function, Location location)
1735 {
1736   return new Func_code_reference_expression(function, location);
1737 }
1738 
1739 // Class Unknown_expression.
1740 
1741 // Return the name of an unknown expression.
1742 
1743 const std::string&
name() const1744 Unknown_expression::name() const
1745 {
1746   return this->named_object_->name();
1747 }
1748 
1749 // Lower a reference to an unknown name.
1750 
1751 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1752 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1753 {
1754   Location location = this->location();
1755   Named_object* no = this->named_object_;
1756   Named_object* real;
1757   if (!no->is_unknown())
1758     real = no;
1759   else
1760     {
1761       real = no->unknown_value()->real_named_object();
1762       if (real == NULL)
1763 	{
1764 	  if (!this->no_error_message_)
1765 	    go_error_at(location, "reference to undefined name %qs",
1766 			this->named_object_->message_name().c_str());
1767 	  return Expression::make_error(location);
1768 	}
1769     }
1770   switch (real->classification())
1771     {
1772     case Named_object::NAMED_OBJECT_CONST:
1773       return Expression::make_const_reference(real, location);
1774     case Named_object::NAMED_OBJECT_TYPE:
1775       return Expression::make_type(real->type_value(), location);
1776     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1777       if (!this->no_error_message_)
1778 	go_error_at(location, "reference to undefined type %qs",
1779 		    real->message_name().c_str());
1780       return Expression::make_error(location);
1781     case Named_object::NAMED_OBJECT_VAR:
1782       real->var_value()->set_is_used();
1783       return Expression::make_var_reference(real, location);
1784     case Named_object::NAMED_OBJECT_FUNC:
1785     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1786       return Expression::make_func_reference(real, NULL, location);
1787     case Named_object::NAMED_OBJECT_PACKAGE:
1788       if (!this->no_error_message_)
1789 	go_error_at(location, "unexpected reference to package");
1790       return Expression::make_error(location);
1791     default:
1792       go_unreachable();
1793     }
1794 }
1795 
1796 // Dump the ast representation for an unknown expression to a dump context.
1797 
1798 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1799 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1800 {
1801   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1802 			      << ")";
1803 }
1804 
1805 // Make a reference to an unknown name.
1806 
1807 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1808 Expression::make_unknown_reference(Named_object* no, Location location)
1809 {
1810   return new Unknown_expression(no, location);
1811 }
1812 
1813 // A boolean expression.
1814 
1815 class Boolean_expression : public Expression
1816 {
1817  public:
Boolean_expression(bool val,Location location)1818   Boolean_expression(bool val, Location location)
1819     : Expression(EXPRESSION_BOOLEAN, location),
1820       val_(val), type_(NULL)
1821   { }
1822 
1823   static Expression*
1824   do_import(Import_expression*, Location);
1825 
1826  protected:
1827   int
1828   do_traverse(Traverse*);
1829 
1830   bool
do_is_constant() const1831   do_is_constant() const
1832   { return true; }
1833 
1834   bool
do_is_zero_value() const1835   do_is_zero_value() const
1836   { return this->val_ == false; }
1837 
1838   bool
do_boolean_constant_value(bool * val) const1839   do_boolean_constant_value(bool* val) const
1840   {
1841     *val = this->val_;
1842     return true;
1843   }
1844 
1845   bool
do_is_static_initializer() const1846   do_is_static_initializer() const
1847   { return true; }
1848 
1849   Type*
1850   do_type();
1851 
1852   void
1853   do_determine_type(const Type_context*);
1854 
1855   Expression*
do_copy()1856   do_copy()
1857   { return this; }
1858 
1859   Bexpression*
do_get_backend(Translate_context * context)1860   do_get_backend(Translate_context* context)
1861   { return context->backend()->boolean_constant_expression(this->val_); }
1862 
1863   int
do_inlining_cost() const1864   do_inlining_cost() const
1865   { return 1; }
1866 
1867   void
do_export(Export_function_body * efb) const1868   do_export(Export_function_body* efb) const
1869   { efb->write_c_string(this->val_ ? "$true" : "$false"); }
1870 
1871   void
do_dump_expression(Ast_dump_context * ast_dump_context) const1872   do_dump_expression(Ast_dump_context* ast_dump_context) const
1873   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1874 
1875  private:
1876   // The constant.
1877   bool val_;
1878   // The type as determined by context.
1879   Type* type_;
1880 };
1881 
1882 // Traverse a boolean expression.  We just need to traverse the type
1883 // if there is one.
1884 
1885 int
do_traverse(Traverse * traverse)1886 Boolean_expression::do_traverse(Traverse* traverse)
1887 {
1888   if (this->type_ != NULL)
1889     return Type::traverse(this->type_, traverse);
1890   return TRAVERSE_CONTINUE;
1891 }
1892 
1893 // Get the type.
1894 
1895 Type*
do_type()1896 Boolean_expression::do_type()
1897 {
1898   if (this->type_ == NULL)
1899     this->type_ = Type::make_boolean_type();
1900   return this->type_;
1901 }
1902 
1903 // Set the type from the context.
1904 
1905 void
do_determine_type(const Type_context * context)1906 Boolean_expression::do_determine_type(const Type_context* context)
1907 {
1908   if (this->type_ != NULL && !this->type_->is_abstract())
1909     ;
1910   else if (context->type != NULL && context->type->is_boolean_type())
1911     this->type_ = context->type;
1912   else if (!context->may_be_abstract)
1913     this->type_ = Type::lookup_bool_type();
1914 }
1915 
1916 // Import a boolean constant.
1917 
1918 Expression*
do_import(Import_expression * imp,Location loc)1919 Boolean_expression::do_import(Import_expression* imp, Location loc)
1920 {
1921   if (imp->version() >= EXPORT_FORMAT_V3)
1922     imp->require_c_string("$");
1923   if (imp->peek_char() == 't')
1924     {
1925       imp->require_c_string("true");
1926       return Expression::make_boolean(true, loc);
1927     }
1928   else
1929     {
1930       imp->require_c_string("false");
1931       return Expression::make_boolean(false, loc);
1932     }
1933 }
1934 
1935 // Make a boolean expression.
1936 
1937 Expression*
make_boolean(bool val,Location location)1938 Expression::make_boolean(bool val, Location location)
1939 {
1940   return new Boolean_expression(val, location);
1941 }
1942 
1943 // Class String_expression.
1944 
1945 // Traverse a string expression.  We just need to traverse the type
1946 // if there is one.
1947 
1948 int
do_traverse(Traverse * traverse)1949 String_expression::do_traverse(Traverse* traverse)
1950 {
1951   if (this->type_ != NULL)
1952     return Type::traverse(this->type_, traverse);
1953   return TRAVERSE_CONTINUE;
1954 }
1955 
1956 // Get the type.
1957 
1958 Type*
do_type()1959 String_expression::do_type()
1960 {
1961   if (this->type_ == NULL)
1962     this->type_ = Type::make_string_type();
1963   return this->type_;
1964 }
1965 
1966 // Set the type from the context.
1967 
1968 void
do_determine_type(const Type_context * context)1969 String_expression::do_determine_type(const Type_context* context)
1970 {
1971   if (this->type_ != NULL && !this->type_->is_abstract())
1972     ;
1973   else if (context->type != NULL && context->type->is_string_type())
1974     this->type_ = context->type;
1975   else if (!context->may_be_abstract)
1976     this->type_ = Type::lookup_string_type();
1977 }
1978 
1979 // Build a string constant.
1980 
1981 Bexpression*
do_get_backend(Translate_context * context)1982 String_expression::do_get_backend(Translate_context* context)
1983 {
1984   Gogo* gogo = context->gogo();
1985   Btype* btype = Type::make_string_type()->get_backend(gogo);
1986 
1987   Location loc = this->location();
1988   std::vector<Bexpression*> init(2);
1989   Bexpression* str_cst =
1990       gogo->backend()->string_constant_expression(this->val_);
1991   init[0] = gogo->backend()->address_expression(str_cst, loc);
1992 
1993   Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1994   mpz_t lenval;
1995   mpz_init_set_ui(lenval, this->val_.length());
1996   init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1997   mpz_clear(lenval);
1998 
1999   return gogo->backend()->constructor_expression(btype, init, loc);
2000 }
2001 
2002  // Write string literal to string dump.
2003 
2004 void
export_string(String_dump * exp,const String_expression * str)2005 String_expression::export_string(String_dump* exp,
2006 				 const String_expression* str)
2007 {
2008   std::string s;
2009   s.reserve(str->val_.length() * 4 + 2);
2010   s += '"';
2011   for (std::string::const_iterator p = str->val_.begin();
2012        p != str->val_.end();
2013        ++p)
2014     {
2015       if (*p == '\\' || *p == '"')
2016 	{
2017 	  s += '\\';
2018 	  s += *p;
2019 	}
2020       else if (*p >= 0x20 && *p < 0x7f)
2021 	s += *p;
2022       else if (*p == '\n')
2023 	s += "\\n";
2024       else if (*p == '\t')
2025 	s += "\\t";
2026       else
2027 	{
2028 	  s += "\\x";
2029 	  unsigned char c = *p;
2030 	  unsigned int dig = c >> 4;
2031 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2032 	  dig = c & 0xf;
2033 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2034 	}
2035     }
2036   s += '"';
2037   exp->write_string(s);
2038 }
2039 
2040 // Export a string expression.
2041 
2042 void
do_export(Export_function_body * efb) const2043 String_expression::do_export(Export_function_body* efb) const
2044 {
2045   String_expression::export_string(efb, this);
2046 }
2047 
2048 // Import a string expression.
2049 
2050 Expression*
do_import(Import_expression * imp,Location loc)2051 String_expression::do_import(Import_expression* imp, Location loc)
2052 {
2053   imp->require_c_string("\"");
2054   std::string val;
2055   while (true)
2056     {
2057       int c = imp->get_char();
2058       if (c == '"' || c == -1)
2059 	break;
2060       if (c != '\\')
2061 	val += static_cast<char>(c);
2062       else
2063 	{
2064 	  c = imp->get_char();
2065 	  if (c == '\\' || c == '"')
2066 	    val += static_cast<char>(c);
2067 	  else if (c == 'n')
2068 	    val += '\n';
2069 	  else if (c == 't')
2070 	    val += '\t';
2071 	  else if (c == 'x')
2072 	    {
2073 	      c = imp->get_char();
2074 	      unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2075 	      c = imp->get_char();
2076 	      unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2077 	      char v = (vh << 4) | vl;
2078 	      val += v;
2079 	    }
2080 	  else
2081 	    {
2082 	      go_error_at(imp->location(), "bad string constant");
2083 	      return Expression::make_error(loc);
2084 	    }
2085 	}
2086     }
2087   return Expression::make_string(val, loc);
2088 }
2089 
2090 // Ast dump for string expression.
2091 
2092 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2093 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2094 {
2095   String_expression::export_string(ast_dump_context, this);
2096 }
2097 
2098 // Make a string expression with abstract string type (common case).
2099 
2100 Expression*
make_string(const std::string & val,Location location)2101 Expression::make_string(const std::string& val, Location location)
2102 {
2103   return new String_expression(val, NULL, location);
2104 }
2105 
2106 // Make a string expression with a specific string type.
2107 
2108 Expression*
make_string_typed(const std::string & val,Type * type,Location location)2109 Expression::make_string_typed(const std::string& val, Type* type, Location location)
2110 {
2111   return new String_expression(val, type, location);
2112 }
2113 
2114 // An expression that evaluates to some characteristic of a string.
2115 // This is used when indexing, bound-checking, or nil checking a string.
2116 
2117 class String_info_expression : public Expression
2118 {
2119  public:
String_info_expression(Expression * string,String_info string_info,Location location)2120   String_info_expression(Expression* string, String_info string_info,
2121                         Location location)
2122     : Expression(EXPRESSION_STRING_INFO, location),
2123       string_(string), string_info_(string_info)
2124   { }
2125 
2126  protected:
2127   Type*
2128   do_type();
2129 
2130   void
do_determine_type(const Type_context *)2131   do_determine_type(const Type_context*)
2132   { go_unreachable(); }
2133 
2134   Expression*
do_copy()2135   do_copy()
2136   {
2137     return new String_info_expression(this->string_->copy(), this->string_info_,
2138 				      this->location());
2139   }
2140 
2141   Bexpression*
2142   do_get_backend(Translate_context* context);
2143 
2144   void
2145   do_dump_expression(Ast_dump_context*) const;
2146 
2147   void
do_issue_nil_check()2148   do_issue_nil_check()
2149   { this->string_->issue_nil_check(); }
2150 
2151  private:
2152   // The string for which we are getting information.
2153   Expression* string_;
2154   // What information we want.
2155   String_info string_info_;
2156 };
2157 
2158 // Return the type of the string info.
2159 
2160 Type*
do_type()2161 String_info_expression::do_type()
2162 {
2163   switch (this->string_info_)
2164     {
2165     case STRING_INFO_DATA:
2166       {
2167 	Type* byte_type = Type::lookup_integer_type("uint8");
2168 	return Type::make_pointer_type(byte_type);
2169       }
2170     case STRING_INFO_LENGTH:
2171         return Type::lookup_integer_type("int");
2172     default:
2173       go_unreachable();
2174     }
2175 }
2176 
2177 // Return string information in GENERIC.
2178 
2179 Bexpression*
do_get_backend(Translate_context * context)2180 String_info_expression::do_get_backend(Translate_context* context)
2181 {
2182   Gogo* gogo = context->gogo();
2183 
2184   Bexpression* bstring = this->string_->get_backend(context);
2185   switch (this->string_info_)
2186     {
2187     case STRING_INFO_DATA:
2188     case STRING_INFO_LENGTH:
2189       return gogo->backend()->struct_field_expression(bstring,
2190 						      this->string_info_,
2191 						      this->location());
2192       break;
2193     default:
2194       go_unreachable();
2195     }
2196 }
2197 
2198 // Dump ast representation for a type info expression.
2199 
2200 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2201 String_info_expression::do_dump_expression(
2202     Ast_dump_context* ast_dump_context) const
2203 {
2204   ast_dump_context->ostream() << "stringinfo(";
2205   this->string_->dump_expression(ast_dump_context);
2206   ast_dump_context->ostream() << ",";
2207   ast_dump_context->ostream() <<
2208       (this->string_info_ == STRING_INFO_DATA ? "data"
2209     : this->string_info_ == STRING_INFO_LENGTH ? "length"
2210     : "unknown");
2211   ast_dump_context->ostream() << ")";
2212 }
2213 
2214 // Make a string info expression.
2215 
2216 Expression*
make_string_info(Expression * string,String_info string_info,Location location)2217 Expression::make_string_info(Expression* string, String_info string_info,
2218                             Location location)
2219 {
2220   return new String_info_expression(string, string_info, location);
2221 }
2222 
2223 // An expression that represents an string value: a struct with value pointer
2224 // and length fields.
2225 
2226 class String_value_expression : public Expression
2227 {
2228  public:
String_value_expression(Expression * valptr,Expression * len,Location location)2229   String_value_expression(Expression* valptr, Expression* len, Location location)
2230       : Expression(EXPRESSION_STRING_VALUE, location),
2231         valptr_(valptr), len_(len)
2232   { }
2233 
2234  protected:
2235   int
2236   do_traverse(Traverse*);
2237 
2238   Type*
do_type()2239   do_type()
2240   { return Type::make_string_type(); }
2241 
2242   void
do_determine_type(const Type_context *)2243   do_determine_type(const Type_context*)
2244   { go_unreachable(); }
2245 
2246   Expression*
do_copy()2247   do_copy()
2248   {
2249     return new String_value_expression(this->valptr_->copy(),
2250                                        this->len_->copy(),
2251                                        this->location());
2252   }
2253 
2254   Bexpression*
2255   do_get_backend(Translate_context* context);
2256 
2257   void
2258   do_dump_expression(Ast_dump_context*) const;
2259 
2260  private:
2261   // The value pointer.
2262   Expression* valptr_;
2263   // The length.
2264   Expression* len_;
2265 };
2266 
2267 int
do_traverse(Traverse * traverse)2268 String_value_expression::do_traverse(Traverse* traverse)
2269 {
2270   if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2271       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
2272     return TRAVERSE_EXIT;
2273   return TRAVERSE_CONTINUE;
2274 }
2275 
2276 Bexpression*
do_get_backend(Translate_context * context)2277 String_value_expression::do_get_backend(Translate_context* context)
2278 {
2279   std::vector<Bexpression*> vals(2);
2280   vals[0] = this->valptr_->get_backend(context);
2281   vals[1] = this->len_->get_backend(context);
2282 
2283   Gogo* gogo = context->gogo();
2284   Btype* btype = Type::make_string_type()->get_backend(gogo);
2285   return gogo->backend()->constructor_expression(btype, vals, this->location());
2286 }
2287 
2288 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2289 String_value_expression::do_dump_expression(
2290     Ast_dump_context* ast_dump_context) const
2291 {
2292   ast_dump_context->ostream() << "stringvalue(";
2293   ast_dump_context->ostream() << "value: ";
2294   this->valptr_->dump_expression(ast_dump_context);
2295   ast_dump_context->ostream() << ", length: ";
2296   this->len_->dump_expression(ast_dump_context);
2297   ast_dump_context->ostream() << ")";
2298 }
2299 
2300 Expression*
make_string_value(Expression * valptr,Expression * len,Location location)2301 Expression::make_string_value(Expression* valptr, Expression* len,
2302                               Location location)
2303 {
2304   return new String_value_expression(valptr, len, location);
2305 }
2306 
2307 // Make an integer expression.
2308 
2309 class Integer_expression : public Expression
2310 {
2311  public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)2312   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
2313 		     Location location)
2314     : Expression(EXPRESSION_INTEGER, location),
2315       type_(type), is_character_constant_(is_character_constant)
2316   { mpz_init_set(this->val_, *val); }
2317 
2318   static Expression*
2319   do_import(Import_expression*, Location);
2320 
2321   // Write VAL to string dump.
2322   static void
2323   export_integer(String_dump* exp, const mpz_t val);
2324 
2325   // Write VAL to dump context.
2326   static void
2327   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
2328 
2329  protected:
2330   int
2331   do_traverse(Traverse*);
2332 
2333   bool
do_is_constant() const2334   do_is_constant() const
2335   { return true; }
2336 
2337   bool
do_is_zero_value() const2338   do_is_zero_value() const
2339   { return mpz_sgn(this->val_) == 0; }
2340 
2341   bool
do_is_static_initializer() const2342   do_is_static_initializer() const
2343   { return true; }
2344 
2345   bool
2346   do_numeric_constant_value(Numeric_constant* nc) const;
2347 
2348   Type*
2349   do_type();
2350 
2351   void
2352   do_determine_type(const Type_context* context);
2353 
2354   void
2355   do_check_types(Gogo*);
2356 
2357   Bexpression*
2358   do_get_backend(Translate_context*);
2359 
2360   Expression*
do_copy()2361   do_copy()
2362   {
2363     if (this->is_character_constant_)
2364       return Expression::make_character(&this->val_,
2365 					(this->type_ == NULL
2366 					 ? NULL
2367 					 : this->type_->copy_expressions()),
2368 					this->location());
2369     else
2370       return Expression::make_integer_z(&this->val_,
2371 					(this->type_ == NULL
2372 					 ? NULL
2373 					 : this->type_->copy_expressions()),
2374 					this->location());
2375   }
2376 
2377   int
do_inlining_cost() const2378   do_inlining_cost() const
2379   { return 1; }
2380 
2381   void
2382   do_export(Export_function_body*) const;
2383 
2384   void
2385   do_dump_expression(Ast_dump_context*) const;
2386 
2387  private:
2388   // The integer value.
2389   mpz_t val_;
2390   // The type so far.
2391   Type* type_;
2392   // Whether this is a character constant.
2393   bool is_character_constant_;
2394 };
2395 
2396 // Traverse an integer expression.  We just need to traverse the type
2397 // if there is one.
2398 
2399 int
do_traverse(Traverse * traverse)2400 Integer_expression::do_traverse(Traverse* traverse)
2401 {
2402   if (this->type_ != NULL)
2403     return Type::traverse(this->type_, traverse);
2404   return TRAVERSE_CONTINUE;
2405 }
2406 
2407 // Return a numeric constant for this expression.  We have to mark
2408 // this as a character when appropriate.
2409 
2410 bool
do_numeric_constant_value(Numeric_constant * nc) const2411 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
2412 {
2413   if (this->is_character_constant_)
2414     nc->set_rune(this->type_, this->val_);
2415   else
2416     nc->set_int(this->type_, this->val_);
2417   return true;
2418 }
2419 
2420 // Return the current type.  If we haven't set the type yet, we return
2421 // an abstract integer type.
2422 
2423 Type*
do_type()2424 Integer_expression::do_type()
2425 {
2426   if (this->type_ == NULL)
2427     {
2428       if (this->is_character_constant_)
2429 	this->type_ = Type::make_abstract_character_type();
2430       else
2431 	this->type_ = Type::make_abstract_integer_type();
2432     }
2433   return this->type_;
2434 }
2435 
2436 // Set the type of the integer value.  Here we may switch from an
2437 // abstract type to a real type.
2438 
2439 void
do_determine_type(const Type_context * context)2440 Integer_expression::do_determine_type(const Type_context* context)
2441 {
2442   if (this->type_ != NULL && !this->type_->is_abstract())
2443     ;
2444   else if (context->type != NULL && context->type->is_numeric_type())
2445     this->type_ = context->type;
2446   else if (!context->may_be_abstract)
2447     {
2448       if (this->is_character_constant_)
2449 	this->type_ = Type::lookup_integer_type("int32");
2450       else
2451 	this->type_ = Type::lookup_integer_type("int");
2452     }
2453 }
2454 
2455 // Check the type of an integer constant.
2456 
2457 void
do_check_types(Gogo *)2458 Integer_expression::do_check_types(Gogo*)
2459 {
2460   Type* type = this->type_;
2461   if (type == NULL)
2462     return;
2463   Numeric_constant nc;
2464   if (this->is_character_constant_)
2465     nc.set_rune(NULL, this->val_);
2466   else
2467     nc.set_int(NULL, this->val_);
2468   if (!nc.set_type(type, true, this->location()))
2469     this->set_is_error();
2470 }
2471 
2472 // Get the backend representation for an integer constant.
2473 
2474 Bexpression*
do_get_backend(Translate_context * context)2475 Integer_expression::do_get_backend(Translate_context* context)
2476 {
2477   if (this->is_error_expression()
2478       || (this->type_ != NULL && this->type_->is_error_type()))
2479     {
2480       go_assert(saw_errors());
2481       return context->gogo()->backend()->error_expression();
2482     }
2483 
2484   Type* resolved_type = NULL;
2485   if (this->type_ != NULL && !this->type_->is_abstract())
2486     resolved_type = this->type_;
2487   else if (this->type_ != NULL && this->type_->float_type() != NULL)
2488     {
2489       // We are converting to an abstract floating point type.
2490       resolved_type = Type::lookup_float_type("float64");
2491     }
2492   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2493     {
2494       // We are converting to an abstract complex type.
2495       resolved_type = Type::lookup_complex_type("complex128");
2496     }
2497   else
2498     {
2499       // If we still have an abstract type here, then this is being
2500       // used in a constant expression which didn't get reduced for
2501       // some reason.  Use a type which will fit the value.  We use <,
2502       // not <=, because we need an extra bit for the sign bit.
2503       int bits = mpz_sizeinbase(this->val_, 2);
2504       Type* int_type = Type::lookup_integer_type("int");
2505       if (bits < int_type->integer_type()->bits())
2506 	resolved_type = int_type;
2507       else if (bits < 64)
2508         resolved_type = Type::lookup_integer_type("int64");
2509       else
2510         {
2511           if (!saw_errors())
2512             go_error_at(this->location(),
2513                         "unknown type for large integer constant");
2514           return context->gogo()->backend()->error_expression();
2515         }
2516     }
2517   Numeric_constant nc;
2518   nc.set_int(resolved_type, this->val_);
2519   return Expression::backend_numeric_constant_expression(context, &nc);
2520 }
2521 
2522 // Write VAL to export data.
2523 
2524 void
export_integer(String_dump * exp,const mpz_t val)2525 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2526 {
2527   char* s = mpz_get_str(NULL, 10, val);
2528   exp->write_c_string(s);
2529   free(s);
2530 }
2531 
2532 // Export an integer in a constant expression.
2533 
2534 void
do_export(Export_function_body * efb) const2535 Integer_expression::do_export(Export_function_body* efb) const
2536 {
2537   bool added_type = false;
2538   if (this->type_ != NULL
2539       && !this->type_->is_abstract()
2540       && this->type_ != efb->type_context())
2541     {
2542       efb->write_c_string("$convert(");
2543       efb->write_type(this->type_);
2544       efb->write_c_string(", ");
2545       added_type = true;
2546     }
2547 
2548   Integer_expression::export_integer(efb, this->val_);
2549   if (this->is_character_constant_)
2550     efb->write_c_string("'");
2551   // A trailing space lets us reliably identify the end of the number.
2552   efb->write_c_string(" ");
2553 
2554   if (added_type)
2555     efb->write_c_string(")");
2556 }
2557 
2558 // Import an integer, floating point, or complex value.  This handles
2559 // all these types because they all start with digits.
2560 
2561 Expression*
do_import(Import_expression * imp,Location loc)2562 Integer_expression::do_import(Import_expression* imp, Location loc)
2563 {
2564   std::string num = imp->read_identifier();
2565   imp->require_c_string(" ");
2566   if (!num.empty() && num[num.length() - 1] == 'i')
2567     {
2568       mpfr_t real;
2569       size_t plus_pos = num.find('+', 1);
2570       size_t minus_pos = num.find('-', 1);
2571       size_t pos;
2572       if (plus_pos == std::string::npos)
2573 	pos = minus_pos;
2574       else if (minus_pos == std::string::npos)
2575 	pos = plus_pos;
2576       else
2577 	{
2578 	  go_error_at(imp->location(), "bad number in import data: %qs",
2579 		      num.c_str());
2580 	  return Expression::make_error(loc);
2581 	}
2582       if (pos == std::string::npos)
2583 	mpfr_set_ui(real, 0, MPFR_RNDN);
2584       else
2585 	{
2586 	  std::string real_str = num.substr(0, pos);
2587 	  if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
2588 	    {
2589 	      go_error_at(imp->location(), "bad number in import data: %qs",
2590 			  real_str.c_str());
2591 	      return Expression::make_error(loc);
2592 	    }
2593 	}
2594 
2595       std::string imag_str;
2596       if (pos == std::string::npos)
2597 	imag_str = num;
2598       else
2599 	imag_str = num.substr(pos);
2600       imag_str = imag_str.substr(0, imag_str.size() - 1);
2601       mpfr_t imag;
2602       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
2603 	{
2604 	  go_error_at(imp->location(), "bad number in import data: %qs",
2605 		      imag_str.c_str());
2606 	  return Expression::make_error(loc);
2607 	}
2608       mpc_t cval;
2609       mpc_init2(cval, mpc_precision);
2610       mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2611       mpfr_clear(real);
2612       mpfr_clear(imag);
2613       Expression* ret = Expression::make_complex(&cval, NULL, loc);
2614       mpc_clear(cval);
2615       return ret;
2616     }
2617   else if (num.find('.') == std::string::npos
2618 	   && num.find('E') == std::string::npos)
2619     {
2620       bool is_character_constant = (!num.empty()
2621 				    && num[num.length() - 1] == '\'');
2622       if (is_character_constant)
2623 	num = num.substr(0, num.length() - 1);
2624       mpz_t val;
2625       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2626 	{
2627 	  go_error_at(imp->location(), "bad number in import data: %qs",
2628 		      num.c_str());
2629 	  return Expression::make_error(loc);
2630 	}
2631       Expression* ret;
2632       if (is_character_constant)
2633 	ret = Expression::make_character(&val, NULL, loc);
2634       else
2635 	ret = Expression::make_integer_z(&val, NULL, loc);
2636       mpz_clear(val);
2637       return ret;
2638     }
2639   else
2640     {
2641       mpfr_t val;
2642       if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
2643 	{
2644 	  go_error_at(imp->location(), "bad number in import data: %qs",
2645 		      num.c_str());
2646 	  return Expression::make_error(loc);
2647 	}
2648       Expression* ret = Expression::make_float(&val, NULL, loc);
2649       mpfr_clear(val);
2650       return ret;
2651     }
2652 }
2653 // Ast dump for integer expression.
2654 
2655 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2656 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2657 {
2658   if (this->is_character_constant_)
2659     ast_dump_context->ostream() << '\'';
2660   Integer_expression::export_integer(ast_dump_context, this->val_);
2661   if (this->is_character_constant_)
2662     ast_dump_context->ostream() << '\'';
2663 }
2664 
2665 // Build a new integer value from a multi-precision integer.
2666 
2667 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2668 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2669 {
2670   return new Integer_expression(val, type, false, location);
2671 }
2672 
2673 // Build a new integer value from an unsigned long.
2674 
2675 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2676 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2677 {
2678   mpz_t zval;
2679   mpz_init_set_ui(zval, val);
2680   Expression* ret = Expression::make_integer_z(&zval, type, location);
2681   mpz_clear(zval);
2682   return ret;
2683 }
2684 
2685 // Build a new integer value from a signed long.
2686 
2687 Expression*
make_integer_sl(long val,Type * type,Location location)2688 Expression::make_integer_sl(long val, Type *type, Location location)
2689 {
2690   mpz_t zval;
2691   mpz_init_set_si(zval, val);
2692   Expression* ret = Expression::make_integer_z(&zval, type, location);
2693   mpz_clear(zval);
2694   return ret;
2695 }
2696 
2697 // Store an int64_t in an uninitialized mpz_t.
2698 
2699 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2700 set_mpz_from_int64(mpz_t* zval, int64_t val)
2701 {
2702   if (val >= 0)
2703     {
2704       unsigned long ul = static_cast<unsigned long>(val);
2705       if (static_cast<int64_t>(ul) == val)
2706 	{
2707 	  mpz_init_set_ui(*zval, ul);
2708 	  return;
2709 	}
2710     }
2711   uint64_t uv;
2712   if (val >= 0)
2713     uv = static_cast<uint64_t>(val);
2714   else
2715     uv = static_cast<uint64_t>(- val);
2716   unsigned long ul = uv & 0xffffffffUL;
2717   mpz_init_set_ui(*zval, ul);
2718   mpz_t hval;
2719   mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2720   mpz_mul_2exp(hval, hval, 32);
2721   mpz_add(*zval, *zval, hval);
2722   mpz_clear(hval);
2723   if (val < 0)
2724     mpz_neg(*zval, *zval);
2725 }
2726 
2727 // Build a new integer value from an int64_t.
2728 
2729 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2730 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2731 {
2732   mpz_t zval;
2733   set_mpz_from_int64(&zval, val);
2734   Expression* ret = Expression::make_integer_z(&zval, type, location);
2735   mpz_clear(zval);
2736   return ret;
2737 }
2738 
2739 // Build a new character constant value.
2740 
2741 Expression*
make_character(const mpz_t * val,Type * type,Location location)2742 Expression::make_character(const mpz_t* val, Type* type, Location location)
2743 {
2744   return new Integer_expression(val, type, true, location);
2745 }
2746 
2747 // Floats.
2748 
2749 class Float_expression : public Expression
2750 {
2751  public:
Float_expression(const mpfr_t * val,Type * type,Location location)2752   Float_expression(const mpfr_t* val, Type* type, Location location)
2753     : Expression(EXPRESSION_FLOAT, location),
2754       type_(type)
2755   {
2756     mpfr_init_set(this->val_, *val, MPFR_RNDN);
2757   }
2758 
2759   // Write VAL to export data.
2760   static void
2761   export_float(String_dump* exp, const mpfr_t val);
2762 
2763   // Write VAL to dump file.
2764   static void
2765   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2766 
2767  protected:
2768   int
2769   do_traverse(Traverse*);
2770 
2771   bool
do_is_constant() const2772   do_is_constant() const
2773   { return true; }
2774 
2775   bool
do_is_zero_value() const2776   do_is_zero_value() const
2777   {
2778     return mpfr_zero_p(this->val_) != 0
2779            && mpfr_signbit(this->val_) == 0;
2780   }
2781 
2782   bool
do_is_static_initializer() const2783   do_is_static_initializer() const
2784   { return true; }
2785 
2786   bool
do_numeric_constant_value(Numeric_constant * nc) const2787   do_numeric_constant_value(Numeric_constant* nc) const
2788   {
2789     nc->set_float(this->type_, this->val_);
2790     return true;
2791   }
2792 
2793   Type*
2794   do_type();
2795 
2796   void
2797   do_determine_type(const Type_context*);
2798 
2799   void
2800   do_check_types(Gogo*);
2801 
2802   Expression*
do_copy()2803   do_copy()
2804   { return Expression::make_float(&this->val_,
2805 				  (this->type_ == NULL
2806 				   ? NULL
2807 				   : this->type_->copy_expressions()),
2808 				  this->location()); }
2809 
2810   Bexpression*
2811   do_get_backend(Translate_context*);
2812 
2813   int
do_inlining_cost() const2814   do_inlining_cost() const
2815   { return 1; }
2816 
2817   void
2818   do_export(Export_function_body*) const;
2819 
2820   void
2821   do_dump_expression(Ast_dump_context*) const;
2822 
2823  private:
2824   // The floating point value.
2825   mpfr_t val_;
2826   // The type so far.
2827   Type* type_;
2828 };
2829 
2830 // Traverse a float expression.  We just need to traverse the type if
2831 // there is one.
2832 
2833 int
do_traverse(Traverse * traverse)2834 Float_expression::do_traverse(Traverse* traverse)
2835 {
2836   if (this->type_ != NULL)
2837     return Type::traverse(this->type_, traverse);
2838   return TRAVERSE_CONTINUE;
2839 }
2840 
2841 // Return the current type.  If we haven't set the type yet, we return
2842 // an abstract float type.
2843 
2844 Type*
do_type()2845 Float_expression::do_type()
2846 {
2847   if (this->type_ == NULL)
2848     this->type_ = Type::make_abstract_float_type();
2849   return this->type_;
2850 }
2851 
2852 // Set the type of the float value.  Here we may switch from an
2853 // abstract type to a real type.
2854 
2855 void
do_determine_type(const Type_context * context)2856 Float_expression::do_determine_type(const Type_context* context)
2857 {
2858   if (this->type_ != NULL && !this->type_->is_abstract())
2859     ;
2860   else if (context->type != NULL
2861 	   && (context->type->integer_type() != NULL
2862 	       || context->type->float_type() != NULL
2863 	       || context->type->complex_type() != NULL))
2864     this->type_ = context->type;
2865   else if (!context->may_be_abstract)
2866     this->type_ = Type::lookup_float_type("float64");
2867 }
2868 
2869 // Check the type of a float value.
2870 
2871 void
do_check_types(Gogo *)2872 Float_expression::do_check_types(Gogo*)
2873 {
2874   Type* type = this->type_;
2875   if (type == NULL)
2876     return;
2877   Numeric_constant nc;
2878   nc.set_float(NULL, this->val_);
2879   if (!nc.set_type(this->type_, true, this->location()))
2880     this->set_is_error();
2881 }
2882 
2883 // Get the backend representation for a float constant.
2884 
2885 Bexpression*
do_get_backend(Translate_context * context)2886 Float_expression::do_get_backend(Translate_context* context)
2887 {
2888   if (this->is_error_expression()
2889       || (this->type_ != NULL && this->type_->is_error_type()))
2890     {
2891       go_assert(saw_errors());
2892       return context->gogo()->backend()->error_expression();
2893     }
2894 
2895   Type* resolved_type;
2896   if (this->type_ != NULL && !this->type_->is_abstract())
2897     resolved_type = this->type_;
2898   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2899     {
2900       // We have an abstract integer type.  We just hope for the best.
2901       resolved_type = Type::lookup_integer_type("int");
2902     }
2903   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2904     {
2905       // We are converting to an abstract complex type.
2906       resolved_type = Type::lookup_complex_type("complex128");
2907     }
2908   else
2909     {
2910       // If we still have an abstract type here, then this is being
2911       // used in a constant expression which didn't get reduced.  We
2912       // just use float64 and hope for the best.
2913       resolved_type = Type::lookup_float_type("float64");
2914     }
2915 
2916   Numeric_constant nc;
2917   nc.set_float(resolved_type, this->val_);
2918   return Expression::backend_numeric_constant_expression(context, &nc);
2919 }
2920 
2921 // Write a floating point number to a string dump.
2922 
2923 void
export_float(String_dump * exp,const mpfr_t val)2924 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2925 {
2926   mpfr_exp_t exponent;
2927   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
2928   if (*s == '-')
2929     exp->write_c_string("-");
2930   exp->write_c_string("0.");
2931   exp->write_c_string(*s == '-' ? s + 1 : s);
2932   mpfr_free_str(s);
2933   char buf[30];
2934   snprintf(buf, sizeof buf, "E%ld", exponent);
2935   exp->write_c_string(buf);
2936 }
2937 
2938 // Export a floating point number in a constant expression.
2939 
2940 void
do_export(Export_function_body * efb) const2941 Float_expression::do_export(Export_function_body* efb) const
2942 {
2943   bool added_type = false;
2944   if (this->type_ != NULL
2945       && !this->type_->is_abstract()
2946       && this->type_ != efb->type_context())
2947     {
2948       efb->write_c_string("$convert(");
2949       efb->write_type(this->type_);
2950       efb->write_c_string(", ");
2951       added_type = true;
2952     }
2953 
2954   Float_expression::export_float(efb, this->val_);
2955   // A trailing space lets us reliably identify the end of the number.
2956   efb->write_c_string(" ");
2957 
2958   if (added_type)
2959     efb->write_c_string(")");
2960 }
2961 
2962 // Dump a floating point number to the dump file.
2963 
2964 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2965 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2966 {
2967   Float_expression::export_float(ast_dump_context, this->val_);
2968 }
2969 
2970 // Make a float expression.
2971 
2972 Expression*
make_float(const mpfr_t * val,Type * type,Location location)2973 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2974 {
2975   return new Float_expression(val, type, location);
2976 }
2977 
2978 // Complex numbers.
2979 
2980 class Complex_expression : public Expression
2981 {
2982  public:
Complex_expression(const mpc_t * val,Type * type,Location location)2983   Complex_expression(const mpc_t* val, Type* type, Location location)
2984     : Expression(EXPRESSION_COMPLEX, location),
2985       type_(type)
2986   {
2987     mpc_init2(this->val_, mpc_precision);
2988     mpc_set(this->val_, *val, MPC_RNDNN);
2989   }
2990 
2991   // Write VAL to string dump.
2992   static void
2993   export_complex(String_dump* exp, const mpc_t val);
2994 
2995   // Write REAL/IMAG to dump context.
2996   static void
2997   dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2998 
2999  protected:
3000   int
3001   do_traverse(Traverse*);
3002 
3003   bool
do_is_constant() const3004   do_is_constant() const
3005   { return true; }
3006 
3007   bool
do_is_zero_value() const3008   do_is_zero_value() const
3009   {
3010     return mpfr_zero_p(mpc_realref(this->val_)) != 0
3011            && mpfr_signbit(mpc_realref(this->val_)) == 0
3012            && mpfr_zero_p(mpc_imagref(this->val_)) != 0
3013            && mpfr_signbit(mpc_imagref(this->val_)) == 0;
3014   }
3015 
3016   bool
do_is_static_initializer() const3017   do_is_static_initializer() const
3018   { return true; }
3019 
3020   bool
do_numeric_constant_value(Numeric_constant * nc) const3021   do_numeric_constant_value(Numeric_constant* nc) const
3022   {
3023     nc->set_complex(this->type_, this->val_);
3024     return true;
3025   }
3026 
3027   Type*
3028   do_type();
3029 
3030   void
3031   do_determine_type(const Type_context*);
3032 
3033   void
3034   do_check_types(Gogo*);
3035 
3036   Expression*
do_copy()3037   do_copy()
3038   {
3039     return Expression::make_complex(&this->val_,
3040 				    (this->type_ == NULL
3041 				     ? NULL
3042 				     : this->type_->copy_expressions()),
3043 				    this->location());
3044   }
3045 
3046   Bexpression*
3047   do_get_backend(Translate_context*);
3048 
3049   int
do_inlining_cost() const3050   do_inlining_cost() const
3051   { return 2; }
3052 
3053   void
3054   do_export(Export_function_body*) const;
3055 
3056   void
3057   do_dump_expression(Ast_dump_context*) const;
3058 
3059  private:
3060   // The complex value.
3061   mpc_t val_;
3062   // The type if known.
3063   Type* type_;
3064 };
3065 
3066 // Traverse a complex expression.  We just need to traverse the type
3067 // if there is one.
3068 
3069 int
do_traverse(Traverse * traverse)3070 Complex_expression::do_traverse(Traverse* traverse)
3071 {
3072   if (this->type_ != NULL)
3073     return Type::traverse(this->type_, traverse);
3074   return TRAVERSE_CONTINUE;
3075 }
3076 
3077 // Return the current type.  If we haven't set the type yet, we return
3078 // an abstract complex type.
3079 
3080 Type*
do_type()3081 Complex_expression::do_type()
3082 {
3083   if (this->type_ == NULL)
3084     this->type_ = Type::make_abstract_complex_type();
3085   return this->type_;
3086 }
3087 
3088 // Set the type of the complex value.  Here we may switch from an
3089 // abstract type to a real type.
3090 
3091 void
do_determine_type(const Type_context * context)3092 Complex_expression::do_determine_type(const Type_context* context)
3093 {
3094   if (this->type_ != NULL && !this->type_->is_abstract())
3095     ;
3096   else if (context->type != NULL && context->type->is_numeric_type())
3097     this->type_ = context->type;
3098   else if (!context->may_be_abstract)
3099     this->type_ = Type::lookup_complex_type("complex128");
3100 }
3101 
3102 // Check the type of a complex value.
3103 
3104 void
do_check_types(Gogo *)3105 Complex_expression::do_check_types(Gogo*)
3106 {
3107   Type* type = this->type_;
3108   if (type == NULL)
3109     return;
3110   Numeric_constant nc;
3111   nc.set_complex(NULL, this->val_);
3112   if (!nc.set_type(this->type_, true, this->location()))
3113     this->set_is_error();
3114 }
3115 
3116 // Get the backend representation for a complex constant.
3117 
3118 Bexpression*
do_get_backend(Translate_context * context)3119 Complex_expression::do_get_backend(Translate_context* context)
3120 {
3121   if (this->is_error_expression()
3122       || (this->type_ != NULL && this->type_->is_error_type()))
3123     {
3124       go_assert(saw_errors());
3125       return context->gogo()->backend()->error_expression();
3126     }
3127 
3128   Type* resolved_type;
3129   if (this->type_ != NULL && !this->type_->is_abstract())
3130     resolved_type = this->type_;
3131   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3132     {
3133       // We are converting to an abstract integer type.
3134       resolved_type = Type::lookup_integer_type("int");
3135     }
3136   else if (this->type_ != NULL && this->type_->float_type() != NULL)
3137     {
3138       // We are converting to an abstract float type.
3139       resolved_type = Type::lookup_float_type("float64");
3140     }
3141   else
3142     {
3143       // If we still have an abstract type here, this is being
3144       // used in a constant expression which didn't get reduced.  We
3145       // just use complex128 and hope for the best.
3146       resolved_type = Type::lookup_complex_type("complex128");
3147     }
3148 
3149   Numeric_constant nc;
3150   nc.set_complex(resolved_type, this->val_);
3151   return Expression::backend_numeric_constant_expression(context, &nc);
3152 }
3153 
3154 // Write REAL/IMAG to export data.
3155 
3156 void
export_complex(String_dump * exp,const mpc_t val)3157 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
3158 {
3159   if (!mpfr_zero_p(mpc_realref(val)))
3160     {
3161       Float_expression::export_float(exp, mpc_realref(val));
3162       if (mpfr_sgn(mpc_imagref(val)) >= 0)
3163 	exp->write_c_string("+");
3164     }
3165   Float_expression::export_float(exp, mpc_imagref(val));
3166   exp->write_c_string("i");
3167 }
3168 
3169 // Export a complex number in a constant expression.
3170 
3171 void
do_export(Export_function_body * efb) const3172 Complex_expression::do_export(Export_function_body* efb) const
3173 {
3174   bool added_type = false;
3175   if (this->type_ != NULL
3176       && !this->type_->is_abstract()
3177       && this->type_ != efb->type_context())
3178     {
3179       efb->write_c_string("$convert(");
3180       efb->write_type(this->type_);
3181       efb->write_c_string(", ");
3182       added_type = true;
3183     }
3184 
3185   Complex_expression::export_complex(efb, this->val_);
3186   // A trailing space lets us reliably identify the end of the number.
3187   efb->write_c_string(" ");
3188 
3189   if (added_type)
3190     efb->write_c_string(")");
3191 }
3192 
3193 // Dump a complex expression to the dump file.
3194 
3195 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3196 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3197 {
3198   Complex_expression::export_complex(ast_dump_context, this->val_);
3199 }
3200 
3201 // Make a complex expression.
3202 
3203 Expression*
make_complex(const mpc_t * val,Type * type,Location location)3204 Expression::make_complex(const mpc_t* val, Type* type, Location location)
3205 {
3206   return new Complex_expression(val, type, location);
3207 }
3208 
3209 // Find a named object in an expression.
3210 
3211 class Find_named_object : public Traverse
3212 {
3213  public:
Find_named_object(Named_object * no)3214   Find_named_object(Named_object* no)
3215     : Traverse(traverse_expressions),
3216       no_(no), found_(false)
3217   { }
3218 
3219   // Whether we found the object.
3220   bool
found() const3221   found() const
3222   { return this->found_; }
3223 
3224  protected:
3225   int
3226   expression(Expression**);
3227 
3228  private:
3229   // The object we are looking for.
3230   Named_object* no_;
3231   // Whether we found it.
3232   bool found_;
3233 };
3234 
3235 // A reference to a const in an expression.
3236 
3237 class Const_expression : public Expression
3238 {
3239  public:
Const_expression(Named_object * constant,Location location)3240   Const_expression(Named_object* constant, Location location)
3241     : Expression(EXPRESSION_CONST_REFERENCE, location),
3242       constant_(constant), type_(NULL), seen_(false)
3243   { }
3244 
3245   Named_object*
named_object()3246   named_object()
3247   { return this->constant_; }
3248 
3249   const Named_object*
named_object() const3250   named_object() const
3251   { return this->constant_; }
3252 
3253   // Check that the initializer does not refer to the constant itself.
3254   void
3255   check_for_init_loop();
3256 
3257  protected:
3258   int
3259   do_traverse(Traverse*);
3260 
3261   Expression*
3262   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3263 
3264   bool
do_is_constant() const3265   do_is_constant() const
3266   { return true; }
3267 
3268   bool
do_is_zero_value() const3269   do_is_zero_value() const
3270   { return this->constant_->const_value()->expr()->is_zero_value(); }
3271 
3272   bool
do_is_static_initializer() const3273   do_is_static_initializer() const
3274   { return true; }
3275 
3276   bool
3277   do_numeric_constant_value(Numeric_constant* nc) const;
3278 
3279   bool
3280   do_string_constant_value(std::string* val) const;
3281 
3282   bool
3283   do_boolean_constant_value(bool* val) const;
3284 
3285   Type*
3286   do_type();
3287 
3288   // The type of a const is set by the declaration, not the use.
3289   void
3290   do_determine_type(const Type_context*);
3291 
3292   void
3293   do_check_types(Gogo*);
3294 
3295   Expression*
do_copy()3296   do_copy()
3297   { return this; }
3298 
3299   Bexpression*
3300   do_get_backend(Translate_context* context);
3301 
3302   int
do_inlining_cost() const3303   do_inlining_cost() const
3304   { return 1; }
3305 
3306   // When exporting a reference to a const as part of a const
3307   // expression, we export the value.  We ignore the fact that it has
3308   // a name.
3309   void
do_export(Export_function_body * efb) const3310   do_export(Export_function_body* efb) const
3311   { this->constant_->const_value()->expr()->export_expression(efb); }
3312 
3313   void
3314   do_dump_expression(Ast_dump_context*) const;
3315 
3316  private:
3317   // The constant.
3318   Named_object* constant_;
3319   // The type of this reference.  This is used if the constant has an
3320   // abstract type.
3321   Type* type_;
3322   // Used to prevent infinite recursion when a constant incorrectly
3323   // refers to itself.
3324   mutable bool seen_;
3325 };
3326 
3327 // Traversal.
3328 
3329 int
do_traverse(Traverse * traverse)3330 Const_expression::do_traverse(Traverse* traverse)
3331 {
3332   if (this->type_ != NULL)
3333     return Type::traverse(this->type_, traverse);
3334   return TRAVERSE_CONTINUE;
3335 }
3336 
3337 // Lower a constant expression.  This is where we convert the
3338 // predeclared constant iota into an integer value.
3339 
3340 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)3341 Const_expression::do_lower(Gogo* gogo, Named_object*,
3342 			   Statement_inserter*, int iota_value)
3343 {
3344   if (this->constant_->const_value()->expr()->classification()
3345       == EXPRESSION_IOTA)
3346     {
3347       if (iota_value == -1)
3348 	{
3349 	  go_error_at(this->location(),
3350 		      "iota is only defined in const declarations");
3351 	  iota_value = 0;
3352 	}
3353       return Expression::make_integer_ul(iota_value, NULL, this->location());
3354     }
3355 
3356   // Make sure that the constant itself has been lowered.
3357   gogo->lower_constant(this->constant_);
3358 
3359   return this;
3360 }
3361 
3362 // Return a numeric constant value.
3363 
3364 bool
do_numeric_constant_value(Numeric_constant * nc) const3365 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
3366 {
3367   if (this->seen_)
3368     return false;
3369 
3370   Expression* e = this->constant_->const_value()->expr();
3371 
3372   this->seen_ = true;
3373 
3374   bool r = e->numeric_constant_value(nc);
3375 
3376   this->seen_ = false;
3377 
3378   Type* ctype;
3379   if (this->type_ != NULL)
3380     ctype = this->type_;
3381   else
3382     ctype = this->constant_->const_value()->type();
3383   if (r && ctype != NULL)
3384     {
3385       if (!nc->set_type(ctype, false, this->location()))
3386 	return false;
3387     }
3388 
3389   return r;
3390 }
3391 
3392 bool
do_string_constant_value(std::string * val) const3393 Const_expression::do_string_constant_value(std::string* val) const
3394 {
3395   if (this->seen_)
3396     return false;
3397 
3398   Expression* e = this->constant_->const_value()->expr();
3399 
3400   this->seen_ = true;
3401   bool ok = e->string_constant_value(val);
3402   this->seen_ = false;
3403 
3404   return ok;
3405 }
3406 
3407 bool
do_boolean_constant_value(bool * val) const3408 Const_expression::do_boolean_constant_value(bool* val) const
3409 {
3410   if (this->seen_)
3411     return false;
3412 
3413   Expression* e = this->constant_->const_value()->expr();
3414 
3415   this->seen_ = true;
3416   bool ok = e->boolean_constant_value(val);
3417   this->seen_ = false;
3418 
3419   return ok;
3420 }
3421 
3422 // Return the type of the const reference.
3423 
3424 Type*
do_type()3425 Const_expression::do_type()
3426 {
3427   if (this->type_ != NULL)
3428     return this->type_;
3429 
3430   Named_constant* nc = this->constant_->const_value();
3431 
3432   if (this->seen_ || nc->lowering())
3433     {
3434       if (nc->type() == NULL || !nc->type()->is_error_type())
3435 	{
3436 	  Location loc = this->location();
3437 	  if (!this->seen_)
3438 	    loc = nc->location();
3439 	  go_error_at(loc, "constant refers to itself");
3440 	}
3441       this->set_is_error();
3442       this->type_ = Type::make_error_type();
3443       nc->set_type(this->type_);
3444       return this->type_;
3445     }
3446 
3447   this->seen_ = true;
3448 
3449   Type* ret = nc->type();
3450 
3451   if (ret != NULL)
3452     {
3453       this->seen_ = false;
3454       return ret;
3455     }
3456 
3457   // During parsing, a named constant may have a NULL type, but we
3458   // must not return a NULL type here.
3459   ret = nc->expr()->type();
3460 
3461   this->seen_ = false;
3462 
3463   if (ret->is_error_type())
3464     nc->set_type(ret);
3465 
3466   return ret;
3467 }
3468 
3469 // Set the type of the const reference.
3470 
3471 void
do_determine_type(const Type_context * context)3472 Const_expression::do_determine_type(const Type_context* context)
3473 {
3474   Type* ctype = this->constant_->const_value()->type();
3475   Type* cetype = (ctype != NULL
3476 		  ? ctype
3477 		  : this->constant_->const_value()->expr()->type());
3478   if (ctype != NULL && !ctype->is_abstract())
3479     ;
3480   else if (context->type != NULL
3481 	   && context->type->is_numeric_type()
3482 	   && cetype->is_numeric_type())
3483     this->type_ = context->type;
3484   else if (context->type != NULL
3485 	   && context->type->is_string_type()
3486 	   && cetype->is_string_type())
3487     this->type_ = context->type;
3488   else if (context->type != NULL
3489 	   && context->type->is_boolean_type()
3490 	   && cetype->is_boolean_type())
3491     this->type_ = context->type;
3492   else if (!context->may_be_abstract)
3493     {
3494       if (cetype->is_abstract())
3495 	cetype = cetype->make_non_abstract_type();
3496       this->type_ = cetype;
3497     }
3498 }
3499 
3500 // Check for a loop in which the initializer of a constant refers to
3501 // the constant itself.
3502 
3503 void
check_for_init_loop()3504 Const_expression::check_for_init_loop()
3505 {
3506   if (this->type_ != NULL && this->type_->is_error())
3507     return;
3508 
3509   if (this->seen_)
3510     {
3511       this->report_error(_("constant refers to itself"));
3512       this->type_ = Type::make_error_type();
3513       return;
3514     }
3515 
3516   Expression* init = this->constant_->const_value()->expr();
3517   Find_named_object find_named_object(this->constant_);
3518 
3519   this->seen_ = true;
3520   Expression::traverse(&init, &find_named_object);
3521   this->seen_ = false;
3522 
3523   if (find_named_object.found())
3524     {
3525       if (this->type_ == NULL || !this->type_->is_error())
3526 	{
3527 	  this->report_error(_("constant refers to itself"));
3528 	  this->type_ = Type::make_error_type();
3529 	}
3530       return;
3531     }
3532 }
3533 
3534 // Check types of a const reference.
3535 
3536 void
do_check_types(Gogo *)3537 Const_expression::do_check_types(Gogo*)
3538 {
3539   if (this->type_ != NULL && this->type_->is_error())
3540     return;
3541 
3542   this->check_for_init_loop();
3543 
3544   // Check that numeric constant fits in type.
3545   if (this->type_ != NULL && this->type_->is_numeric_type())
3546     {
3547       Numeric_constant nc;
3548       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
3549 	{
3550 	  if (!nc.set_type(this->type_, true, this->location()))
3551 	    this->set_is_error();
3552 	}
3553     }
3554 }
3555 
3556 // Return the backend representation for a const reference.
3557 
3558 Bexpression*
do_get_backend(Translate_context * context)3559 Const_expression::do_get_backend(Translate_context* context)
3560 {
3561   if (this->is_error_expression()
3562       || (this->type_ != NULL && this->type_->is_error()))
3563     {
3564       go_assert(saw_errors());
3565       return context->backend()->error_expression();
3566     }
3567 
3568   // If the type has been set for this expression, but the underlying
3569   // object is an abstract int or float, we try to get the abstract
3570   // value.  Otherwise we may lose something in the conversion.
3571   Expression* expr = this->constant_->const_value()->expr();
3572   if (this->type_ != NULL
3573       && this->type_->is_numeric_type()
3574       && (this->constant_->const_value()->type() == NULL
3575 	  || this->constant_->const_value()->type()->is_abstract()))
3576     {
3577       Numeric_constant nc;
3578       if (expr->numeric_constant_value(&nc)
3579 	  && nc.set_type(this->type_, false, this->location()))
3580 	{
3581 	  Expression* e = nc.expression(this->location());
3582 	  return e->get_backend(context);
3583 	}
3584     }
3585 
3586   if (this->type_ != NULL)
3587     expr = Expression::make_cast(this->type_, expr, this->location());
3588   return expr->get_backend(context);
3589 }
3590 
3591 // Dump ast representation for constant expression.
3592 
3593 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3594 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3595 {
3596   ast_dump_context->ostream() << this->constant_->name();
3597 }
3598 
3599 // Make a reference to a constant in an expression.
3600 
3601 Expression*
make_const_reference(Named_object * constant,Location location)3602 Expression::make_const_reference(Named_object* constant,
3603 				 Location location)
3604 {
3605   return new Const_expression(constant, location);
3606 }
3607 
3608 // Find a named object in an expression.
3609 
3610 int
expression(Expression ** pexpr)3611 Find_named_object::expression(Expression** pexpr)
3612 {
3613   switch ((*pexpr)->classification())
3614     {
3615     case Expression::EXPRESSION_CONST_REFERENCE:
3616       {
3617 	Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3618 	if (ce->named_object() == this->no_)
3619 	  break;
3620 
3621 	// We need to check a constant initializer explicitly, as
3622 	// loops here will not be caught by the loop checking for
3623 	// variable initializers.
3624 	ce->check_for_init_loop();
3625 
3626 	return TRAVERSE_CONTINUE;
3627       }
3628 
3629     case Expression::EXPRESSION_VAR_REFERENCE:
3630       if ((*pexpr)->var_expression()->named_object() == this->no_)
3631 	break;
3632       return TRAVERSE_CONTINUE;
3633     case Expression::EXPRESSION_FUNC_REFERENCE:
3634       if ((*pexpr)->func_expression()->named_object() == this->no_)
3635 	break;
3636       return TRAVERSE_CONTINUE;
3637     default:
3638       return TRAVERSE_CONTINUE;
3639     }
3640   this->found_ = true;
3641   return TRAVERSE_EXIT;
3642 }
3643 
3644 // The nil value.
3645 
3646 class Nil_expression : public Expression
3647 {
3648  public:
Nil_expression(Location location)3649   Nil_expression(Location location)
3650     : Expression(EXPRESSION_NIL, location)
3651   { }
3652 
3653   static Expression*
3654   do_import(Import_expression*, Location);
3655 
3656  protected:
3657   bool
do_is_constant() const3658   do_is_constant() const
3659   { return true; }
3660 
3661   bool
do_is_zero_value() const3662   do_is_zero_value() const
3663   { return true; }
3664 
3665   bool
do_is_static_initializer() const3666   do_is_static_initializer() const
3667   { return true; }
3668 
3669   Type*
do_type()3670   do_type()
3671   { return Type::make_nil_type(); }
3672 
3673   void
do_determine_type(const Type_context *)3674   do_determine_type(const Type_context*)
3675   { }
3676 
3677   Expression*
do_copy()3678   do_copy()
3679   { return this; }
3680 
3681   Bexpression*
do_get_backend(Translate_context * context)3682   do_get_backend(Translate_context* context)
3683   { return context->backend()->nil_pointer_expression(); }
3684 
3685   int
do_inlining_cost() const3686   do_inlining_cost() const
3687   { return 1; }
3688 
3689   void
do_export(Export_function_body * efb) const3690   do_export(Export_function_body* efb) const
3691   { efb->write_c_string("$nil"); }
3692 
3693   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3694   do_dump_expression(Ast_dump_context* ast_dump_context) const
3695   { ast_dump_context->ostream() << "nil"; }
3696 };
3697 
3698 // Import a nil expression.
3699 
3700 Expression*
do_import(Import_expression * imp,Location loc)3701 Nil_expression::do_import(Import_expression* imp, Location loc)
3702 {
3703   if (imp->version() >= EXPORT_FORMAT_V3)
3704     imp->require_c_string("$");
3705   imp->require_c_string("nil");
3706   return Expression::make_nil(loc);
3707 }
3708 
3709 // Make a nil expression.
3710 
3711 Expression*
make_nil(Location location)3712 Expression::make_nil(Location location)
3713 {
3714   return new Nil_expression(location);
3715 }
3716 
3717 // The value of the predeclared constant iota.  This is little more
3718 // than a marker.  This will be lowered to an integer in
3719 // Const_expression::do_lower, which is where we know the value that
3720 // it should have.
3721 
3722 class Iota_expression : public Parser_expression
3723 {
3724  public:
Iota_expression(Location location)3725   Iota_expression(Location location)
3726     : Parser_expression(EXPRESSION_IOTA, location)
3727   { }
3728 
3729  protected:
3730   Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3731   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3732   { go_unreachable(); }
3733 
3734   // There should only ever be one of these.
3735   Expression*
do_copy()3736   do_copy()
3737   { go_unreachable(); }
3738 
3739   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3740   do_dump_expression(Ast_dump_context* ast_dump_context) const
3741   { ast_dump_context->ostream() << "iota"; }
3742 };
3743 
3744 // Make an iota expression.  This is only called for one case: the
3745 // value of the predeclared constant iota.
3746 
3747 Expression*
make_iota()3748 Expression::make_iota()
3749 {
3750   static Iota_expression iota_expression(Linemap::unknown_location());
3751   return &iota_expression;
3752 }
3753 
3754 // Class Type_conversion_expression.
3755 
3756 // Traversal.
3757 
3758 int
do_traverse(Traverse * traverse)3759 Type_conversion_expression::do_traverse(Traverse* traverse)
3760 {
3761   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3762       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3763     return TRAVERSE_EXIT;
3764   return TRAVERSE_CONTINUE;
3765 }
3766 
3767 // Convert to a constant at lowering time.
3768 
3769 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3770 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3771 				     Statement_inserter*, int)
3772 {
3773   Type* type = this->type_;
3774   Expression* val = this->expr_;
3775   Location location = this->location();
3776 
3777   if (type->is_numeric_type())
3778     {
3779       Numeric_constant nc;
3780       if (val->numeric_constant_value(&nc))
3781 	{
3782 	  if (!nc.set_type(type, true, location))
3783 	    return Expression::make_error(location);
3784 	  return nc.expression(location);
3785 	}
3786     }
3787 
3788   // According to the language specification on string conversions
3789   // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3790   // When converting an integer into a string, the string will be a UTF-8
3791   // representation of the integer and integers "outside the range of valid
3792   // Unicode code points are converted to '\uFFFD'."
3793   if (type->is_string_type())
3794     {
3795       Numeric_constant nc;
3796       if (val->numeric_constant_value(&nc) && nc.is_int())
3797         {
3798           // An integer value doesn't fit in the Unicode code point range if it
3799           // overflows the Go "int" type or is negative.
3800           unsigned long ul;
3801           if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3802               || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3803             return Expression::make_string("\ufffd", location);
3804         }
3805     }
3806 
3807   if (type->is_slice_type())
3808     {
3809       Type* element_type = type->array_type()->element_type()->forwarded();
3810       bool is_byte = (element_type->integer_type() != NULL
3811 		      && element_type->integer_type()->is_byte());
3812       bool is_rune = (element_type->integer_type() != NULL
3813 		      && element_type->integer_type()->is_rune());
3814       if (is_byte || is_rune)
3815 	{
3816 	  std::string s;
3817 	  if (val->string_constant_value(&s))
3818 	    {
3819 	      Expression_list* vals = new Expression_list();
3820 	      if (is_byte)
3821 		{
3822 		  for (std::string::const_iterator p = s.begin();
3823 		       p != s.end();
3824 		       p++)
3825 		    {
3826 		      unsigned char c = static_cast<unsigned char>(*p);
3827 		      vals->push_back(Expression::make_integer_ul(c,
3828 								  element_type,
3829 								  location));
3830 		    }
3831 		}
3832 	      else
3833 		{
3834 		  const char *p = s.data();
3835 		  const char *pend = s.data() + s.length();
3836 		  while (p < pend)
3837 		    {
3838 		      unsigned int c;
3839 		      int adv = Lex::fetch_char(p, &c);
3840 		      if (adv == 0)
3841 			{
3842 			  go_warning_at(this->location(), 0,
3843 				     "invalid UTF-8 encoding");
3844 			  adv = 1;
3845 			}
3846 		      p += adv;
3847 		      vals->push_back(Expression::make_integer_ul(c,
3848 								  element_type,
3849 								  location));
3850 		    }
3851 		}
3852 
3853 	      return Expression::make_slice_composite_literal(type, vals,
3854 							      location);
3855 	    }
3856 	}
3857     }
3858 
3859   return this;
3860 }
3861 
3862 // Flatten a type conversion by using a temporary variable for the slice
3863 // in slice to string conversions.
3864 
3865 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)3866 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3867                                        Statement_inserter* inserter)
3868 {
3869   if (this->type()->is_error_type() || this->expr_->is_error_expression())
3870     {
3871       go_assert(saw_errors());
3872       return Expression::make_error(this->location());
3873     }
3874 
3875   if (((this->type()->is_string_type()
3876         && this->expr_->type()->is_slice_type())
3877        || this->expr_->type()->interface_type() != NULL)
3878       && !this->expr_->is_variable())
3879     {
3880       Temporary_statement* temp =
3881           Statement::make_temporary(NULL, this->expr_, this->location());
3882       inserter->insert(temp);
3883       this->expr_ = Expression::make_temporary_reference(temp, this->location());
3884     }
3885 
3886   // For interface conversion and string to/from slice conversions,
3887   // decide if we can allocate on stack.
3888   if (this->type()->interface_type() != NULL
3889       || this->type()->is_string_type()
3890       || this->expr_->type()->is_string_type())
3891     {
3892       Node* n = Node::make_node(this);
3893       if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
3894         this->no_escape_ = true;
3895     }
3896   return this;
3897 }
3898 
3899 // Return whether a type conversion is a constant.
3900 
3901 bool
do_is_constant() const3902 Type_conversion_expression::do_is_constant() const
3903 {
3904   if (!this->expr_->is_constant())
3905     return false;
3906 
3907   // A conversion to a type that may not be used as a constant is not
3908   // a constant.  For example, []byte(nil).
3909   Type* type = this->type_;
3910   if (type->integer_type() == NULL
3911       && type->float_type() == NULL
3912       && type->complex_type() == NULL
3913       && !type->is_boolean_type()
3914       && !type->is_string_type())
3915     return false;
3916 
3917   return true;
3918 }
3919 
3920 // Return whether a type conversion is a zero value.
3921 
3922 bool
do_is_zero_value() const3923 Type_conversion_expression::do_is_zero_value() const
3924 {
3925   if (!this->expr_->is_zero_value())
3926     return false;
3927 
3928   // Some type conversion from zero value is still not zero value.
3929   // For example, []byte("") or interface{}(0).
3930   // Conservatively, only report true if the RHS is nil.
3931   Type* type = this->type_;
3932   if (type->integer_type() == NULL
3933       && type->float_type() == NULL
3934       && type->complex_type() == NULL
3935       && !type->is_boolean_type()
3936       && !type->is_string_type())
3937     return this->expr_->is_nil_expression();
3938 
3939   return true;
3940 }
3941 
3942 // Return whether a type conversion can be used in a constant
3943 // initializer.
3944 
3945 bool
do_is_static_initializer() const3946 Type_conversion_expression::do_is_static_initializer() const
3947 {
3948   Type* type = this->type_;
3949   Type* expr_type = this->expr_->type();
3950 
3951   if (type->interface_type() != NULL
3952       || expr_type->interface_type() != NULL)
3953     return false;
3954 
3955   if (!this->expr_->is_static_initializer())
3956     return false;
3957 
3958   if (Type::are_identical(type, expr_type,
3959 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
3960 			  NULL))
3961     return true;
3962 
3963   if (type->is_string_type() && expr_type->is_string_type())
3964     return true;
3965 
3966   if ((type->is_numeric_type()
3967        || type->is_boolean_type()
3968        || type->points_to() != NULL)
3969       && (expr_type->is_numeric_type()
3970 	  || expr_type->is_boolean_type()
3971 	  || expr_type->points_to() != NULL))
3972     return true;
3973 
3974   return false;
3975 }
3976 
3977 // Return the constant numeric value if there is one.
3978 
3979 bool
do_numeric_constant_value(Numeric_constant * nc) const3980 Type_conversion_expression::do_numeric_constant_value(
3981     Numeric_constant* nc) const
3982 {
3983   if (!this->type_->is_numeric_type())
3984     return false;
3985   if (!this->expr_->numeric_constant_value(nc))
3986     return false;
3987   return nc->set_type(this->type_, false, this->location());
3988 }
3989 
3990 // Return the constant string value if there is one.
3991 
3992 bool
do_string_constant_value(std::string * val) const3993 Type_conversion_expression::do_string_constant_value(std::string* val) const
3994 {
3995   if (this->type_->is_string_type()
3996       && this->expr_->type()->integer_type() != NULL)
3997     {
3998       Numeric_constant nc;
3999       if (this->expr_->numeric_constant_value(&nc))
4000 	{
4001 	  unsigned long ival;
4002 	  if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
4003 	    {
4004 	      val->clear();
4005 	      Lex::append_char(ival, true, val, this->location());
4006 	      return true;
4007 	    }
4008 	}
4009     }
4010 
4011   // FIXME: Could handle conversion from const []int here.
4012 
4013   return false;
4014 }
4015 
4016 // Return the constant boolean value if there is one.
4017 
4018 bool
do_boolean_constant_value(bool * val) const4019 Type_conversion_expression::do_boolean_constant_value(bool* val) const
4020 {
4021   if (!this->type_->is_boolean_type())
4022     return false;
4023   return this->expr_->boolean_constant_value(val);
4024 }
4025 
4026 // Determine the resulting type of the conversion.
4027 
4028 void
do_determine_type(const Type_context *)4029 Type_conversion_expression::do_determine_type(const Type_context*)
4030 {
4031   Type_context subcontext(this->type_, false);
4032   this->expr_->determine_type(&subcontext);
4033 }
4034 
4035 // Check that types are convertible.
4036 
4037 void
do_check_types(Gogo *)4038 Type_conversion_expression::do_check_types(Gogo*)
4039 {
4040   Type* type = this->type_;
4041   Type* expr_type = this->expr_->type();
4042   std::string reason;
4043 
4044   if (type->is_error() || expr_type->is_error())
4045     {
4046       this->set_is_error();
4047       return;
4048     }
4049 
4050   if (this->may_convert_function_types_
4051       && type->function_type() != NULL
4052       && expr_type->function_type() != NULL)
4053     return;
4054 
4055   if (Type::are_convertible(type, expr_type, &reason))
4056     return;
4057 
4058   go_error_at(this->location(), "%s", reason.c_str());
4059   this->set_is_error();
4060 }
4061 
4062 // Copy.
4063 
4064 Expression*
do_copy()4065 Type_conversion_expression::do_copy()
4066 {
4067   Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
4068                                                    this->expr_->copy(),
4069                                                    this->location());
4070   ret->conversion_expression()->set_no_copy(this->no_copy_);
4071   return ret;
4072 }
4073 
4074 // Get the backend representation for a type conversion.
4075 
4076 Bexpression*
do_get_backend(Translate_context * context)4077 Type_conversion_expression::do_get_backend(Translate_context* context)
4078 {
4079   Type* type = this->type_;
4080   Type* expr_type = this->expr_->type();
4081 
4082   Gogo* gogo = context->gogo();
4083   Btype* btype = type->get_backend(gogo);
4084   Location loc = this->location();
4085 
4086   if (Type::are_identical(type, expr_type,
4087 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4088 			  NULL))
4089     {
4090       Bexpression* bexpr = this->expr_->get_backend(context);
4091       return gogo->backend()->convert_expression(btype, bexpr, loc);
4092     }
4093   else if (type->interface_type() != NULL
4094            && expr_type->interface_type() == NULL)
4095     {
4096       Expression* conversion =
4097           Expression::convert_type_to_interface(type, this->expr_,
4098                                                 this->no_escape_, loc);
4099       return conversion->get_backend(context);
4100     }
4101   else if (type->interface_type() != NULL
4102 	   || expr_type->interface_type() != NULL)
4103     {
4104       Expression* conversion =
4105           Expression::convert_for_assignment(gogo, type, this->expr_,
4106                                              loc);
4107       return conversion->get_backend(context);
4108     }
4109   else if (type->is_string_type()
4110 	   && expr_type->integer_type() != NULL)
4111     {
4112       mpz_t intval;
4113       Numeric_constant nc;
4114       if (this->expr_->numeric_constant_value(&nc)
4115 	  && nc.to_int(&intval))
4116 	{
4117 	  std::string s;
4118           unsigned int x;
4119           if (mpz_fits_uint_p(intval))
4120             x = mpz_get_ui(intval);
4121           else
4122             {
4123               char* ms = mpz_get_str(NULL, 16, intval);
4124               go_warning_at(loc, 0,
4125                             "unicode code point 0x%s out of range in string",
4126                             ms);
4127               free(ms);
4128               x = 0xfffd;
4129             }
4130 	  Lex::append_char(x, true, &s, loc);
4131 	  mpz_clear(intval);
4132 	  Expression* se = Expression::make_string(s, loc);
4133 	  return se->get_backend(context);
4134 	}
4135 
4136       Expression* buf;
4137       if (this->no_escape_)
4138         {
4139           Type* byte_type = Type::lookup_integer_type("uint8");
4140           Expression* buflen =
4141             Expression::make_integer_ul(4, NULL, loc);
4142           Type* array_type = Type::make_array_type(byte_type, buflen);
4143           buf = Expression::make_allocation(array_type, loc);
4144           buf->allocation_expression()->set_allocate_on_stack();
4145           buf->allocation_expression()->set_no_zero();
4146         }
4147       else
4148         buf = Expression::make_nil(loc);
4149       Expression* i2s_expr =
4150         Runtime::make_call(Runtime::INTSTRING, loc, 2, buf, this->expr_);
4151       return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
4152     }
4153   else if (type->is_string_type() && expr_type->is_slice_type())
4154     {
4155       Array_type* a = expr_type->array_type();
4156       Type* e = a->element_type()->forwarded();
4157       go_assert(e->integer_type() != NULL);
4158       go_assert(this->expr_->is_variable());
4159 
4160       Runtime::Function code;
4161       if (e->integer_type()->is_byte())
4162         {
4163           if (this->no_copy_)
4164             {
4165               if (gogo->debug_optimization())
4166                 go_debug(loc, "no copy string([]byte)");
4167               Expression* ptr = Expression::make_slice_info(this->expr_,
4168                                                             SLICE_INFO_VALUE_POINTER,
4169                                                             loc);
4170               Expression* len = Expression::make_slice_info(this->expr_,
4171                                                             SLICE_INFO_LENGTH,
4172                                                             loc);
4173               Expression* str = Expression::make_string_value(ptr, len, loc);
4174               return str->get_backend(context);
4175             }
4176           code = Runtime::SLICEBYTETOSTRING;
4177         }
4178       else
4179         {
4180           go_assert(e->integer_type()->is_rune());
4181           code = Runtime::SLICERUNETOSTRING;
4182         }
4183 
4184       Expression* buf;
4185       if (this->no_escape_)
4186         {
4187           Type* byte_type = Type::lookup_integer_type("uint8");
4188           Expression* buflen =
4189             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4190           Type* array_type = Type::make_array_type(byte_type, buflen);
4191           buf = Expression::make_allocation(array_type, loc);
4192           buf->allocation_expression()->set_allocate_on_stack();
4193           buf->allocation_expression()->set_no_zero();
4194         }
4195       else
4196         buf = Expression::make_nil(loc);
4197       return Runtime::make_call(code, loc, 2, buf,
4198 				this->expr_)->get_backend(context);
4199     }
4200   else if (type->is_slice_type() && expr_type->is_string_type())
4201     {
4202       Type* e = type->array_type()->element_type()->forwarded();
4203       go_assert(e->integer_type() != NULL);
4204 
4205       Runtime::Function code;
4206       if (e->integer_type()->is_byte())
4207 	code = Runtime::STRINGTOSLICEBYTE;
4208       else
4209 	{
4210 	  go_assert(e->integer_type()->is_rune());
4211 	  code = Runtime::STRINGTOSLICERUNE;
4212 	}
4213 
4214       Expression* buf;
4215       if (this->no_escape_)
4216         {
4217           Expression* buflen =
4218             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4219           Type* array_type = Type::make_array_type(e, buflen);
4220           buf = Expression::make_allocation(array_type, loc);
4221           buf->allocation_expression()->set_allocate_on_stack();
4222           buf->allocation_expression()->set_no_zero();
4223         }
4224       else
4225         buf = Expression::make_nil(loc);
4226       Expression* s2a = Runtime::make_call(code, loc, 2, buf, this->expr_);
4227       return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
4228     }
4229   else if (type->is_numeric_type())
4230     {
4231       go_assert(Type::are_convertible(type, expr_type, NULL));
4232       Bexpression* bexpr = this->expr_->get_backend(context);
4233       return gogo->backend()->convert_expression(btype, bexpr, loc);
4234     }
4235   else if ((type->is_unsafe_pointer_type()
4236 	    && (expr_type->points_to() != NULL
4237                 || expr_type->integer_type()))
4238            || (expr_type->is_unsafe_pointer_type()
4239 	       && type->points_to() != NULL)
4240            || (this->may_convert_function_types_
4241                && type->function_type() != NULL
4242                && expr_type->function_type() != NULL))
4243     {
4244       Bexpression* bexpr = this->expr_->get_backend(context);
4245       return gogo->backend()->convert_expression(btype, bexpr, loc);
4246     }
4247   else
4248     {
4249       Expression* conversion =
4250           Expression::convert_for_assignment(gogo, type, this->expr_, loc);
4251       return conversion->get_backend(context);
4252     }
4253 }
4254 
4255 // Cost of inlining a type conversion.
4256 
4257 int
do_inlining_cost() const4258 Type_conversion_expression::do_inlining_cost() const
4259 {
4260   Type* type = this->type_;
4261   Type* expr_type = this->expr_->type();
4262   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
4263     return 10;
4264   else if (type->is_string_type() && expr_type->integer_type() != NULL)
4265     return 10;
4266   else if (type->is_string_type() && expr_type->is_slice_type())
4267     return 10;
4268   else if (type->is_slice_type() && expr_type->is_string_type())
4269     return 10;
4270   else
4271     return 1;
4272 }
4273 
4274 // Output a type conversion in a constant expression.
4275 
4276 void
do_export(Export_function_body * efb) const4277 Type_conversion_expression::do_export(Export_function_body* efb) const
4278 {
4279   efb->write_c_string("$convert(");
4280   efb->write_type(this->type_);
4281   efb->write_c_string(", ");
4282 
4283   Type* old_context = efb->type_context();
4284   efb->set_type_context(this->type_);
4285 
4286   this->expr_->export_expression(efb);
4287 
4288   efb->set_type_context(old_context);
4289 
4290   efb->write_c_string(")");
4291 }
4292 
4293 // Import a type conversion or a struct construction.
4294 
4295 Expression*
do_import(Import_expression * imp,Location loc)4296 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
4297 {
4298   imp->require_c_string("$convert(");
4299   Type* type = imp->read_type();
4300   imp->require_c_string(", ");
4301   Expression* val = Expression::import_expression(imp, loc);
4302   imp->require_c_string(")");
4303   return Expression::make_cast(type, val, loc);
4304 }
4305 
4306 // Dump ast representation for a type conversion expression.
4307 
4308 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4309 Type_conversion_expression::do_dump_expression(
4310     Ast_dump_context* ast_dump_context) const
4311 {
4312   ast_dump_context->dump_type(this->type_);
4313   ast_dump_context->ostream() << "(";
4314   ast_dump_context->dump_expression(this->expr_);
4315   ast_dump_context->ostream() << ") ";
4316 }
4317 
4318 // Make a type cast expression.
4319 
4320 Expression*
make_cast(Type * type,Expression * val,Location location)4321 Expression::make_cast(Type* type, Expression* val, Location location)
4322 {
4323   if (type->is_error_type() || val->is_error_expression())
4324     return Expression::make_error(location);
4325   return new Type_conversion_expression(type, val, location);
4326 }
4327 
4328 // Class Unsafe_type_conversion_expression.
4329 
4330 // Traversal.
4331 
4332 int
do_traverse(Traverse * traverse)4333 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
4334 {
4335   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4336       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4337     return TRAVERSE_EXIT;
4338   return TRAVERSE_CONTINUE;
4339 }
4340 
4341 // Return whether an unsafe type conversion can be used as a constant
4342 // initializer.
4343 
4344 bool
do_is_static_initializer() const4345 Unsafe_type_conversion_expression::do_is_static_initializer() const
4346 {
4347   Type* type = this->type_;
4348   Type* expr_type = this->expr_->type();
4349 
4350   if (type->interface_type() != NULL
4351       || expr_type->interface_type() != NULL)
4352     return false;
4353 
4354   if (!this->expr_->is_static_initializer())
4355     return false;
4356 
4357   if (Type::are_convertible(type, expr_type, NULL))
4358     return true;
4359 
4360   if (type->is_string_type() && expr_type->is_string_type())
4361     return true;
4362 
4363   if ((type->is_numeric_type()
4364        || type->is_boolean_type()
4365        || type->points_to() != NULL)
4366       && (expr_type->is_numeric_type()
4367 	  || expr_type->is_boolean_type()
4368 	  || expr_type->points_to() != NULL))
4369     return true;
4370 
4371   return false;
4372 }
4373 
4374 // Copy.
4375 
4376 Expression*
do_copy()4377 Unsafe_type_conversion_expression::do_copy()
4378 {
4379   return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
4380 					       this->expr_->copy(),
4381 					       this->location());
4382 }
4383 
4384 // Convert to backend representation.
4385 
4386 Bexpression*
do_get_backend(Translate_context * context)4387 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
4388 {
4389   // We are only called for a limited number of cases.
4390 
4391   Type* t = this->type_;
4392   Type* et = this->expr_->type();
4393 
4394   if (t->is_error_type()
4395       || this->expr_->is_error_expression()
4396       || et->is_error_type())
4397     {
4398       go_assert(saw_errors());
4399       return context->backend()->error_expression();
4400     }
4401 
4402   if (t->array_type() != NULL)
4403     go_assert(et->array_type() != NULL
4404               && t->is_slice_type() == et->is_slice_type());
4405   else if (t->struct_type() != NULL)
4406     {
4407       if (t->named_type() != NULL
4408           && et->named_type() != NULL
4409           && !Type::are_convertible(t, et, NULL))
4410 	{
4411 	  go_assert(saw_errors());
4412 	  return context->backend()->error_expression();
4413 	}
4414 
4415       go_assert(et->struct_type() != NULL
4416                 && Type::are_convertible(t, et, NULL));
4417     }
4418   else if (t->map_type() != NULL)
4419     go_assert(et->map_type() != NULL || et->points_to() != NULL);
4420   else if (t->channel_type() != NULL)
4421     go_assert(et->channel_type() != NULL || et->points_to() != NULL);
4422   else if (t->points_to() != NULL)
4423     go_assert(et->points_to() != NULL
4424               || et->channel_type() != NULL
4425               || et->map_type() != NULL
4426               || et->function_type() != NULL
4427 	      || et->integer_type() != NULL
4428               || et->is_nil_type());
4429   else if (t->function_type() != NULL)
4430     go_assert(et->points_to() != NULL);
4431   else if (et->is_unsafe_pointer_type())
4432     go_assert(t->points_to() != NULL
4433 	      || (t->integer_type() != NULL
4434 		  && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
4435   else if (t->interface_type() != NULL)
4436     {
4437       bool empty_iface = t->interface_type()->is_empty();
4438       go_assert(et->interface_type() != NULL
4439                 && et->interface_type()->is_empty() == empty_iface);
4440     }
4441   else if (t->integer_type() != NULL)
4442     go_assert(et->is_boolean_type()
4443               || et->integer_type() != NULL
4444               || et->function_type() != NULL
4445               || et->points_to() != NULL
4446               || et->map_type() != NULL
4447               || et->channel_type() != NULL
4448 	      || et->is_nil_type());
4449   else
4450     go_unreachable();
4451 
4452   Gogo* gogo = context->gogo();
4453   Btype* btype = t->get_backend(gogo);
4454   Bexpression* bexpr = this->expr_->get_backend(context);
4455   Location loc = this->location();
4456   return gogo->backend()->convert_expression(btype, bexpr, loc);
4457 }
4458 
4459 // Dump ast representation for an unsafe type conversion expression.
4460 
4461 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4462 Unsafe_type_conversion_expression::do_dump_expression(
4463     Ast_dump_context* ast_dump_context) const
4464 {
4465   ast_dump_context->dump_type(this->type_);
4466   ast_dump_context->ostream() << "(";
4467   ast_dump_context->dump_expression(this->expr_);
4468   ast_dump_context->ostream() << ") ";
4469 }
4470 
4471 // Make an unsafe type conversion expression.
4472 
4473 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)4474 Expression::make_unsafe_cast(Type* type, Expression* expr,
4475 			     Location location)
4476 {
4477   return new Unsafe_type_conversion_expression(type, expr, location);
4478 }
4479 
4480 // Class Unary_expression.
4481 
4482 // Call the address_taken method of the operand if needed.  This is
4483 // called after escape analysis but before inserting write barriers.
4484 
4485 void
check_operand_address_taken(Gogo *)4486 Unary_expression::check_operand_address_taken(Gogo*)
4487 {
4488   if (this->op_ != OPERATOR_AND)
4489     return;
4490 
4491   // If this->escapes_ is false at this point, then it was set to
4492   // false by an explicit call to set_does_not_escape, and the value
4493   // does not escape.  If this->escapes_ is true, we may be able to
4494   // set it to false based on the escape analysis pass.
4495   if (this->escapes_)
4496     {
4497       Node* n = Node::make_node(this);
4498       if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
4499 	this->escapes_ = false;
4500     }
4501 
4502   this->expr_->address_taken(this->escapes_);
4503 }
4504 
4505 // If we are taking the address of a composite literal, and the
4506 // contents are not constant, then we want to make a heap expression
4507 // instead.
4508 
4509 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)4510 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4511 {
4512   Location loc = this->location();
4513   Operator op = this->op_;
4514   Expression* expr = this->expr_;
4515 
4516   if (op == OPERATOR_MULT && expr->is_type_expression())
4517     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4518 
4519   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
4520   // moving x to the heap.  FIXME: Is it worth doing a real escape
4521   // analysis here?  This case is found in math/unsafe.go and is
4522   // therefore worth special casing.
4523   if (op == OPERATOR_MULT)
4524     {
4525       Expression* e = expr;
4526       while (e->classification() == EXPRESSION_CONVERSION)
4527 	{
4528 	  Type_conversion_expression* te
4529 	    = static_cast<Type_conversion_expression*>(e);
4530 	  e = te->expr();
4531 	}
4532 
4533       if (e->classification() == EXPRESSION_UNARY)
4534 	{
4535 	  Unary_expression* ue = static_cast<Unary_expression*>(e);
4536 	  if (ue->op_ == OPERATOR_AND)
4537 	    {
4538 	      if (e == expr)
4539 		{
4540 		  // *&x == x.
4541 		  if (!ue->expr_->is_addressable() && !ue->create_temp_)
4542 		    {
4543 		      go_error_at(ue->location(),
4544 				  "invalid operand for unary %<&%>");
4545 		      this->set_is_error();
4546 		    }
4547 		  return ue->expr_;
4548 		}
4549 	      ue->set_does_not_escape();
4550 	    }
4551 	}
4552     }
4553 
4554   // Catching an invalid indirection of unsafe.Pointer here avoid
4555   // having to deal with TYPE_VOID in other places.
4556   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4557     {
4558       go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4559       return Expression::make_error(this->location());
4560     }
4561 
4562   // Check for an invalid pointer dereference.  We need to do this
4563   // here because Unary_expression::do_type will return an error type
4564   // in this case.  That can cause code to appear erroneous, and
4565   // therefore disappear at lowering time, without any error message.
4566   if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
4567     {
4568       this->report_error(_("expected pointer"));
4569       return Expression::make_error(this->location());
4570     }
4571 
4572   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
4573     {
4574       Numeric_constant nc;
4575       if (expr->numeric_constant_value(&nc))
4576 	{
4577 	  Numeric_constant result;
4578 	  bool issued_error;
4579 	  if (Unary_expression::eval_constant(op, &nc, loc, &result,
4580 					      &issued_error))
4581 	    return result.expression(loc);
4582 	  else if (issued_error)
4583 	    return Expression::make_error(this->location());
4584 	}
4585     }
4586 
4587   return this;
4588 }
4589 
4590 // Flatten expression if a nil check must be performed and create temporary
4591 // variables if necessary.
4592 
4593 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)4594 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
4595                              Statement_inserter* inserter)
4596 {
4597   if (this->is_error_expression()
4598       || this->expr_->is_error_expression()
4599       || this->expr_->type()->is_error_type())
4600     {
4601       go_assert(saw_errors());
4602       return Expression::make_error(this->location());
4603     }
4604 
4605   Location location = this->location();
4606   if (this->op_ == OPERATOR_MULT
4607       && !this->expr_->is_variable())
4608     {
4609       go_assert(this->expr_->type()->points_to() != NULL);
4610       switch (this->requires_nil_check(gogo))
4611         {
4612           case NIL_CHECK_ERROR_ENCOUNTERED:
4613             {
4614               go_assert(saw_errors());
4615               return Expression::make_error(this->location());
4616             }
4617           case NIL_CHECK_NOT_NEEDED:
4618             break;
4619           case NIL_CHECK_NEEDED:
4620             this->create_temp_ = true;
4621             break;
4622           case NIL_CHECK_DEFAULT:
4623             go_unreachable();
4624         }
4625     }
4626 
4627   if (this->create_temp_ && !this->expr_->is_variable())
4628     {
4629       Temporary_statement* temp =
4630           Statement::make_temporary(NULL, this->expr_, location);
4631       inserter->insert(temp);
4632       this->expr_ = Expression::make_temporary_reference(temp, location);
4633     }
4634 
4635   return this;
4636 }
4637 
4638 // Return whether a unary expression is a constant.
4639 
4640 bool
do_is_constant() const4641 Unary_expression::do_is_constant() const
4642 {
4643   if (this->op_ == OPERATOR_MULT)
4644     {
4645       // Indirecting through a pointer is only constant if the object
4646       // to which the expression points is constant, but we currently
4647       // have no way to determine that.
4648       return false;
4649     }
4650   else if (this->op_ == OPERATOR_AND)
4651     {
4652       // Taking the address of a variable is constant if it is a
4653       // global variable, not constant otherwise.  In other cases taking the
4654       // address is probably not a constant.
4655       Var_expression* ve = this->expr_->var_expression();
4656       if (ve != NULL)
4657 	{
4658 	  Named_object* no = ve->named_object();
4659 	  return no->is_variable() && no->var_value()->is_global();
4660 	}
4661       return false;
4662     }
4663   else
4664     return this->expr_->is_constant();
4665 }
4666 
4667 // Return whether a unary expression can be used as a constant
4668 // initializer.
4669 
4670 bool
do_is_static_initializer() const4671 Unary_expression::do_is_static_initializer() const
4672 {
4673   if (this->op_ == OPERATOR_MULT)
4674     return false;
4675   else if (this->op_ == OPERATOR_AND)
4676     return Unary_expression::base_is_static_initializer(this->expr_);
4677   else
4678     return this->expr_->is_static_initializer();
4679 }
4680 
4681 // Return whether the address of EXPR can be used as a static
4682 // initializer.
4683 
4684 bool
base_is_static_initializer(Expression * expr)4685 Unary_expression::base_is_static_initializer(Expression* expr)
4686 {
4687   // The address of a field reference can be a static initializer if
4688   // the base can be a static initializer.
4689   Field_reference_expression* fre = expr->field_reference_expression();
4690   if (fre != NULL)
4691     return Unary_expression::base_is_static_initializer(fre->expr());
4692 
4693   // The address of an index expression can be a static initializer if
4694   // the base can be a static initializer and the index is constant.
4695   Array_index_expression* aind = expr->array_index_expression();
4696   if (aind != NULL)
4697     return (aind->end() == NULL
4698 	    && aind->start()->is_constant()
4699 	    && Unary_expression::base_is_static_initializer(aind->array()));
4700 
4701   // The address of a global variable can be a static initializer.
4702   Var_expression* ve = expr->var_expression();
4703   if (ve != NULL)
4704     {
4705       Named_object* no = ve->named_object();
4706       return no->is_variable() && no->var_value()->is_global();
4707     }
4708 
4709   // The address of a composite literal can be used as a static
4710   // initializer if the composite literal is itself usable as a
4711   // static initializer.
4712   if (expr->is_composite_literal() && expr->is_static_initializer())
4713     return true;
4714 
4715   // The address of a string constant can be used as a static
4716   // initializer.  This can not be written in Go itself but this is
4717   // used when building a type descriptor.
4718   if (expr->string_expression() != NULL)
4719     return true;
4720 
4721   return false;
4722 }
4723 
4724 // Return whether this dereference expression requires an explicit nil
4725 // check. If we are dereferencing the pointer to a large struct
4726 // (greater than the specified size threshold), we need to check for
4727 // nil. We don't bother to check for small structs because we expect
4728 // the system to crash on a nil pointer dereference. However, if we
4729 // know the address of this expression is being taken, we must always
4730 // check for nil.
4731 Unary_expression::Nil_check_classification
requires_nil_check(Gogo * gogo)4732 Unary_expression::requires_nil_check(Gogo* gogo)
4733 {
4734   go_assert(this->op_ == OPERATOR_MULT);
4735   go_assert(this->expr_->type()->points_to() != NULL);
4736 
4737   if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4738     return NIL_CHECK_NEEDED;
4739   else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4740     return NIL_CHECK_NOT_NEEDED;
4741 
4742   Type* ptype = this->expr_->type()->points_to();
4743   int64_t type_size = -1;
4744   if (!ptype->is_void_type())
4745     {
4746       bool ok = ptype->backend_type_size(gogo, &type_size);
4747       if (!ok)
4748         return NIL_CHECK_ERROR_ENCOUNTERED;
4749     }
4750 
4751   int64_t size_cutoff = gogo->nil_check_size_threshold();
4752   if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4753     this->issue_nil_check_ = NIL_CHECK_NEEDED;
4754   else
4755     this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4756   return this->issue_nil_check_;
4757 }
4758 
4759 // Apply unary opcode OP to UNC, setting NC.  Return true if this
4760 // could be done, false if not.  On overflow, issues an error and sets
4761 // *ISSUED_ERROR.
4762 
4763 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)4764 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4765 				Location location, Numeric_constant* nc,
4766 				bool* issued_error)
4767 {
4768   *issued_error = false;
4769   switch (op)
4770     {
4771     case OPERATOR_PLUS:
4772       *nc = *unc;
4773       return true;
4774 
4775     case OPERATOR_MINUS:
4776       if (unc->is_int() || unc->is_rune())
4777 	break;
4778       else if (unc->is_float())
4779 	{
4780 	  mpfr_t uval;
4781 	  unc->get_float(&uval);
4782 	  mpfr_t val;
4783 	  mpfr_init(val);
4784 	  mpfr_neg(val, uval, MPFR_RNDN);
4785 	  nc->set_float(unc->type(), val);
4786 	  mpfr_clear(uval);
4787 	  mpfr_clear(val);
4788 	  return true;
4789 	}
4790       else if (unc->is_complex())
4791 	{
4792 	  mpc_t uval;
4793 	  unc->get_complex(&uval);
4794 	  mpc_t val;
4795 	  mpc_init2(val, mpc_precision);
4796 	  mpc_neg(val, uval, MPC_RNDNN);
4797 	  nc->set_complex(unc->type(), val);
4798 	  mpc_clear(uval);
4799 	  mpc_clear(val);
4800 	  return true;
4801 	}
4802       else
4803 	go_unreachable();
4804 
4805     case OPERATOR_XOR:
4806       break;
4807 
4808     case OPERATOR_NOT:
4809     case OPERATOR_AND:
4810     case OPERATOR_MULT:
4811       return false;
4812 
4813     default:
4814       go_unreachable();
4815     }
4816 
4817   if (!unc->is_int() && !unc->is_rune())
4818     return false;
4819 
4820   mpz_t uval;
4821   if (unc->is_rune())
4822     unc->get_rune(&uval);
4823   else
4824     unc->get_int(&uval);
4825   mpz_t val;
4826   mpz_init(val);
4827 
4828   switch (op)
4829     {
4830     case OPERATOR_MINUS:
4831       mpz_neg(val, uval);
4832       break;
4833 
4834     case OPERATOR_NOT:
4835       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4836       break;
4837 
4838     case OPERATOR_XOR:
4839       {
4840 	Type* utype = unc->type();
4841 	if (utype->integer_type() == NULL
4842 	    || utype->integer_type()->is_abstract())
4843 	  mpz_com(val, uval);
4844 	else
4845 	  {
4846 	    // The number of HOST_WIDE_INTs that it takes to represent
4847 	    // UVAL.
4848 	    size_t count = ((mpz_sizeinbase(uval, 2)
4849 			     + HOST_BITS_PER_WIDE_INT
4850 			     - 1)
4851 			    / HOST_BITS_PER_WIDE_INT);
4852 
4853 	    unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4854 	    memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4855 
4856 	    size_t obits = utype->integer_type()->bits();
4857 
4858 	    if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4859 	      {
4860 		mpz_t adj;
4861 		mpz_init_set_ui(adj, 1);
4862 		mpz_mul_2exp(adj, adj, obits);
4863 		mpz_add(uval, uval, adj);
4864 		mpz_clear(adj);
4865 	      }
4866 
4867 	    size_t ecount;
4868 	    mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4869 	    go_assert(ecount <= count);
4870 
4871 	    // Trim down to the number of words required by the type.
4872 	    size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4873 			     / HOST_BITS_PER_WIDE_INT);
4874 	    go_assert(ocount <= count);
4875 
4876 	    for (size_t i = 0; i < ocount; ++i)
4877 	      phwi[i] = ~phwi[i];
4878 
4879 	    size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4880 	    if (clearbits != 0)
4881 	      phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4882 				   >> clearbits);
4883 
4884 	    mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4885 
4886 	    if (!utype->integer_type()->is_unsigned()
4887 		&& mpz_tstbit(val, obits - 1))
4888 	      {
4889 		mpz_t adj;
4890 		mpz_init_set_ui(adj, 1);
4891 		mpz_mul_2exp(adj, adj, obits);
4892 		mpz_sub(val, val, adj);
4893 		mpz_clear(adj);
4894 	      }
4895 
4896 	    delete[] phwi;
4897 	  }
4898       }
4899       break;
4900 
4901     default:
4902       go_unreachable();
4903     }
4904 
4905   if (unc->is_rune())
4906     nc->set_rune(NULL, val);
4907   else
4908     nc->set_int(NULL, val);
4909 
4910   mpz_clear(uval);
4911   mpz_clear(val);
4912 
4913   if (!nc->set_type(unc->type(), true, location))
4914     {
4915       *issued_error = true;
4916       return false;
4917     }
4918   return true;
4919 }
4920 
4921 // Return the integral constant value of a unary expression, if it has one.
4922 
4923 bool
do_numeric_constant_value(Numeric_constant * nc) const4924 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4925 {
4926   Numeric_constant unc;
4927   if (!this->expr_->numeric_constant_value(&unc))
4928     return false;
4929   bool issued_error;
4930   return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4931 					 nc, &issued_error);
4932 }
4933 
4934 // Return the boolean constant value of a unary expression, if it has one.
4935 
4936 bool
do_boolean_constant_value(bool * val) const4937 Unary_expression::do_boolean_constant_value(bool* val) const
4938 {
4939   if (this->op_ == OPERATOR_NOT
4940       && this->expr_->boolean_constant_value(val))
4941     {
4942       *val = !*val;
4943       return true;
4944     }
4945   return false;
4946 }
4947 
4948 // Return the type of a unary expression.
4949 
4950 Type*
do_type()4951 Unary_expression::do_type()
4952 {
4953   switch (this->op_)
4954     {
4955     case OPERATOR_PLUS:
4956     case OPERATOR_MINUS:
4957     case OPERATOR_NOT:
4958     case OPERATOR_XOR:
4959       return this->expr_->type();
4960 
4961     case OPERATOR_AND:
4962       return Type::make_pointer_type(this->expr_->type());
4963 
4964     case OPERATOR_MULT:
4965       {
4966 	Type* subtype = this->expr_->type();
4967 	Type* points_to = subtype->points_to();
4968 	if (points_to == NULL)
4969 	  return Type::make_error_type();
4970 	return points_to;
4971       }
4972 
4973     default:
4974       go_unreachable();
4975     }
4976 }
4977 
4978 // Determine abstract types for a unary expression.
4979 
4980 void
do_determine_type(const Type_context * context)4981 Unary_expression::do_determine_type(const Type_context* context)
4982 {
4983   switch (this->op_)
4984     {
4985     case OPERATOR_PLUS:
4986     case OPERATOR_MINUS:
4987     case OPERATOR_NOT:
4988     case OPERATOR_XOR:
4989       this->expr_->determine_type(context);
4990       break;
4991 
4992     case OPERATOR_AND:
4993       // Taking the address of something.
4994       {
4995 	Type* subtype = (context->type == NULL
4996 			 ? NULL
4997 			 : context->type->points_to());
4998 	Type_context subcontext(subtype, false);
4999 	this->expr_->determine_type(&subcontext);
5000       }
5001       break;
5002 
5003     case OPERATOR_MULT:
5004       // Indirecting through a pointer.
5005       {
5006 	Type* subtype = (context->type == NULL
5007 			 ? NULL
5008 			 : Type::make_pointer_type(context->type));
5009 	Type_context subcontext(subtype, false);
5010 	this->expr_->determine_type(&subcontext);
5011       }
5012       break;
5013 
5014     default:
5015       go_unreachable();
5016     }
5017 }
5018 
5019 // Check types for a unary expression.
5020 
5021 void
do_check_types(Gogo *)5022 Unary_expression::do_check_types(Gogo*)
5023 {
5024   Type* type = this->expr_->type();
5025   if (type->is_error())
5026     {
5027       this->set_is_error();
5028       return;
5029     }
5030 
5031   switch (this->op_)
5032     {
5033     case OPERATOR_PLUS:
5034     case OPERATOR_MINUS:
5035       if (type->integer_type() == NULL
5036 	  && type->float_type() == NULL
5037 	  && type->complex_type() == NULL)
5038 	this->report_error(_("expected numeric type"));
5039       break;
5040 
5041     case OPERATOR_NOT:
5042       if (!type->is_boolean_type())
5043 	this->report_error(_("expected boolean type"));
5044       break;
5045 
5046     case OPERATOR_XOR:
5047       if (type->integer_type() == NULL)
5048 	this->report_error(_("expected integer"));
5049       break;
5050 
5051     case OPERATOR_AND:
5052       if (!this->expr_->is_addressable())
5053 	{
5054 	  if (!this->create_temp_)
5055 	    {
5056 	      go_error_at(this->location(), "invalid operand for unary %<&%>");
5057 	      this->set_is_error();
5058 	    }
5059 	}
5060       else
5061 	this->expr_->issue_nil_check();
5062       break;
5063 
5064     case OPERATOR_MULT:
5065       // Indirecting through a pointer.
5066       if (type->points_to() == NULL)
5067 	this->report_error(_("expected pointer"));
5068       if (type->points_to()->is_error())
5069 	this->set_is_error();
5070       break;
5071 
5072     default:
5073       go_unreachable();
5074     }
5075 }
5076 
5077 // Get the backend representation for a unary expression.
5078 
5079 Bexpression*
do_get_backend(Translate_context * context)5080 Unary_expression::do_get_backend(Translate_context* context)
5081 {
5082   Gogo* gogo = context->gogo();
5083   Location loc = this->location();
5084 
5085   // Taking the address of a set-and-use-temporary expression requires
5086   // setting the temporary and then taking the address.
5087   if (this->op_ == OPERATOR_AND)
5088     {
5089       Set_and_use_temporary_expression* sut =
5090 	this->expr_->set_and_use_temporary_expression();
5091       if (sut != NULL)
5092 	{
5093 	  Temporary_statement* temp = sut->temporary();
5094 	  Bvariable* bvar = temp->get_backend_variable(context);
5095           Bexpression* bvar_expr =
5096               gogo->backend()->var_expression(bvar, loc);
5097           Bexpression* bval = sut->expression()->get_backend(context);
5098 
5099           Named_object* fn = context->function();
5100           go_assert(fn != NULL);
5101           Bfunction* bfn =
5102               fn->func_value()->get_or_make_decl(gogo, fn);
5103           Bstatement* bassign =
5104               gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
5105           Bexpression* bvar_addr =
5106               gogo->backend()->address_expression(bvar_expr, loc);
5107 	  return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
5108 	}
5109     }
5110 
5111   Bexpression* ret;
5112   Bexpression* bexpr = this->expr_->get_backend(context);
5113   Btype* btype = this->expr_->type()->get_backend(gogo);
5114   switch (this->op_)
5115     {
5116     case OPERATOR_PLUS:
5117       ret = bexpr;
5118       break;
5119 
5120     case OPERATOR_MINUS:
5121       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5122       ret = gogo->backend()->convert_expression(btype, ret, loc);
5123       break;
5124 
5125     case OPERATOR_NOT:
5126     case OPERATOR_XOR:
5127       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5128       break;
5129 
5130     case OPERATOR_AND:
5131       if (!this->create_temp_)
5132 	{
5133 	  // We should not see a non-constant constructor here; cases
5134 	  // where we would see one should have been moved onto the
5135 	  // heap at parse time.  Taking the address of a nonconstant
5136 	  // constructor will not do what the programmer expects.
5137 
5138           go_assert(!this->expr_->is_composite_literal()
5139                     || this->expr_->is_static_initializer());
5140 	  if (this->expr_->classification() == EXPRESSION_UNARY)
5141 	    {
5142 	      Unary_expression* ue =
5143 		static_cast<Unary_expression*>(this->expr_);
5144 	      go_assert(ue->op() != OPERATOR_AND);
5145 	    }
5146 	}
5147 
5148       if (this->is_gc_root_ || this->is_slice_init_)
5149 	{
5150 	  std::string var_name;
5151 	  bool copy_to_heap = false;
5152 	  if (this->is_gc_root_)
5153 	    {
5154 	      // Build a decl for a GC root variable.  GC roots are mutable, so
5155 	      // they cannot be represented as an immutable_struct in the
5156 	      // backend.
5157 	      var_name = gogo->gc_root_name();
5158 	    }
5159 	  else
5160 	    {
5161 	      // Build a decl for a slice value initializer.  An immutable slice
5162 	      // value initializer may have to be copied to the heap if it
5163 	      // contains pointers in a non-constant context.
5164 	      var_name = gogo->initializer_name();
5165 
5166 	      Array_type* at = this->expr_->type()->array_type();
5167 	      go_assert(at != NULL);
5168 
5169 	      // If we are not copying the value to the heap, we will only
5170 	      // initialize the value once, so we can use this directly
5171 	      // rather than copying it.  In that case we can't make it
5172 	      // read-only, because the program is permitted to change it.
5173 	      copy_to_heap = (context->function() != NULL
5174                               || context->is_const());
5175 	    }
5176 	  std::string asm_name(go_selectively_encode_id(var_name));
5177 	  Bvariable* implicit =
5178               gogo->backend()->implicit_variable(var_name, asm_name,
5179                                                  btype, true, copy_to_heap,
5180                                                  false, 0);
5181 	  gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
5182 						      true, copy_to_heap, false,
5183 						      bexpr);
5184 	  bexpr = gogo->backend()->var_expression(implicit, loc);
5185 
5186 	  // If we are not copying a slice initializer to the heap,
5187 	  // then it can be changed by the program, so if it can
5188 	  // contain pointers we must register it as a GC root.
5189 	  if (this->is_slice_init_
5190 	      && !copy_to_heap
5191 	      && this->expr_->type()->has_pointer())
5192 	    {
5193 	      Bexpression* root =
5194                   gogo->backend()->var_expression(implicit, loc);
5195 	      root = gogo->backend()->address_expression(root, loc);
5196 	      Type* type = Type::make_pointer_type(this->expr_->type());
5197 	      gogo->add_gc_root(Expression::make_backend(root, type, loc));
5198 	    }
5199 	}
5200       else if ((this->expr_->is_composite_literal()
5201 		|| this->expr_->string_expression() != NULL)
5202 	       && this->expr_->is_static_initializer())
5203         {
5204 	  std::string var_name(gogo->initializer_name());
5205 	  std::string asm_name(go_selectively_encode_id(var_name));
5206           Bvariable* decl =
5207               gogo->backend()->immutable_struct(var_name, asm_name,
5208                                                 true, false, btype, loc);
5209           gogo->backend()->immutable_struct_set_init(decl, var_name, true,
5210 						     false, btype, loc, bexpr);
5211           bexpr = gogo->backend()->var_expression(decl, loc);
5212         }
5213       else if (this->expr_->is_constant())
5214         {
5215           std::string var_name(gogo->initializer_name());
5216           std::string asm_name(go_selectively_encode_id(var_name));
5217           Bvariable* decl =
5218               gogo->backend()->implicit_variable(var_name, asm_name, btype,
5219                                                  true, true, false, 0);
5220           gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
5221                                                       true, true, false,
5222                                                       bexpr);
5223           bexpr = gogo->backend()->var_expression(decl, loc);
5224         }
5225 
5226       go_assert(!this->create_temp_ || this->expr_->is_variable());
5227       ret = gogo->backend()->address_expression(bexpr, loc);
5228       break;
5229 
5230     case OPERATOR_MULT:
5231       {
5232         go_assert(this->expr_->type()->points_to() != NULL);
5233 
5234         bool known_valid = false;
5235         Type* ptype = this->expr_->type()->points_to();
5236         Btype* pbtype = ptype->get_backend(gogo);
5237         switch (this->requires_nil_check(gogo))
5238           {
5239             case NIL_CHECK_NOT_NEEDED:
5240               break;
5241             case NIL_CHECK_ERROR_ENCOUNTERED:
5242               {
5243                 go_assert(saw_errors());
5244                 return gogo->backend()->error_expression();
5245               }
5246             case NIL_CHECK_NEEDED:
5247               {
5248                 go_assert(this->expr_->is_variable());
5249 
5250                 // If we're nil-checking the result of a set-and-use-temporary
5251                 // expression, then pick out the target temp and use that
5252                 // for the final result of the conditional.
5253                 Bexpression* tbexpr = bexpr;
5254                 Bexpression* ubexpr = bexpr;
5255                 Set_and_use_temporary_expression* sut =
5256                     this->expr_->set_and_use_temporary_expression();
5257                 if (sut != NULL) {
5258                   Temporary_statement* temp = sut->temporary();
5259                   Bvariable* bvar = temp->get_backend_variable(context);
5260                   ubexpr = gogo->backend()->var_expression(bvar, loc);
5261                 }
5262                 Bexpression* nil =
5263                     Expression::make_nil(loc)->get_backend(context);
5264                 Bexpression* compare =
5265                     gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
5266                                                        nil, loc);
5267 		Expression* crash = Runtime::make_call(Runtime::PANIC_MEM,
5268 						       loc, 0);
5269 		Bexpression* bcrash = crash->get_backend(context);
5270                 Bfunction* bfn = context->function()->func_value()->get_decl();
5271                 bexpr = gogo->backend()->conditional_expression(bfn, btype,
5272                                                                 compare,
5273                                                                 bcrash, ubexpr,
5274                                                                 loc);
5275                 known_valid = true;
5276                 break;
5277               }
5278             case NIL_CHECK_DEFAULT:
5279               go_unreachable();
5280           }
5281         ret = gogo->backend()->indirect_expression(pbtype, bexpr,
5282                                                    known_valid, loc);
5283       }
5284       break;
5285 
5286     default:
5287       go_unreachable();
5288     }
5289 
5290   return ret;
5291 }
5292 
5293 // Export a unary expression.
5294 
5295 void
do_export(Export_function_body * efb) const5296 Unary_expression::do_export(Export_function_body* efb) const
5297 {
5298   switch (this->op_)
5299     {
5300     case OPERATOR_PLUS:
5301       efb->write_c_string("+");
5302       break;
5303     case OPERATOR_MINUS:
5304       efb->write_c_string("-");
5305       break;
5306     case OPERATOR_NOT:
5307       efb->write_c_string("!");
5308       break;
5309     case OPERATOR_XOR:
5310       efb->write_c_string("^");
5311       break;
5312     case OPERATOR_AND:
5313       efb->write_c_string("&");
5314       break;
5315     case OPERATOR_MULT:
5316       efb->write_c_string("*");
5317       break;
5318     default:
5319       go_unreachable();
5320     }
5321   this->expr_->export_expression(efb);
5322 }
5323 
5324 // Import a unary expression.
5325 
5326 Expression*
do_import(Import_expression * imp,Location loc)5327 Unary_expression::do_import(Import_expression* imp, Location loc)
5328 {
5329   Operator op;
5330   switch (imp->get_char())
5331     {
5332     case '+':
5333       op = OPERATOR_PLUS;
5334       break;
5335     case '-':
5336       op = OPERATOR_MINUS;
5337       break;
5338     case '!':
5339       op = OPERATOR_NOT;
5340       break;
5341     case '^':
5342       op = OPERATOR_XOR;
5343       break;
5344     case '&':
5345       op = OPERATOR_AND;
5346       break;
5347     case '*':
5348       op = OPERATOR_MULT;
5349       break;
5350     default:
5351       go_unreachable();
5352     }
5353   if (imp->version() < EXPORT_FORMAT_V3)
5354     imp->require_c_string(" ");
5355   Expression* expr = Expression::import_expression(imp, loc);
5356   return Expression::make_unary(op, expr, loc);
5357 }
5358 
5359 // Dump ast representation of an unary expression.
5360 
5361 void
do_dump_expression(Ast_dump_context * ast_dump_context) const5362 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5363 {
5364   ast_dump_context->dump_operator(this->op_);
5365   ast_dump_context->ostream() << "(";
5366   ast_dump_context->dump_expression(this->expr_);
5367   ast_dump_context->ostream() << ") ";
5368 }
5369 
5370 // Make a unary expression.
5371 
5372 Expression*
make_unary(Operator op,Expression * expr,Location location)5373 Expression::make_unary(Operator op, Expression* expr, Location location)
5374 {
5375   return new Unary_expression(op, expr, location);
5376 }
5377 
5378 Expression*
make_dereference(Expression * ptr,Nil_check_classification docheck,Location location)5379 Expression::make_dereference(Expression* ptr,
5380                              Nil_check_classification docheck,
5381                              Location location)
5382 {
5383   Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
5384   if (docheck == NIL_CHECK_NEEDED)
5385     deref->unary_expression()->set_requires_nil_check(true);
5386   else if (docheck == NIL_CHECK_NOT_NEEDED)
5387     deref->unary_expression()->set_requires_nil_check(false);
5388   return deref;
5389 }
5390 
5391 // If this is an indirection through a pointer, return the expression
5392 // being pointed through.  Otherwise return this.
5393 
5394 Expression*
deref()5395 Expression::deref()
5396 {
5397   if (this->classification_ == EXPRESSION_UNARY)
5398     {
5399       Unary_expression* ue = static_cast<Unary_expression*>(this);
5400       if (ue->op() == OPERATOR_MULT)
5401 	return ue->operand();
5402     }
5403   return this;
5404 }
5405 
5406 // Class Binary_expression.
5407 
5408 // Traversal.
5409 
5410 int
do_traverse(Traverse * traverse)5411 Binary_expression::do_traverse(Traverse* traverse)
5412 {
5413   int t = Expression::traverse(&this->left_, traverse);
5414   if (t == TRAVERSE_EXIT)
5415     return TRAVERSE_EXIT;
5416   return Expression::traverse(&this->right_, traverse);
5417 }
5418 
5419 // Return whether this expression may be used as a static initializer.
5420 
5421 bool
do_is_static_initializer() const5422 Binary_expression::do_is_static_initializer() const
5423 {
5424   if (!this->left_->is_static_initializer()
5425       || !this->right_->is_static_initializer())
5426     return false;
5427 
5428   // Addresses can be static initializers, but we can't implement
5429   // arbitray binary expressions of them.
5430   Unary_expression* lu = this->left_->unary_expression();
5431   Unary_expression* ru = this->right_->unary_expression();
5432   if (lu != NULL && lu->op() == OPERATOR_AND)
5433     {
5434       if (ru != NULL && ru->op() == OPERATOR_AND)
5435 	return this->op_ == OPERATOR_MINUS;
5436       else
5437 	return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5438     }
5439   else if (ru != NULL && ru->op() == OPERATOR_AND)
5440     return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5441 
5442   // Other cases should resolve in the backend.
5443   return true;
5444 }
5445 
5446 // Return the type to use for a binary operation on operands of
5447 // LEFT_TYPE and RIGHT_TYPE.  These are the types of constants and as
5448 // such may be NULL or abstract.
5449 
5450 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)5451 Binary_expression::operation_type(Operator op, Type* left_type,
5452 				  Type* right_type, Type** result_type)
5453 {
5454   if (left_type != right_type
5455       && !left_type->is_abstract()
5456       && !right_type->is_abstract()
5457       && left_type->base() != right_type->base()
5458       && op != OPERATOR_LSHIFT
5459       && op != OPERATOR_RSHIFT)
5460     {
5461       // May be a type error--let it be diagnosed elsewhere.
5462       return false;
5463     }
5464 
5465   if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5466     {
5467       if (left_type->integer_type() != NULL)
5468 	*result_type = left_type;
5469       else
5470 	*result_type = Type::make_abstract_integer_type();
5471     }
5472   else if (!left_type->is_abstract() && left_type->named_type() != NULL)
5473     *result_type = left_type;
5474   else if (!right_type->is_abstract() && right_type->named_type() != NULL)
5475     *result_type = right_type;
5476   else if (!left_type->is_abstract())
5477     *result_type = left_type;
5478   else if (!right_type->is_abstract())
5479     *result_type = right_type;
5480   else if (left_type->complex_type() != NULL)
5481     *result_type = left_type;
5482   else if (right_type->complex_type() != NULL)
5483     *result_type = right_type;
5484   else if (left_type->float_type() != NULL)
5485     *result_type = left_type;
5486   else if (right_type->float_type() != NULL)
5487     *result_type = right_type;
5488   else if (left_type->integer_type() != NULL
5489 	   && left_type->integer_type()->is_rune())
5490     *result_type = left_type;
5491   else if (right_type->integer_type() != NULL
5492 	   && right_type->integer_type()->is_rune())
5493     *result_type = right_type;
5494   else
5495     *result_type = left_type;
5496 
5497   return true;
5498 }
5499 
5500 // Convert an integer comparison code and an operator to a boolean
5501 // value.
5502 
5503 bool
cmp_to_bool(Operator op,int cmp)5504 Binary_expression::cmp_to_bool(Operator op, int cmp)
5505 {
5506   switch (op)
5507     {
5508     case OPERATOR_EQEQ:
5509       return cmp == 0;
5510       break;
5511     case OPERATOR_NOTEQ:
5512       return cmp != 0;
5513       break;
5514     case OPERATOR_LT:
5515       return cmp < 0;
5516       break;
5517     case OPERATOR_LE:
5518       return cmp <= 0;
5519     case OPERATOR_GT:
5520       return cmp > 0;
5521     case OPERATOR_GE:
5522       return cmp >= 0;
5523     default:
5524       go_unreachable();
5525     }
5526 }
5527 
5528 // Compare constants according to OP.
5529 
5530 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)5531 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
5532 				    Numeric_constant* right_nc,
5533 				    Location location, bool* result)
5534 {
5535   Type* left_type = left_nc->type();
5536   Type* right_type = right_nc->type();
5537 
5538   Type* type;
5539   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5540     return false;
5541 
5542   // When comparing an untyped operand to a typed operand, we are
5543   // effectively coercing the untyped operand to the other operand's
5544   // type, so make sure that is valid.
5545   if (!left_nc->set_type(type, true, location)
5546       || !right_nc->set_type(type, true, location))
5547     return false;
5548 
5549   bool ret;
5550   int cmp;
5551   if (type->complex_type() != NULL)
5552     {
5553       if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
5554 	return false;
5555       ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
5556     }
5557   else if (type->float_type() != NULL)
5558     ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
5559   else
5560     ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
5561 
5562   if (ret)
5563     *result = Binary_expression::cmp_to_bool(op, cmp);
5564 
5565   return ret;
5566 }
5567 
5568 // Compare integer constants.
5569 
5570 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5571 Binary_expression::compare_integer(const Numeric_constant* left_nc,
5572 				   const Numeric_constant* right_nc,
5573 				   int* cmp)
5574 {
5575   mpz_t left_val;
5576   if (!left_nc->to_int(&left_val))
5577     return false;
5578   mpz_t right_val;
5579   if (!right_nc->to_int(&right_val))
5580     {
5581       mpz_clear(left_val);
5582       return false;
5583     }
5584 
5585   *cmp = mpz_cmp(left_val, right_val);
5586 
5587   mpz_clear(left_val);
5588   mpz_clear(right_val);
5589 
5590   return true;
5591 }
5592 
5593 // Compare floating point constants.
5594 
5595 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5596 Binary_expression::compare_float(const Numeric_constant* left_nc,
5597 				 const Numeric_constant* right_nc,
5598 				 int* cmp)
5599 {
5600   mpfr_t left_val;
5601   if (!left_nc->to_float(&left_val))
5602     return false;
5603   mpfr_t right_val;
5604   if (!right_nc->to_float(&right_val))
5605     {
5606       mpfr_clear(left_val);
5607       return false;
5608     }
5609 
5610   // We already coerced both operands to the same type.  If that type
5611   // is not an abstract type, we need to round the values accordingly.
5612   Type* type = left_nc->type();
5613   if (!type->is_abstract() && type->float_type() != NULL)
5614     {
5615       int bits = type->float_type()->bits();
5616       mpfr_prec_round(left_val, bits, MPFR_RNDN);
5617       mpfr_prec_round(right_val, bits, MPFR_RNDN);
5618     }
5619 
5620   *cmp = mpfr_cmp(left_val, right_val);
5621 
5622   mpfr_clear(left_val);
5623   mpfr_clear(right_val);
5624 
5625   return true;
5626 }
5627 
5628 // Compare complex constants.  Complex numbers may only be compared
5629 // for equality.
5630 
5631 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5632 Binary_expression::compare_complex(const Numeric_constant* left_nc,
5633 				   const Numeric_constant* right_nc,
5634 				   int* cmp)
5635 {
5636   mpc_t left_val;
5637   if (!left_nc->to_complex(&left_val))
5638     return false;
5639   mpc_t right_val;
5640   if (!right_nc->to_complex(&right_val))
5641     {
5642       mpc_clear(left_val);
5643       return false;
5644     }
5645 
5646   // We already coerced both operands to the same type.  If that type
5647   // is not an abstract type, we need to round the values accordingly.
5648   Type* type = left_nc->type();
5649   if (!type->is_abstract() && type->complex_type() != NULL)
5650     {
5651       int bits = type->complex_type()->bits();
5652       mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
5653       mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
5654       mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
5655       mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
5656     }
5657 
5658   *cmp = mpc_cmp(left_val, right_val) != 0;
5659 
5660   mpc_clear(left_val);
5661   mpc_clear(right_val);
5662 
5663   return true;
5664 }
5665 
5666 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC.  Return
5667 // true if this could be done, false if not.  Issue errors at LOCATION
5668 // as appropriate, and sets *ISSUED_ERROR if it did.
5669 
5670 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)5671 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
5672 				 Numeric_constant* right_nc,
5673 				 Location location, Numeric_constant* nc,
5674 				 bool* issued_error)
5675 {
5676   *issued_error = false;
5677   switch (op)
5678     {
5679     case OPERATOR_OROR:
5680     case OPERATOR_ANDAND:
5681     case OPERATOR_EQEQ:
5682     case OPERATOR_NOTEQ:
5683     case OPERATOR_LT:
5684     case OPERATOR_LE:
5685     case OPERATOR_GT:
5686     case OPERATOR_GE:
5687       // These return boolean values, not numeric.
5688       return false;
5689     default:
5690       break;
5691     }
5692 
5693   Type* left_type = left_nc->type();
5694   Type* right_type = right_nc->type();
5695 
5696   Type* type;
5697   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5698     return false;
5699 
5700   bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
5701 
5702   // When combining an untyped operand with a typed operand, we are
5703   // effectively coercing the untyped operand to the other operand's
5704   // type, so make sure that is valid.
5705   if (!left_nc->set_type(type, true, location))
5706     return false;
5707   if (!is_shift && !right_nc->set_type(type, true, location))
5708     return false;
5709   if (is_shift
5710       && ((left_type->integer_type() == NULL
5711            && !left_type->is_abstract())
5712           || (right_type->integer_type() == NULL
5713               && !right_type->is_abstract())))
5714     return false;
5715 
5716   bool r;
5717   if (type->complex_type() != NULL)
5718     r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
5719   else if (type->float_type() != NULL)
5720     r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
5721   else
5722     r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
5723 
5724   if (r)
5725     {
5726       r = nc->set_type(type, true, location);
5727       if (!r)
5728 	*issued_error = true;
5729     }
5730 
5731   return r;
5732 }
5733 
5734 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5735 // integer operations.  Return true if this could be done, false if
5736 // not.
5737 
5738 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5739 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
5740 				const Numeric_constant* right_nc,
5741 				Location location, Numeric_constant* nc)
5742 {
5743   mpz_t left_val;
5744   if (!left_nc->to_int(&left_val))
5745     return false;
5746   mpz_t right_val;
5747   if (!right_nc->to_int(&right_val))
5748     {
5749       mpz_clear(left_val);
5750       return false;
5751     }
5752 
5753   mpz_t val;
5754   mpz_init(val);
5755 
5756   switch (op)
5757     {
5758     case OPERATOR_PLUS:
5759       mpz_add(val, left_val, right_val);
5760       if (mpz_sizeinbase(val, 2) > 0x100000)
5761 	{
5762 	  go_error_at(location, "constant addition overflow");
5763           nc->set_invalid();
5764 	  mpz_set_ui(val, 1);
5765 	}
5766       break;
5767     case OPERATOR_MINUS:
5768       mpz_sub(val, left_val, right_val);
5769       if (mpz_sizeinbase(val, 2) > 0x100000)
5770 	{
5771 	  go_error_at(location, "constant subtraction overflow");
5772           nc->set_invalid();
5773 	  mpz_set_ui(val, 1);
5774 	}
5775       break;
5776     case OPERATOR_OR:
5777       mpz_ior(val, left_val, right_val);
5778       break;
5779     case OPERATOR_XOR:
5780       mpz_xor(val, left_val, right_val);
5781       break;
5782     case OPERATOR_MULT:
5783       mpz_mul(val, left_val, right_val);
5784       if (mpz_sizeinbase(val, 2) > 0x100000)
5785 	{
5786 	  go_error_at(location, "constant multiplication overflow");
5787           nc->set_invalid();
5788 	  mpz_set_ui(val, 1);
5789 	}
5790       break;
5791     case OPERATOR_DIV:
5792       if (mpz_sgn(right_val) != 0)
5793 	mpz_tdiv_q(val, left_val, right_val);
5794       else
5795 	{
5796 	  go_error_at(location, "division by zero");
5797           nc->set_invalid();
5798 	  mpz_set_ui(val, 0);
5799 	}
5800       break;
5801     case OPERATOR_MOD:
5802       if (mpz_sgn(right_val) != 0)
5803 	mpz_tdiv_r(val, left_val, right_val);
5804       else
5805 	{
5806 	  go_error_at(location, "division by zero");
5807           nc->set_invalid();
5808 	  mpz_set_ui(val, 0);
5809 	}
5810       break;
5811     case OPERATOR_LSHIFT:
5812       {
5813 	unsigned long shift = mpz_get_ui(right_val);
5814 	if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5815 	  mpz_mul_2exp(val, left_val, shift);
5816 	else
5817 	  {
5818 	    go_error_at(location, "shift count overflow");
5819             nc->set_invalid();
5820 	    mpz_set_ui(val, 1);
5821 	  }
5822 	break;
5823       }
5824       break;
5825     case OPERATOR_RSHIFT:
5826       {
5827 	unsigned long shift = mpz_get_ui(right_val);
5828 	if (mpz_cmp_ui(right_val, shift) != 0)
5829 	  {
5830 	    go_error_at(location, "shift count overflow");
5831             nc->set_invalid();
5832 	    mpz_set_ui(val, 1);
5833 	  }
5834 	else
5835 	  {
5836 	    if (mpz_cmp_ui(left_val, 0) >= 0)
5837 	      mpz_tdiv_q_2exp(val, left_val, shift);
5838 	    else
5839 	      mpz_fdiv_q_2exp(val, left_val, shift);
5840 	  }
5841 	break;
5842       }
5843       break;
5844     case OPERATOR_AND:
5845       mpz_and(val, left_val, right_val);
5846       break;
5847     case OPERATOR_BITCLEAR:
5848       {
5849 	mpz_t tval;
5850 	mpz_init(tval);
5851 	mpz_com(tval, right_val);
5852 	mpz_and(val, left_val, tval);
5853 	mpz_clear(tval);
5854       }
5855       break;
5856     default:
5857       go_unreachable();
5858     }
5859 
5860   mpz_clear(left_val);
5861   mpz_clear(right_val);
5862 
5863   if (left_nc->is_rune()
5864       || (op != OPERATOR_LSHIFT
5865 	  && op != OPERATOR_RSHIFT
5866 	  && right_nc->is_rune()))
5867     nc->set_rune(NULL, val);
5868   else
5869     nc->set_int(NULL, val);
5870 
5871   mpz_clear(val);
5872 
5873   return true;
5874 }
5875 
5876 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5877 // floating point operations.  Return true if this could be done,
5878 // false if not.
5879 
5880 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5881 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5882 			      const Numeric_constant* right_nc,
5883 			      Location location, Numeric_constant* nc)
5884 {
5885   mpfr_t left_val;
5886   if (!left_nc->to_float(&left_val))
5887     return false;
5888   mpfr_t right_val;
5889   if (!right_nc->to_float(&right_val))
5890     {
5891       mpfr_clear(left_val);
5892       return false;
5893     }
5894 
5895   mpfr_t val;
5896   mpfr_init(val);
5897 
5898   bool ret = true;
5899   switch (op)
5900     {
5901     case OPERATOR_PLUS:
5902       mpfr_add(val, left_val, right_val, MPFR_RNDN);
5903       break;
5904     case OPERATOR_MINUS:
5905       mpfr_sub(val, left_val, right_val, MPFR_RNDN);
5906       break;
5907     case OPERATOR_OR:
5908     case OPERATOR_XOR:
5909     case OPERATOR_AND:
5910     case OPERATOR_BITCLEAR:
5911     case OPERATOR_MOD:
5912     case OPERATOR_LSHIFT:
5913     case OPERATOR_RSHIFT:
5914       mpfr_set_ui(val, 0, MPFR_RNDN);
5915       ret = false;
5916       break;
5917     case OPERATOR_MULT:
5918       mpfr_mul(val, left_val, right_val, MPFR_RNDN);
5919       break;
5920     case OPERATOR_DIV:
5921       if (!mpfr_zero_p(right_val))
5922 	mpfr_div(val, left_val, right_val, MPFR_RNDN);
5923       else
5924 	{
5925 	  go_error_at(location, "division by zero");
5926           nc->set_invalid();
5927 	  mpfr_set_ui(val, 0, MPFR_RNDN);
5928 	}
5929       break;
5930     default:
5931       go_unreachable();
5932     }
5933 
5934   mpfr_clear(left_val);
5935   mpfr_clear(right_val);
5936 
5937   nc->set_float(NULL, val);
5938   mpfr_clear(val);
5939 
5940   return ret;
5941 }
5942 
5943 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5944 // complex operations.  Return true if this could be done, false if
5945 // not.
5946 
5947 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5948 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5949 				const Numeric_constant* right_nc,
5950 				Location location, Numeric_constant* nc)
5951 {
5952   mpc_t left_val;
5953   if (!left_nc->to_complex(&left_val))
5954     return false;
5955   mpc_t right_val;
5956   if (!right_nc->to_complex(&right_val))
5957     {
5958       mpc_clear(left_val);
5959       return false;
5960     }
5961 
5962   mpc_t val;
5963   mpc_init2(val, mpc_precision);
5964 
5965   bool ret = true;
5966   switch (op)
5967     {
5968     case OPERATOR_PLUS:
5969       mpc_add(val, left_val, right_val, MPC_RNDNN);
5970       break;
5971     case OPERATOR_MINUS:
5972       mpc_sub(val, left_val, right_val, MPC_RNDNN);
5973       break;
5974     case OPERATOR_OR:
5975     case OPERATOR_XOR:
5976     case OPERATOR_AND:
5977     case OPERATOR_BITCLEAR:
5978     case OPERATOR_MOD:
5979     case OPERATOR_LSHIFT:
5980     case OPERATOR_RSHIFT:
5981       mpc_set_ui(val, 0, MPC_RNDNN);
5982       ret = false;
5983       break;
5984     case OPERATOR_MULT:
5985       mpc_mul(val, left_val, right_val, MPC_RNDNN);
5986       break;
5987     case OPERATOR_DIV:
5988       if (mpc_cmp_si(right_val, 0) == 0)
5989 	{
5990 	  go_error_at(location, "division by zero");
5991           nc->set_invalid();
5992 	  mpc_set_ui(val, 0, MPC_RNDNN);
5993 	  break;
5994 	}
5995       mpc_div(val, left_val, right_val, MPC_RNDNN);
5996       break;
5997     default:
5998       go_unreachable();
5999     }
6000 
6001   mpc_clear(left_val);
6002   mpc_clear(right_val);
6003 
6004   nc->set_complex(NULL, val);
6005   mpc_clear(val);
6006 
6007   return ret;
6008 }
6009 
6010 // Lower a binary expression.  We have to evaluate constant
6011 // expressions now, in order to implement Go's unlimited precision
6012 // constants.
6013 
6014 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)6015 Binary_expression::do_lower(Gogo* gogo, Named_object*,
6016 			    Statement_inserter* inserter, int)
6017 {
6018   Location location = this->location();
6019   Operator op = this->op_;
6020   Expression* left = this->left_;
6021   Expression* right = this->right_;
6022 
6023   const bool is_comparison = (op == OPERATOR_EQEQ
6024 			      || op == OPERATOR_NOTEQ
6025 			      || op == OPERATOR_LT
6026 			      || op == OPERATOR_LE
6027 			      || op == OPERATOR_GT
6028 			      || op == OPERATOR_GE);
6029 
6030   // Numeric constant expressions.
6031   {
6032     Numeric_constant left_nc;
6033     Numeric_constant right_nc;
6034     if (left->numeric_constant_value(&left_nc)
6035 	&& right->numeric_constant_value(&right_nc))
6036       {
6037 	if (is_comparison)
6038 	  {
6039 	    bool result;
6040 	    if (!Binary_expression::compare_constant(op, &left_nc,
6041 						     &right_nc, location,
6042 						     &result))
6043 	      return this;
6044 	    return Expression::make_cast(Type::make_boolean_type(),
6045 					 Expression::make_boolean(result,
6046 								  location),
6047 					 location);
6048 	  }
6049 	else
6050 	  {
6051 	    Numeric_constant nc;
6052 	    bool issued_error;
6053 	    if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
6054 						  location, &nc,
6055 						  &issued_error))
6056 	      {
6057 		if (issued_error)
6058 		  return Expression::make_error(location);
6059                 return this;
6060 	      }
6061 	    return nc.expression(location);
6062 	  }
6063       }
6064   }
6065 
6066   // String constant expressions.
6067   //
6068   // Avoid constant folding here if the left and right types are incompatible
6069   // (leave the operation intact so that the type checker can complain about it
6070   // later on). If concatenating an abstract string with a named string type,
6071   // result type needs to be of the named type (see issue 31412).
6072   if (left->type()->is_string_type()
6073       && right->type()->is_string_type()
6074       && (left->type()->named_type() == NULL
6075           || right->type()->named_type() == NULL
6076           || left->type()->named_type() == right->type()->named_type()))
6077     {
6078       std::string left_string;
6079       std::string right_string;
6080       if (left->string_constant_value(&left_string)
6081 	  && right->string_constant_value(&right_string))
6082 	{
6083 	  if (op == OPERATOR_PLUS)
6084             {
6085               Type* result_type = (left->type()->named_type() != NULL
6086                                    ? left->type()
6087                                    : right->type());
6088               return Expression::make_string_typed(left_string + right_string,
6089                                                    result_type, location);
6090             }
6091 	  else if (is_comparison)
6092 	    {
6093 	      int cmp = left_string.compare(right_string);
6094 	      bool r = Binary_expression::cmp_to_bool(op, cmp);
6095 	      return Expression::make_boolean(r, location);
6096 	    }
6097 	}
6098     }
6099 
6100   // Lower struct, array, and some interface comparisons.
6101   if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6102     {
6103       if (left->type()->struct_type() != NULL
6104 	  && right->type()->struct_type() != NULL)
6105 	return this->lower_struct_comparison(gogo, inserter);
6106       else if (left->type()->array_type() != NULL
6107 	       && !left->type()->is_slice_type()
6108 	       && right->type()->array_type() != NULL
6109 	       && !right->type()->is_slice_type())
6110 	return this->lower_array_comparison(gogo, inserter);
6111       else if ((left->type()->interface_type() != NULL
6112                 && right->type()->interface_type() == NULL)
6113                || (left->type()->interface_type() == NULL
6114                    && right->type()->interface_type() != NULL))
6115 	return this->lower_interface_value_comparison(gogo, inserter);
6116     }
6117 
6118   // Lower string concatenation to String_concat_expression, so that
6119   // we can group sequences of string additions.
6120   if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
6121     {
6122       Expression_list* exprs;
6123       String_concat_expression* left_sce =
6124 	this->left_->string_concat_expression();
6125       if (left_sce != NULL)
6126 	exprs = left_sce->exprs();
6127       else
6128 	{
6129 	  exprs = new Expression_list();
6130 	  exprs->push_back(this->left_);
6131 	}
6132 
6133       String_concat_expression* right_sce =
6134 	this->right_->string_concat_expression();
6135       if (right_sce != NULL)
6136 	exprs->append(right_sce->exprs());
6137       else
6138 	exprs->push_back(this->right_);
6139 
6140       return Expression::make_string_concat(exprs);
6141     }
6142 
6143   return this;
6144 }
6145 
6146 // Lower a struct comparison.
6147 
6148 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)6149 Binary_expression::lower_struct_comparison(Gogo* gogo,
6150 					   Statement_inserter* inserter)
6151 {
6152   Struct_type* st = this->left_->type()->struct_type();
6153   Struct_type* st2 = this->right_->type()->struct_type();
6154   if (st2 == NULL)
6155     return this;
6156   if (st != st2
6157       && !Type::are_identical(st, st2,
6158 			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6159 			      NULL))
6160     return this;
6161   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6162 					   this->right_->type(), NULL))
6163     return this;
6164 
6165   // See if we can compare using memcmp.  As a heuristic, we use
6166   // memcmp rather than field references and comparisons if there are
6167   // more than two fields.
6168   if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
6169     return this->lower_compare_to_memcmp(gogo, inserter);
6170 
6171   Location loc = this->location();
6172 
6173   Expression* left = this->left_;
6174   Temporary_statement* left_temp = NULL;
6175   if (left->var_expression() == NULL
6176       && left->temporary_reference_expression() == NULL)
6177     {
6178       left_temp = Statement::make_temporary(left->type(), NULL, loc);
6179       inserter->insert(left_temp);
6180       left = Expression::make_set_and_use_temporary(left_temp, left, loc);
6181     }
6182 
6183   Expression* right = this->right_;
6184   Temporary_statement* right_temp = NULL;
6185   if (right->var_expression() == NULL
6186       && right->temporary_reference_expression() == NULL)
6187     {
6188       right_temp = Statement::make_temporary(right->type(), NULL, loc);
6189       inserter->insert(right_temp);
6190       right = Expression::make_set_and_use_temporary(right_temp, right, loc);
6191     }
6192 
6193   Expression* ret = Expression::make_boolean(true, loc);
6194   const Struct_field_list* fields = st->fields();
6195   unsigned int field_index = 0;
6196   for (Struct_field_list::const_iterator pf = fields->begin();
6197        pf != fields->end();
6198        ++pf, ++field_index)
6199     {
6200       if (Gogo::is_sink_name(pf->field_name()))
6201 	continue;
6202 
6203       if (field_index > 0)
6204 	{
6205 	  if (left_temp == NULL)
6206 	    left = left->copy();
6207 	  else
6208 	    left = Expression::make_temporary_reference(left_temp, loc);
6209 	  if (right_temp == NULL)
6210 	    right = right->copy();
6211 	  else
6212 	    right = Expression::make_temporary_reference(right_temp, loc);
6213 	}
6214       Expression* f1 = Expression::make_field_reference(left, field_index,
6215 							loc);
6216       Expression* f2 = Expression::make_field_reference(right, field_index,
6217 							loc);
6218       Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6219       ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6220     }
6221 
6222   if (this->op_ == OPERATOR_NOTEQ)
6223     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6224 
6225   return ret;
6226 }
6227 
6228 // Lower an array comparison.
6229 
6230 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)6231 Binary_expression::lower_array_comparison(Gogo* gogo,
6232 					  Statement_inserter* inserter)
6233 {
6234   Array_type* at = this->left_->type()->array_type();
6235   Array_type* at2 = this->right_->type()->array_type();
6236   if (at2 == NULL)
6237     return this;
6238   if (at != at2
6239       && !Type::are_identical(at, at2,
6240 			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6241 			      NULL))
6242     return this;
6243   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6244 					   this->right_->type(), NULL))
6245     return this;
6246 
6247   // Call memcmp directly if possible.  This may let the middle-end
6248   // optimize the call.
6249   if (at->compare_is_identity(gogo))
6250     return this->lower_compare_to_memcmp(gogo, inserter);
6251 
6252   // Call the array comparison function.
6253   Named_object* equal_fn =
6254     at->equal_function(gogo, this->left_->type()->named_type(), NULL);
6255 
6256   Location loc = this->location();
6257 
6258   Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6259 
6260   Expression_list* args = new Expression_list();
6261   args->push_back(this->operand_address(inserter, this->left_));
6262   args->push_back(this->operand_address(inserter, this->right_));
6263 
6264   Expression* ret = Expression::make_call(func, args, false, loc);
6265 
6266   if (this->op_ == OPERATOR_NOTEQ)
6267     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6268 
6269   return ret;
6270 }
6271 
6272 // Lower an interface to value comparison.
6273 
6274 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)6275 Binary_expression::lower_interface_value_comparison(Gogo*,
6276                                                     Statement_inserter* inserter)
6277 {
6278   Type* left_type = this->left_->type();
6279   Type* right_type = this->right_->type();
6280   Interface_type* ift;
6281   if (left_type->interface_type() != NULL)
6282     {
6283       ift = left_type->interface_type();
6284       if (!ift->implements_interface(right_type, NULL))
6285         return this;
6286     }
6287   else
6288     {
6289       ift = right_type->interface_type();
6290       if (!ift->implements_interface(left_type, NULL))
6291         return this;
6292     }
6293   if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
6294     return this;
6295 
6296   Location loc = this->location();
6297 
6298   if (left_type->interface_type() == NULL
6299       && left_type->points_to() == NULL
6300       && !this->left_->is_addressable())
6301     {
6302       Temporary_statement* temp =
6303           Statement::make_temporary(left_type, NULL, loc);
6304       inserter->insert(temp);
6305       this->left_ =
6306           Expression::make_set_and_use_temporary(temp, this->left_, loc);
6307     }
6308 
6309   if (right_type->interface_type() == NULL
6310       && right_type->points_to() == NULL
6311       && !this->right_->is_addressable())
6312     {
6313       Temporary_statement* temp =
6314           Statement::make_temporary(right_type, NULL, loc);
6315       inserter->insert(temp);
6316       this->right_ =
6317           Expression::make_set_and_use_temporary(temp, this->right_, loc);
6318     }
6319 
6320   return this;
6321 }
6322 
6323 // Lower a struct or array comparison to a call to memcmp.
6324 
6325 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)6326 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6327 {
6328   Location loc = this->location();
6329 
6330   Expression* a1 = this->operand_address(inserter, this->left_);
6331   Expression* a2 = this->operand_address(inserter, this->right_);
6332   Expression* len = Expression::make_type_info(this->left_->type(),
6333 					       TYPE_INFO_SIZE);
6334 
6335   Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6336   Type* int32_type = Type::lookup_integer_type("int32");
6337   Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
6338   return Expression::make_binary(this->op_, call, zero, loc);
6339 }
6340 
6341 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)6342 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
6343                               Statement_inserter* inserter)
6344 {
6345   Location loc = this->location();
6346   if (this->left_->type()->is_error_type()
6347       || this->right_->type()->is_error_type()
6348       || this->left_->is_error_expression()
6349       || this->right_->is_error_expression())
6350     {
6351       go_assert(saw_errors());
6352       return Expression::make_error(loc);
6353     }
6354 
6355   Temporary_statement* temp;
6356 
6357   Type* left_type = this->left_->type();
6358   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6359                       || this->op_ == OPERATOR_RSHIFT);
6360   bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
6361                       left_type->integer_type() != NULL)
6362                      || this->op_ == OPERATOR_MOD);
6363   bool is_string_op = (left_type->is_string_type()
6364                        && this->right_->type()->is_string_type());
6365 
6366   if (is_string_op)
6367     {
6368       // Mark string([]byte) operands to reuse the backing store.
6369       // String comparison does not keep the reference, so it is safe.
6370       Type_conversion_expression* lce =
6371         this->left_->conversion_expression();
6372       if (lce != NULL && lce->expr()->type()->is_slice_type())
6373         lce->set_no_copy(true);
6374       Type_conversion_expression* rce =
6375         this->right_->conversion_expression();
6376       if (rce != NULL && rce->expr()->type()->is_slice_type())
6377         rce->set_no_copy(true);
6378     }
6379 
6380   if (is_shift_op
6381       || (is_idiv_op
6382 	  && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
6383       || is_string_op)
6384     {
6385       if (!this->left_->is_variable() && !this->left_->is_constant())
6386         {
6387           temp = Statement::make_temporary(NULL, this->left_, loc);
6388           inserter->insert(temp);
6389           this->left_ = Expression::make_temporary_reference(temp, loc);
6390         }
6391       if (!this->right_->is_variable() && !this->right_->is_constant())
6392         {
6393           temp =
6394               Statement::make_temporary(NULL, this->right_, loc);
6395           this->right_ = Expression::make_temporary_reference(temp, loc);
6396           inserter->insert(temp);
6397         }
6398     }
6399   return this;
6400 }
6401 
6402 
6403 // Return the address of EXPR, cast to unsafe.Pointer.
6404 
6405 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)6406 Binary_expression::operand_address(Statement_inserter* inserter,
6407 				   Expression* expr)
6408 {
6409   Location loc = this->location();
6410 
6411   if (!expr->is_addressable())
6412     {
6413       Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6414 							    loc);
6415       inserter->insert(temp);
6416       expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6417     }
6418   expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6419   static_cast<Unary_expression*>(expr)->set_does_not_escape();
6420   Type* void_type = Type::make_void_type();
6421   Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6422   return Expression::make_cast(unsafe_pointer_type, expr, loc);
6423 }
6424 
6425 // Return the numeric constant value, if it has one.
6426 
6427 bool
do_numeric_constant_value(Numeric_constant * nc) const6428 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
6429 {
6430   Numeric_constant left_nc;
6431   if (!this->left_->numeric_constant_value(&left_nc))
6432     return false;
6433   Numeric_constant right_nc;
6434   if (!this->right_->numeric_constant_value(&right_nc))
6435     return false;
6436   bool issued_error;
6437   return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
6438 					  this->location(), nc, &issued_error);
6439 }
6440 
6441 // Return the boolean constant value, if it has one.
6442 
6443 bool
do_boolean_constant_value(bool * val) const6444 Binary_expression::do_boolean_constant_value(bool* val) const
6445 {
6446   bool is_comparison = false;
6447   switch (this->op_)
6448     {
6449     case OPERATOR_EQEQ:
6450     case OPERATOR_NOTEQ:
6451     case OPERATOR_LT:
6452     case OPERATOR_LE:
6453     case OPERATOR_GT:
6454     case OPERATOR_GE:
6455       is_comparison = true;
6456       break;
6457     case OPERATOR_ANDAND:
6458     case OPERATOR_OROR:
6459       break;
6460     default:
6461       return false;
6462     }
6463 
6464   Numeric_constant left_nc, right_nc;
6465   if (is_comparison
6466       && this->left_->numeric_constant_value(&left_nc)
6467       && this->right_->numeric_constant_value(&right_nc))
6468     return Binary_expression::compare_constant(this->op_, &left_nc,
6469                                                &right_nc,
6470                                                this->location(),
6471                                                val);
6472 
6473   std::string left_str, right_str;
6474   if (is_comparison
6475       && this->left_->string_constant_value(&left_str)
6476       && this->right_->string_constant_value(&right_str))
6477     {
6478       *val = Binary_expression::cmp_to_bool(this->op_,
6479                                             left_str.compare(right_str));
6480       return true;
6481     }
6482 
6483   bool left_bval;
6484   if (this->left_->boolean_constant_value(&left_bval))
6485     {
6486       if (this->op_ == OPERATOR_ANDAND && !left_bval)
6487         {
6488           *val = false;
6489           return true;
6490         }
6491       else if (this->op_ == OPERATOR_OROR && left_bval)
6492         {
6493           *val = true;
6494           return true;
6495         }
6496 
6497       bool right_bval;
6498       if (this->right_->boolean_constant_value(&right_bval))
6499         {
6500           switch (this->op_)
6501             {
6502             case OPERATOR_EQEQ:
6503               *val = (left_bval == right_bval);
6504               return true;
6505             case OPERATOR_NOTEQ:
6506               *val = (left_bval != right_bval);
6507               return true;
6508             case OPERATOR_ANDAND:
6509             case OPERATOR_OROR:
6510               *val = right_bval;
6511               return true;
6512             default:
6513               go_unreachable();
6514             }
6515         }
6516     }
6517 
6518   return false;
6519 }
6520 
6521 // Note that the value is being discarded.
6522 
6523 bool
do_discarding_value()6524 Binary_expression::do_discarding_value()
6525 {
6526   if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6527     return this->right_->discarding_value();
6528   else
6529     {
6530       this->unused_value_error();
6531       return false;
6532     }
6533 }
6534 
6535 // Get type.
6536 
6537 Type*
do_type()6538 Binary_expression::do_type()
6539 {
6540   if (this->classification() == EXPRESSION_ERROR)
6541     return Type::make_error_type();
6542 
6543   switch (this->op_)
6544     {
6545     case OPERATOR_EQEQ:
6546     case OPERATOR_NOTEQ:
6547     case OPERATOR_LT:
6548     case OPERATOR_LE:
6549     case OPERATOR_GT:
6550     case OPERATOR_GE:
6551       if (this->type_ == NULL)
6552 	this->type_ = Type::make_boolean_type();
6553       return this->type_;
6554 
6555     case OPERATOR_PLUS:
6556     case OPERATOR_MINUS:
6557     case OPERATOR_OR:
6558     case OPERATOR_XOR:
6559     case OPERATOR_MULT:
6560     case OPERATOR_DIV:
6561     case OPERATOR_MOD:
6562     case OPERATOR_AND:
6563     case OPERATOR_BITCLEAR:
6564     case OPERATOR_OROR:
6565     case OPERATOR_ANDAND:
6566       {
6567 	Type* type;
6568 	if (!Binary_expression::operation_type(this->op_,
6569 					       this->left_->type(),
6570 					       this->right_->type(),
6571 					       &type))
6572 	  return Type::make_error_type();
6573 	return type;
6574       }
6575 
6576     case OPERATOR_LSHIFT:
6577     case OPERATOR_RSHIFT:
6578       return this->left_->type();
6579 
6580     default:
6581       go_unreachable();
6582     }
6583 }
6584 
6585 // Set type for a binary expression.
6586 
6587 void
do_determine_type(const Type_context * context)6588 Binary_expression::do_determine_type(const Type_context* context)
6589 {
6590   Type* tleft = this->left_->type();
6591   Type* tright = this->right_->type();
6592 
6593   // Both sides should have the same type, except for the shift
6594   // operations.  For a comparison, we should ignore the incoming
6595   // type.
6596 
6597   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6598 		      || this->op_ == OPERATOR_RSHIFT);
6599 
6600   bool is_comparison = (this->op_ == OPERATOR_EQEQ
6601 			|| this->op_ == OPERATOR_NOTEQ
6602 			|| this->op_ == OPERATOR_LT
6603 			|| this->op_ == OPERATOR_LE
6604 			|| this->op_ == OPERATOR_GT
6605 			|| this->op_ == OPERATOR_GE);
6606 
6607   // For constant expressions, the context of the result is not useful in
6608   // determining the types of the operands.  It is only legal to use abstract
6609   // boolean, numeric, and string constants as operands where it is legal to
6610   // use non-abstract boolean, numeric, and string constants, respectively.
6611   // Any issues with the operation will be resolved in the check_types pass.
6612   bool is_constant_expr = (this->left_->is_constant()
6613                            && this->right_->is_constant());
6614 
6615   Type_context subcontext(*context);
6616 
6617   if (is_constant_expr && !is_shift_op)
6618     {
6619       subcontext.type = NULL;
6620       subcontext.may_be_abstract = true;
6621     }
6622   else if (is_comparison)
6623     {
6624       // In a comparison, the context does not determine the types of
6625       // the operands.
6626       subcontext.type = NULL;
6627     }
6628 
6629   // Set the context for the left hand operand.
6630   if (is_shift_op)
6631     {
6632       // The right hand operand of a shift plays no role in
6633       // determining the type of the left hand operand.
6634     }
6635   else if (!tleft->is_abstract())
6636     subcontext.type = tleft;
6637   else if (!tright->is_abstract())
6638     subcontext.type = tright;
6639   else if (subcontext.type == NULL)
6640     {
6641       if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6642 	  || (tleft->float_type() != NULL && tright->float_type() != NULL)
6643 	  || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6644 	{
6645 	  // Both sides have an abstract integer, abstract float, or
6646 	  // abstract complex type.  Just let CONTEXT determine
6647 	  // whether they may remain abstract or not.
6648 	}
6649       else if (tleft->complex_type() != NULL)
6650 	subcontext.type = tleft;
6651       else if (tright->complex_type() != NULL)
6652 	subcontext.type = tright;
6653       else if (tleft->float_type() != NULL)
6654 	subcontext.type = tleft;
6655       else if (tright->float_type() != NULL)
6656 	subcontext.type = tright;
6657       else
6658 	subcontext.type = tleft;
6659 
6660       if (subcontext.type != NULL && !context->may_be_abstract)
6661 	subcontext.type = subcontext.type->make_non_abstract_type();
6662     }
6663 
6664   this->left_->determine_type(&subcontext);
6665 
6666   if (is_shift_op)
6667     {
6668       // We may have inherited an unusable type for the shift operand.
6669       // Give a useful error if that happened.
6670       if (tleft->is_abstract()
6671 	  && subcontext.type != NULL
6672 	  && !subcontext.may_be_abstract
6673 	  && subcontext.type->interface_type() == NULL
6674 	  && subcontext.type->integer_type() == NULL)
6675 	this->report_error(("invalid context-determined non-integer type "
6676 			    "for left operand of shift"));
6677 
6678       // The context for the right hand operand is the same as for the
6679       // left hand operand, except for a shift operator.
6680       subcontext.type = Type::lookup_integer_type("uint");
6681       subcontext.may_be_abstract = false;
6682     }
6683 
6684   this->right_->determine_type(&subcontext);
6685 
6686   if (is_comparison)
6687     {
6688       if (this->type_ != NULL && !this->type_->is_abstract())
6689 	;
6690       else if (context->type != NULL && context->type->is_boolean_type())
6691 	this->type_ = context->type;
6692       else if (!context->may_be_abstract)
6693 	this->type_ = Type::lookup_bool_type();
6694     }
6695 }
6696 
6697 // Report an error if the binary operator OP does not support TYPE.
6698 // OTYPE is the type of the other operand.  Return whether the
6699 // operation is OK.  This should not be used for shift.
6700 
6701 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)6702 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6703 				       Location location)
6704 {
6705   switch (op)
6706     {
6707     case OPERATOR_OROR:
6708     case OPERATOR_ANDAND:
6709       if (!type->is_boolean_type()
6710           || !otype->is_boolean_type())
6711 	{
6712 	  go_error_at(location, "expected boolean type");
6713 	  return false;
6714 	}
6715       break;
6716 
6717     case OPERATOR_EQEQ:
6718     case OPERATOR_NOTEQ:
6719       {
6720 	std::string reason;
6721 	if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6722 	  {
6723 	    go_error_at(location, "%s", reason.c_str());
6724 	    return false;
6725 	  }
6726       }
6727       break;
6728 
6729     case OPERATOR_LT:
6730     case OPERATOR_LE:
6731     case OPERATOR_GT:
6732     case OPERATOR_GE:
6733       {
6734 	std::string reason;
6735 	if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6736 	  {
6737 	    go_error_at(location, "%s", reason.c_str());
6738 	    return false;
6739 	  }
6740       }
6741       break;
6742 
6743     case OPERATOR_PLUS:
6744     case OPERATOR_PLUSEQ:
6745       if ((!type->is_numeric_type() && !type->is_string_type())
6746           || (!otype->is_numeric_type() && !otype->is_string_type()))
6747 	{
6748 	  go_error_at(location,
6749 		   "expected integer, floating, complex, or string type");
6750 	  return false;
6751 	}
6752       break;
6753 
6754     case OPERATOR_MINUS:
6755     case OPERATOR_MINUSEQ:
6756     case OPERATOR_MULT:
6757     case OPERATOR_MULTEQ:
6758     case OPERATOR_DIV:
6759     case OPERATOR_DIVEQ:
6760       if (!type->is_numeric_type() || !otype->is_numeric_type())
6761 	{
6762 	  go_error_at(location, "expected integer, floating, or complex type");
6763 	  return false;
6764 	}
6765       break;
6766 
6767     case OPERATOR_MOD:
6768     case OPERATOR_MODEQ:
6769     case OPERATOR_OR:
6770     case OPERATOR_OREQ:
6771     case OPERATOR_AND:
6772     case OPERATOR_ANDEQ:
6773     case OPERATOR_XOR:
6774     case OPERATOR_XOREQ:
6775     case OPERATOR_BITCLEAR:
6776     case OPERATOR_BITCLEAREQ:
6777       if (type->integer_type() == NULL || otype->integer_type() == NULL)
6778 	{
6779 	  go_error_at(location, "expected integer type");
6780 	  return false;
6781 	}
6782       break;
6783 
6784     default:
6785       go_unreachable();
6786     }
6787 
6788   return true;
6789 }
6790 
6791 // Check types.
6792 
6793 void
do_check_types(Gogo *)6794 Binary_expression::do_check_types(Gogo*)
6795 {
6796   if (this->classification() == EXPRESSION_ERROR)
6797     return;
6798 
6799   Type* left_type = this->left_->type();
6800   Type* right_type = this->right_->type();
6801   if (left_type->is_error() || right_type->is_error())
6802     {
6803       this->set_is_error();
6804       return;
6805     }
6806 
6807   if (this->op_ == OPERATOR_EQEQ
6808       || this->op_ == OPERATOR_NOTEQ
6809       || this->op_ == OPERATOR_LT
6810       || this->op_ == OPERATOR_LE
6811       || this->op_ == OPERATOR_GT
6812       || this->op_ == OPERATOR_GE)
6813     {
6814       if (left_type->is_nil_type() && right_type->is_nil_type())
6815 	{
6816 	  this->report_error(_("invalid comparison of nil with nil"));
6817 	  return;
6818 	}
6819       if (!Type::are_assignable(left_type, right_type, NULL)
6820 	  && !Type::are_assignable(right_type, left_type, NULL))
6821 	{
6822 	  this->report_error(_("incompatible types in binary expression"));
6823 	  return;
6824 	}
6825       if (!Binary_expression::check_operator_type(this->op_, left_type,
6826 						  right_type,
6827 						  this->location())
6828 	  || !Binary_expression::check_operator_type(this->op_, right_type,
6829 						     left_type,
6830 						     this->location()))
6831 	{
6832 	  this->set_is_error();
6833 	  return;
6834 	}
6835     }
6836   else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6837     {
6838       if (!Type::are_compatible_for_binop(left_type, right_type))
6839 	{
6840 	  this->report_error(_("incompatible types in binary expression"));
6841 	  return;
6842 	}
6843       if (!Binary_expression::check_operator_type(this->op_, left_type,
6844 						  right_type,
6845 						  this->location()))
6846 	{
6847 	  this->set_is_error();
6848 	  return;
6849 	}
6850       if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
6851 	{
6852 	  // Division by a zero integer constant is an error.
6853 	  Numeric_constant rconst;
6854 	  unsigned long rval;
6855 	  if (left_type->integer_type() != NULL
6856 	      && this->right_->numeric_constant_value(&rconst)
6857 	      && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6858 	      && rval == 0)
6859 	    {
6860 	      this->report_error(_("integer division by zero"));
6861 	      return;
6862 	    }
6863 	}
6864     }
6865   else
6866     {
6867       if (left_type->integer_type() == NULL)
6868 	this->report_error(_("shift of non-integer operand"));
6869 
6870       if (right_type->is_string_type())
6871         this->report_error(_("shift count not integer"));
6872       else if (!right_type->is_abstract()
6873 	       && right_type->integer_type() == NULL)
6874 	this->report_error(_("shift count not integer"));
6875       else
6876 	{
6877 	  Numeric_constant nc;
6878 	  if (this->right_->numeric_constant_value(&nc))
6879 	    {
6880 	      mpz_t val;
6881 	      if (!nc.to_int(&val))
6882 		this->report_error(_("shift count not integer"));
6883 	      else
6884 		{
6885 		  if (mpz_sgn(val) < 0)
6886 		    {
6887 		      this->report_error(_("negative shift count"));
6888 		      Location rloc = this->right_->location();
6889 		      this->right_ = Expression::make_integer_ul(0, right_type,
6890 								 rloc);
6891 		    }
6892 		  mpz_clear(val);
6893 		}
6894 	    }
6895 	}
6896     }
6897 }
6898 
6899 // Get the backend representation for a binary expression.
6900 
6901 Bexpression*
do_get_backend(Translate_context * context)6902 Binary_expression::do_get_backend(Translate_context* context)
6903 {
6904   Gogo* gogo = context->gogo();
6905   Location loc = this->location();
6906   Type* left_type = this->left_->type();
6907   Type* right_type = this->right_->type();
6908 
6909   bool use_left_type = true;
6910   bool is_shift_op = false;
6911   bool is_idiv_op = false;
6912   switch (this->op_)
6913     {
6914     case OPERATOR_EQEQ:
6915     case OPERATOR_NOTEQ:
6916     case OPERATOR_LT:
6917     case OPERATOR_LE:
6918     case OPERATOR_GT:
6919     case OPERATOR_GE:
6920       return Expression::comparison(context, this->type_, this->op_,
6921 				    this->left_, this->right_, loc);
6922 
6923     case OPERATOR_OROR:
6924     case OPERATOR_ANDAND:
6925       use_left_type = false;
6926       break;
6927     case OPERATOR_PLUS:
6928     case OPERATOR_MINUS:
6929     case OPERATOR_OR:
6930     case OPERATOR_XOR:
6931     case OPERATOR_MULT:
6932       break;
6933     case OPERATOR_DIV:
6934       if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6935         break;
6936       // Fall through.
6937     case OPERATOR_MOD:
6938       is_idiv_op = true;
6939       break;
6940     case OPERATOR_LSHIFT:
6941     case OPERATOR_RSHIFT:
6942       is_shift_op = true;
6943       break;
6944     case OPERATOR_BITCLEAR:
6945       this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6946     case OPERATOR_AND:
6947       break;
6948     default:
6949       go_unreachable();
6950     }
6951 
6952   // The only binary operation for string is +, and that should have
6953   // been converted to a String_concat_expression in do_lower.
6954   go_assert(!left_type->is_string_type());
6955 
6956   // For complex division Go might want slightly different results than the
6957   // backend implementation provides, so we have our own runtime routine.
6958   if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6959     {
6960       Runtime::Function complex_code;
6961       switch (this->left_->type()->complex_type()->bits())
6962 	{
6963 	case 64:
6964           complex_code = Runtime::COMPLEX64_DIV;
6965 	  break;
6966 	case 128:
6967           complex_code = Runtime::COMPLEX128_DIV;
6968 	  break;
6969 	default:
6970 	  go_unreachable();
6971 	}
6972       Expression* complex_div =
6973           Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6974       return complex_div->get_backend(context);
6975     }
6976 
6977   Bexpression* left = this->left_->get_backend(context);
6978   Bexpression* right = this->right_->get_backend(context);
6979 
6980   Type* type = use_left_type ? left_type : right_type;
6981   Btype* btype = type->get_backend(gogo);
6982 
6983   Bexpression* ret =
6984       gogo->backend()->binary_expression(this->op_, left, right, loc);
6985   ret = gogo->backend()->convert_expression(btype, ret, loc);
6986 
6987   // Initialize overflow constants.
6988   Bexpression* overflow;
6989   mpz_t zero;
6990   mpz_init_set_ui(zero, 0UL);
6991   mpz_t one;
6992   mpz_init_set_ui(one, 1UL);
6993   mpz_t neg_one;
6994   mpz_init_set_si(neg_one, -1);
6995 
6996   Btype* left_btype = left_type->get_backend(gogo);
6997   Btype* right_btype = right_type->get_backend(gogo);
6998 
6999   // In Go, a shift larger than the size of the type is well-defined.
7000   // This is not true in C, so we need to insert a conditional.
7001   // We also need to check for a negative shift count.
7002   if (is_shift_op)
7003     {
7004       go_assert(left_type->integer_type() != NULL);
7005       go_assert(right_type->integer_type() != NULL);
7006 
7007       int bits = left_type->integer_type()->bits();
7008 
7009       Numeric_constant nc;
7010       unsigned long ul;
7011       if (!this->right_->numeric_constant_value(&nc)
7012 	  || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
7013 	  || ul >= static_cast<unsigned long>(bits))
7014 	{
7015 	  mpz_t bitsval;
7016 	  mpz_init_set_ui(bitsval, bits);
7017 	  Bexpression* bits_expr =
7018 	    gogo->backend()->integer_constant_expression(right_btype, bitsval);
7019 	  Bexpression* compare =
7020 	    gogo->backend()->binary_expression(OPERATOR_LT,
7021 					       right, bits_expr, loc);
7022 
7023 	  Bexpression* zero_expr =
7024 	    gogo->backend()->integer_constant_expression(left_btype, zero);
7025 	  overflow = zero_expr;
7026 	  Bfunction* bfn = context->function()->func_value()->get_decl();
7027 	  if (this->op_ == OPERATOR_RSHIFT
7028 	      && !left_type->integer_type()->is_unsigned())
7029 	    {
7030 	      Bexpression* neg_expr =
7031 		gogo->backend()->binary_expression(OPERATOR_LT, left,
7032 						   zero_expr, loc);
7033 	      Bexpression* neg_one_expr =
7034 		gogo->backend()->integer_constant_expression(left_btype,
7035 							     neg_one);
7036 	      overflow = gogo->backend()->conditional_expression(bfn,
7037 								 btype,
7038 								 neg_expr,
7039 								 neg_one_expr,
7040 								 zero_expr,
7041 								 loc);
7042 	    }
7043 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7044 							ret, overflow, loc);
7045 	  mpz_clear(bitsval);
7046 	}
7047 
7048       if (!right_type->integer_type()->is_unsigned()
7049 	  && (!this->right_->numeric_constant_value(&nc)
7050 	      || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
7051 	{
7052 	  Bexpression* zero_expr =
7053 	    gogo->backend()->integer_constant_expression(right_btype, zero);
7054 	  Bexpression* compare =
7055 	    gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
7056 					       loc);
7057 	  Expression* crash = Runtime::make_call(Runtime::PANIC_SHIFT,
7058 						 loc, 0);
7059 	  Bexpression* bcrash = crash->get_backend(context);
7060 	  Bfunction* bfn = context->function()->func_value()->get_decl();
7061 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7062 							bcrash, ret, loc);
7063 	}
7064     }
7065 
7066   // Add checks for division by zero and division overflow as needed.
7067   if (is_idiv_op)
7068     {
7069       if (gogo->check_divide_by_zero())
7070 	{
7071 	  // right == 0
7072           Bexpression* zero_expr =
7073               gogo->backend()->integer_constant_expression(right_btype, zero);
7074           Bexpression* check =
7075               gogo->backend()->binary_expression(OPERATOR_EQEQ,
7076                                                  right, zero_expr, loc);
7077 
7078 	  Expression* crash = Runtime::make_call(Runtime::PANIC_DIVIDE,
7079 						 loc, 0);
7080 	  Bexpression* bcrash = crash->get_backend(context);
7081 
7082 	  // right == 0 ? (panicdivide(), 0) : ret
7083           Bfunction* bfn = context->function()->func_value()->get_decl();
7084           ret = gogo->backend()->conditional_expression(bfn, btype,
7085                                                         check, bcrash,
7086 							ret, loc);
7087 	}
7088 
7089       if (gogo->check_divide_overflow())
7090 	{
7091 	  // right == -1
7092 	  // FIXME: It would be nice to say that this test is expected
7093 	  // to return false.
7094 
7095           Bexpression* neg_one_expr =
7096               gogo->backend()->integer_constant_expression(right_btype, neg_one);
7097           Bexpression* check =
7098               gogo->backend()->binary_expression(OPERATOR_EQEQ,
7099                                                  right, neg_one_expr, loc);
7100 
7101           Bexpression* zero_expr =
7102               gogo->backend()->integer_constant_expression(btype, zero);
7103           Bexpression* one_expr =
7104               gogo->backend()->integer_constant_expression(btype, one);
7105           Bfunction* bfn = context->function()->func_value()->get_decl();
7106 
7107 	  if (type->integer_type()->is_unsigned())
7108 	    {
7109 	      // An unsigned -1 is the largest possible number, so
7110 	      // dividing is always 1 or 0.
7111 
7112               Bexpression* cmp =
7113                   gogo->backend()->binary_expression(OPERATOR_EQEQ,
7114                                                      left, right, loc);
7115 	      if (this->op_ == OPERATOR_DIV)
7116                 overflow =
7117                     gogo->backend()->conditional_expression(bfn, btype, cmp,
7118                                                             one_expr, zero_expr,
7119                                                             loc);
7120 	      else
7121                 overflow =
7122                     gogo->backend()->conditional_expression(bfn, btype, cmp,
7123                                                             zero_expr, left,
7124                                                             loc);
7125 	    }
7126 	  else
7127 	    {
7128 	      // Computing left / -1 is the same as computing - left,
7129 	      // which does not overflow since Go sets -fwrapv.
7130 	      if (this->op_ == OPERATOR_DIV)
7131                 {
7132                   Expression* negate_expr =
7133                       Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
7134                   overflow = negate_expr->get_backend(context);
7135                 }
7136 	      else
7137                 overflow = zero_expr;
7138 	    }
7139           overflow = gogo->backend()->convert_expression(btype, overflow, loc);
7140 
7141 	  // right == -1 ? - left : ret
7142           ret = gogo->backend()->conditional_expression(bfn, btype,
7143                                                         check, overflow,
7144                                                         ret, loc);
7145 	}
7146     }
7147 
7148   mpz_clear(zero);
7149   mpz_clear(one);
7150   mpz_clear(neg_one);
7151   return ret;
7152 }
7153 
7154 // Export a binary expression.
7155 
7156 void
do_export(Export_function_body * efb) const7157 Binary_expression::do_export(Export_function_body* efb) const
7158 {
7159   efb->write_c_string("(");
7160   this->left_->export_expression(efb);
7161   switch (this->op_)
7162     {
7163     case OPERATOR_OROR:
7164       efb->write_c_string(" || ");
7165       break;
7166     case OPERATOR_ANDAND:
7167       efb->write_c_string(" && ");
7168       break;
7169     case OPERATOR_EQEQ:
7170       efb->write_c_string(" == ");
7171       break;
7172     case OPERATOR_NOTEQ:
7173       efb->write_c_string(" != ");
7174       break;
7175     case OPERATOR_LT:
7176       efb->write_c_string(" < ");
7177       break;
7178     case OPERATOR_LE:
7179       efb->write_c_string(" <= ");
7180       break;
7181     case OPERATOR_GT:
7182       efb->write_c_string(" > ");
7183       break;
7184     case OPERATOR_GE:
7185       efb->write_c_string(" >= ");
7186       break;
7187     case OPERATOR_PLUS:
7188       efb->write_c_string(" + ");
7189       break;
7190     case OPERATOR_MINUS:
7191       efb->write_c_string(" - ");
7192       break;
7193     case OPERATOR_OR:
7194       efb->write_c_string(" | ");
7195       break;
7196     case OPERATOR_XOR:
7197       efb->write_c_string(" ^ ");
7198       break;
7199     case OPERATOR_MULT:
7200       efb->write_c_string(" * ");
7201       break;
7202     case OPERATOR_DIV:
7203       efb->write_c_string(" / ");
7204       break;
7205     case OPERATOR_MOD:
7206       efb->write_c_string(" % ");
7207       break;
7208     case OPERATOR_LSHIFT:
7209       efb->write_c_string(" << ");
7210       break;
7211     case OPERATOR_RSHIFT:
7212       efb->write_c_string(" >> ");
7213       break;
7214     case OPERATOR_AND:
7215       efb->write_c_string(" & ");
7216       break;
7217     case OPERATOR_BITCLEAR:
7218       efb->write_c_string(" &^ ");
7219       break;
7220     default:
7221       go_unreachable();
7222     }
7223   this->right_->export_expression(efb);
7224   efb->write_c_string(")");
7225 }
7226 
7227 // Import a binary expression.
7228 
7229 Expression*
do_import(Import_expression * imp,Location loc)7230 Binary_expression::do_import(Import_expression* imp, Location loc)
7231 {
7232   imp->require_c_string("(");
7233 
7234   Expression* left = Expression::import_expression(imp, loc);
7235 
7236   Operator op;
7237   if (imp->match_c_string(" || "))
7238     {
7239       op = OPERATOR_OROR;
7240       imp->advance(4);
7241     }
7242   else if (imp->match_c_string(" && "))
7243     {
7244       op = OPERATOR_ANDAND;
7245       imp->advance(4);
7246     }
7247   else if (imp->match_c_string(" == "))
7248     {
7249       op = OPERATOR_EQEQ;
7250       imp->advance(4);
7251     }
7252   else if (imp->match_c_string(" != "))
7253     {
7254       op = OPERATOR_NOTEQ;
7255       imp->advance(4);
7256     }
7257   else if (imp->match_c_string(" < "))
7258     {
7259       op = OPERATOR_LT;
7260       imp->advance(3);
7261     }
7262   else if (imp->match_c_string(" <= "))
7263     {
7264       op = OPERATOR_LE;
7265       imp->advance(4);
7266     }
7267   else if (imp->match_c_string(" > "))
7268     {
7269       op = OPERATOR_GT;
7270       imp->advance(3);
7271     }
7272   else if (imp->match_c_string(" >= "))
7273     {
7274       op = OPERATOR_GE;
7275       imp->advance(4);
7276     }
7277   else if (imp->match_c_string(" + "))
7278     {
7279       op = OPERATOR_PLUS;
7280       imp->advance(3);
7281     }
7282   else if (imp->match_c_string(" - "))
7283     {
7284       op = OPERATOR_MINUS;
7285       imp->advance(3);
7286     }
7287   else if (imp->match_c_string(" | "))
7288     {
7289       op = OPERATOR_OR;
7290       imp->advance(3);
7291     }
7292   else if (imp->match_c_string(" ^ "))
7293     {
7294       op = OPERATOR_XOR;
7295       imp->advance(3);
7296     }
7297   else if (imp->match_c_string(" * "))
7298     {
7299       op = OPERATOR_MULT;
7300       imp->advance(3);
7301     }
7302   else if (imp->match_c_string(" / "))
7303     {
7304       op = OPERATOR_DIV;
7305       imp->advance(3);
7306     }
7307   else if (imp->match_c_string(" % "))
7308     {
7309       op = OPERATOR_MOD;
7310       imp->advance(3);
7311     }
7312   else if (imp->match_c_string(" << "))
7313     {
7314       op = OPERATOR_LSHIFT;
7315       imp->advance(4);
7316     }
7317   else if (imp->match_c_string(" >> "))
7318     {
7319       op = OPERATOR_RSHIFT;
7320       imp->advance(4);
7321     }
7322   else if (imp->match_c_string(" & "))
7323     {
7324       op = OPERATOR_AND;
7325       imp->advance(3);
7326     }
7327   else if (imp->match_c_string(" &^ "))
7328     {
7329       op = OPERATOR_BITCLEAR;
7330       imp->advance(4);
7331     }
7332   else if (imp->match_c_string(")"))
7333     {
7334       // Not a binary operator after all.
7335       imp->advance(1);
7336       return left;
7337     }
7338   else
7339     {
7340       go_error_at(imp->location(), "unrecognized binary operator");
7341       return Expression::make_error(loc);
7342     }
7343 
7344   Expression* right = Expression::import_expression(imp, loc);
7345 
7346   imp->require_c_string(")");
7347 
7348   return Expression::make_binary(op, left, right, loc);
7349 }
7350 
7351 // Dump ast representation of a binary expression.
7352 
7353 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7354 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
7355 {
7356   ast_dump_context->ostream() << "(";
7357   ast_dump_context->dump_expression(this->left_);
7358   ast_dump_context->ostream() << " ";
7359   ast_dump_context->dump_operator(this->op_);
7360   ast_dump_context->ostream() << " ";
7361   ast_dump_context->dump_expression(this->right_);
7362   ast_dump_context->ostream() << ") ";
7363 }
7364 
7365 // Make a binary expression.
7366 
7367 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)7368 Expression::make_binary(Operator op, Expression* left, Expression* right,
7369 			Location location)
7370 {
7371   return new Binary_expression(op, left, right, location);
7372 }
7373 
7374 // Implement a comparison.
7375 
7376 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)7377 Expression::comparison(Translate_context* context, Type* result_type,
7378 		       Operator op, Expression* left, Expression* right,
7379 		       Location location)
7380 {
7381   Type* left_type = left->type();
7382   Type* right_type = right->type();
7383 
7384   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
7385 
7386   if (left_type->is_string_type() && right_type->is_string_type())
7387     {
7388       go_assert(left->is_variable() || left->is_constant());
7389       go_assert(right->is_variable() || right->is_constant());
7390 
7391       if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
7392 	{
7393           // (l.len == r.len
7394           //  ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
7395           //  : false)
7396           Expression* llen = Expression::make_string_info(left,
7397                                                           STRING_INFO_LENGTH,
7398                                                           location);
7399           Expression* rlen = Expression::make_string_info(right,
7400                                                           STRING_INFO_LENGTH,
7401                                                           location);
7402           Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
7403                                                       location);
7404           Expression* lptr = Expression::make_string_info(left->copy(),
7405                                                           STRING_INFO_DATA,
7406                                                           location);
7407           Expression* rptr = Expression::make_string_info(right->copy(),
7408                                                           STRING_INFO_DATA,
7409                                                           location);
7410           Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
7411                                                       location);
7412           Expression* btrue = Expression::make_boolean(true, location);
7413           Expression* call = Runtime::make_call(Runtime::MEMCMP, location, 3,
7414                                                 lptr->copy(), rptr->copy(),
7415                                                 rlen->copy());
7416           Type* int32_type = Type::lookup_integer_type("int32");
7417           Expression* zero = Expression::make_integer_ul(0, int32_type, location);
7418           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
7419                                                     location);
7420           Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
7421                                                           location);
7422           Expression* bfalse = Expression::make_boolean(false, location);
7423           left = Expression::make_conditional(leneq, cond, bfalse, location);
7424 	  right = Expression::make_boolean(true, location);
7425 	}
7426       else
7427 	{
7428 	  left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
7429 				    left, right);
7430 	  right = zexpr;
7431 	}
7432     }
7433   else if ((left_type->interface_type() != NULL
7434 	    && right_type->interface_type() == NULL
7435 	    && !right_type->is_nil_type())
7436 	   || (left_type->interface_type() == NULL
7437 	       && !left_type->is_nil_type()
7438 	       && right_type->interface_type() != NULL))
7439     {
7440       // Comparing an interface value to a non-interface value.
7441       if (left_type->interface_type() == NULL)
7442 	{
7443 	  std::swap(left_type, right_type);
7444 	  std::swap(left, right);
7445 	}
7446 
7447       // The right operand is not an interface.  We need to take its
7448       // address if it is not a direct interface type.
7449       Expression* pointer_arg = NULL;
7450       if (right_type->is_direct_iface_type())
7451         pointer_arg = Expression::unpack_direct_iface(right, location);
7452       else
7453 	{
7454           go_assert(right->is_addressable());
7455           pointer_arg = Expression::make_unary(OPERATOR_AND, right,
7456                                                location);
7457 	}
7458 
7459       Expression* descriptor =
7460           Expression::make_type_descriptor(right_type, location);
7461       left =
7462           Runtime::make_call((left_type->interface_type()->is_empty()
7463                               ? Runtime::EFACEVALEQ
7464                               : Runtime::IFACEVALEQ),
7465                              location, 3, left, descriptor,
7466                              pointer_arg);
7467       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7468       right = Expression::make_boolean(true, location);
7469     }
7470   else if (left_type->interface_type() != NULL
7471 	   && right_type->interface_type() != NULL)
7472     {
7473       Runtime::Function compare_function;
7474       if (left_type->interface_type()->is_empty()
7475 	  && right_type->interface_type()->is_empty())
7476 	compare_function = Runtime::EFACEEQ;
7477       else if (!left_type->interface_type()->is_empty()
7478 	       && !right_type->interface_type()->is_empty())
7479 	compare_function = Runtime::IFACEEQ;
7480       else
7481 	{
7482 	  if (left_type->interface_type()->is_empty())
7483 	    {
7484 	      std::swap(left_type, right_type);
7485 	      std::swap(left, right);
7486 	    }
7487 	  go_assert(!left_type->interface_type()->is_empty());
7488 	  go_assert(right_type->interface_type()->is_empty());
7489 	  compare_function = Runtime::IFACEEFACEEQ;
7490 	}
7491 
7492       left = Runtime::make_call(compare_function, location, 2, left, right);
7493       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7494       right = Expression::make_boolean(true, location);
7495     }
7496 
7497   if (left_type->is_nil_type()
7498       && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7499     {
7500       std::swap(left_type, right_type);
7501       std::swap(left, right);
7502     }
7503 
7504   if (right_type->is_nil_type())
7505     {
7506       right = Expression::make_nil(location);
7507       if (left_type->array_type() != NULL
7508 	  && left_type->array_type()->length() == NULL)
7509 	{
7510 	  Array_type* at = left_type->array_type();
7511           bool is_lvalue = false;
7512           left = at->get_value_pointer(context->gogo(), left, is_lvalue);
7513 	}
7514       else if (left_type->interface_type() != NULL)
7515 	{
7516 	  // An interface is nil if the first field is nil.
7517           left = Expression::make_field_reference(left, 0, location);
7518 	}
7519     }
7520 
7521   Bexpression* left_bexpr = left->get_backend(context);
7522   Bexpression* right_bexpr = right->get_backend(context);
7523 
7524   Gogo* gogo = context->gogo();
7525   Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
7526                                                         right_bexpr, location);
7527   if (result_type != NULL)
7528     ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
7529                                               ret, location);
7530   return ret;
7531 }
7532 
7533 // Class String_concat_expression.
7534 
7535 bool
do_is_constant() const7536 String_concat_expression::do_is_constant() const
7537 {
7538   for (Expression_list::const_iterator pe = this->exprs_->begin();
7539        pe != this->exprs_->end();
7540        ++pe)
7541     {
7542       if (!(*pe)->is_constant())
7543 	return false;
7544     }
7545   return true;
7546 }
7547 
7548 bool
do_is_zero_value() const7549 String_concat_expression::do_is_zero_value() const
7550 {
7551   for (Expression_list::const_iterator pe = this->exprs_->begin();
7552        pe != this->exprs_->end();
7553        ++pe)
7554     {
7555       if (!(*pe)->is_zero_value())
7556 	return false;
7557     }
7558   return true;
7559 }
7560 
7561 bool
do_is_static_initializer() const7562 String_concat_expression::do_is_static_initializer() const
7563 {
7564   for (Expression_list::const_iterator pe = this->exprs_->begin();
7565        pe != this->exprs_->end();
7566        ++pe)
7567     {
7568       if (!(*pe)->is_static_initializer())
7569 	return false;
7570     }
7571   return true;
7572 }
7573 
7574 Type*
do_type()7575 String_concat_expression::do_type()
7576 {
7577   Type* t = this->exprs_->front()->type();
7578   Expression_list::iterator pe = this->exprs_->begin();
7579   ++pe;
7580   for (; pe != this->exprs_->end(); ++pe)
7581     {
7582       Type* t1;
7583       if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
7584 					     (*pe)->type(),
7585 					     &t1))
7586 	return Type::make_error_type();
7587       t = t1;
7588     }
7589   return t;
7590 }
7591 
7592 void
do_determine_type(const Type_context * context)7593 String_concat_expression::do_determine_type(const Type_context* context)
7594 {
7595   Type_context subcontext(*context);
7596   for (Expression_list::iterator pe = this->exprs_->begin();
7597        pe != this->exprs_->end();
7598        ++pe)
7599     {
7600       Type* t = (*pe)->type();
7601       if (!t->is_abstract())
7602 	{
7603 	  subcontext.type = t;
7604 	  break;
7605 	}
7606     }
7607   if (subcontext.type == NULL)
7608     subcontext.type = this->exprs_->front()->type();
7609   for (Expression_list::iterator pe = this->exprs_->begin();
7610        pe != this->exprs_->end();
7611        ++pe)
7612     (*pe)->determine_type(&subcontext);
7613 }
7614 
7615 void
do_check_types(Gogo *)7616 String_concat_expression::do_check_types(Gogo*)
7617 {
7618   if (this->is_error_expression())
7619     return;
7620   Type* t = this->exprs_->front()->type();
7621   if (t->is_error())
7622     {
7623       this->set_is_error();
7624       return;
7625     }
7626   Expression_list::iterator pe = this->exprs_->begin();
7627   ++pe;
7628   for (; pe != this->exprs_->end(); ++pe)
7629     {
7630       Type* t1 = (*pe)->type();
7631       if (!Type::are_compatible_for_binop(t, t1))
7632 	{
7633 	  this->report_error("incompatible types in binary expression");
7634 	  return;
7635 	}
7636       if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
7637 						  this->location()))
7638 	{
7639 	  this->set_is_error();
7640 	  return;
7641 	}
7642     }
7643 }
7644 
7645 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)7646 String_concat_expression::do_flatten(Gogo*, Named_object*,
7647 				     Statement_inserter* inserter)
7648 {
7649   if (this->is_error_expression())
7650     return this;
7651   Location loc = this->location();
7652   Type* type = this->type();
7653 
7654   // Mark string([]byte) operands to reuse the backing store.
7655   // runtime.concatstrings does not keep the reference.
7656   //
7657   // Note: in the gc runtime, if all but one inputs are empty,
7658   // concatstrings returns the only nonempty input without copy.
7659   // So it is not safe to reuse the backing store if it is a
7660   // string([]byte) conversion. So the gc compiler does the
7661   // no-copy optimization only when there is at least one
7662   // constant nonempty input. Currently the gccgo runtime
7663   // doesn't do this, so we don't do the check.
7664   for (Expression_list::iterator p = this->exprs_->begin();
7665        p != this->exprs_->end();
7666        ++p)
7667     {
7668       Type_conversion_expression* tce = (*p)->conversion_expression();
7669       if (tce != NULL)
7670         tce->set_no_copy(true);
7671     }
7672 
7673   Expression* buf = NULL;
7674   Node* n = Node::make_node(this);
7675   if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7676     {
7677       size_t size = 0;
7678       for (Expression_list::iterator p = this->exprs_->begin();
7679            p != this->exprs_->end();
7680            ++p)
7681         {
7682           std::string s;
7683           if ((*p)->string_constant_value(&s))
7684             size += s.length();
7685         }
7686       // Make a buffer on stack if the result does not escape.
7687       // But don't do this if we know it won't fit.
7688       if (size < (size_t)tmp_string_buf_size)
7689         {
7690           Type* byte_type = Type::lookup_integer_type("uint8");
7691           Expression* buflen =
7692             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7693           Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7694           Type* array_type = Type::make_array_type(byte_type, buflen);
7695           buf = Expression::make_allocation(array_type, loc);
7696           buf->allocation_expression()->set_allocate_on_stack();
7697           buf->allocation_expression()->set_no_zero();
7698         }
7699     }
7700   if (buf == NULL)
7701     buf = Expression::make_nil(loc);
7702   go_assert(this->exprs_->size() > 1);
7703   Expression* len =
7704     Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
7705   Array_type* array_type = Type::make_array_type(type, len);
7706   array_type->set_is_array_incomparable();
7707   Expression* array =
7708     Expression::make_array_composite_literal(array_type, this->exprs_,
7709                                              loc);
7710   Temporary_statement* ts =
7711     Statement::make_temporary(array_type, array, loc);
7712   inserter->insert(ts);
7713   Expression* ref = Expression::make_temporary_reference(ts, loc);
7714   ref = Expression::make_unary(OPERATOR_AND, ref, loc);
7715 	Expression* call =
7716     Runtime::make_call(Runtime::CONCATSTRINGS, loc, 3, buf,
7717                        ref, len->copy());
7718   return Expression::make_cast(type, call, loc);
7719 }
7720 
7721 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7722 String_concat_expression::do_dump_expression(
7723     Ast_dump_context* ast_dump_context) const
7724 {
7725   ast_dump_context->ostream() << "concat(";
7726   ast_dump_context->dump_expression_list(this->exprs_, false);
7727   ast_dump_context->ostream() << ")";
7728 }
7729 
7730 Expression*
make_string_concat(Expression_list * exprs)7731 Expression::make_string_concat(Expression_list* exprs)
7732 {
7733   return new String_concat_expression(exprs);
7734 }
7735 
7736 // Class Bound_method_expression.
7737 
7738 // Traversal.
7739 
7740 int
do_traverse(Traverse * traverse)7741 Bound_method_expression::do_traverse(Traverse* traverse)
7742 {
7743   return Expression::traverse(&this->expr_, traverse);
7744 }
7745 
7746 // Return the type of a bound method expression.  The type of this
7747 // object is simply the type of the method with no receiver.
7748 
7749 Type*
do_type()7750 Bound_method_expression::do_type()
7751 {
7752   Named_object* fn = this->method_->named_object();
7753   Function_type* fntype;
7754   if (fn->is_function())
7755     fntype = fn->func_value()->type();
7756   else if (fn->is_function_declaration())
7757     fntype = fn->func_declaration_value()->type();
7758   else
7759     return Type::make_error_type();
7760   return fntype->copy_without_receiver();
7761 }
7762 
7763 // Determine the types of a method expression.
7764 
7765 void
do_determine_type(const Type_context *)7766 Bound_method_expression::do_determine_type(const Type_context*)
7767 {
7768   Named_object* fn = this->method_->named_object();
7769   Function_type* fntype;
7770   if (fn->is_function())
7771     fntype = fn->func_value()->type();
7772   else if (fn->is_function_declaration())
7773     fntype = fn->func_declaration_value()->type();
7774   else
7775     fntype = NULL;
7776   if (fntype == NULL || !fntype->is_method())
7777     this->expr_->determine_type_no_context();
7778   else
7779     {
7780       Type_context subcontext(fntype->receiver()->type(), false);
7781       this->expr_->determine_type(&subcontext);
7782     }
7783 }
7784 
7785 // Check the types of a method expression.
7786 
7787 void
do_check_types(Gogo *)7788 Bound_method_expression::do_check_types(Gogo*)
7789 {
7790   Named_object* fn = this->method_->named_object();
7791   if (!fn->is_function() && !fn->is_function_declaration())
7792     {
7793       this->report_error(_("object is not a method"));
7794       return;
7795     }
7796 
7797   Function_type* fntype;
7798   if (fn->is_function())
7799     fntype = fn->func_value()->type();
7800   else if (fn->is_function_declaration())
7801     fntype = fn->func_declaration_value()->type();
7802   else
7803     go_unreachable();
7804   Type* rtype = fntype->receiver()->type()->deref();
7805   Type* etype = (this->expr_type_ != NULL
7806 		 ? this->expr_type_
7807 		 : this->expr_->type());
7808   etype = etype->deref();
7809   if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
7810     this->report_error(_("method type does not match object type"));
7811 }
7812 
7813 // If a bound method expression is not simply called, then it is
7814 // represented as a closure.  The closure will hold a single variable,
7815 // the receiver to pass to the method.  The function will be a simple
7816 // thunk that pulls that value from the closure and calls the method
7817 // with the remaining arguments.
7818 //
7819 // Because method values are not common, we don't build all thunks for
7820 // every methods, but instead only build them as we need them.  In
7821 // particular, we even build them on demand for methods defined in
7822 // other packages.
7823 
7824 Bound_method_expression::Method_value_thunks
7825   Bound_method_expression::method_value_thunks;
7826 
7827 // Find or create the thunk for METHOD.
7828 
7829 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)7830 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
7831 				      Named_object* fn)
7832 {
7833   std::pair<Named_object*, Named_object*> val(fn, NULL);
7834   std::pair<Method_value_thunks::iterator, bool> ins =
7835     Bound_method_expression::method_value_thunks.insert(val);
7836   if (!ins.second)
7837     {
7838       // We have seen this method before.
7839       go_assert(ins.first->second != NULL);
7840       return ins.first->second;
7841     }
7842 
7843   Location loc = fn->location();
7844 
7845   Function_type* orig_fntype;
7846   if (fn->is_function())
7847     orig_fntype = fn->func_value()->type();
7848   else if (fn->is_function_declaration())
7849     orig_fntype = fn->func_declaration_value()->type();
7850   else
7851     orig_fntype = NULL;
7852 
7853   if (orig_fntype == NULL || !orig_fntype->is_method())
7854     {
7855       ins.first->second =
7856 	Named_object::make_erroneous_name(gogo->thunk_name());
7857       return ins.first->second;
7858     }
7859 
7860   Struct_field_list* sfl = new Struct_field_list();
7861   // The type here is wrong--it should be the C function type.  But it
7862   // doesn't really matter.
7863   Type* vt = Type::make_pointer_type(Type::make_void_type());
7864   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
7865   sfl->push_back(Struct_field(Typed_identifier("val",
7866 					       orig_fntype->receiver()->type(),
7867 					       loc)));
7868   Struct_type* st = Type::make_struct_type(sfl, loc);
7869   st->set_is_struct_incomparable();
7870   Type* closure_type = Type::make_pointer_type(st);
7871 
7872   Function_type* new_fntype = orig_fntype->copy_with_names();
7873 
7874   std::string thunk_name = gogo->thunk_name();
7875   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
7876 					      false, loc);
7877 
7878   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
7879   cvar->set_is_used();
7880   cvar->set_is_closure();
7881   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
7882 						 NULL, cvar);
7883   new_no->func_value()->set_closure_var(cp);
7884 
7885   gogo->start_block(loc);
7886 
7887   // Field 0 of the closure is the function code pointer, field 1 is
7888   // the value on which to invoke the method.
7889   Expression* arg = Expression::make_var_reference(cp, loc);
7890   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
7891   arg = Expression::make_field_reference(arg, 1, loc);
7892 
7893   Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
7894 
7895   const Typed_identifier_list* orig_params = orig_fntype->parameters();
7896   Expression_list* args;
7897   if (orig_params == NULL || orig_params->empty())
7898     args = NULL;
7899   else
7900     {
7901       const Typed_identifier_list* new_params = new_fntype->parameters();
7902       args = new Expression_list();
7903       for (Typed_identifier_list::const_iterator p = new_params->begin();
7904 	   p != new_params->end();
7905 	   ++p)
7906 	{
7907 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
7908 	  go_assert(p_no != NULL
7909 		    && p_no->is_variable()
7910 		    && p_no->var_value()->is_parameter());
7911 	  args->push_back(Expression::make_var_reference(p_no, loc));
7912 	}
7913     }
7914 
7915   Call_expression* call = Expression::make_call(bme, args,
7916 						orig_fntype->is_varargs(),
7917 						loc);
7918   call->set_varargs_are_lowered();
7919 
7920   Statement* s = Statement::make_return_from_call(call, loc);
7921   gogo->add_statement(s);
7922   Block* b = gogo->finish_block(loc);
7923   gogo->add_block(b, loc);
7924   gogo->lower_block(new_no, b);
7925   gogo->flatten_block(new_no, b);
7926   gogo->finish_function(loc);
7927 
7928   ins.first->second = new_no;
7929   return new_no;
7930 }
7931 
7932 // Return an expression to check *REF for nil while dereferencing
7933 // according to FIELD_INDEXES.  Update *REF to build up the field
7934 // reference.  This is a static function so that we don't have to
7935 // worry about declaring Field_indexes in expressions.h.
7936 
7937 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)7938 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
7939 	      Expression** ref)
7940 {
7941   if (field_indexes == NULL)
7942     return Expression::make_boolean(false, loc);
7943   Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
7944   Struct_type* stype = (*ref)->type()->deref()->struct_type();
7945   go_assert(stype != NULL
7946 	    && field_indexes->field_index < stype->field_count());
7947   if ((*ref)->type()->struct_type() == NULL)
7948     {
7949       go_assert((*ref)->type()->points_to() != NULL);
7950       Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
7951 					      Expression::make_nil(loc),
7952 					      loc);
7953       cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
7954       *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
7955                                           loc);
7956       go_assert((*ref)->type()->struct_type() == stype);
7957     }
7958   *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
7959 					  loc);
7960   return cond;
7961 }
7962 
7963 // Flatten a method value into a struct with nil checks.  We can't do
7964 // this in the lowering phase, because if the method value is called
7965 // directly we don't need a thunk.  That case will have been handled
7966 // by Call_expression::do_lower, so if we get here then we do need a
7967 // thunk.
7968 
7969 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)7970 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
7971 				    Statement_inserter* inserter)
7972 {
7973   Location loc = this->location();
7974 
7975   Named_object* thunk = Bound_method_expression::create_thunk(gogo,
7976 							      this->method_,
7977 							      this->function_);
7978   if (thunk->is_erroneous())
7979     {
7980       go_assert(saw_errors());
7981       return Expression::make_error(loc);
7982     }
7983 
7984   // Force the expression into a variable.  This is only necessary if
7985   // we are going to do nil checks below, but it's easy enough to
7986   // always do it.
7987   Expression* expr = this->expr_;
7988   if (!expr->is_variable())
7989     {
7990       Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
7991       inserter->insert(etemp);
7992       expr = Expression::make_temporary_reference(etemp, loc);
7993     }
7994 
7995   // If the method expects a value, and we have a pointer, we need to
7996   // dereference the pointer.
7997 
7998   Named_object* fn = this->method_->named_object();
7999   Function_type *fntype;
8000   if (fn->is_function())
8001     fntype = fn->func_value()->type();
8002   else if (fn->is_function_declaration())
8003     fntype = fn->func_declaration_value()->type();
8004   else
8005     go_unreachable();
8006 
8007   Expression* val = expr;
8008   if (fntype->receiver()->type()->points_to() == NULL
8009       && val->type()->points_to() != NULL)
8010     val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
8011 
8012   // Note that we are ignoring this->expr_type_ here.  The thunk will
8013   // expect a closure whose second field has type this->expr_type_ (if
8014   // that is not NULL).  We are going to pass it a closure whose
8015   // second field has type this->expr_->type().  Since
8016   // this->expr_type_ is only not-NULL for pointer types, we can get
8017   // away with this.
8018 
8019   Struct_field_list* fields = new Struct_field_list();
8020   fields->push_back(Struct_field(Typed_identifier("fn",
8021 						  thunk->func_value()->type(),
8022 						  loc)));
8023   fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
8024   Struct_type* st = Type::make_struct_type(fields, loc);
8025   st->set_is_struct_incomparable();
8026 
8027   Expression_list* vals = new Expression_list();
8028   vals->push_back(Expression::make_func_code_reference(thunk, loc));
8029   vals->push_back(val);
8030 
8031   Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
8032   ret = Expression::make_heap_expression(ret, loc);
8033 
8034   Node* node = Node::make_node(this);
8035   if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8036     ret->heap_expression()->set_allocate_on_stack();
8037   else if (gogo->compiling_runtime()
8038 	   && gogo->package_name() == "runtime"
8039 	   && !saw_errors())
8040     go_error_at(loc, "%s escapes to heap, not allowed in runtime",
8041                 node->ast_format(gogo).c_str());
8042 
8043   // If necessary, check whether the expression or any embedded
8044   // pointers are nil.
8045 
8046   Expression* nil_check = NULL;
8047   if (this->method_->field_indexes() != NULL)
8048     {
8049       Expression* ref = expr;
8050       nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
8051       expr = ref;
8052     }
8053 
8054   if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
8055     {
8056       Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
8057 					      Expression::make_nil(loc),
8058 					      loc);
8059       if (nil_check == NULL)
8060 	nil_check = n;
8061       else
8062 	nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
8063     }
8064 
8065   if (nil_check != NULL)
8066     {
8067       Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
8068       // Fix the type of the conditional expression by pretending to
8069       // evaluate to RET either way through the conditional.
8070       crash = Expression::make_compound(crash, ret, loc);
8071       ret = Expression::make_conditional(nil_check, crash, ret, loc);
8072     }
8073 
8074   // RET is a pointer to a struct, but we want a function type.
8075   ret = Expression::make_unsafe_cast(this->type(), ret, loc);
8076 
8077   return ret;
8078 }
8079 
8080 // Dump ast representation of a bound method expression.
8081 
8082 void
do_dump_expression(Ast_dump_context * ast_dump_context) const8083 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
8084     const
8085 {
8086   if (this->expr_type_ != NULL)
8087     ast_dump_context->ostream() << "(";
8088   ast_dump_context->dump_expression(this->expr_);
8089   if (this->expr_type_ != NULL)
8090     {
8091       ast_dump_context->ostream() << ":";
8092       ast_dump_context->dump_type(this->expr_type_);
8093       ast_dump_context->ostream() << ")";
8094     }
8095 
8096   ast_dump_context->ostream() << "." << this->function_->name();
8097 }
8098 
8099 // Make a method expression.
8100 
8101 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)8102 Expression::make_bound_method(Expression* expr, const Method* method,
8103 			      Named_object* function, Location location)
8104 {
8105   return new Bound_method_expression(expr, method, function, location);
8106 }
8107 
8108 // Class Builtin_call_expression.  This is used for a call to a
8109 // builtin function.
8110 
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)8111 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
8112 						 Expression* fn,
8113 						 Expression_list* args,
8114 						 bool is_varargs,
8115 						 Location location)
8116   : Call_expression(fn, args, is_varargs, location),
8117     gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
8118     recover_arg_is_set_(false)
8119 {
8120   Func_expression* fnexp = this->fn()->func_expression();
8121   if (fnexp == NULL)
8122     {
8123       this->code_ = BUILTIN_INVALID;
8124       return;
8125     }
8126   const std::string& name(fnexp->named_object()->name());
8127   if (name == "append")
8128     this->code_ = BUILTIN_APPEND;
8129   else if (name == "cap")
8130     this->code_ = BUILTIN_CAP;
8131   else if (name == "close")
8132     this->code_ = BUILTIN_CLOSE;
8133   else if (name == "complex")
8134     this->code_ = BUILTIN_COMPLEX;
8135   else if (name == "copy")
8136     this->code_ = BUILTIN_COPY;
8137   else if (name == "delete")
8138     this->code_ = BUILTIN_DELETE;
8139   else if (name == "imag")
8140     this->code_ = BUILTIN_IMAG;
8141   else if (name == "len")
8142     this->code_ = BUILTIN_LEN;
8143   else if (name == "make")
8144     this->code_ = BUILTIN_MAKE;
8145   else if (name == "new")
8146     this->code_ = BUILTIN_NEW;
8147   else if (name == "panic")
8148     this->code_ = BUILTIN_PANIC;
8149   else if (name == "print")
8150     this->code_ = BUILTIN_PRINT;
8151   else if (name == "println")
8152     this->code_ = BUILTIN_PRINTLN;
8153   else if (name == "real")
8154     this->code_ = BUILTIN_REAL;
8155   else if (name == "recover")
8156     this->code_ = BUILTIN_RECOVER;
8157   else if (name == "Alignof")
8158     this->code_ = BUILTIN_ALIGNOF;
8159   else if (name == "Offsetof")
8160     this->code_ = BUILTIN_OFFSETOF;
8161   else if (name == "Sizeof")
8162     this->code_ = BUILTIN_SIZEOF;
8163   else
8164     go_unreachable();
8165 }
8166 
8167 // Return whether this is a call to recover.  This is a virtual
8168 // function called from the parent class.
8169 
8170 bool
do_is_recover_call() const8171 Builtin_call_expression::do_is_recover_call() const
8172 {
8173   if (this->classification() == EXPRESSION_ERROR)
8174     return false;
8175   return this->code_ == BUILTIN_RECOVER;
8176 }
8177 
8178 // Set the argument for a call to recover.
8179 
8180 void
do_set_recover_arg(Expression * arg)8181 Builtin_call_expression::do_set_recover_arg(Expression* arg)
8182 {
8183   const Expression_list* args = this->args();
8184   go_assert(args == NULL || args->empty());
8185   Expression_list* new_args = new Expression_list();
8186   new_args->push_back(arg);
8187   this->set_args(new_args);
8188   this->recover_arg_is_set_ = true;
8189 }
8190 
8191 // Lower a builtin call expression.  This turns new and make into
8192 // specific expressions.  We also convert to a constant if we can.
8193 
8194 Expression*
do_lower(Gogo *,Named_object * function,Statement_inserter * inserter,int)8195 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
8196 				  Statement_inserter* inserter, int)
8197 {
8198   if (this->is_error_expression())
8199     return this;
8200 
8201   Location loc = this->location();
8202 
8203   if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
8204     {
8205       this->report_error(_("invalid use of %<...%> with builtin function"));
8206       return Expression::make_error(loc);
8207     }
8208 
8209   if (this->code_ == BUILTIN_OFFSETOF)
8210     {
8211       Expression* arg = this->one_arg();
8212 
8213       if (arg->bound_method_expression() != NULL
8214 	  || arg->interface_field_reference_expression() != NULL)
8215 	{
8216 	  this->report_error(_("invalid use of method value as argument "
8217 			       "of Offsetof"));
8218 	  return this;
8219 	}
8220 
8221       Field_reference_expression* farg = arg->field_reference_expression();
8222       while (farg != NULL)
8223 	{
8224 	  if (!farg->implicit())
8225 	    break;
8226 	  // When the selector refers to an embedded field,
8227 	  // it must not be reached through pointer indirections.
8228 	  if (farg->expr()->deref() != farg->expr())
8229 	    {
8230 	      this->report_error(_("argument of Offsetof implies "
8231 				   "indirection of an embedded field"));
8232 	      return this;
8233 	    }
8234 	  // Go up until we reach the original base.
8235 	  farg = farg->expr()->field_reference_expression();
8236 	}
8237     }
8238 
8239   if (this->is_constant())
8240     {
8241       Numeric_constant nc;
8242       if (this->numeric_constant_value(&nc))
8243 	return nc.expression(loc);
8244     }
8245 
8246   switch (this->code_)
8247     {
8248     default:
8249       break;
8250 
8251     case BUILTIN_NEW:
8252       {
8253 	const Expression_list* args = this->args();
8254 	if (args == NULL || args->size() < 1)
8255 	  this->report_error(_("not enough arguments"));
8256 	else if (args->size() > 1)
8257 	  this->report_error(_("too many arguments"));
8258 	else
8259 	  {
8260 	    Expression* arg = args->front();
8261 	    if (!arg->is_type_expression())
8262 	      {
8263 		go_error_at(arg->location(), "expected type");
8264 		this->set_is_error();
8265 	      }
8266 	    else
8267 	      return Expression::make_allocation(arg->type(), loc);
8268 	  }
8269       }
8270       break;
8271 
8272     case BUILTIN_MAKE:
8273       return this->lower_make(inserter);
8274 
8275     case BUILTIN_RECOVER:
8276       if (function != NULL)
8277 	function->func_value()->set_calls_recover();
8278       else
8279 	{
8280 	  // Calling recover outside of a function always returns the
8281 	  // nil empty interface.
8282 	  Type* eface = Type::make_empty_interface_type(loc);
8283 	  return Expression::make_cast(eface, Expression::make_nil(loc), loc);
8284 	}
8285       break;
8286 
8287     case BUILTIN_DELETE:
8288       {
8289         const Expression_list* args = this->args();
8290         if (args == NULL || args->size() < 2)
8291           this->report_error(_("not enough arguments"));
8292         else if (args->size() > 2)
8293           this->report_error(_("too many arguments"));
8294         else if (args->front()->type()->map_type() == NULL)
8295           this->report_error(_("argument 1 must be a map"));
8296         else
8297           {
8298             Type* key_type =
8299               args->front()->type()->map_type()->key_type();
8300             Expression_list::iterator pa = this->args()->begin();
8301             pa++;
8302             Type* arg_type = (*pa)->type();
8303             std::string reason;
8304             if (!Type::are_assignable(key_type, arg_type, &reason))
8305               {
8306                 if (reason.empty())
8307                   go_error_at(loc, "argument 2 has incompatible type");
8308                 else
8309                   go_error_at(loc, "argument 2 has incompatible type (%s)",
8310                               reason.c_str());
8311                 this->set_is_error();
8312               }
8313             else if (!Type::are_identical(key_type, arg_type, 0, NULL))
8314               *pa = Expression::make_cast(key_type, *pa, loc);
8315           }
8316       }
8317       break;
8318 
8319     case BUILTIN_PRINT:
8320     case BUILTIN_PRINTLN:
8321       // Force all the arguments into temporary variables, so that we
8322       // don't try to evaluate something while holding the print lock.
8323       if (this->args() == NULL)
8324 	break;
8325       for (Expression_list::iterator pa = this->args()->begin();
8326 	   pa != this->args()->end();
8327 	   ++pa)
8328 	{
8329 	  if (!(*pa)->is_variable() && !(*pa)->is_constant())
8330 	    {
8331 	      Temporary_statement* temp =
8332 		Statement::make_temporary(NULL, *pa, loc);
8333 	      inserter->insert(temp);
8334 	      *pa = Expression::make_temporary_reference(temp, loc);
8335 	    }
8336 	}
8337       break;
8338     }
8339 
8340   return this;
8341 }
8342 
8343 // Flatten a builtin call expression.  This turns the arguments of some
8344 // builtin calls into temporary expressions.  Also expand copy and append
8345 // to runtime calls.
8346 
8347 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)8348 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
8349                                     Statement_inserter* inserter)
8350 {
8351   if (this->is_error_expression())
8352     {
8353       go_assert(saw_errors());
8354       return this;
8355     }
8356 
8357   Location loc = this->location();
8358 
8359   switch (this->code_)
8360     {
8361     default:
8362       break;
8363 
8364     case BUILTIN_APPEND:
8365       return this->flatten_append(gogo, function, inserter, NULL, NULL);
8366 
8367     case BUILTIN_COPY:
8368       {
8369 	Type* at = this->args()->front()->type();
8370 	for (Expression_list::iterator pa = this->args()->begin();
8371 	     pa != this->args()->end();
8372 	     ++pa)
8373 	  {
8374 	    if ((*pa)->is_nil_expression())
8375 	      {
8376 		Expression* nil = Expression::make_nil(loc);
8377 		Expression* zero = Expression::make_integer_ul(0, NULL, loc);
8378 		*pa = Expression::make_slice_value(at, nil, zero, zero, loc);
8379 	      }
8380 	    if (!(*pa)->is_variable())
8381 	      {
8382 		Temporary_statement* temp =
8383                   Statement::make_temporary(NULL, *pa, loc);
8384 		inserter->insert(temp);
8385 		*pa = Expression::make_temporary_reference(temp, loc);
8386 	      }
8387 	  }
8388 
8389         // Lower to runtime call.
8390         const Expression_list* args = this->args();
8391         go_assert(args != NULL && args->size() == 2);
8392         Expression* arg1 = args->front();
8393         Expression* arg2 = args->back();
8394         go_assert(arg1->is_variable());
8395         go_assert(arg2->is_variable());
8396         bool arg2_is_string = arg2->type()->is_string_type();
8397 
8398         Expression* ret;
8399         Type* et = at->array_type()->element_type();
8400         if (et->has_pointer())
8401           {
8402             Expression* td = Expression::make_type_descriptor(et, loc);
8403             ret = Runtime::make_call(Runtime::TYPEDSLICECOPY, loc,
8404                                      3, td, arg1, arg2);
8405           }
8406         else
8407           {
8408             Type* int_type = Type::lookup_integer_type("int");
8409             Type* uintptr_type = Type::lookup_integer_type("uintptr");
8410 
8411             // l1 = len(arg1)
8412             Named_object* lenfn = gogo->lookup_global("len");
8413             Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8414             Expression_list* len_args = new Expression_list();
8415             len_args->push_back(arg1->copy());
8416             Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
8417             gogo->lower_expression(function, inserter, &len1);
8418             gogo->flatten_expression(function, inserter, &len1);
8419             Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
8420             inserter->insert(l1tmp);
8421 
8422             // l2 = len(arg2)
8423             len_args = new Expression_list();
8424             len_args->push_back(arg2->copy());
8425             Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
8426             gogo->lower_expression(function, inserter, &len2);
8427             gogo->flatten_expression(function, inserter, &len2);
8428             Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
8429             inserter->insert(l2tmp);
8430 
8431             // n = (l1 < l2 ? l1 : l2)
8432             Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
8433             Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
8434             Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
8435             Expression* n = Expression::make_conditional(cond,
8436                                                          l1ref->copy(),
8437                                                          l2ref->copy(),
8438                                                          loc);
8439             Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
8440             inserter->insert(ntmp);
8441 
8442             // sz = n * sizeof(elem_type)
8443             Expression* nref = Expression::make_temporary_reference(ntmp, loc);
8444             nref = Expression::make_cast(uintptr_type, nref, loc);
8445             Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
8446             sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
8447 
8448             // memmove(arg1.ptr, arg2.ptr, sz)
8449             Expression* p1 = Expression::make_slice_info(arg1,
8450                                                          SLICE_INFO_VALUE_POINTER,
8451                                                          loc);
8452             Expression* p2 = (arg2_is_string
8453                               ? Expression::make_string_info(arg2,
8454                                                              STRING_INFO_DATA,
8455                                                              loc)
8456                               : Expression::make_slice_info(arg2,
8457                                                             SLICE_INFO_VALUE_POINTER,
8458                                                             loc));
8459             Expression* call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
8460                                                   p1, p2, sz);
8461 
8462             // n is the return value of copy
8463             nref = Expression::make_temporary_reference(ntmp, loc);
8464             ret = Expression::make_compound(call, nref, loc);
8465           }
8466         return ret;
8467       }
8468       break;
8469 
8470     case BUILTIN_PANIC:
8471       for (Expression_list::iterator pa = this->args()->begin();
8472 	   pa != this->args()->end();
8473 	   ++pa)
8474 	{
8475 	  if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
8476 	    {
8477 	      Temporary_statement* temp =
8478 		Statement::make_temporary(NULL, *pa, loc);
8479 	      inserter->insert(temp);
8480 	      *pa = Expression::make_temporary_reference(temp, loc);
8481 	    }
8482 	}
8483       break;
8484 
8485     case BUILTIN_LEN:
8486     case BUILTIN_CAP:
8487       {
8488 	Expression_list::iterator pa = this->args()->begin();
8489 	if (!(*pa)->is_variable()
8490 	    && ((*pa)->type()->map_type() != NULL
8491 		|| (*pa)->type()->channel_type() != NULL))
8492 	  {
8493 	    Temporary_statement* temp =
8494 	      Statement::make_temporary(NULL, *pa, loc);
8495 	    inserter->insert(temp);
8496 	    *pa = Expression::make_temporary_reference(temp, loc);
8497 	  }
8498       }
8499       break;
8500 
8501     case BUILTIN_DELETE:
8502       {
8503         // Lower to a runtime function call.
8504         const Expression_list* args = this->args();
8505 
8506         // Since this function returns no value it must appear in
8507         // a statement by itself, so we don't have to worry about
8508         // order of evaluation of values around it.  Evaluate the
8509         // map first to get order of evaluation right.
8510         Map_type* mt = args->front()->type()->map_type();
8511         Temporary_statement* map_temp =
8512           Statement::make_temporary(mt, args->front(), loc);
8513         inserter->insert(map_temp);
8514 
8515         Temporary_statement* key_temp =
8516           Statement::make_temporary(mt->key_type(), args->back(), loc);
8517         inserter->insert(key_temp);
8518 
8519         Expression* e1 = Expression::make_type_descriptor(mt, loc);
8520         Expression* e2 = Expression::make_temporary_reference(map_temp,
8521                                                               loc);
8522         Expression* e3 = Expression::make_temporary_reference(key_temp,
8523                                                               loc);
8524 
8525         Runtime::Function code;
8526         switch (mt->algorithm(gogo))
8527           {
8528             case Map_type::MAP_ALG_FAST32:
8529             case Map_type::MAP_ALG_FAST32PTR:
8530               {
8531                 code = Runtime::MAPDELETE_FAST32;
8532                 Type* uint32_type = Type::lookup_integer_type("uint32");
8533                 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
8534                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8535                 e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
8536                                                   loc);
8537                 e3 = Expression::make_dereference(e3,
8538                                                   Expression::NIL_CHECK_NOT_NEEDED,
8539                                                   loc);
8540                 break;
8541               }
8542             case Map_type::MAP_ALG_FAST64:
8543             case Map_type::MAP_ALG_FAST64PTR:
8544               {
8545                 code = Runtime::MAPDELETE_FAST64;
8546                 Type* uint64_type = Type::lookup_integer_type("uint64");
8547                 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
8548                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8549                 e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
8550                                                   loc);
8551                 e3 = Expression::make_dereference(e3,
8552                                                   Expression::NIL_CHECK_NOT_NEEDED,
8553                                                   loc);
8554                 break;
8555               }
8556             case Map_type::MAP_ALG_FASTSTR:
8557               code = Runtime::MAPDELETE_FASTSTR;
8558               break;
8559             default:
8560               code = Runtime::MAPDELETE;
8561 
8562               // If the call to delete is deferred, and is in a loop,
8563               // then the loop will only have a single instance of the
8564               // temporary variable.  Passing the address of the
8565               // temporary variable here means that the deferred call
8566               // will see the last value in the loop, not the current
8567               // value.  So for this unusual case copy the value into
8568               // the heap.
8569               if (!this->is_deferred())
8570                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8571               else
8572                 {
8573                   Expression* a = Expression::make_allocation(mt->key_type(),
8574                                                               loc);
8575                   Temporary_statement* atemp =
8576                     Statement::make_temporary(NULL, a, loc);
8577                   inserter->insert(atemp);
8578 
8579                   a = Expression::make_temporary_reference(atemp, loc);
8580                   a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
8581                   Statement* s = Statement::make_assignment(a, e3, loc);
8582                   inserter->insert(s);
8583 
8584                   e3 = Expression::make_temporary_reference(atemp, loc);
8585                 }
8586           }
8587 
8588         return Runtime::make_call(code, loc, 3, e1, e2, e3);
8589       }
8590     }
8591 
8592   return this;
8593 }
8594 
8595 // Lower a make expression.
8596 
8597 Expression*
lower_make(Statement_inserter * inserter)8598 Builtin_call_expression::lower_make(Statement_inserter* inserter)
8599 {
8600   Location loc = this->location();
8601 
8602   const Expression_list* args = this->args();
8603   if (args == NULL || args->size() < 1)
8604     {
8605       this->report_error(_("not enough arguments"));
8606       return Expression::make_error(this->location());
8607     }
8608 
8609   Expression_list::const_iterator parg = args->begin();
8610 
8611   Expression* first_arg = *parg;
8612   if (!first_arg->is_type_expression())
8613     {
8614       go_error_at(first_arg->location(), "expected type");
8615       this->set_is_error();
8616       return Expression::make_error(this->location());
8617     }
8618   Type* type = first_arg->type();
8619 
8620   if (!type->in_heap())
8621     go_error_at(first_arg->location(),
8622 		"cannot make slice of go:notinheap type");
8623 
8624   bool is_slice = false;
8625   bool is_map = false;
8626   bool is_chan = false;
8627   if (type->is_slice_type())
8628     is_slice = true;
8629   else if (type->map_type() != NULL)
8630     is_map = true;
8631   else if (type->channel_type() != NULL)
8632     is_chan = true;
8633   else
8634     {
8635       this->report_error(_("invalid type for make function"));
8636       return Expression::make_error(this->location());
8637     }
8638 
8639   Type_context int_context(Type::lookup_integer_type("int"), false);
8640 
8641   ++parg;
8642   Expression* len_arg;
8643   bool len_small = false;
8644   if (parg == args->end())
8645     {
8646       if (is_slice)
8647 	{
8648 	  this->report_error(_("length required when allocating a slice"));
8649 	  return Expression::make_error(this->location());
8650 	}
8651       len_arg = Expression::make_integer_ul(0, NULL, loc);
8652       len_small = true;
8653     }
8654   else
8655     {
8656       len_arg = *parg;
8657       len_arg->determine_type(&int_context);
8658       if (len_arg->type()->integer_type() == NULL)
8659 	{
8660 	  go_error_at(len_arg->location(), "non-integer len argument in make");
8661 	  return Expression::make_error(this->location());
8662 	}
8663       if (!this->check_int_value(len_arg, true, &len_small))
8664 	return Expression::make_error(this->location());
8665       ++parg;
8666     }
8667 
8668   Expression* cap_arg = NULL;
8669   bool cap_small = false;
8670   Numeric_constant nclen;
8671   Numeric_constant nccap;
8672   unsigned long vlen;
8673   unsigned long vcap;
8674   if (is_slice && parg != args->end())
8675     {
8676       cap_arg = *parg;
8677       cap_arg->determine_type(&int_context);
8678       if (cap_arg->type()->integer_type() == NULL)
8679 	{
8680 	  go_error_at(cap_arg->location(), "non-integer cap argument in make");
8681 	  return Expression::make_error(this->location());
8682 	}
8683       if (!this->check_int_value(cap_arg, false, &cap_small))
8684 	return Expression::make_error(this->location());
8685 
8686       if (len_arg->numeric_constant_value(&nclen)
8687 	  && cap_arg->numeric_constant_value(&nccap)
8688 	  && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8689 	  && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
8690 	  && vlen > vcap)
8691 	{
8692 	  this->report_error(_("len larger than cap"));
8693 	  return Expression::make_error(this->location());
8694 	}
8695 
8696       ++parg;
8697     }
8698 
8699   if (parg != args->end())
8700     {
8701       this->report_error(_("too many arguments to make"));
8702       return Expression::make_error(this->location());
8703     }
8704 
8705   Location type_loc = first_arg->location();
8706 
8707   Expression* call;
8708   if (is_slice)
8709     {
8710       Temporary_statement* len_temp = NULL;
8711       if (!len_arg->is_constant())
8712 	{
8713 	  len_temp = Statement::make_temporary(NULL, len_arg, loc);
8714 	  inserter->insert(len_temp);
8715 	  len_arg = Expression::make_temporary_reference(len_temp, loc);
8716 	}
8717 
8718       if (cap_arg == NULL)
8719 	{
8720           cap_small = len_small;
8721 	  if (len_temp == NULL)
8722 	    cap_arg = len_arg->copy();
8723 	  else
8724 	    cap_arg = Expression::make_temporary_reference(len_temp, loc);
8725 	}
8726       else if (!cap_arg->is_constant())
8727 	{
8728 	  Temporary_statement* cap_temp = Statement::make_temporary(NULL,
8729 								    cap_arg,
8730 								    loc);
8731 	  inserter->insert(cap_temp);
8732 	  cap_arg = Expression::make_temporary_reference(cap_temp, loc);
8733 	}
8734 
8735       Type* et = type->array_type()->element_type();
8736       Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
8737       Runtime::Function code = Runtime::MAKESLICE;
8738       if (!len_small || !cap_small)
8739 	code = Runtime::MAKESLICE64;
8740       Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
8741 					   cap_arg);
8742       mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
8743 					 loc);
8744       Type* int_type = Type::lookup_integer_type("int");
8745       len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
8746       cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
8747       call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
8748     }
8749   else if (is_map)
8750     {
8751       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8752       if (!len_small)
8753 	call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
8754 				  len_arg,
8755 				  Expression::make_nil(loc));
8756       else
8757 	{
8758 	  if (len_arg->numeric_constant_value(&nclen)
8759 	      && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8760 	      && vlen <= Map_type::bucket_size)
8761 	    call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
8762 	  else
8763 	    call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
8764 				      len_arg,
8765 				      Expression::make_nil(loc));
8766 	}
8767     }
8768   else if (is_chan)
8769     {
8770       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8771       Runtime::Function code = Runtime::MAKECHAN;
8772       if (!len_small)
8773 	code = Runtime::MAKECHAN64;
8774       call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
8775     }
8776   else
8777     go_unreachable();
8778 
8779   return Expression::make_unsafe_cast(type, call, loc);
8780 }
8781 
8782 // Flatten a call to the predeclared append function.  We do this in
8783 // the flatten phase, not the lowering phase, so that we run after
8784 // type checking and after order_evaluations.  If ASSIGN_LHS is not
8785 // NULL, this append is the right-hand-side of an assignment and
8786 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
8787 // rather than returning a slice.  This lets us omit a write barrier
8788 // in common cases like a = append(a, ...) when the slice does not
8789 // need to grow.  ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
8790 
8791 Expression*
flatten_append(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Expression * assign_lhs,Block * enclosing)8792 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
8793 					Statement_inserter* inserter,
8794 					Expression* assign_lhs,
8795 					Block* enclosing)
8796 {
8797   if (this->is_error_expression())
8798     return this;
8799 
8800   Location loc = this->location();
8801 
8802   const Expression_list* args = this->args();
8803   go_assert(args != NULL && !args->empty());
8804 
8805   Type* slice_type = args->front()->type();
8806   go_assert(slice_type->is_slice_type());
8807   Type* element_type = slice_type->array_type()->element_type();
8808 
8809   if (args->size() == 1)
8810     {
8811       // append(s) evaluates to s.
8812       if (assign_lhs != NULL)
8813 	return NULL;
8814       return args->front();
8815     }
8816 
8817   Type* int_type = Type::lookup_integer_type("int");
8818   Type* uint_type = Type::lookup_integer_type("uint");
8819 
8820   // Implementing
8821   //   append(s1, s2...)
8822   // or
8823   //   append(s1, a1, a2, a3, ...)
8824 
8825   // s1tmp := s1
8826   Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
8827 							 loc);
8828   inserter->insert(s1tmp);
8829 
8830   // l1tmp := len(s1tmp)
8831   Named_object* lenfn = gogo->lookup_global("len");
8832   Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8833   Expression_list* call_args = new Expression_list();
8834   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8835   Expression* len = Expression::make_call(lenref, call_args, false, loc);
8836   gogo->lower_expression(function, inserter, &len);
8837   gogo->flatten_expression(function, inserter, &len);
8838   Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
8839   inserter->insert(l1tmp);
8840 
8841   Temporary_statement* s2tmp = NULL;
8842   Temporary_statement* l2tmp = NULL;
8843   Expression_list* add = NULL;
8844   Expression* len2;
8845   Call_expression* makecall = NULL;
8846   if (this->is_varargs())
8847     {
8848       go_assert(args->size() == 2);
8849 
8850       std::pair<Call_expression*, Temporary_statement*> p =
8851         Expression::find_makeslice_call(args->back());
8852       makecall = p.first;
8853       if (makecall != NULL)
8854         {
8855           // We are handling
8856           // 	append(s, make([]T, len[, cap])...))
8857           // which has already been lowered to
8858           // 	append(s, runtime.makeslice(T, len, cap)).
8859           // We will optimize this to directly zeroing the tail,
8860           // instead of allocating a new slice then copy.
8861 
8862           // Retrieve the length. Cannot reference s2 as we will remove
8863           // the makeslice call.
8864           Expression* len_arg = makecall->args()->at(1);
8865           len_arg = Expression::make_cast(int_type, len_arg, loc);
8866           l2tmp = Statement::make_temporary(int_type, len_arg, loc);
8867           inserter->insert(l2tmp);
8868 
8869           Expression* cap_arg = makecall->args()->at(2);
8870           cap_arg = Expression::make_cast(int_type, cap_arg, loc);
8871           Temporary_statement* c2tmp =
8872             Statement::make_temporary(int_type, cap_arg, loc);
8873           inserter->insert(c2tmp);
8874 
8875           // Check bad len/cap here.
8876           // if len2 < 0 { panicmakeslicelen(); }
8877           len2 = Expression::make_temporary_reference(l2tmp, loc);
8878           Expression* zero = Expression::make_integer_ul(0, int_type, loc);
8879           Expression* cond = Expression::make_binary(OPERATOR_LT, len2,
8880                                                      zero, loc);
8881 	  Expression* call = Runtime::make_call(Runtime::PANIC_MAKE_SLICE_LEN,
8882 						loc, 0);
8883           cond = Expression::make_conditional(cond, call, zero->copy(), loc);
8884           gogo->lower_expression(function, inserter, &cond);
8885           gogo->flatten_expression(function, inserter, &cond);
8886           Statement* s = Statement::make_statement(cond, false);
8887           inserter->insert(s);
8888 
8889           // if cap2 < 0 { panicmakeslicecap(); }
8890           Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
8891           cond = Expression::make_binary(OPERATOR_LT, cap2,
8892                                          zero->copy(), loc);
8893 	  call = Runtime::make_call(Runtime::PANIC_MAKE_SLICE_CAP, loc, 0);
8894           cond = Expression::make_conditional(cond, call, zero->copy(), loc);
8895           gogo->lower_expression(function, inserter, &cond);
8896           gogo->flatten_expression(function, inserter, &cond);
8897           s = Statement::make_statement(cond, false);
8898           inserter->insert(s);
8899 
8900           // Remove the original makeslice call.
8901           Temporary_statement* ts = p.second;
8902           if (ts != NULL && ts->uses() == 1)
8903             ts->set_init(Expression::make_nil(loc));
8904         }
8905       else
8906         {
8907           // s2tmp := s2
8908           s2tmp = Statement::make_temporary(NULL, args->back(), loc);
8909           inserter->insert(s2tmp);
8910 
8911           // l2tmp := len(s2tmp)
8912           lenref = Expression::make_func_reference(lenfn, NULL, loc);
8913           call_args = new Expression_list();
8914           call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
8915           len = Expression::make_call(lenref, call_args, false, loc);
8916           gogo->lower_expression(function, inserter, &len);
8917           gogo->flatten_expression(function, inserter, &len);
8918           l2tmp = Statement::make_temporary(int_type, len, loc);
8919           inserter->insert(l2tmp);
8920         }
8921 
8922       // len2 = l2tmp
8923       len2 = Expression::make_temporary_reference(l2tmp, loc);
8924     }
8925   else
8926     {
8927       // We have to ensure that all the arguments are in variables
8928       // now, because otherwise if one of them is an index expression
8929       // into the current slice we could overwrite it before we fetch
8930       // it.
8931       add = new Expression_list();
8932       Expression_list::const_iterator pa = args->begin();
8933       for (++pa; pa != args->end(); ++pa)
8934 	{
8935 	  if ((*pa)->is_variable())
8936 	    add->push_back(*pa);
8937 	  else
8938 	    {
8939 	      Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
8940 								   loc);
8941 	      inserter->insert(tmp);
8942 	      add->push_back(Expression::make_temporary_reference(tmp, loc));
8943 	    }
8944 	}
8945 
8946       // len2 = len(add)
8947       len2 = Expression::make_integer_ul(add->size(), int_type, loc);
8948     }
8949 
8950   // ntmp := l1tmp + len2
8951   Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
8952   Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
8953   gogo->lower_expression(function, inserter, &sum);
8954   gogo->flatten_expression(function, inserter, &sum);
8955   Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
8956   inserter->insert(ntmp);
8957 
8958   // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
8959   //   growslice(type, s1tmp, ntmp) :
8960   //   s1tmp[:ntmp]
8961   // Using uint here means that if the computation of ntmp overflowed,
8962   // we will call growslice which will panic.
8963 
8964   Named_object* capfn = gogo->lookup_global("cap");
8965   Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
8966   call_args = new Expression_list();
8967   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8968   Expression* cap = Expression::make_call(capref, call_args, false, loc);
8969   gogo->lower_expression(function, inserter, &cap);
8970   gogo->flatten_expression(function, inserter, &cap);
8971   Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
8972   inserter->insert(c1tmp);
8973 
8974   Expression* left = Expression::make_temporary_reference(ntmp, loc);
8975   left = Expression::make_cast(uint_type, left, loc);
8976   Expression* right = Expression::make_temporary_reference(c1tmp, loc);
8977   right = Expression::make_cast(uint_type, right, loc);
8978 
8979   Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
8980 
8981   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8982   Expression* a1 = Expression::make_type_descriptor(element_type, loc);
8983   Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
8984   a2 = slice_type->array_type()->get_value_pointer(gogo, a2, false);
8985   a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
8986   Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
8987   Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
8988   Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
8989   Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
8990 					a1, a2, a3, a4, a5);
8991   call = Expression::make_unsafe_cast(slice_type, call, loc);
8992 
8993   ref = Expression::make_temporary_reference(s1tmp, loc);
8994   Expression* zero = Expression::make_integer_ul(0, int_type, loc);
8995   Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
8996   ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
8997   ref->array_index_expression()->set_needs_bounds_check(false);
8998 
8999   if (assign_lhs == NULL)
9000     {
9001       Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
9002 
9003       gogo->lower_expression(function, inserter, &rhs);
9004       gogo->flatten_expression(function, inserter, &rhs);
9005 
9006       ref = Expression::make_temporary_reference(s1tmp, loc);
9007       Statement* assign = Statement::make_assignment(ref, rhs, loc);
9008       inserter->insert(assign);
9009     }
9010   else
9011     {
9012       gogo->lower_expression(function, inserter, &cond);
9013       gogo->flatten_expression(function, inserter, &cond);
9014       gogo->lower_expression(function, inserter, &call);
9015       gogo->flatten_expression(function, inserter, &call);
9016       gogo->lower_expression(function, inserter, &ref);
9017       gogo->flatten_expression(function, inserter, &ref);
9018 
9019       Block* then_block = new Block(enclosing, loc);
9020       Assignment_statement* assign =
9021 	Statement::make_assignment(assign_lhs, call, loc);
9022       then_block->add_statement(assign);
9023 
9024       Block* else_block = new Block(enclosing, loc);
9025       assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
9026       // This assignment will not change the pointer value, so it does
9027       // not need a write barrier.
9028       assign->set_omit_write_barrier();
9029       else_block->add_statement(assign);
9030 
9031       Statement* s = Statement::make_if_statement(cond, then_block,
9032 						  else_block, loc);
9033       inserter->insert(s);
9034 
9035       ref = Expression::make_temporary_reference(s1tmp, loc);
9036       assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
9037       inserter->insert(assign);
9038     }
9039 
9040   Type* uintptr_type = Type::lookup_integer_type("uintptr");
9041 
9042   if (this->is_varargs())
9043     {
9044       if (makecall != NULL)
9045         {
9046           // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
9047           a1 = Expression::make_temporary_reference(s1tmp, loc);
9048           ref = Expression::make_temporary_reference(l1tmp, loc);
9049           a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9050           a1->array_index_expression()->set_needs_bounds_check(false);
9051           a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9052 
9053           ref = Expression::make_temporary_reference(l2tmp, loc);
9054           ref = Expression::make_cast(uintptr_type, ref, loc);
9055           a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9056           a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
9057 
9058           if (element_type->has_pointer())
9059             call = Runtime::make_call(Runtime::MEMCLRHASPTR, loc, 2, a1, a2);
9060           else
9061             {
9062               Type* int32_type = Type::lookup_integer_type("int32");
9063               zero = Expression::make_integer_ul(0, int32_type, loc);
9064               call = Runtime::make_call(Runtime::BUILTIN_MEMSET, loc, 3, a1,
9065                                         zero, a2);
9066             }
9067 
9068           if (element_type->has_pointer())
9069             {
9070               // For a slice containing pointers, growslice already zeroed
9071               // the memory. We only need to zero in non-growing case.
9072               // Note: growslice does not zero the memory in non-pointer case.
9073               ref = Expression::make_temporary_reference(ntmp, loc);
9074               ref = Expression::make_cast(uint_type, ref, loc);
9075               ref2 = Expression::make_temporary_reference(c1tmp, loc);
9076               ref2 = Expression::make_cast(uint_type, ref2, loc);
9077               cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
9078               zero = Expression::make_integer_ul(0, int_type, loc);
9079               call = Expression::make_conditional(cond, call, zero, loc);
9080             }
9081         }
9082       else
9083         {
9084           if (element_type->has_pointer())
9085             {
9086               // copy(s1tmp[l1tmp:], s2tmp)
9087               a1 = Expression::make_temporary_reference(s1tmp, loc);
9088               ref = Expression::make_temporary_reference(l1tmp, loc);
9089               Expression* nil = Expression::make_nil(loc);
9090               a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
9091               a1->array_index_expression()->set_needs_bounds_check(false);
9092 
9093               a2 = Expression::make_temporary_reference(s2tmp, loc);
9094 
9095               Named_object* copyfn = gogo->lookup_global("copy");
9096               Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
9097               call_args = new Expression_list();
9098               call_args->push_back(a1);
9099               call_args->push_back(a2);
9100               call = Expression::make_call(copyref, call_args, false, loc);
9101             }
9102           else
9103             {
9104               // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
9105               a1 = Expression::make_temporary_reference(s1tmp, loc);
9106               ref = Expression::make_temporary_reference(l1tmp, loc);
9107               a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9108               a1->array_index_expression()->set_needs_bounds_check(false);
9109               a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9110 
9111               a2 = Expression::make_temporary_reference(s2tmp, loc);
9112               a2 = (a2->type()->is_string_type()
9113                     ? Expression::make_string_info(a2,
9114                                                    STRING_INFO_DATA,
9115                                                    loc)
9116                     : Expression::make_slice_info(a2,
9117                                                   SLICE_INFO_VALUE_POINTER,
9118                                                   loc));
9119 
9120               ref = Expression::make_temporary_reference(l2tmp, loc);
9121               ref = Expression::make_cast(uintptr_type, ref, loc);
9122               a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9123               a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
9124 
9125               call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
9126                                         a1, a2, a3);
9127             }
9128         }
9129       gogo->lower_expression(function, inserter, &call);
9130       gogo->flatten_expression(function, inserter, &call);
9131       inserter->insert(Statement::make_statement(call, false));
9132     }
9133   else
9134     {
9135       // For each argument:
9136       //  s1tmp[l1tmp+i] = a
9137       unsigned long i = 0;
9138       for (Expression_list::const_iterator pa = add->begin();
9139 	   pa != add->end();
9140 	   ++pa, ++i)
9141 	{
9142 	  ref = Expression::make_temporary_reference(s1tmp, loc);
9143 	  ref2 = Expression::make_temporary_reference(l1tmp, loc);
9144 	  Expression* off = Expression::make_integer_ul(i, int_type, loc);
9145 	  ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
9146 	  Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
9147                                                          NULL, loc);
9148           lhs->array_index_expression()->set_needs_bounds_check(false);
9149 	  gogo->lower_expression(function, inserter, &lhs);
9150 	  gogo->flatten_expression(function, inserter, &lhs);
9151       Expression* elem = *pa;
9152       if (!Type::are_identical(element_type, elem->type(), 0, NULL)
9153           && element_type->interface_type() != NULL)
9154         elem = Expression::make_cast(element_type, elem, loc);
9155 	  // The flatten pass runs after the write barrier pass, so we
9156 	  // need to insert a write barrier here if necessary.
9157 	  // However, if ASSIGN_LHS is not NULL, we have been called
9158 	  // directly before the write barrier pass.
9159 	  Statement* assign;
9160 	  if (assign_lhs != NULL
9161 	      || !gogo->assign_needs_write_barrier(lhs, NULL))
9162 	    assign = Statement::make_assignment(lhs, elem, loc);
9163 	  else
9164 	    {
9165 	      Function* f = function == NULL ? NULL : function->func_value();
9166 	      assign = gogo->assign_with_write_barrier(f, NULL, inserter,
9167 						       lhs, elem, loc);
9168 	    }
9169 	  inserter->insert(assign);
9170 	}
9171     }
9172 
9173   if (assign_lhs != NULL)
9174     return NULL;
9175 
9176   return Expression::make_temporary_reference(s1tmp, loc);
9177 }
9178 
9179 // Return whether an expression has an integer value.  Report an error
9180 // if not.  This is used when handling calls to the predeclared make
9181 // function.  Set *SMALL if the value is known to fit in type "int".
9182 
9183 bool
check_int_value(Expression * e,bool is_length,bool * small)9184 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
9185 					 bool *small)
9186 {
9187   *small = false;
9188 
9189   Numeric_constant nc;
9190   if (e->numeric_constant_value(&nc))
9191     {
9192       unsigned long v;
9193       switch (nc.to_unsigned_long(&v))
9194 	{
9195 	case Numeric_constant::NC_UL_VALID:
9196 	  break;
9197 	case Numeric_constant::NC_UL_NOTINT:
9198 	  go_error_at(e->location(), "non-integer %s argument to make",
9199 		      is_length ? "len" : "cap");
9200 	  return false;
9201 	case Numeric_constant::NC_UL_NEGATIVE:
9202 	  go_error_at(e->location(), "negative %s argument to make",
9203 		      is_length ? "len" : "cap");
9204 	  return false;
9205 	case Numeric_constant::NC_UL_BIG:
9206 	  // We don't want to give a compile-time error for a 64-bit
9207 	  // value on a 32-bit target.
9208 	  break;
9209 	}
9210 
9211       mpz_t val;
9212       if (!nc.to_int(&val))
9213 	go_unreachable();
9214       int bits = mpz_sizeinbase(val, 2);
9215       mpz_clear(val);
9216       Type* int_type = Type::lookup_integer_type("int");
9217       if (bits >= int_type->integer_type()->bits())
9218 	{
9219 	  go_error_at(e->location(), "%s argument too large for make",
9220 		      is_length ? "len" : "cap");
9221 	  return false;
9222 	}
9223 
9224       *small = true;
9225       return true;
9226     }
9227 
9228   if (e->type()->integer_type() != NULL)
9229     {
9230       int ebits = e->type()->integer_type()->bits();
9231       int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
9232 
9233       // We can treat ebits == intbits as small even for an unsigned
9234       // integer type, because we will convert the value to int and
9235       // then reject it in the runtime if it is negative.
9236       *small = ebits <= intbits;
9237 
9238       return true;
9239     }
9240 
9241   go_error_at(e->location(), "non-integer %s argument to make",
9242 	      is_length ? "len" : "cap");
9243   return false;
9244 }
9245 
9246 // Return the type of the real or imag functions, given the type of
9247 // the argument.  We need to map complex64 to float32 and complex128
9248 // to float64, so it has to be done by name.  This returns NULL if it
9249 // can't figure out the type.
9250 
9251 Type*
real_imag_type(Type * arg_type)9252 Builtin_call_expression::real_imag_type(Type* arg_type)
9253 {
9254   if (arg_type == NULL || arg_type->is_abstract())
9255     return NULL;
9256   Named_type* nt = arg_type->named_type();
9257   if (nt == NULL)
9258     return NULL;
9259   while (nt->real_type()->named_type() != NULL)
9260     nt = nt->real_type()->named_type();
9261   if (nt->name() == "complex64")
9262     return Type::lookup_float_type("float32");
9263   else if (nt->name() == "complex128")
9264     return Type::lookup_float_type("float64");
9265   else
9266     return NULL;
9267 }
9268 
9269 // Return the type of the complex function, given the type of one of the
9270 // argments.  Like real_imag_type, we have to map by name.
9271 
9272 Type*
complex_type(Type * arg_type)9273 Builtin_call_expression::complex_type(Type* arg_type)
9274 {
9275   if (arg_type == NULL || arg_type->is_abstract())
9276     return NULL;
9277   Named_type* nt = arg_type->named_type();
9278   if (nt == NULL)
9279     return NULL;
9280   while (nt->real_type()->named_type() != NULL)
9281     nt = nt->real_type()->named_type();
9282   if (nt->name() == "float32")
9283     return Type::lookup_complex_type("complex64");
9284   else if (nt->name() == "float64")
9285     return Type::lookup_complex_type("complex128");
9286   else
9287     return NULL;
9288 }
9289 
9290 // Return a single argument, or NULL if there isn't one.
9291 
9292 Expression*
one_arg() const9293 Builtin_call_expression::one_arg() const
9294 {
9295   const Expression_list* args = this->args();
9296   if (args == NULL || args->size() != 1)
9297     return NULL;
9298   return args->front();
9299 }
9300 
9301 // A traversal class which looks for a call or receive expression.
9302 
9303 class Find_call_expression : public Traverse
9304 {
9305  public:
Find_call_expression()9306   Find_call_expression()
9307     : Traverse(traverse_expressions),
9308       found_(false)
9309   { }
9310 
9311   int
9312   expression(Expression**);
9313 
9314   bool
found()9315   found()
9316   { return this->found_; }
9317 
9318  private:
9319   bool found_;
9320 };
9321 
9322 int
expression(Expression ** pexpr)9323 Find_call_expression::expression(Expression** pexpr)
9324 {
9325   Expression* expr = *pexpr;
9326   if (!expr->is_constant()
9327       && (expr->call_expression() != NULL
9328 	  || expr->receive_expression() != NULL))
9329     {
9330       this->found_ = true;
9331       return TRAVERSE_EXIT;
9332     }
9333   return TRAVERSE_CONTINUE;
9334 }
9335 
9336 // Return whether calling len or cap on EXPR, of array type, is a
9337 // constant.  The language spec says "the expressions len(s) and
9338 // cap(s) are constants if the type of s is an array or pointer to an
9339 // array and the expression s does not contain channel receives or
9340 // (non-constant) function calls."
9341 
9342 bool
array_len_is_constant(Expression * expr)9343 Builtin_call_expression::array_len_is_constant(Expression* expr)
9344 {
9345   go_assert(expr->type()->deref()->array_type() != NULL
9346 	    && !expr->type()->deref()->is_slice_type());
9347   if (expr->is_constant())
9348     return true;
9349   Find_call_expression find_call;
9350   Expression::traverse(&expr, &find_call);
9351   return !find_call.found();
9352 }
9353 
9354 // Return whether this is constant: len of a string constant, or len
9355 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
9356 // unsafe.Alignof.
9357 
9358 bool
do_is_constant() const9359 Builtin_call_expression::do_is_constant() const
9360 {
9361   if (this->is_error_expression())
9362     return true;
9363   switch (this->code_)
9364     {
9365     case BUILTIN_LEN:
9366     case BUILTIN_CAP:
9367       {
9368 	if (this->seen_)
9369 	  return false;
9370 
9371 	Expression* arg = this->one_arg();
9372 	if (arg == NULL)
9373 	  return false;
9374 	Type* arg_type = arg->type();
9375 
9376 	if (arg_type->points_to() != NULL
9377 	    && arg_type->points_to()->array_type() != NULL
9378 	    && !arg_type->points_to()->is_slice_type())
9379 	  arg_type = arg_type->points_to();
9380 
9381 	if (arg_type->array_type() != NULL
9382 	    && arg_type->array_type()->length() != NULL)
9383           {
9384 	    this->seen_ = true;
9385 	    bool ret = Builtin_call_expression::array_len_is_constant(arg);
9386 	    this->seen_ = false;
9387 	    return ret;
9388           }
9389 
9390 	if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9391 	  {
9392 	    this->seen_ = true;
9393 	    bool ret = arg->is_constant();
9394 	    this->seen_ = false;
9395 	    return ret;
9396 	  }
9397       }
9398       break;
9399 
9400     case BUILTIN_SIZEOF:
9401     case BUILTIN_ALIGNOF:
9402       return this->one_arg() != NULL;
9403 
9404     case BUILTIN_OFFSETOF:
9405       {
9406 	Expression* arg = this->one_arg();
9407 	if (arg == NULL)
9408 	  return false;
9409 	return arg->field_reference_expression() != NULL;
9410       }
9411 
9412     case BUILTIN_COMPLEX:
9413       {
9414 	const Expression_list* args = this->args();
9415 	if (args != NULL && args->size() == 2)
9416 	  return args->front()->is_constant() && args->back()->is_constant();
9417       }
9418       break;
9419 
9420     case BUILTIN_REAL:
9421     case BUILTIN_IMAG:
9422       {
9423 	Expression* arg = this->one_arg();
9424 	return arg != NULL && arg->is_constant();
9425       }
9426 
9427     default:
9428       break;
9429     }
9430 
9431   return false;
9432 }
9433 
9434 // Return a numeric constant if possible.
9435 
9436 bool
do_numeric_constant_value(Numeric_constant * nc) const9437 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
9438 {
9439   if (this->code_ == BUILTIN_LEN
9440       || this->code_ == BUILTIN_CAP)
9441     {
9442       Expression* arg = this->one_arg();
9443       if (arg == NULL)
9444 	return false;
9445       Type* arg_type = arg->type();
9446 
9447       if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9448 	{
9449 	  std::string sval;
9450 	  if (arg->string_constant_value(&sval))
9451 	    {
9452 	      nc->set_unsigned_long(Type::lookup_integer_type("int"),
9453 				    sval.length());
9454 	      return true;
9455 	    }
9456 	}
9457 
9458       if (arg_type->points_to() != NULL
9459 	  && arg_type->points_to()->array_type() != NULL
9460 	  && !arg_type->points_to()->is_slice_type())
9461 	arg_type = arg_type->points_to();
9462 
9463       if (arg_type->array_type() != NULL
9464 	  && arg_type->array_type()->length() != NULL)
9465 	{
9466 	  if (this->seen_)
9467 	    return false;
9468 	  Expression* e = arg_type->array_type()->length();
9469 	  this->seen_ = true;
9470 	  bool r = e->numeric_constant_value(nc);
9471 	  this->seen_ = false;
9472 	  if (r)
9473 	    {
9474 	      if (!nc->set_type(Type::lookup_integer_type("int"), false,
9475 				this->location()))
9476 		r = false;
9477 	    }
9478 	  return r;
9479 	}
9480     }
9481   else if (this->code_ == BUILTIN_SIZEOF
9482 	   || this->code_ == BUILTIN_ALIGNOF)
9483     {
9484       Expression* arg = this->one_arg();
9485       if (arg == NULL)
9486 	return false;
9487       Type* arg_type = arg->type();
9488       if (arg_type->is_error())
9489 	return false;
9490       if (arg_type->is_abstract())
9491 	arg_type = arg_type->make_non_abstract_type();
9492       if (this->seen_)
9493         return false;
9494 
9495       int64_t ret;
9496       if (this->code_ == BUILTIN_SIZEOF)
9497 	{
9498           this->seen_ = true;
9499 	  bool ok = arg_type->backend_type_size(this->gogo_, &ret);
9500           this->seen_ = false;
9501 	  if (!ok)
9502 	    return false;
9503 	}
9504       else if (this->code_ == BUILTIN_ALIGNOF)
9505 	{
9506 	  bool ok;
9507           this->seen_ = true;
9508 	  if (arg->field_reference_expression() == NULL)
9509 	    ok = arg_type->backend_type_align(this->gogo_, &ret);
9510 	  else
9511 	    {
9512 	      // Calling unsafe.Alignof(s.f) returns the alignment of
9513 	      // the type of f when it is used as a field in a struct.
9514 	      ok = arg_type->backend_type_field_align(this->gogo_, &ret);
9515 	    }
9516           this->seen_ = false;
9517 	  if (!ok)
9518 	    return false;
9519 	}
9520       else
9521 	go_unreachable();
9522 
9523       mpz_t zval;
9524       set_mpz_from_int64(&zval, ret);
9525       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9526       mpz_clear(zval);
9527       return true;
9528     }
9529   else if (this->code_ == BUILTIN_OFFSETOF)
9530     {
9531       Expression* arg = this->one_arg();
9532       if (arg == NULL)
9533 	return false;
9534       Field_reference_expression* farg = arg->field_reference_expression();
9535       if (farg == NULL)
9536 	return false;
9537       if (this->seen_)
9538         return false;
9539 
9540       int64_t total_offset = 0;
9541       while (true)
9542         {
9543           Expression* struct_expr = farg->expr();
9544           Type* st = struct_expr->type();
9545           if (st->struct_type() == NULL)
9546             return false;
9547           if (st->named_type() != NULL)
9548             st->named_type()->convert(this->gogo_);
9549           if (st->is_error_type())
9550             {
9551               go_assert(saw_errors());
9552               return false;
9553             }
9554           int64_t offset;
9555           this->seen_ = true;
9556           bool ok = st->struct_type()->backend_field_offset(this->gogo_,
9557 							    farg->field_index(),
9558 							    &offset);
9559           this->seen_ = false;
9560 	  if (!ok)
9561 	    return false;
9562           total_offset += offset;
9563           if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
9564             {
9565               // Go up until we reach the original base.
9566               farg = struct_expr->field_reference_expression();
9567               continue;
9568             }
9569           break;
9570         }
9571       mpz_t zval;
9572       set_mpz_from_int64(&zval, total_offset);
9573       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9574       mpz_clear(zval);
9575       return true;
9576     }
9577   else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
9578     {
9579       Expression* arg = this->one_arg();
9580       if (arg == NULL)
9581 	return false;
9582 
9583       Numeric_constant argnc;
9584       if (!arg->numeric_constant_value(&argnc))
9585 	return false;
9586 
9587       mpc_t val;
9588       if (!argnc.to_complex(&val))
9589 	return false;
9590 
9591       Type* type = Builtin_call_expression::real_imag_type(argnc.type());
9592       if (this->code_ == BUILTIN_REAL)
9593 	nc->set_float(type, mpc_realref(val));
9594       else
9595 	nc->set_float(type, mpc_imagref(val));
9596       mpc_clear(val);
9597       return true;
9598     }
9599   else if (this->code_ == BUILTIN_COMPLEX)
9600     {
9601       const Expression_list* args = this->args();
9602       if (args == NULL || args->size() != 2)
9603 	return false;
9604 
9605       Numeric_constant rnc;
9606       if (!args->front()->numeric_constant_value(&rnc))
9607 	return false;
9608       Numeric_constant inc;
9609       if (!args->back()->numeric_constant_value(&inc))
9610 	return false;
9611 
9612       if (rnc.type() != NULL
9613 	  && !rnc.type()->is_abstract()
9614 	  && inc.type() != NULL
9615 	  && !inc.type()->is_abstract()
9616 	  && !Type::are_identical(rnc.type(), inc.type(),
9617 				  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
9618 				  NULL))
9619 	return false;
9620 
9621       mpfr_t r;
9622       if (!rnc.to_float(&r))
9623 	return false;
9624       mpfr_t i;
9625       if (!inc.to_float(&i))
9626 	{
9627 	  mpfr_clear(r);
9628 	  return false;
9629 	}
9630 
9631       Type* arg_type = rnc.type();
9632       if (arg_type == NULL || arg_type->is_abstract())
9633 	arg_type = inc.type();
9634 
9635       mpc_t val;
9636       mpc_init2(val, mpc_precision);
9637       mpc_set_fr_fr(val, r, i, MPC_RNDNN);
9638       mpfr_clear(r);
9639       mpfr_clear(i);
9640 
9641       Type* type = Builtin_call_expression::complex_type(arg_type);
9642       nc->set_complex(type, val);
9643 
9644       mpc_clear(val);
9645 
9646       return true;
9647     }
9648 
9649   return false;
9650 }
9651 
9652 // Give an error if we are discarding the value of an expression which
9653 // should not normally be discarded.  We don't give an error for
9654 // discarding the value of an ordinary function call, but we do for
9655 // builtin functions, purely for consistency with the gc compiler.
9656 
9657 bool
do_discarding_value()9658 Builtin_call_expression::do_discarding_value()
9659 {
9660   switch (this->code_)
9661     {
9662     case BUILTIN_INVALID:
9663     default:
9664       go_unreachable();
9665 
9666     case BUILTIN_APPEND:
9667     case BUILTIN_CAP:
9668     case BUILTIN_COMPLEX:
9669     case BUILTIN_IMAG:
9670     case BUILTIN_LEN:
9671     case BUILTIN_MAKE:
9672     case BUILTIN_NEW:
9673     case BUILTIN_REAL:
9674     case BUILTIN_ALIGNOF:
9675     case BUILTIN_OFFSETOF:
9676     case BUILTIN_SIZEOF:
9677       this->unused_value_error();
9678       return false;
9679 
9680     case BUILTIN_CLOSE:
9681     case BUILTIN_COPY:
9682     case BUILTIN_DELETE:
9683     case BUILTIN_PANIC:
9684     case BUILTIN_PRINT:
9685     case BUILTIN_PRINTLN:
9686     case BUILTIN_RECOVER:
9687       return true;
9688     }
9689 }
9690 
9691 // Return the type.
9692 
9693 Type*
do_type()9694 Builtin_call_expression::do_type()
9695 {
9696   if (this->is_error_expression())
9697     return Type::make_error_type();
9698   switch (this->code_)
9699     {
9700     case BUILTIN_INVALID:
9701     default:
9702       return Type::make_error_type();
9703 
9704     case BUILTIN_NEW:
9705       {
9706 	const Expression_list* args = this->args();
9707 	if (args == NULL || args->empty())
9708 	  return Type::make_error_type();
9709 	return Type::make_pointer_type(args->front()->type());
9710       }
9711 
9712     case BUILTIN_MAKE:
9713       {
9714 	const Expression_list* args = this->args();
9715 	if (args == NULL || args->empty())
9716 	  return Type::make_error_type();
9717 	return args->front()->type();
9718       }
9719 
9720     case BUILTIN_CAP:
9721     case BUILTIN_COPY:
9722     case BUILTIN_LEN:
9723       return Type::lookup_integer_type("int");
9724 
9725     case BUILTIN_ALIGNOF:
9726     case BUILTIN_OFFSETOF:
9727     case BUILTIN_SIZEOF:
9728       return Type::lookup_integer_type("uintptr");
9729 
9730     case BUILTIN_CLOSE:
9731     case BUILTIN_DELETE:
9732     case BUILTIN_PANIC:
9733     case BUILTIN_PRINT:
9734     case BUILTIN_PRINTLN:
9735       return Type::make_void_type();
9736 
9737     case BUILTIN_RECOVER:
9738       return Type::make_empty_interface_type(Linemap::predeclared_location());
9739 
9740     case BUILTIN_APPEND:
9741       {
9742 	const Expression_list* args = this->args();
9743 	if (args == NULL || args->empty())
9744 	  return Type::make_error_type();
9745 	Type *ret = args->front()->type();
9746 	if (!ret->is_slice_type())
9747 	  return Type::make_error_type();
9748 	return ret;
9749       }
9750 
9751     case BUILTIN_REAL:
9752     case BUILTIN_IMAG:
9753       {
9754 	Expression* arg = this->one_arg();
9755 	if (arg == NULL)
9756 	  return Type::make_error_type();
9757 	Type* t = arg->type();
9758 	if (t->is_abstract())
9759 	  t = t->make_non_abstract_type();
9760 	t = Builtin_call_expression::real_imag_type(t);
9761 	if (t == NULL)
9762 	  t = Type::make_error_type();
9763 	return t;
9764       }
9765 
9766     case BUILTIN_COMPLEX:
9767       {
9768 	const Expression_list* args = this->args();
9769 	if (args == NULL || args->size() != 2)
9770 	  return Type::make_error_type();
9771 	Type* t = args->front()->type();
9772 	if (t->is_abstract())
9773 	  {
9774 	    t = args->back()->type();
9775 	    if (t->is_abstract())
9776 	      t = t->make_non_abstract_type();
9777 	  }
9778 	t = Builtin_call_expression::complex_type(t);
9779 	if (t == NULL)
9780 	  t = Type::make_error_type();
9781 	return t;
9782       }
9783     }
9784 }
9785 
9786 // Determine the type.
9787 
9788 void
do_determine_type(const Type_context * context)9789 Builtin_call_expression::do_determine_type(const Type_context* context)
9790 {
9791   if (!this->determining_types())
9792     return;
9793 
9794   this->fn()->determine_type_no_context();
9795 
9796   const Expression_list* args = this->args();
9797 
9798   bool is_print;
9799   Type* arg_type = NULL;
9800   Type* trailing_arg_types = NULL;
9801   switch (this->code_)
9802     {
9803     case BUILTIN_PRINT:
9804     case BUILTIN_PRINTLN:
9805       // Do not force a large integer constant to "int".
9806       is_print = true;
9807       break;
9808 
9809     case BUILTIN_REAL:
9810     case BUILTIN_IMAG:
9811       arg_type = Builtin_call_expression::complex_type(context->type);
9812       if (arg_type == NULL)
9813 	arg_type = Type::lookup_complex_type("complex128");
9814       is_print = false;
9815       break;
9816 
9817     case BUILTIN_COMPLEX:
9818       {
9819 	// For the complex function the type of one operand can
9820 	// determine the type of the other, as in a binary expression.
9821 	arg_type = Builtin_call_expression::real_imag_type(context->type);
9822 	if (arg_type == NULL)
9823 	  arg_type = Type::lookup_float_type("float64");
9824 	if (args != NULL && args->size() == 2)
9825 	  {
9826 	    Type* t1 = args->front()->type();
9827 	    Type* t2 = args->back()->type();
9828 	    if (!t1->is_abstract())
9829 	      arg_type = t1;
9830 	    else if (!t2->is_abstract())
9831 	      arg_type = t2;
9832 	  }
9833 	is_print = false;
9834       }
9835       break;
9836 
9837     case BUILTIN_APPEND:
9838       if (!this->is_varargs()
9839 	  && args != NULL
9840 	  && !args->empty()
9841 	  && args->front()->type()->is_slice_type())
9842 	trailing_arg_types =
9843 	  args->front()->type()->array_type()->element_type();
9844       is_print = false;
9845       break;
9846 
9847     default:
9848       is_print = false;
9849       break;
9850     }
9851 
9852   if (args != NULL)
9853     {
9854       for (Expression_list::const_iterator pa = args->begin();
9855 	   pa != args->end();
9856 	   ++pa)
9857 	{
9858 	  Type_context subcontext;
9859 	  subcontext.type = arg_type;
9860 
9861 	  if (is_print)
9862 	    {
9863 	      // We want to print large constants, we so can't just
9864 	      // use the appropriate nonabstract type.  Use uint64 for
9865 	      // an integer if we know it is nonnegative, otherwise
9866 	      // use int64 for a integer, otherwise use float64 for a
9867 	      // float or complex128 for a complex.
9868 	      Type* want_type = NULL;
9869 	      Type* atype = (*pa)->type();
9870 	      if (atype->is_abstract())
9871 		{
9872 		  if (atype->integer_type() != NULL)
9873 		    {
9874 		      Numeric_constant nc;
9875 		      if (this->numeric_constant_value(&nc))
9876 			{
9877 			  mpz_t val;
9878 			  if (nc.to_int(&val))
9879 			    {
9880 			      if (mpz_sgn(val) >= 0)
9881 				want_type = Type::lookup_integer_type("uint64");
9882 			      mpz_clear(val);
9883 			    }
9884 			}
9885 		      if (want_type == NULL)
9886 			want_type = Type::lookup_integer_type("int64");
9887 		    }
9888 		  else if (atype->float_type() != NULL)
9889 		    want_type = Type::lookup_float_type("float64");
9890 		  else if (atype->complex_type() != NULL)
9891 		    want_type = Type::lookup_complex_type("complex128");
9892 		  else if (atype->is_abstract_string_type())
9893 		    want_type = Type::lookup_string_type();
9894 		  else if (atype->is_abstract_boolean_type())
9895 		    want_type = Type::lookup_bool_type();
9896 		  else
9897 		    go_unreachable();
9898 		  subcontext.type = want_type;
9899 		}
9900 	    }
9901 
9902 	  (*pa)->determine_type(&subcontext);
9903 
9904 	  if (trailing_arg_types != NULL)
9905 	    {
9906 	      arg_type = trailing_arg_types;
9907 	      trailing_arg_types = NULL;
9908 	    }
9909 	}
9910     }
9911 }
9912 
9913 // If there is exactly one argument, return true.  Otherwise give an
9914 // error message and return false.
9915 
9916 bool
check_one_arg()9917 Builtin_call_expression::check_one_arg()
9918 {
9919   const Expression_list* args = this->args();
9920   if (args == NULL || args->size() < 1)
9921     {
9922       this->report_error(_("not enough arguments"));
9923       return false;
9924     }
9925   else if (args->size() > 1)
9926     {
9927       this->report_error(_("too many arguments"));
9928       return false;
9929     }
9930   if (args->front()->is_error_expression()
9931       || args->front()->type()->is_error())
9932     {
9933       this->set_is_error();
9934       return false;
9935     }
9936   return true;
9937 }
9938 
9939 // Check argument types for a builtin function.
9940 
9941 void
do_check_types(Gogo *)9942 Builtin_call_expression::do_check_types(Gogo*)
9943 {
9944   if (this->is_error_expression())
9945     return;
9946   switch (this->code_)
9947     {
9948     case BUILTIN_INVALID:
9949     case BUILTIN_NEW:
9950     case BUILTIN_MAKE:
9951     case BUILTIN_DELETE:
9952       return;
9953 
9954     case BUILTIN_LEN:
9955     case BUILTIN_CAP:
9956       {
9957 	// The single argument may be either a string or an array or a
9958 	// map or a channel, or a pointer to a closed array.
9959 	if (this->check_one_arg())
9960 	  {
9961 	    Type* arg_type = this->one_arg()->type();
9962 	    if (arg_type->points_to() != NULL
9963 		&& arg_type->points_to()->array_type() != NULL
9964 		&& !arg_type->points_to()->is_slice_type())
9965 	      arg_type = arg_type->points_to();
9966 	    if (this->code_ == BUILTIN_CAP)
9967 	      {
9968 		if (!arg_type->is_error()
9969 		    && arg_type->array_type() == NULL
9970 		    && arg_type->channel_type() == NULL)
9971 		  this->report_error(_("argument must be array or slice "
9972 				       "or channel"));
9973 	      }
9974 	    else
9975 	      {
9976 		if (!arg_type->is_error()
9977 		    && !arg_type->is_string_type()
9978 		    && arg_type->array_type() == NULL
9979 		    && arg_type->map_type() == NULL
9980 		    && arg_type->channel_type() == NULL)
9981 		  this->report_error(_("argument must be string or "
9982 				       "array or slice or map or channel"));
9983 	      }
9984 	  }
9985       }
9986       break;
9987 
9988     case BUILTIN_PRINT:
9989     case BUILTIN_PRINTLN:
9990       {
9991 	const Expression_list* args = this->args();
9992 	if (args == NULL)
9993 	  {
9994 	    if (this->code_ == BUILTIN_PRINT)
9995 	      go_warning_at(this->location(), 0,
9996 			 "no arguments for built-in function %<%s%>",
9997 			 (this->code_ == BUILTIN_PRINT
9998 			  ? "print"
9999 			  : "println"));
10000 	  }
10001 	else
10002 	  {
10003 	    for (Expression_list::const_iterator p = args->begin();
10004 		 p != args->end();
10005 		 ++p)
10006 	      {
10007 		Type* type = (*p)->type();
10008 		if (type->is_error()
10009 		    || type->is_string_type()
10010 		    || type->integer_type() != NULL
10011 		    || type->float_type() != NULL
10012 		    || type->complex_type() != NULL
10013 		    || type->is_boolean_type()
10014 		    || type->points_to() != NULL
10015 		    || type->interface_type() != NULL
10016 		    || type->channel_type() != NULL
10017 		    || type->map_type() != NULL
10018 		    || type->function_type() != NULL
10019 		    || type->is_slice_type())
10020 		  ;
10021 		else if ((*p)->is_type_expression())
10022 		  {
10023 		    // If this is a type expression it's going to give
10024 		    // an error anyhow, so we don't need one here.
10025 		  }
10026 		else
10027 		  this->report_error(_("unsupported argument type to "
10028 				       "builtin function"));
10029 	      }
10030 	  }
10031       }
10032       break;
10033 
10034     case BUILTIN_CLOSE:
10035       if (this->check_one_arg())
10036 	{
10037 	  if (this->one_arg()->type()->channel_type() == NULL)
10038 	    this->report_error(_("argument must be channel"));
10039 	  else if (!this->one_arg()->type()->channel_type()->may_send())
10040 	    this->report_error(_("cannot close receive-only channel"));
10041 	}
10042       break;
10043 
10044     case BUILTIN_PANIC:
10045     case BUILTIN_SIZEOF:
10046     case BUILTIN_ALIGNOF:
10047       this->check_one_arg();
10048       break;
10049 
10050     case BUILTIN_RECOVER:
10051       if (this->args() != NULL
10052 	  && !this->args()->empty()
10053 	  && !this->recover_arg_is_set_)
10054 	this->report_error(_("too many arguments"));
10055       break;
10056 
10057     case BUILTIN_OFFSETOF:
10058       if (this->check_one_arg())
10059 	{
10060 	  Expression* arg = this->one_arg();
10061 	  if (arg->field_reference_expression() == NULL)
10062 	    this->report_error(_("argument must be a field reference"));
10063 	}
10064       break;
10065 
10066     case BUILTIN_COPY:
10067       {
10068 	const Expression_list* args = this->args();
10069 	if (args == NULL || args->size() < 2)
10070 	  {
10071 	    this->report_error(_("not enough arguments"));
10072 	    break;
10073 	  }
10074 	else if (args->size() > 2)
10075 	  {
10076 	    this->report_error(_("too many arguments"));
10077 	    break;
10078 	  }
10079 	Type* arg1_type = args->front()->type();
10080 	Type* arg2_type = args->back()->type();
10081 	if (arg1_type->is_error() || arg2_type->is_error())
10082 	  {
10083 	    this->set_is_error();
10084 	    break;
10085 	  }
10086 
10087 	Type* e1;
10088 	if (arg1_type->is_slice_type())
10089 	  e1 = arg1_type->array_type()->element_type();
10090 	else
10091 	  {
10092 	    this->report_error(_("left argument must be a slice"));
10093 	    break;
10094 	  }
10095 
10096 	if (arg2_type->is_slice_type())
10097 	  {
10098 	    Type* e2 = arg2_type->array_type()->element_type();
10099 	    if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
10100 	      this->report_error(_("element types must be the same"));
10101 	  }
10102 	else if (arg2_type->is_string_type())
10103 	  {
10104 	    if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
10105 	      this->report_error(_("first argument must be []byte"));
10106 	  }
10107 	else
10108 	    this->report_error(_("second argument must be slice or string"));
10109       }
10110       break;
10111 
10112     case BUILTIN_APPEND:
10113       {
10114 	const Expression_list* args = this->args();
10115 	if (args == NULL || args->empty())
10116 	  {
10117 	    this->report_error(_("not enough arguments"));
10118 	    break;
10119 	  }
10120 
10121 	Type* slice_type = args->front()->type();
10122 	if (!slice_type->is_slice_type())
10123 	  {
10124 	    if (slice_type->is_error_type())
10125 	      break;
10126 	    if (slice_type->is_nil_type())
10127 	      go_error_at(args->front()->location(), "use of untyped nil");
10128 	    else
10129 	      go_error_at(args->front()->location(),
10130 			  "argument 1 must be a slice");
10131 	    this->set_is_error();
10132 	    break;
10133 	  }
10134 
10135 	Type* element_type = slice_type->array_type()->element_type();
10136 	if (!element_type->in_heap())
10137 	  go_error_at(args->front()->location(),
10138 		      "cannot append to slice of go:notinheap type");
10139 	if (this->is_varargs())
10140 	  {
10141 	    if (!args->back()->type()->is_slice_type()
10142 		&& !args->back()->type()->is_string_type())
10143 	      {
10144 		go_error_at(args->back()->location(),
10145 			    "invalid use of %<...%> with non-slice/non-string");
10146 		this->set_is_error();
10147 		break;
10148 	      }
10149 
10150 	    if (args->size() < 2)
10151 	      {
10152 		this->report_error(_("not enough arguments"));
10153 		break;
10154 	      }
10155 	    if (args->size() > 2)
10156 	      {
10157 		this->report_error(_("too many arguments"));
10158 		break;
10159 	      }
10160 
10161 	    if (args->back()->type()->is_string_type()
10162 		&& element_type->integer_type() != NULL
10163 		&& element_type->integer_type()->is_byte())
10164 	      {
10165 		// Permit append(s1, s2...) when s1 is a slice of
10166 		// bytes and s2 is a string type.
10167 	      }
10168 	    else
10169 	      {
10170 		// We have to test for assignment compatibility to a
10171 		// slice of the element type, which is not necessarily
10172 		// the same as the type of the first argument: the
10173 		// first argument might have a named type.
10174 		Type* check_type = Type::make_array_type(element_type, NULL);
10175 		std::string reason;
10176 		if (!Type::are_assignable(check_type, args->back()->type(),
10177 					  &reason))
10178 		  {
10179 		    if (reason.empty())
10180 		      go_error_at(args->back()->location(),
10181 				  "argument 2 has invalid type");
10182 		    else
10183 		      go_error_at(args->back()->location(),
10184 				  "argument 2 has invalid type (%s)",
10185 				  reason.c_str());
10186 		    this->set_is_error();
10187 		    break;
10188 		  }
10189 	      }
10190 	  }
10191 	else
10192 	  {
10193 	    Expression_list::const_iterator pa = args->begin();
10194 	    int i = 2;
10195 	    for (++pa; pa != args->end(); ++pa, ++i)
10196 	      {
10197 		std::string reason;
10198 		if (!Type::are_assignable(element_type, (*pa)->type(),
10199 					  &reason))
10200 		  {
10201 		    if (reason.empty())
10202 		      go_error_at((*pa)->location(),
10203 				  "argument %d has incompatible type", i);
10204 		    else
10205 		      go_error_at((*pa)->location(),
10206 				  "argument %d has incompatible type (%s)",
10207 				  i, reason.c_str());
10208 		    this->set_is_error();
10209 		  }
10210 	      }
10211 	  }
10212       }
10213       break;
10214 
10215     case BUILTIN_REAL:
10216     case BUILTIN_IMAG:
10217       if (this->check_one_arg())
10218 	{
10219 	  if (this->one_arg()->type()->complex_type() == NULL)
10220 	    this->report_error(_("argument must have complex type"));
10221 	}
10222       break;
10223 
10224     case BUILTIN_COMPLEX:
10225       {
10226 	const Expression_list* args = this->args();
10227 	if (args == NULL || args->size() < 2)
10228 	  this->report_error(_("not enough arguments"));
10229 	else if (args->size() > 2)
10230 	  this->report_error(_("too many arguments"));
10231 	else if (args->front()->is_error_expression()
10232 		 || args->front()->type()->is_error()
10233 		 || args->back()->is_error_expression()
10234 		 || args->back()->type()->is_error())
10235 	  this->set_is_error();
10236 	else if (!Type::are_identical(args->front()->type(),
10237 				      args->back()->type(),
10238 				      Type::COMPARE_TAGS, NULL))
10239 	  this->report_error(_("complex arguments must have identical types"));
10240 	else if (args->front()->type()->float_type() == NULL)
10241 	  this->report_error(_("complex arguments must have "
10242 			       "floating-point type"));
10243       }
10244       break;
10245 
10246     default:
10247       go_unreachable();
10248     }
10249 }
10250 
10251 Expression*
do_copy()10252 Builtin_call_expression::do_copy()
10253 {
10254   Call_expression* bce =
10255     new Builtin_call_expression(this->gogo_, this->fn()->copy(),
10256 				(this->args() == NULL
10257 				 ? NULL
10258 				 : this->args()->copy()),
10259 				this->is_varargs(),
10260 				this->location());
10261 
10262   if (this->varargs_are_lowered())
10263     bce->set_varargs_are_lowered();
10264   if (this->is_deferred())
10265     bce->set_is_deferred();
10266   if (this->is_concurrent())
10267     bce->set_is_concurrent();
10268   return bce;
10269 }
10270 
10271 // Return the backend representation for a builtin function.
10272 
10273 Bexpression*
do_get_backend(Translate_context * context)10274 Builtin_call_expression::do_get_backend(Translate_context* context)
10275 {
10276   Gogo* gogo = context->gogo();
10277   Location location = this->location();
10278 
10279   if (this->is_erroneous_call())
10280     {
10281       go_assert(saw_errors());
10282       return gogo->backend()->error_expression();
10283     }
10284 
10285   switch (this->code_)
10286     {
10287     case BUILTIN_INVALID:
10288     case BUILTIN_NEW:
10289     case BUILTIN_MAKE:
10290       go_unreachable();
10291 
10292     case BUILTIN_LEN:
10293     case BUILTIN_CAP:
10294       {
10295 	const Expression_list* args = this->args();
10296 	go_assert(args != NULL && args->size() == 1);
10297 	Expression* arg = args->front();
10298 	Type* arg_type = arg->type();
10299 
10300 	if (this->seen_)
10301 	  {
10302 	    go_assert(saw_errors());
10303 	    return context->backend()->error_expression();
10304 	  }
10305 	this->seen_ = true;
10306 	this->seen_ = false;
10307 	if (arg_type->points_to() != NULL)
10308 	  {
10309 	    arg_type = arg_type->points_to();
10310 	    go_assert(arg_type->array_type() != NULL
10311 		       && !arg_type->is_slice_type());
10312             arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
10313                                                location);
10314 	  }
10315 
10316 	Type* int_type = Type::lookup_integer_type("int");
10317         Expression* val;
10318 	if (this->code_ == BUILTIN_LEN)
10319 	  {
10320 	    if (arg_type->is_string_type())
10321 	      val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
10322 						 location);
10323 	    else if (arg_type->array_type() != NULL)
10324 	      {
10325 		if (this->seen_)
10326 		  {
10327 		    go_assert(saw_errors());
10328 		    return context->backend()->error_expression();
10329 		  }
10330 		this->seen_ = true;
10331 	        val = arg_type->array_type()->get_length(gogo, arg);
10332 		this->seen_ = false;
10333 	      }
10334 	    else if (arg_type->map_type() != NULL
10335 		     || arg_type->channel_type() != NULL)
10336 	      {
10337 		// The first field is the length.  If the pointer is
10338 		// nil, the length is zero.
10339 		Type* pint_type = Type::make_pointer_type(int_type);
10340 		arg = Expression::make_unsafe_cast(pint_type, arg, location);
10341 		Expression* nil = Expression::make_nil(location);
10342 		nil = Expression::make_cast(pint_type, nil, location);
10343 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10344 							  arg, nil, location);
10345 		Expression* zero = Expression::make_integer_ul(0, int_type,
10346 							       location);
10347                 Expression* indir =
10348                     Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
10349                                                  location);
10350 		val = Expression::make_conditional(cmp, zero, indir, location);
10351 	      }
10352 	    else
10353 	      go_unreachable();
10354 	  }
10355 	else
10356 	  {
10357 	    if (arg_type->array_type() != NULL)
10358 	      {
10359 		if (this->seen_)
10360 		  {
10361 		    go_assert(saw_errors());
10362 		    return context->backend()->error_expression();
10363 		  }
10364 		this->seen_ = true;
10365                 val = arg_type->array_type()->get_capacity(gogo, arg);
10366 		this->seen_ = false;
10367 	      }
10368 	    else if (arg_type->channel_type() != NULL)
10369 	      {
10370 		// The second field is the capacity.  If the pointer
10371 		// is nil, the capacity is zero.
10372 		Type* uintptr_type = Type::lookup_integer_type("uintptr");
10373 		Type* pint_type = Type::make_pointer_type(int_type);
10374 		Expression* parg = Expression::make_unsafe_cast(uintptr_type,
10375 								arg,
10376 								location);
10377 		int off = int_type->integer_type()->bits() / 8;
10378 		Expression* eoff = Expression::make_integer_ul(off,
10379 							       uintptr_type,
10380 							       location);
10381 		parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
10382 					       location);
10383 		parg = Expression::make_unsafe_cast(pint_type, parg, location);
10384 		Expression* nil = Expression::make_nil(location);
10385 		nil = Expression::make_cast(pint_type, nil, location);
10386 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10387 							  arg, nil, location);
10388 		Expression* zero = Expression::make_integer_ul(0, int_type,
10389 							       location);
10390                 Expression* indir =
10391                     Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
10392                                                  location);
10393 		val = Expression::make_conditional(cmp, zero, indir, location);
10394 	      }
10395 	    else
10396 	      go_unreachable();
10397 	  }
10398 
10399 	return Expression::make_cast(int_type, val,
10400 				     location)->get_backend(context);
10401       }
10402 
10403     case BUILTIN_PRINT:
10404     case BUILTIN_PRINTLN:
10405       {
10406 	const bool is_ln = this->code_ == BUILTIN_PRINTLN;
10407 
10408 	Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
10409 						     location, 0);
10410 
10411 	const Expression_list* call_args = this->args();
10412 	if (call_args != NULL)
10413 	  {
10414 	    for (Expression_list::const_iterator p = call_args->begin();
10415 		 p != call_args->end();
10416 		 ++p)
10417 	      {
10418 		if (is_ln && p != call_args->begin())
10419 		  {
10420                     Expression* print_space =
10421 		      Runtime::make_call(Runtime::PRINTSP, location, 0);
10422 
10423                     print_stmts =
10424                         Expression::make_compound(print_stmts, print_space,
10425                                                   location);
10426 		  }
10427 
10428                 Expression* arg = *p;
10429 		Type* type = arg->type();
10430                 Runtime::Function code;
10431 		if (type->is_string_type())
10432                   code = Runtime::PRINTSTRING;
10433 		else if (type->integer_type() != NULL
10434 			 && type->integer_type()->is_unsigned())
10435 		  {
10436 		    Type* itype = Type::lookup_integer_type("uint64");
10437 		    arg = Expression::make_cast(itype, arg, location);
10438                     if (gogo->compiling_runtime()
10439                         && type->named_type() != NULL
10440                         && gogo->unpack_hidden_name(type->named_type()->name())
10441                            == "hex")
10442                       code = Runtime::PRINTHEX;
10443                     else
10444                       code = Runtime::PRINTUINT;
10445 		  }
10446 		else if (type->integer_type() != NULL)
10447 		  {
10448 		    Type* itype = Type::lookup_integer_type("int64");
10449 		    arg = Expression::make_cast(itype, arg, location);
10450                     code = Runtime::PRINTINT;
10451 		  }
10452 		else if (type->float_type() != NULL)
10453 		  {
10454                     Type* dtype = Type::lookup_float_type("float64");
10455                     arg = Expression::make_cast(dtype, arg, location);
10456                     code = Runtime::PRINTFLOAT;
10457 		  }
10458 		else if (type->complex_type() != NULL)
10459 		  {
10460                     Type* ctype = Type::lookup_complex_type("complex128");
10461                     arg = Expression::make_cast(ctype, arg, location);
10462                     code = Runtime::PRINTCOMPLEX;
10463 		  }
10464 		else if (type->is_boolean_type())
10465                   code = Runtime::PRINTBOOL;
10466 		else if (type->points_to() != NULL
10467 			 || type->channel_type() != NULL
10468 			 || type->map_type() != NULL
10469 			 || type->function_type() != NULL)
10470 		  {
10471                     arg = Expression::make_cast(type, arg, location);
10472                     code = Runtime::PRINTPOINTER;
10473 		  }
10474 		else if (type->interface_type() != NULL)
10475 		  {
10476 		    if (type->interface_type()->is_empty())
10477                       code = Runtime::PRINTEFACE;
10478 		    else
10479                       code = Runtime::PRINTIFACE;
10480 		  }
10481 		else if (type->is_slice_type())
10482                   code = Runtime::PRINTSLICE;
10483 		else
10484 		  {
10485 		    go_assert(saw_errors());
10486 		    return context->backend()->error_expression();
10487 		  }
10488 
10489                 Expression* call = Runtime::make_call(code, location, 1, arg);
10490 		print_stmts = Expression::make_compound(print_stmts, call,
10491 							location);
10492 	      }
10493 	  }
10494 
10495 	if (is_ln)
10496 	  {
10497             Expression* print_nl =
10498                 Runtime::make_call(Runtime::PRINTNL, location, 0);
10499 	    print_stmts = Expression::make_compound(print_stmts, print_nl,
10500 						    location);
10501 	  }
10502 
10503 	Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
10504 						location, 0);
10505 	print_stmts = Expression::make_compound(print_stmts, unlock, location);
10506 
10507         return print_stmts->get_backend(context);
10508       }
10509 
10510     case BUILTIN_PANIC:
10511       {
10512 	const Expression_list* args = this->args();
10513 	go_assert(args != NULL && args->size() == 1);
10514 	Expression* arg = args->front();
10515 	Type *empty =
10516 	  Type::make_empty_interface_type(Linemap::predeclared_location());
10517         arg = Expression::convert_for_assignment(gogo, empty, arg, location);
10518 
10519         Expression* panic =
10520             Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
10521         return panic->get_backend(context);
10522       }
10523 
10524     case BUILTIN_RECOVER:
10525       {
10526 	// The argument is set when building recover thunks.  It's a
10527 	// boolean value which is true if we can recover a value now.
10528 	const Expression_list* args = this->args();
10529 	go_assert(args != NULL && args->size() == 1);
10530 	Expression* arg = args->front();
10531 	Type *empty =
10532 	  Type::make_empty_interface_type(Linemap::predeclared_location());
10533 
10534 	Expression* nil = Expression::make_nil(location);
10535         nil = Expression::make_interface_value(empty, nil, nil, location);
10536 
10537 	// We need to handle a deferred call to recover specially,
10538 	// because it changes whether it can recover a panic or not.
10539 	// See test7 in test/recover1.go.
10540         Expression* recover = Runtime::make_call((this->is_deferred()
10541                                                   ? Runtime::DEFERREDRECOVER
10542                                                   : Runtime::GORECOVER),
10543                                                  location, 0);
10544         Expression* cond =
10545             Expression::make_conditional(arg, recover, nil, location);
10546         return cond->get_backend(context);
10547       }
10548 
10549     case BUILTIN_CLOSE:
10550       {
10551 	const Expression_list* args = this->args();
10552 	go_assert(args != NULL && args->size() == 1);
10553 	Expression* arg = args->front();
10554         Expression* close = Runtime::make_call(Runtime::CLOSE, location,
10555 					       1, arg);
10556         return close->get_backend(context);
10557       }
10558 
10559     case BUILTIN_SIZEOF:
10560     case BUILTIN_OFFSETOF:
10561     case BUILTIN_ALIGNOF:
10562       {
10563 	Numeric_constant nc;
10564 	unsigned long val;
10565 	if (!this->numeric_constant_value(&nc)
10566 	    || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
10567 	  {
10568 	    go_assert(saw_errors());
10569 	    return context->backend()->error_expression();
10570 	  }
10571 	Type* uintptr_type = Type::lookup_integer_type("uintptr");
10572         mpz_t ival;
10573         nc.get_int(&ival);
10574         Expression* int_cst =
10575             Expression::make_integer_z(&ival, uintptr_type, location);
10576         mpz_clear(ival);
10577         return int_cst->get_backend(context);
10578       }
10579 
10580     case BUILTIN_COPY:
10581       // Handled in Builtin_call_expression::do_flatten.
10582       go_unreachable();
10583 
10584     case BUILTIN_APPEND:
10585       // Handled in Builtin_call_expression::flatten_append.
10586       go_unreachable();
10587 
10588     case BUILTIN_REAL:
10589     case BUILTIN_IMAG:
10590       {
10591 	const Expression_list* args = this->args();
10592 	go_assert(args != NULL && args->size() == 1);
10593 
10594         Bexpression* ret;
10595         Bexpression* bcomplex = args->front()->get_backend(context);
10596         if (this->code_ == BUILTIN_REAL)
10597           ret = gogo->backend()->real_part_expression(bcomplex, location);
10598         else
10599           ret = gogo->backend()->imag_part_expression(bcomplex, location);
10600         return ret;
10601       }
10602 
10603     case BUILTIN_COMPLEX:
10604       {
10605 	const Expression_list* args = this->args();
10606 	go_assert(args != NULL && args->size() == 2);
10607 	Bexpression* breal = args->front()->get_backend(context);
10608 	Bexpression* bimag = args->back()->get_backend(context);
10609 	return gogo->backend()->complex_expression(breal, bimag, location);
10610       }
10611 
10612     default:
10613       go_unreachable();
10614     }
10615 }
10616 
10617 // We have to support exporting a builtin call expression, because
10618 // code can set a constant to the result of a builtin expression.
10619 
10620 void
do_export(Export_function_body * efb) const10621 Builtin_call_expression::do_export(Export_function_body* efb) const
10622 {
10623   Numeric_constant nc;
10624   if (this->numeric_constant_value(&nc))
10625     {
10626       if (nc.is_int())
10627 	{
10628 	  mpz_t val;
10629 	  nc.get_int(&val);
10630 	  Integer_expression::export_integer(efb, val);
10631 	  mpz_clear(val);
10632 	}
10633       else if (nc.is_float())
10634 	{
10635 	  mpfr_t fval;
10636 	  nc.get_float(&fval);
10637 	  Float_expression::export_float(efb, fval);
10638 	  mpfr_clear(fval);
10639 	}
10640       else if (nc.is_complex())
10641 	{
10642 	  mpc_t cval;
10643 	  nc.get_complex(&cval);
10644 	  Complex_expression::export_complex(efb, cval);
10645 	  mpc_clear(cval);
10646 	}
10647       else
10648 	go_unreachable();
10649 
10650       // A trailing space lets us reliably identify the end of the number.
10651       efb->write_c_string(" ");
10652     }
10653   else
10654     {
10655       const char *s = NULL;
10656       switch (this->code_)
10657 	{
10658 	default:
10659 	  go_unreachable();
10660 	case BUILTIN_APPEND:
10661 	  s = "append";
10662 	  break;
10663 	case BUILTIN_COPY:
10664 	  s = "copy";
10665 	  break;
10666 	case BUILTIN_LEN:
10667 	  s = "len";
10668 	  break;
10669 	case BUILTIN_CAP:
10670 	  s = "cap";
10671 	  break;
10672 	case BUILTIN_DELETE:
10673 	  s = "delete";
10674 	  break;
10675 	case BUILTIN_PRINT:
10676 	  s = "print";
10677 	  break;
10678 	case BUILTIN_PRINTLN:
10679 	  s = "println";
10680 	  break;
10681 	case BUILTIN_PANIC:
10682 	  s = "panic";
10683 	  break;
10684 	case BUILTIN_RECOVER:
10685 	  s = "recover";
10686 	  break;
10687 	case BUILTIN_CLOSE:
10688 	  s = "close";
10689 	  break;
10690 	case BUILTIN_REAL:
10691 	  s = "real";
10692 	  break;
10693 	case BUILTIN_IMAG:
10694 	  s = "imag";
10695 	  break;
10696 	case BUILTIN_COMPLEX:
10697 	  s = "complex";
10698 	  break;
10699 	}
10700       efb->write_c_string(s);
10701       this->export_arguments(efb);
10702     }
10703 }
10704 
10705 // Class Call_expression.
10706 
10707 // A Go function can be viewed in a couple of different ways.  The
10708 // code of a Go function becomes a backend function with parameters
10709 // whose types are simply the backend representation of the Go types.
10710 // If there are multiple results, they are returned as a backend
10711 // struct.
10712 
10713 // However, when Go code refers to a function other than simply
10714 // calling it, the backend type of that function is actually a struct.
10715 // The first field of the struct points to the Go function code
10716 // (sometimes a wrapper as described below).  The remaining fields
10717 // hold addresses of closed-over variables.  This struct is called a
10718 // closure.
10719 
10720 // There are a few cases to consider.
10721 
10722 // A direct function call of a known function in package scope.  In
10723 // this case there are no closed-over variables, and we know the name
10724 // of the function code.  We can simply produce a backend call to the
10725 // function directly, and not worry about the closure.
10726 
10727 // A direct function call of a known function literal.  In this case
10728 // we know the function code and we know the closure.  We generate the
10729 // function code such that it expects an additional final argument of
10730 // the closure type.  We pass the closure as the last argument, after
10731 // the other arguments.
10732 
10733 // An indirect function call.  In this case we have a closure.  We
10734 // load the pointer to the function code from the first field of the
10735 // closure.  We pass the address of the closure as the last argument.
10736 
10737 // A call to a method of an interface.  Type methods are always at
10738 // package scope, so we call the function directly, and don't worry
10739 // about the closure.
10740 
10741 // This means that for a function at package scope we have two cases.
10742 // One is the direct call, which has no closure.  The other is the
10743 // indirect call, which does have a closure.  We can't simply ignore
10744 // the closure, even though it is the last argument, because that will
10745 // fail on targets where the function pops its arguments.  So when
10746 // generating a closure for a package-scope function we set the
10747 // function code pointer in the closure to point to a wrapper
10748 // function.  This wrapper function accepts a final argument that
10749 // points to the closure, ignores it, and calls the real function as a
10750 // direct function call.  This wrapper will normally be efficient, and
10751 // can often simply be a tail call to the real function.
10752 
10753 // We don't use GCC's static chain pointer because 1) we don't need
10754 // it; 2) GCC only permits using a static chain to call a known
10755 // function, so we can't use it for an indirect call anyhow.  Since we
10756 // can't use it for an indirect call, we may as well not worry about
10757 // using it for a direct call either.
10758 
10759 // We pass the closure last rather than first because it means that
10760 // the function wrapper we put into a closure for a package-scope
10761 // function can normally just be a tail call to the real function.
10762 
10763 // For method expressions we generate a wrapper that loads the
10764 // receiver from the closure and then calls the method.  This
10765 // unfortunately forces reshuffling the arguments, since there is a
10766 // new first argument, but we can't avoid reshuffling either for
10767 // method expressions or for indirect calls of package-scope
10768 // functions, and since the latter are more common we reshuffle for
10769 // method expressions.
10770 
10771 // Note that the Go code retains the Go types.  The extra final
10772 // argument only appears when we convert to the backend
10773 // representation.
10774 
10775 // Traversal.
10776 
10777 int
do_traverse(Traverse * traverse)10778 Call_expression::do_traverse(Traverse* traverse)
10779 {
10780   // If we are calling a function in a different package that returns
10781   // an unnamed type, this may be the only chance we get to traverse
10782   // that type.  We don't traverse this->type_ because it may be a
10783   // Call_multiple_result_type that will just lead back here.
10784   if (this->type_ != NULL && !this->type_->is_error_type())
10785     {
10786       Function_type *fntype = this->get_function_type();
10787       if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
10788 	return TRAVERSE_EXIT;
10789     }
10790   if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
10791     return TRAVERSE_EXIT;
10792   if (this->args_ != NULL)
10793     {
10794       if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
10795 	return TRAVERSE_EXIT;
10796     }
10797   return TRAVERSE_CONTINUE;
10798 }
10799 
10800 // Lower a call statement.
10801 
10802 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)10803 Call_expression::do_lower(Gogo* gogo, Named_object* function,
10804 			  Statement_inserter* inserter, int)
10805 {
10806   Location loc = this->location();
10807 
10808   // A type cast can look like a function call.
10809   if (this->fn_->is_type_expression()
10810       && this->args_ != NULL
10811       && this->args_->size() == 1)
10812     return Expression::make_cast(this->fn_->type(), this->args_->front(),
10813 				 loc);
10814 
10815   // Because do_type will return an error type and thus prevent future
10816   // errors, check for that case now to ensure that the error gets
10817   // reported.
10818   Function_type* fntype = this->get_function_type();
10819   if (fntype == NULL)
10820     {
10821       if (!this->fn_->type()->is_error())
10822 	this->report_error(_("expected function"));
10823       this->set_is_error();
10824       return this;
10825     }
10826 
10827   // Handle an argument which is a call to a function which returns
10828   // multiple results.
10829   if (this->args_ != NULL
10830       && this->args_->size() == 1
10831       && this->args_->front()->call_expression() != NULL)
10832     {
10833       size_t rc = this->args_->front()->call_expression()->result_count();
10834       if (rc > 1
10835 	  && ((fntype->parameters() != NULL
10836                && (fntype->parameters()->size() == rc
10837                    || (fntype->is_varargs()
10838                        && fntype->parameters()->size() - 1 <= rc)))
10839               || fntype->is_builtin()))
10840 	{
10841 	  Call_expression* call = this->args_->front()->call_expression();
10842 	  call->set_is_multi_value_arg();
10843 	  if (this->is_varargs_)
10844 	    {
10845 	      // It is not clear which result of a multiple result call
10846 	      // the ellipsis operator should be applied to.  If we unpack the
10847 	      // the call into its individual results here, the ellipsis will be
10848 	      // applied to the last result.
10849 	      go_error_at(call->location(),
10850 			  _("multiple-value argument in single-value context"));
10851 	      return Expression::make_error(call->location());
10852 	    }
10853 
10854 	  Expression_list* args = new Expression_list;
10855 	  for (size_t i = 0; i < rc; ++i)
10856 	    args->push_back(Expression::make_call_result(call, i));
10857 	  // We can't return a new call expression here, because this
10858 	  // one may be referenced by Call_result expressions.  We
10859 	  // also can't delete the old arguments, because we may still
10860 	  // traverse them somewhere up the call stack.  FIXME.
10861 	  this->args_ = args;
10862 	}
10863     }
10864 
10865   // Recognize a call to a builtin function.
10866   if (fntype->is_builtin())
10867     {
10868       Builtin_call_expression* bce =
10869 	new Builtin_call_expression(gogo, this->fn_, this->args_,
10870 				    this->is_varargs_, loc);
10871       if (this->is_deferred_)
10872 	bce->set_is_deferred();
10873       if (this->is_concurrent_)
10874 	bce->set_is_concurrent();
10875       return bce;
10876     }
10877 
10878   // If this call returns multiple results, create a temporary
10879   // variable to hold them.
10880   if (this->result_count() > 1 && this->call_temp_ == NULL)
10881     {
10882       Struct_field_list* sfl = new Struct_field_list();
10883       const Typed_identifier_list* results = fntype->results();
10884 
10885       int i = 0;
10886       char buf[20];
10887       for (Typed_identifier_list::const_iterator p = results->begin();
10888            p != results->end();
10889            ++p, ++i)
10890         {
10891           snprintf(buf, sizeof buf, "res%d", i);
10892           sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
10893         }
10894 
10895       Struct_type* st = Type::make_struct_type(sfl, loc);
10896       st->set_is_struct_incomparable();
10897       this->call_temp_ = Statement::make_temporary(st, NULL, loc);
10898       inserter->insert(this->call_temp_);
10899     }
10900 
10901   // Handle a call to a varargs function by packaging up the extra
10902   // parameters.
10903   if (fntype->is_varargs())
10904     {
10905       const Typed_identifier_list* parameters = fntype->parameters();
10906       go_assert(parameters != NULL && !parameters->empty());
10907       Type* varargs_type = parameters->back().type();
10908       this->lower_varargs(gogo, function, inserter, varargs_type,
10909 			  parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
10910     }
10911 
10912   // If this is call to a method, call the method directly passing the
10913   // object as the first parameter.
10914   Bound_method_expression* bme = this->fn_->bound_method_expression();
10915   if (bme != NULL)
10916     {
10917       Named_object* methodfn = bme->function();
10918       Function_type* mft = (methodfn->is_function()
10919                             ? methodfn->func_value()->type()
10920                             : methodfn->func_declaration_value()->type());
10921       Expression* first_arg = bme->first_argument();
10922 
10923       // We always pass a pointer when calling a method, except for
10924       // direct interface types when calling a value method.
10925       if (!first_arg->type()->is_error()
10926           && !first_arg->type()->is_direct_iface_type())
10927 	{
10928 	  first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
10929 	  // We may need to create a temporary variable so that we can
10930 	  // take the address.  We can't do that here because it will
10931 	  // mess up the order of evaluation.
10932 	  Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
10933 	  ue->set_create_temp();
10934 	}
10935       else if (mft->receiver()->type()->points_to() == NULL
10936                && first_arg->type()->points_to() != NULL
10937                && first_arg->type()->points_to()->is_direct_iface_type())
10938         first_arg = Expression::make_dereference(first_arg,
10939                                                  Expression::NIL_CHECK_DEFAULT,
10940                                                  loc);
10941 
10942       // If we are calling a method which was inherited from an
10943       // embedded struct, and the method did not get a stub, then the
10944       // first type may be wrong.
10945       Type* fatype = bme->first_argument_type();
10946       if (fatype != NULL)
10947 	{
10948 	  if (fatype->points_to() == NULL)
10949 	    fatype = Type::make_pointer_type(fatype);
10950 	  first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
10951 	}
10952 
10953       Expression_list* new_args = new Expression_list();
10954       new_args->push_back(first_arg);
10955       if (this->args_ != NULL)
10956 	{
10957 	  for (Expression_list::const_iterator p = this->args_->begin();
10958 	       p != this->args_->end();
10959 	       ++p)
10960 	    new_args->push_back(*p);
10961 	}
10962 
10963       // We have to change in place because this structure may be
10964       // referenced by Call_result_expressions.  We can't delete the
10965       // old arguments, because we may be traversing them up in some
10966       // caller.  FIXME.
10967       this->args_ = new_args;
10968       this->fn_ = Expression::make_func_reference(methodfn, NULL,
10969 						  bme->location());
10970     }
10971 
10972   // If this is a call to an imported function for which we have an
10973   // inlinable function body, add it to the list of functions to give
10974   // to the backend as inlining opportunities.
10975   Func_expression* fe = this->fn_->func_expression();
10976   if (fe != NULL
10977       && fe->named_object()->is_function_declaration()
10978       && fe->named_object()->func_declaration_value()->has_imported_body())
10979     gogo->add_imported_inlinable_function(fe->named_object());
10980 
10981   return this;
10982 }
10983 
10984 // Lower a call to a varargs function.  FUNCTION is the function in
10985 // which the call occurs--it's not the function we are calling.
10986 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
10987 // PARAM_COUNT is the number of parameters of the function we are
10988 // calling; the last of these parameters will be the varargs
10989 // parameter.
10990 
10991 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count,Slice_storage_escape_disp escape_disp)10992 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
10993 			       Statement_inserter* inserter,
10994 			       Type* varargs_type, size_t param_count,
10995                                Slice_storage_escape_disp escape_disp)
10996 {
10997   if (this->varargs_are_lowered_)
10998     return;
10999 
11000   Location loc = this->location();
11001 
11002   go_assert(param_count > 0);
11003   go_assert(varargs_type->is_slice_type());
11004 
11005   size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
11006   if (arg_count < param_count - 1)
11007     {
11008       // Not enough arguments; will be caught in check_types.
11009       return;
11010     }
11011 
11012   Expression_list* old_args = this->args_;
11013   Expression_list* new_args = new Expression_list();
11014   bool push_empty_arg = false;
11015   if (old_args == NULL || old_args->empty())
11016     {
11017       go_assert(param_count == 1);
11018       push_empty_arg = true;
11019     }
11020   else
11021     {
11022       Expression_list::const_iterator pa;
11023       int i = 1;
11024       for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
11025 	{
11026 	  if (static_cast<size_t>(i) == param_count)
11027 	    break;
11028 	  new_args->push_back(*pa);
11029 	}
11030 
11031       // We have reached the varargs parameter.
11032 
11033       bool issued_error = false;
11034       if (pa == old_args->end())
11035 	push_empty_arg = true;
11036       else if (pa + 1 == old_args->end() && this->is_varargs_)
11037 	new_args->push_back(*pa);
11038       else if (this->is_varargs_)
11039 	{
11040 	  if ((*pa)->type()->is_slice_type())
11041 	    this->report_error(_("too many arguments"));
11042 	  else
11043 	    {
11044 	      go_error_at(this->location(),
11045 			  _("invalid use of %<...%> with non-slice"));
11046 	      this->set_is_error();
11047 	    }
11048 	  return;
11049 	}
11050       else
11051 	{
11052 	  Type* element_type = varargs_type->array_type()->element_type();
11053 	  Expression_list* vals = new Expression_list;
11054 	  for (; pa != old_args->end(); ++pa, ++i)
11055 	    {
11056 	      // Check types here so that we get a better message.
11057 	      Type* patype = (*pa)->type();
11058 	      Location paloc = (*pa)->location();
11059 	      if (!this->check_argument_type(i, element_type, patype,
11060 					     paloc, issued_error))
11061 		continue;
11062 	      vals->push_back(*pa);
11063 	    }
11064 	  Slice_construction_expression* sce =
11065 	    Expression::make_slice_composite_literal(varargs_type, vals, loc);
11066 	  if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
11067 	      sce->set_storage_does_not_escape();
11068           Expression* val = sce;
11069 	  gogo->lower_expression(function, inserter, &val);
11070 	  new_args->push_back(val);
11071 	}
11072     }
11073 
11074   if (push_empty_arg)
11075     new_args->push_back(Expression::make_nil(loc));
11076 
11077   // We can't return a new call expression here, because this one may
11078   // be referenced by Call_result expressions.  FIXME.  We can't
11079   // delete OLD_ARGS because we may have both a Call_expression and a
11080   // Builtin_call_expression which refer to them.  FIXME.
11081   this->args_ = new_args;
11082   this->varargs_are_lowered_ = true;
11083 }
11084 
11085 // Flatten a call with multiple results into a temporary.
11086 
11087 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)11088 Call_expression::do_flatten(Gogo* gogo, Named_object*,
11089 			    Statement_inserter* inserter)
11090 {
11091   if (this->is_erroneous_call())
11092     {
11093       go_assert(saw_errors());
11094       return Expression::make_error(this->location());
11095     }
11096 
11097   if (this->is_flattened_)
11098     return this;
11099   this->is_flattened_ = true;
11100 
11101   // Add temporary variables for all arguments that require type
11102   // conversion.
11103   Function_type* fntype = this->get_function_type();
11104   if (fntype == NULL)
11105     {
11106       go_assert(saw_errors());
11107       return this;
11108     }
11109   if (this->args_ != NULL && !this->args_->empty()
11110       && fntype->parameters() != NULL && !fntype->parameters()->empty())
11111     {
11112       bool is_interface_method =
11113 	this->fn_->interface_field_reference_expression() != NULL;
11114 
11115       Expression_list *args = new Expression_list();
11116       Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11117       Expression_list::const_iterator pa = this->args_->begin();
11118       if (!is_interface_method && fntype->is_method())
11119 	{
11120 	  // The receiver argument.
11121 	  args->push_back(*pa);
11122 	  ++pa;
11123 	}
11124       for (; pa != this->args_->end(); ++pa, ++pp)
11125 	{
11126 	  go_assert(pp != fntype->parameters()->end());
11127 	  if (Type::are_identical(pp->type(), (*pa)->type(),
11128 				  Type::COMPARE_TAGS, NULL))
11129 	    args->push_back(*pa);
11130 	  else
11131 	    {
11132 	      Location loc = (*pa)->location();
11133 	      Expression* arg = *pa;
11134 	      if (!arg->is_variable())
11135 		{
11136 		  Temporary_statement *temp =
11137 		    Statement::make_temporary(NULL, arg, loc);
11138 		  inserter->insert(temp);
11139 		  arg = Expression::make_temporary_reference(temp, loc);
11140 		}
11141 	      arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
11142 						       loc);
11143 	      args->push_back(arg);
11144 	    }
11145 	}
11146       delete this->args_;
11147       this->args_ = args;
11148     }
11149 
11150   // Lower to compiler intrinsic if possible.
11151   Func_expression* fe = this->fn_->func_expression();
11152   if (!this->is_concurrent_ && !this->is_deferred_
11153       && fe != NULL
11154       && (fe->named_object()->is_function_declaration()
11155           || fe->named_object()->is_function()))
11156     {
11157       Expression* ret = this->intrinsify(gogo, inserter);
11158       if (ret != NULL)
11159         return ret;
11160     }
11161 
11162   return this;
11163 }
11164 
11165 // Lower a call to a compiler intrinsic if possible.
11166 // Returns NULL if it is not an intrinsic.
11167 
11168 Expression*
intrinsify(Gogo * gogo,Statement_inserter * inserter)11169 Call_expression::intrinsify(Gogo* gogo,
11170                             Statement_inserter* inserter)
11171 {
11172   Func_expression* fe = this->fn_->func_expression();
11173   Named_object* no = fe->named_object();
11174   std::string name = Gogo::unpack_hidden_name(no->name());
11175   std::string package = (no->package() != NULL
11176                          ? no->package()->pkgpath()
11177                          : gogo->pkgpath());
11178   Location loc = this->location();
11179 
11180   Type* int_type = Type::lookup_integer_type("int");
11181   Type* int32_type = Type::lookup_integer_type("int32");
11182   Type* int64_type = Type::lookup_integer_type("int64");
11183   Type* uint_type = Type::lookup_integer_type("uint");
11184   Type* uint32_type = Type::lookup_integer_type("uint32");
11185   Type* uint64_type = Type::lookup_integer_type("uint64");
11186   Type* uintptr_type = Type::lookup_integer_type("uintptr");
11187   Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
11188 
11189   int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
11190   int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
11191 
11192   if (package == "sync/atomic")
11193     {
11194       // sync/atomic functions and runtime/internal/atomic functions
11195       // are very similar. In order not to duplicate code, we just
11196       // redirect to the latter and let the code below to handle them.
11197       // In case there is no equivalent functions (slight variance
11198       // in types), we just make an artificial name (begin with '$').
11199       // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
11200       // as they need write barriers.
11201       if (name == "LoadInt32")
11202         name = "$Loadint32";
11203       else if (name == "LoadInt64")
11204         name = "Loadint64";
11205       else if (name == "LoadUint32")
11206         name = "Load";
11207       else if (name == "LoadUint64")
11208         name = "Load64";
11209       else if (name == "LoadUintptr")
11210         name = "Loaduintptr";
11211       else if (name == "LoadPointer")
11212         name = "Loadp";
11213       else if (name == "StoreInt32")
11214         name = "$Storeint32";
11215       else if (name == "StoreInt64")
11216         name = "$Storeint64";
11217       else if (name == "StoreUint32")
11218         name = "Store";
11219       else if (name == "StoreUint64")
11220         name = "Store64";
11221       else if (name == "StoreUintptr")
11222         name = "Storeuintptr";
11223       else if (name == "AddInt32")
11224         name = "$Xaddint32";
11225       else if (name == "AddInt64")
11226         name = "Xaddint64";
11227       else if (name == "AddUint32")
11228         name = "Xadd";
11229       else if (name == "AddUint64")
11230         name = "Xadd64";
11231       else if (name == "AddUintptr")
11232         name = "Xadduintptr";
11233       else if (name == "SwapInt32")
11234         name = "$Xchgint32";
11235       else if (name == "SwapInt64")
11236         name = "$Xchgint64";
11237       else if (name == "SwapUint32")
11238         name = "Xchg";
11239       else if (name == "SwapUint64")
11240         name = "Xchg64";
11241       else if (name == "SwapUintptr")
11242         name = "Xchguintptr";
11243       else if (name == "CompareAndSwapInt32")
11244         name = "$Casint32";
11245       else if (name == "CompareAndSwapInt64")
11246         name = "$Casint64";
11247       else if (name == "CompareAndSwapUint32")
11248         name = "Cas";
11249       else if (name == "CompareAndSwapUint64")
11250         name = "Cas64";
11251       else if (name == "CompareAndSwapUintptr")
11252         name = "Casuintptr";
11253       else
11254         return NULL;
11255 
11256       package = "runtime/internal/atomic";
11257     }
11258 
11259   if (package == "runtime/internal/sys")
11260     {
11261       // runtime/internal/sys functions and math/bits functions
11262       // are very similar. In order not to duplicate code, we just
11263       // redirect to the latter and let the code below to handle them.
11264       if (name == "Bswap32")
11265         name = "ReverseBytes32";
11266       else if (name == "Bswap64")
11267         name = "ReverseBytes64";
11268       else if (name == "Ctz32")
11269         name = "TrailingZeros32";
11270       else if (name == "Ctz64")
11271         name = "TrailingZeros64";
11272       else
11273         return NULL;
11274 
11275       package = "math/bits";
11276     }
11277 
11278   if (package == "runtime")
11279     {
11280       // Handle a couple of special runtime functions.  In the runtime
11281       // package, getcallerpc returns the PC of the caller, and
11282       // getcallersp returns the frame pointer of the caller.  Implement
11283       // these by turning them into calls to GCC builtin functions.  We
11284       // could implement them in normal code, but then we would have to
11285       // explicitly unwind the stack.  These functions are intended to be
11286       // efficient.  Note that this technique obviously only works for
11287       // direct calls, but that is the only way they are used.
11288       if (name == "getcallerpc"
11289           && (this->args_ == NULL || this->args_->size() == 0))
11290         {
11291           Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
11292           Expression* call =
11293             Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, loc,
11294                                1, arg);
11295           // The builtin functions return void*, but the Go functions return uintptr.
11296           return Expression::make_cast(uintptr_type, call, loc);
11297         }
11298       else if (name == "getcallersp"
11299                && (this->args_ == NULL || this->args_->size() == 0))
11300 
11301         {
11302           Expression* call =
11303             Runtime::make_call(Runtime::BUILTIN_DWARF_CFA, loc, 0);
11304           // The builtin functions return void*, but the Go functions return uintptr.
11305           return Expression::make_cast(uintptr_type, call, loc);
11306         }
11307     }
11308   else if (package == "math/bits")
11309     {
11310       if ((name == "ReverseBytes16" || name == "ReverseBytes32"
11311            || name == "ReverseBytes64" || name == "ReverseBytes")
11312           && this->args_ != NULL && this->args_->size() == 1)
11313         {
11314           Runtime::Function code;
11315           if (name == "ReverseBytes16")
11316             code = Runtime::BUILTIN_BSWAP16;
11317           else if (name == "ReverseBytes32")
11318             code = Runtime::BUILTIN_BSWAP32;
11319           else if (name == "ReverseBytes64")
11320             code = Runtime::BUILTIN_BSWAP64;
11321           else if (name == "ReverseBytes")
11322             code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
11323           else
11324             go_unreachable();
11325           Expression* arg = this->args_->front();
11326           Expression* call = Runtime::make_call(code, loc, 1, arg);
11327           if (name == "ReverseBytes")
11328             return Expression::make_cast(uint_type, call, loc);
11329           return call;
11330         }
11331       else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
11332                && this->args_ != NULL && this->args_->size() == 1)
11333         {
11334           // GCC does not have a ctz8 or ctz16 intrinsic. We do
11335           // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
11336           Expression* arg = this->args_->front();
11337           arg = Expression::make_cast(uint32_type, arg, loc);
11338           unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
11339           Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
11340           arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11341           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg);
11342           return Expression::make_cast(int_type, call, loc);
11343         }
11344       else if ((name == "TrailingZeros32"
11345                 || (name == "TrailingZeros" && int_size == 4))
11346                && this->args_ != NULL && this->args_->size() == 1)
11347         {
11348           Expression* arg = this->args_->front();
11349           if (!arg->is_variable())
11350             {
11351               Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11352               inserter->insert(ts);
11353               arg = Expression::make_temporary_reference(ts, loc);
11354             }
11355           // arg == 0 ? 32 : __builtin_ctz(arg)
11356           Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11357           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11358           Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11359           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg->copy());
11360           call = Expression::make_cast(int_type, call, loc);
11361           return Expression::make_conditional(cmp, c32, call, loc);
11362         }
11363       else if ((name == "TrailingZeros64"
11364                 || (name == "TrailingZeros" && int_size == 8))
11365                && this->args_ != NULL && this->args_->size() == 1)
11366         {
11367           Expression* arg = this->args_->front();
11368           if (!arg->is_variable())
11369             {
11370               Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11371               inserter->insert(ts);
11372               arg = Expression::make_temporary_reference(ts, loc);
11373             }
11374           // arg == 0 ? 64 : __builtin_ctzll(arg)
11375           Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11376           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11377           Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11378           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZLL, loc, 1, arg->copy());
11379           call = Expression::make_cast(int_type, call, loc);
11380           return Expression::make_conditional(cmp, c64, call, loc);
11381         }
11382       else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
11383                 || name == "Len8" || name == "Len16")
11384                && this->args_ != NULL && this->args_->size() == 1)
11385         {
11386           // GCC does not have a clz8 ir clz16 intrinsic. We do
11387           // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
11388           Expression* arg = this->args_->front();
11389           arg = Expression::make_cast(uint32_type, arg, loc);
11390           unsigned long shift =
11391             ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
11392           Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
11393           arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
11394           unsigned long mask =
11395             ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
11396           c = Expression::make_integer_ul(mask, uint32_type, loc);
11397           arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11398           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg);
11399           call = Expression::make_cast(int_type, call, loc);
11400           // len = width - clz
11401           if (name == "Len8")
11402             {
11403               c = Expression::make_integer_ul(8, int_type, loc);
11404               return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11405             }
11406           else if (name == "Len16")
11407             {
11408               c = Expression::make_integer_ul(16, int_type, loc);
11409               return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11410             }
11411           return call;
11412         }
11413       else if ((name == "LeadingZeros32" || name == "Len32"
11414                 || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
11415                && this->args_ != NULL && this->args_->size() == 1)
11416         {
11417           Expression* arg = this->args_->front();
11418           if (!arg->is_variable())
11419             {
11420               Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11421               inserter->insert(ts);
11422               arg = Expression::make_temporary_reference(ts, loc);
11423             }
11424           // arg == 0 ? 32 : __builtin_clz(arg)
11425           Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11426           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11427           Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11428           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg->copy());
11429           call = Expression::make_cast(int_type, call, loc);
11430           Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
11431           // len = 32 - clz
11432           if (name == "Len32" || name == "Len")
11433             return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
11434           return cond;
11435         }
11436       else if ((name == "LeadingZeros64" || name == "Len64"
11437                 || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
11438                && this->args_ != NULL && this->args_->size() == 1)
11439         {
11440           Expression* arg = this->args_->front();
11441           if (!arg->is_variable())
11442             {
11443               Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11444               inserter->insert(ts);
11445               arg = Expression::make_temporary_reference(ts, loc);
11446             }
11447           // arg == 0 ? 64 : __builtin_clzll(arg)
11448           Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11449           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11450           Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11451           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZLL, loc, 1, arg->copy());
11452           call = Expression::make_cast(int_type, call, loc);
11453           Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
11454           // len = 64 - clz
11455           if (name == "Len64" || name == "Len")
11456             return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
11457           return cond;
11458         }
11459       else if ((name == "OnesCount8" || name == "OnesCount16"
11460            || name == "OnesCount32" || name == "OnesCount64"
11461            || name == "OnesCount")
11462           && this->args_ != NULL && this->args_->size() == 1)
11463         {
11464           Runtime::Function code;
11465           if (name == "OnesCount64")
11466             code = Runtime::BUILTIN_POPCOUNTLL;
11467           else if (name == "OnesCount")
11468             code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
11469           else
11470             code = Runtime::BUILTIN_POPCOUNT;
11471           Expression* arg = this->args_->front();
11472           Expression* call = Runtime::make_call(code, loc, 1, arg);
11473           return Expression::make_cast(int_type, call, loc);
11474         }
11475     }
11476   else if (package == "runtime/internal/atomic")
11477     {
11478       int memorder = __ATOMIC_SEQ_CST;
11479 
11480       if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
11481            || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
11482            || name == "$Loadint32")
11483           && this->args_ != NULL && this->args_->size() == 1)
11484         {
11485           if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
11486             // On 32-bit architectures we need to check alignment.
11487             // Not intrinsify for now.
11488             return NULL;
11489 
11490           Runtime::Function code;
11491           Type* res_type;
11492           if (name == "Load")
11493             {
11494               code = Runtime::ATOMIC_LOAD_4;
11495               res_type = uint32_type;
11496             }
11497           else if (name == "Load64")
11498             {
11499               code = Runtime::ATOMIC_LOAD_8;
11500               res_type = uint64_type;
11501             }
11502           else if (name == "$Loadint32")
11503             {
11504               code = Runtime::ATOMIC_LOAD_4;
11505               res_type = int32_type;
11506             }
11507           else if (name == "Loadint64")
11508             {
11509               code = Runtime::ATOMIC_LOAD_8;
11510               res_type = int64_type;
11511             }
11512           else if (name == "Loaduint")
11513             {
11514               code = (int_size == 8
11515                       ? Runtime::ATOMIC_LOAD_8
11516                       : Runtime::ATOMIC_LOAD_4);
11517               res_type = uint_type;
11518             }
11519           else if (name == "Loaduintptr")
11520             {
11521               code = (ptr_size == 8
11522                       ? Runtime::ATOMIC_LOAD_8
11523                       : Runtime::ATOMIC_LOAD_4);
11524               res_type = uintptr_type;
11525             }
11526           else if (name == "Loadp")
11527             {
11528               code = (ptr_size == 8
11529                       ? Runtime::ATOMIC_LOAD_8
11530                       : Runtime::ATOMIC_LOAD_4);
11531               res_type = pointer_type;
11532             }
11533           else if (name == "LoadAcq")
11534             {
11535               code = Runtime::ATOMIC_LOAD_4;
11536               res_type = uint32_type;
11537               memorder = __ATOMIC_ACQUIRE;
11538             }
11539           else
11540             go_unreachable();
11541           Expression* a1 = this->args_->front();
11542           Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
11543           Expression* call = Runtime::make_call(code, loc, 2, a1, a2);
11544           return Expression::make_unsafe_cast(res_type, call, loc);
11545         }
11546 
11547       if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
11548            || name == "Storeuintptr" || name == "StoreRel"
11549            || name == "$Storeint32" || name == "$Storeint64")
11550           && this->args_ != NULL && this->args_->size() == 2)
11551         {
11552           if (int_size < 8 && (name == "Store64" || name == "$Storeint64"))
11553             return NULL;
11554 
11555           Runtime::Function code;
11556           Expression* a1 = this->args_->at(0);
11557           Expression* a2 = this->args_->at(1);
11558           if (name == "Store")
11559             code = Runtime::ATOMIC_STORE_4;
11560           else if (name == "Store64")
11561             code = Runtime::ATOMIC_STORE_8;
11562           else if (name == "$Storeint32")
11563             code = Runtime::ATOMIC_STORE_4;
11564           else if (name == "$Storeint64")
11565             code = Runtime::ATOMIC_STORE_8;
11566           else if (name == "Storeuintptr")
11567             code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11568           else if (name == "StorepNoWB")
11569             {
11570               code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11571               a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
11572               a2 = Expression::make_cast(uint64_type, a2, loc);
11573             }
11574           else if (name == "StoreRel")
11575             {
11576               code = Runtime::ATOMIC_STORE_4;
11577               memorder = __ATOMIC_RELEASE;
11578             }
11579           else
11580             go_unreachable();
11581           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11582           return Runtime::make_call(code, loc, 3, a1, a2, a3);
11583         }
11584 
11585       if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
11586            || name == "$Xchgint32" || name == "$Xchgint64")
11587           && this->args_ != NULL && this->args_->size() == 2)
11588         {
11589           if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
11590             return NULL;
11591 
11592           Runtime::Function code;
11593           Type* res_type;
11594           if (name == "Xchg")
11595             {
11596               code = Runtime::ATOMIC_EXCHANGE_4;
11597               res_type = uint32_type;
11598             }
11599           else if (name == "Xchg64")
11600             {
11601               code = Runtime::ATOMIC_EXCHANGE_8;
11602               res_type = uint64_type;
11603             }
11604           else if (name == "$Xchgint32")
11605             {
11606               code = Runtime::ATOMIC_EXCHANGE_4;
11607               res_type = int32_type;
11608             }
11609           else if (name == "$Xchgint64")
11610             {
11611               code = Runtime::ATOMIC_EXCHANGE_8;
11612               res_type = int64_type;
11613             }
11614           else if (name == "Xchguintptr")
11615             {
11616               code = (ptr_size == 8
11617                       ? Runtime::ATOMIC_EXCHANGE_8
11618                       : Runtime::ATOMIC_EXCHANGE_4);
11619               res_type = uintptr_type;
11620             }
11621           else
11622             go_unreachable();
11623           Expression* a1 = this->args_->at(0);
11624           Expression* a2 = this->args_->at(1);
11625           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11626           Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11627           return Expression::make_cast(res_type, call, loc);
11628         }
11629 
11630       if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
11631            || name == "Casp1" || name == "CasRel"
11632            || name == "$Casint32" || name == "$Casint64")
11633           && this->args_ != NULL && this->args_->size() == 3)
11634         {
11635           if (int_size < 8 && (name == "Cas64" || name == "$Casint64"))
11636             return NULL;
11637 
11638           Runtime::Function code;
11639           Expression* a1 = this->args_->at(0);
11640 
11641           // Builtin cas takes a pointer to the old value.
11642           // Store it in a temporary and take the address.
11643           Expression* a2 = this->args_->at(1);
11644           Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
11645           inserter->insert(ts);
11646           a2 = Expression::make_temporary_reference(ts, loc);
11647           a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
11648 
11649           Expression* a3 = this->args_->at(2);
11650           if (name == "Cas")
11651             code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11652           else if (name == "Cas64")
11653             code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11654           else if (name == "$Casint32")
11655             code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11656           else if (name == "$Casint64")
11657             code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11658           else if (name == "Casuintptr")
11659             code = (ptr_size == 8
11660                     ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11661                     : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11662           else if (name == "Casp1")
11663             {
11664               code = (ptr_size == 8
11665                       ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11666                       : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11667               a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
11668               a3 = Expression::make_cast(uint64_type, a3, loc);
11669             }
11670           else if (name == "CasRel")
11671             {
11672               code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11673               memorder = __ATOMIC_RELEASE;
11674             }
11675           else
11676             go_unreachable();
11677           Expression* a4 = Expression::make_boolean(false, loc);
11678           Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
11679           Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
11680           return Runtime::make_call(code, loc, 6, a1, a2, a3, a4, a5, a6);
11681         }
11682 
11683       if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
11684            || name == "Xadduintptr" || name == "$Xaddint32")
11685           && this->args_ != NULL && this->args_->size() == 2)
11686         {
11687           if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
11688             return NULL;
11689 
11690           Runtime::Function code;
11691           Type* res_type;
11692           if (name == "Xadd")
11693             {
11694               code = Runtime::ATOMIC_ADD_FETCH_4;
11695               res_type = uint32_type;
11696             }
11697           else if (name == "Xadd64")
11698             {
11699               code = Runtime::ATOMIC_ADD_FETCH_8;
11700               res_type = uint64_type;
11701             }
11702           else if (name == "$Xaddint32")
11703             {
11704               code = Runtime::ATOMIC_ADD_FETCH_4;
11705               res_type = int32_type;
11706             }
11707           else if (name == "Xaddint64")
11708             {
11709               code = Runtime::ATOMIC_ADD_FETCH_8;
11710               res_type = int64_type;
11711             }
11712           else if (name == "Xadduintptr")
11713             {
11714               code = (ptr_size == 8
11715                       ? Runtime::ATOMIC_ADD_FETCH_8
11716                       : Runtime::ATOMIC_ADD_FETCH_4);
11717               res_type = uintptr_type;
11718             }
11719           else
11720             go_unreachable();
11721           Expression* a1 = this->args_->at(0);
11722           Expression* a2 = this->args_->at(1);
11723           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11724           Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11725           return Expression::make_cast(res_type, call, loc);
11726         }
11727 
11728       if ((name == "And8" || name == "Or8")
11729           && this->args_ != NULL && this->args_->size() == 2)
11730         {
11731           Runtime::Function code;
11732           if (name == "And8")
11733             code = Runtime::ATOMIC_AND_FETCH_1;
11734           else if (name == "Or8")
11735             code = Runtime::ATOMIC_OR_FETCH_1;
11736           else
11737             go_unreachable();
11738           Expression* a1 = this->args_->at(0);
11739           Expression* a2 = this->args_->at(1);
11740           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11741           return Runtime::make_call(code, loc, 3, a1, a2, a3);
11742         }
11743     }
11744 
11745   return NULL;
11746 }
11747 
11748 // Make implicit type conversions explicit.
11749 
11750 void
do_add_conversions()11751 Call_expression::do_add_conversions()
11752 {
11753   // Skip call that requires a thunk. We generate conversions inside the thunk.
11754   if (this->is_concurrent_ || this->is_deferred_)
11755     return;
11756 
11757   if (this->args_ == NULL || this->args_->empty())
11758     return;
11759 
11760   Function_type* fntype = this->get_function_type();
11761   if (fntype == NULL)
11762     {
11763       go_assert(saw_errors());
11764       return;
11765     }
11766   if (fntype->parameters() == NULL || fntype->parameters()->empty())
11767     return;
11768 
11769   Location loc = this->location();
11770   Expression_list::iterator pa = this->args_->begin();
11771   Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11772   bool is_interface_method =
11773     this->fn_->interface_field_reference_expression() != NULL;
11774   size_t argcount = this->args_->size();
11775   if (!is_interface_method && fntype->is_method())
11776     {
11777       // Skip the receiver argument, which cannot be interface.
11778       pa++;
11779       argcount--;
11780     }
11781   if (argcount != fntype->parameters()->size())
11782     {
11783       go_assert(saw_errors());
11784       return;
11785     }
11786   for (; pa != this->args_->end(); ++pa, ++pp)
11787     {
11788       Type* pt = pp->type();
11789       if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
11790           && pt->interface_type() != NULL)
11791         *pa = Expression::make_cast(pt, *pa, loc);
11792     }
11793 }
11794 
11795 // Get the function type.  This can return NULL in error cases.
11796 
11797 Function_type*
get_function_type() const11798 Call_expression::get_function_type() const
11799 {
11800   return this->fn_->type()->function_type();
11801 }
11802 
11803 // Return the number of values which this call will return.
11804 
11805 size_t
result_count() const11806 Call_expression::result_count() const
11807 {
11808   const Function_type* fntype = this->get_function_type();
11809   if (fntype == NULL)
11810     return 0;
11811   if (fntype->results() == NULL)
11812     return 0;
11813   return fntype->results()->size();
11814 }
11815 
11816 // Return the temporary that holds the result for a call with multiple
11817 // results.
11818 
11819 Temporary_statement*
results() const11820 Call_expression::results() const
11821 {
11822   if (this->call_temp_ == NULL)
11823     {
11824       go_assert(saw_errors());
11825       return NULL;
11826     }
11827   return this->call_temp_;
11828 }
11829 
11830 // Set the number of results expected from a call expression.
11831 
11832 void
set_expected_result_count(size_t count)11833 Call_expression::set_expected_result_count(size_t count)
11834 {
11835   go_assert(this->expected_result_count_ == 0);
11836   this->expected_result_count_ = count;
11837 }
11838 
11839 // Return whether this is a call to the predeclared function recover.
11840 
11841 bool
is_recover_call() const11842 Call_expression::is_recover_call() const
11843 {
11844   return this->do_is_recover_call();
11845 }
11846 
11847 // Set the argument to the recover function.
11848 
11849 void
set_recover_arg(Expression * arg)11850 Call_expression::set_recover_arg(Expression* arg)
11851 {
11852   this->do_set_recover_arg(arg);
11853 }
11854 
11855 // Virtual functions also implemented by Builtin_call_expression.
11856 
11857 bool
do_is_recover_call() const11858 Call_expression::do_is_recover_call() const
11859 {
11860   return false;
11861 }
11862 
11863 void
do_set_recover_arg(Expression *)11864 Call_expression::do_set_recover_arg(Expression*)
11865 {
11866   go_unreachable();
11867 }
11868 
11869 // We have found an error with this call expression; return true if
11870 // we should report it.
11871 
11872 bool
issue_error()11873 Call_expression::issue_error()
11874 {
11875   if (this->issued_error_)
11876     return false;
11877   else
11878     {
11879       this->issued_error_ = true;
11880       return true;
11881     }
11882 }
11883 
11884 // Whether or not this call contains errors, either in the call or the
11885 // arguments to the call.
11886 
11887 bool
is_erroneous_call()11888 Call_expression::is_erroneous_call()
11889 {
11890   if (this->is_error_expression() || this->fn()->is_error_expression())
11891     return true;
11892 
11893   if (this->args() == NULL)
11894     return false;
11895   for (Expression_list::iterator pa = this->args()->begin();
11896        pa != this->args()->end();
11897        ++pa)
11898     {
11899       if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
11900         return true;
11901     }
11902   return false;
11903 }
11904 
11905 // Get the type.
11906 
11907 Type*
do_type()11908 Call_expression::do_type()
11909 {
11910   if (this->is_error_expression())
11911     return Type::make_error_type();
11912   if (this->type_ != NULL)
11913     return this->type_;
11914 
11915   Type* ret;
11916   Function_type* fntype = this->get_function_type();
11917   if (fntype == NULL)
11918     return Type::make_error_type();
11919 
11920   const Typed_identifier_list* results = fntype->results();
11921   if (results == NULL)
11922     ret = Type::make_void_type();
11923   else if (results->size() == 1)
11924     ret = results->begin()->type();
11925   else
11926     ret = Type::make_call_multiple_result_type(this);
11927 
11928   this->type_ = ret;
11929 
11930   return this->type_;
11931 }
11932 
11933 // Determine types for a call expression.  We can use the function
11934 // parameter types to set the types of the arguments.
11935 
11936 void
do_determine_type(const Type_context *)11937 Call_expression::do_determine_type(const Type_context*)
11938 {
11939   if (!this->determining_types())
11940     return;
11941 
11942   this->fn_->determine_type_no_context();
11943   Function_type* fntype = this->get_function_type();
11944   const Typed_identifier_list* parameters = NULL;
11945   if (fntype != NULL)
11946     parameters = fntype->parameters();
11947   if (this->args_ != NULL)
11948     {
11949       Typed_identifier_list::const_iterator pt;
11950       if (parameters != NULL)
11951 	pt = parameters->begin();
11952       bool first = true;
11953       for (Expression_list::const_iterator pa = this->args_->begin();
11954 	   pa != this->args_->end();
11955 	   ++pa)
11956 	{
11957 	  if (first)
11958 	    {
11959 	      first = false;
11960 	      // If this is a method, the first argument is the
11961 	      // receiver.
11962 	      if (fntype != NULL && fntype->is_method())
11963 		{
11964 		  Type* rtype = fntype->receiver()->type();
11965 		  // The receiver is always passed as a pointer.
11966 		  if (rtype->points_to() == NULL)
11967 		    rtype = Type::make_pointer_type(rtype);
11968 		  Type_context subcontext(rtype, false);
11969 		  (*pa)->determine_type(&subcontext);
11970 		  continue;
11971 		}
11972 	    }
11973 
11974 	  if (parameters != NULL && pt != parameters->end())
11975 	    {
11976 	      Type_context subcontext(pt->type(), false);
11977 	      (*pa)->determine_type(&subcontext);
11978 	      ++pt;
11979 	    }
11980 	  else
11981 	    (*pa)->determine_type_no_context();
11982 	}
11983     }
11984 }
11985 
11986 // Called when determining types for a Call_expression.  Return true
11987 // if we should go ahead, false if they have already been determined.
11988 
11989 bool
determining_types()11990 Call_expression::determining_types()
11991 {
11992   if (this->types_are_determined_)
11993     return false;
11994   else
11995     {
11996       this->types_are_determined_ = true;
11997       return true;
11998     }
11999 }
12000 
12001 // Check types for parameter I.
12002 
12003 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)12004 Call_expression::check_argument_type(int i, const Type* parameter_type,
12005 				     const Type* argument_type,
12006 				     Location argument_location,
12007 				     bool issued_error)
12008 {
12009   std::string reason;
12010   if (!Type::are_assignable(parameter_type, argument_type, &reason))
12011     {
12012       if (!issued_error)
12013 	{
12014 	  if (reason.empty())
12015 	    go_error_at(argument_location, "argument %d has incompatible type", i);
12016 	  else
12017 	    go_error_at(argument_location,
12018 			"argument %d has incompatible type (%s)",
12019 			i, reason.c_str());
12020 	}
12021       this->set_is_error();
12022       return false;
12023     }
12024   return true;
12025 }
12026 
12027 // Check types.
12028 
12029 void
do_check_types(Gogo *)12030 Call_expression::do_check_types(Gogo*)
12031 {
12032   if (this->classification() == EXPRESSION_ERROR)
12033     return;
12034 
12035   Function_type* fntype = this->get_function_type();
12036   if (fntype == NULL)
12037     {
12038       if (!this->fn_->type()->is_error())
12039 	this->report_error(_("expected function"));
12040       return;
12041     }
12042 
12043   if (this->expected_result_count_ != 0
12044       && this->expected_result_count_ != this->result_count())
12045     {
12046       if (this->issue_error())
12047 	this->report_error(_("function result count mismatch"));
12048       this->set_is_error();
12049       return;
12050     }
12051 
12052   bool is_method = fntype->is_method();
12053   if (is_method)
12054     {
12055       go_assert(this->args_ != NULL && !this->args_->empty());
12056       Type* rtype = fntype->receiver()->type();
12057       Expression* first_arg = this->args_->front();
12058       // We dereference the values since receivers are always passed
12059       // as pointers.
12060       std::string reason;
12061       if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
12062 				&reason))
12063 	{
12064 	  if (reason.empty())
12065 	    this->report_error(_("incompatible type for receiver"));
12066 	  else
12067 	    {
12068 	      go_error_at(this->location(),
12069                           "incompatible type for receiver (%s)",
12070                           reason.c_str());
12071 	      this->set_is_error();
12072 	    }
12073 	}
12074     }
12075 
12076   // Note that varargs was handled by the lower_varargs() method, so
12077   // we don't have to worry about it here unless something is wrong.
12078   if (this->is_varargs_ && !this->varargs_are_lowered_)
12079     {
12080       if (!fntype->is_varargs())
12081 	{
12082 	  go_error_at(this->location(),
12083                       _("invalid use of %<...%> calling non-variadic function"));
12084 	  this->set_is_error();
12085 	  return;
12086 	}
12087     }
12088 
12089   const Typed_identifier_list* parameters = fntype->parameters();
12090   if (this->args_ == NULL || this->args_->size() == 0)
12091     {
12092       if (parameters != NULL && !parameters->empty())
12093 	this->report_error(_("not enough arguments"));
12094     }
12095   else if (parameters == NULL)
12096     {
12097       if (!is_method || this->args_->size() > 1)
12098 	this->report_error(_("too many arguments"));
12099     }
12100   else if (this->args_->size() == 1
12101 	   && this->args_->front()->call_expression() != NULL
12102 	   && this->args_->front()->call_expression()->result_count() > 1)
12103     {
12104       // This is F(G()) when G returns more than one result.  If the
12105       // results can be matched to parameters, it would have been
12106       // lowered in do_lower.  If we get here we know there is a
12107       // mismatch.
12108       if (this->args_->front()->call_expression()->result_count()
12109 	  < parameters->size())
12110 	this->report_error(_("not enough arguments"));
12111       else
12112 	this->report_error(_("too many arguments"));
12113     }
12114   else
12115     {
12116       int i = 0;
12117       Expression_list::const_iterator pa = this->args_->begin();
12118       if (is_method)
12119 	++pa;
12120       for (Typed_identifier_list::const_iterator pt = parameters->begin();
12121 	   pt != parameters->end();
12122 	   ++pt, ++pa, ++i)
12123 	{
12124 	  if (pa == this->args_->end())
12125 	    {
12126 	      this->report_error(_("not enough arguments"));
12127 	      return;
12128 	    }
12129 	  this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
12130 				    (*pa)->location(), false);
12131 	}
12132       if (pa != this->args_->end())
12133 	this->report_error(_("too many arguments"));
12134     }
12135 }
12136 
12137 Expression*
do_copy()12138 Call_expression::do_copy()
12139 {
12140   Call_expression* call =
12141     Expression::make_call(this->fn_->copy(),
12142 			  (this->args_ == NULL
12143 			   ? NULL
12144 			   : this->args_->copy()),
12145 			  this->is_varargs_, this->location());
12146 
12147   if (this->varargs_are_lowered_)
12148     call->set_varargs_are_lowered();
12149   if (this->is_deferred_)
12150     call->set_is_deferred();
12151   if (this->is_concurrent_)
12152     call->set_is_concurrent();
12153   return call;
12154 }
12155 
12156 // Return whether we have to use a temporary variable to ensure that
12157 // we evaluate this call expression in order.  If the call returns no
12158 // results then it will inevitably be executed last.
12159 
12160 bool
do_must_eval_in_order() const12161 Call_expression::do_must_eval_in_order() const
12162 {
12163   return this->result_count() > 0;
12164 }
12165 
12166 // Get the function and the first argument to use when calling an
12167 // interface method.
12168 
12169 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr,Location location)12170 Call_expression::interface_method_function(
12171     Interface_field_reference_expression* interface_method,
12172     Expression** first_arg_ptr,
12173     Location location)
12174 {
12175   Expression* object = interface_method->get_underlying_object();
12176   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
12177   *first_arg_ptr =
12178       Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
12179   return interface_method->get_function();
12180 }
12181 
12182 // Build the call expression.
12183 
12184 Bexpression*
do_get_backend(Translate_context * context)12185 Call_expression::do_get_backend(Translate_context* context)
12186 {
12187   Location location = this->location();
12188 
12189   if (this->call_ != NULL)
12190     {
12191       // If the call returns multiple results, make a new reference to
12192       // the temporary.
12193       if (this->call_temp_ != NULL)
12194 	{
12195 	  Expression* ref =
12196 	    Expression::make_temporary_reference(this->call_temp_, location);
12197 	  return ref->get_backend(context);
12198 	}
12199 
12200       return this->call_;
12201     }
12202 
12203   Function_type* fntype = this->get_function_type();
12204   if (fntype == NULL)
12205     return context->backend()->error_expression();
12206 
12207   if (this->fn_->is_error_expression())
12208     return context->backend()->error_expression();
12209 
12210   Gogo* gogo = context->gogo();
12211 
12212   Func_expression* func = this->fn_->func_expression();
12213   Interface_field_reference_expression* interface_method =
12214     this->fn_->interface_field_reference_expression();
12215   const bool has_closure = func != NULL && func->closure() != NULL;
12216   const bool is_interface_method = interface_method != NULL;
12217 
12218   bool has_closure_arg;
12219   if (has_closure)
12220     has_closure_arg = true;
12221   else if (func != NULL)
12222     has_closure_arg = false;
12223   else if (is_interface_method)
12224     has_closure_arg = false;
12225   else
12226     has_closure_arg = true;
12227 
12228   Expression* first_arg = NULL;
12229   if (!is_interface_method && fntype->is_method())
12230     {
12231       first_arg = this->args_->front();
12232       if (first_arg->type()->points_to() == NULL
12233           && first_arg->type()->is_direct_iface_type())
12234         first_arg = Expression::unpack_direct_iface(first_arg,
12235                                                     first_arg->location());
12236     }
12237 
12238   int nargs;
12239   std::vector<Bexpression*> fn_args;
12240   if (this->args_ == NULL || this->args_->empty())
12241     {
12242       nargs = is_interface_method ? 1 : 0;
12243       if (nargs > 0)
12244         fn_args.resize(1);
12245     }
12246   else if (fntype->parameters() == NULL || fntype->parameters()->empty())
12247     {
12248       // Passing a receiver parameter.
12249       go_assert(!is_interface_method
12250 		&& fntype->is_method()
12251 		&& this->args_->size() == 1);
12252       nargs = 1;
12253       fn_args.resize(1);
12254       fn_args[0] = first_arg->get_backend(context);
12255     }
12256   else
12257     {
12258       const Typed_identifier_list* params = fntype->parameters();
12259 
12260       nargs = this->args_->size();
12261       int i = is_interface_method ? 1 : 0;
12262       nargs += i;
12263       fn_args.resize(nargs);
12264 
12265       Typed_identifier_list::const_iterator pp = params->begin();
12266       Expression_list::const_iterator pe = this->args_->begin();
12267       if (!is_interface_method && fntype->is_method())
12268 	{
12269           fn_args[i] = first_arg->get_backend(context);
12270 	  ++pe;
12271 	  ++i;
12272 	}
12273       for (; pe != this->args_->end(); ++pe, ++pp, ++i)
12274 	{
12275 	  go_assert(pp != params->end());
12276           Expression* arg =
12277               Expression::convert_for_assignment(gogo, pp->type(), *pe,
12278                                                  location);
12279           fn_args[i] = arg->get_backend(context);
12280 	}
12281       go_assert(pp == params->end());
12282       go_assert(i == nargs);
12283     }
12284 
12285   Expression* fn;
12286   Expression* closure = NULL;
12287   if (func != NULL)
12288     {
12289       Named_object* no = func->named_object();
12290       fn = Expression::make_func_code_reference(no, location);
12291       if (has_closure)
12292         closure = func->closure();
12293     }
12294   else if (!is_interface_method)
12295     {
12296       closure = this->fn_;
12297 
12298       // The backend representation of this function type is a pointer
12299       // to a struct whose first field is the actual function to call.
12300       Type* pfntype =
12301           Type::make_pointer_type(
12302               Type::make_pointer_type(Type::make_void_type()));
12303       fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
12304       fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
12305     }
12306   else
12307     {
12308       Expression* arg0;
12309       fn = this->interface_method_function(interface_method, &arg0,
12310                                            location);
12311       fn_args[0] = arg0->get_backend(context);
12312     }
12313 
12314   Bexpression* bclosure = NULL;
12315   if (has_closure_arg)
12316     bclosure = closure->get_backend(context);
12317   else
12318     go_assert(closure == NULL);
12319 
12320   Bexpression* bfn = fn->get_backend(context);
12321 
12322   // When not calling a named function directly, use a type conversion
12323   // in case the type of the function is a recursive type which refers
12324   // to itself.  We don't do this for an interface method because 1)
12325   // an interface method never refers to itself, so we always have a
12326   // function type here; 2) we pass an extra first argument to an
12327   // interface method, so fntype is not correct.
12328   if (func == NULL && !is_interface_method)
12329     {
12330       Btype* bft = fntype->get_backend_fntype(gogo);
12331       bfn = gogo->backend()->convert_expression(bft, bfn, location);
12332     }
12333 
12334   Bfunction* bfunction = NULL;
12335   if (context->function())
12336     bfunction = context->function()->func_value()->get_decl();
12337   Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
12338                                                        fn_args, bclosure,
12339                                                        location);
12340 
12341   if (this->call_temp_ != NULL)
12342     {
12343       // This case occurs when the call returns multiple results.
12344 
12345       Expression* ref = Expression::make_temporary_reference(this->call_temp_,
12346 							     location);
12347       Bexpression* bref = ref->get_backend(context);
12348       Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
12349 								bref, call,
12350 								location);
12351 
12352       ref = Expression::make_temporary_reference(this->call_temp_, location);
12353       this->call_ = ref->get_backend(context);
12354 
12355       return gogo->backend()->compound_expression(bassn, this->call_,
12356 						  location);
12357     }
12358 
12359   this->call_ = call;
12360   return this->call_;
12361 }
12362 
12363 // The cost of inlining a call expression.
12364 
12365 int
do_inlining_cost() const12366 Call_expression::do_inlining_cost() const
12367 {
12368   Func_expression* fn = this->fn_->func_expression();
12369 
12370   // FIXME: We don't yet support all kinds of calls.
12371   if (fn != NULL && fn->closure() != NULL)
12372     return 0x100000;
12373   if (this->fn_->interface_field_reference_expression())
12374     return 0x100000;
12375   if (this->get_function_type()->is_method())
12376     return 0x100000;
12377 
12378   return 5;
12379 }
12380 
12381 // Export a call expression.
12382 
12383 void
do_export(Export_function_body * efb) const12384 Call_expression::do_export(Export_function_body* efb) const
12385 {
12386   bool simple_call = (this->fn_->func_expression() != NULL);
12387   if (!simple_call)
12388     efb->write_c_string("(");
12389   this->fn_->export_expression(efb);
12390   if (!simple_call)
12391     efb->write_c_string(")");
12392   this->export_arguments(efb);
12393 }
12394 
12395 // Export call expression arguments.
12396 
12397 void
export_arguments(Export_function_body * efb) const12398 Call_expression::export_arguments(Export_function_body* efb) const
12399 {
12400   efb->write_c_string("(");
12401   if (this->args_ != NULL && !this->args_->empty())
12402     {
12403       Expression_list::const_iterator pa = this->args_->begin();
12404       (*pa)->export_expression(efb);
12405       for (pa++; pa != this->args_->end(); pa++)
12406 	{
12407 	  efb->write_c_string(", ");
12408 	  (*pa)->export_expression(efb);
12409 	}
12410       if (this->is_varargs_)
12411 	efb->write_c_string("...");
12412     }
12413   efb->write_c_string(")");
12414 }
12415 
12416 // Dump ast representation for a call expression.
12417 
12418 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12419 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12420 {
12421   this->fn_->dump_expression(ast_dump_context);
12422   ast_dump_context->ostream() << "(";
12423   if (args_ != NULL)
12424     ast_dump_context->dump_expression_list(this->args_);
12425 
12426   ast_dump_context->ostream() << ") ";
12427 }
12428 
12429 // Make a call expression.
12430 
12431 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)12432 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
12433 		      Location location)
12434 {
12435   return new Call_expression(fn, args, is_varargs, location);
12436 }
12437 
12438 // Class Call_result_expression.
12439 
12440 // Traverse a call result.
12441 
12442 int
do_traverse(Traverse * traverse)12443 Call_result_expression::do_traverse(Traverse* traverse)
12444 {
12445   if (traverse->remember_expression(this->call_))
12446     {
12447       // We have already traversed the call expression.
12448       return TRAVERSE_CONTINUE;
12449     }
12450   return Expression::traverse(&this->call_, traverse);
12451 }
12452 
12453 // Get the type.
12454 
12455 Type*
do_type()12456 Call_result_expression::do_type()
12457 {
12458   if (this->classification() == EXPRESSION_ERROR)
12459     return Type::make_error_type();
12460 
12461   // THIS->CALL_ can be replaced with a temporary reference due to
12462   // Call_expression::do_must_eval_in_order when there is an error.
12463   Call_expression* ce = this->call_->call_expression();
12464   if (ce == NULL)
12465     {
12466       this->set_is_error();
12467       return Type::make_error_type();
12468     }
12469   Function_type* fntype = ce->get_function_type();
12470   if (fntype == NULL)
12471     {
12472       if (ce->issue_error())
12473 	{
12474 	  if (!ce->fn()->type()->is_error())
12475 	    this->report_error(_("expected function"));
12476 	}
12477       this->set_is_error();
12478       return Type::make_error_type();
12479     }
12480   const Typed_identifier_list* results = fntype->results();
12481   if (results == NULL || results->size() < 2)
12482     {
12483       if (ce->issue_error())
12484 	this->report_error(_("number of results does not match "
12485 			     "number of values"));
12486       return Type::make_error_type();
12487     }
12488   Typed_identifier_list::const_iterator pr = results->begin();
12489   for (unsigned int i = 0; i < this->index_; ++i)
12490     {
12491       if (pr == results->end())
12492 	break;
12493       ++pr;
12494     }
12495   if (pr == results->end())
12496     {
12497       if (ce->issue_error())
12498 	this->report_error(_("number of results does not match "
12499 			     "number of values"));
12500       return Type::make_error_type();
12501     }
12502   return pr->type();
12503 }
12504 
12505 // Check the type.  Just make sure that we trigger the warning in
12506 // do_type.
12507 
12508 void
do_check_types(Gogo *)12509 Call_result_expression::do_check_types(Gogo*)
12510 {
12511   this->type();
12512 }
12513 
12514 // Determine the type.  We have nothing to do here, but the 0 result
12515 // needs to pass down to the caller.
12516 
12517 void
do_determine_type(const Type_context *)12518 Call_result_expression::do_determine_type(const Type_context*)
12519 {
12520   this->call_->determine_type_no_context();
12521 }
12522 
12523 // Return the backend representation.  We just refer to the temporary set by the
12524 // call expression.  We don't do this at lowering time because it makes it
12525 // hard to evaluate the call at the right time.
12526 
12527 Bexpression*
do_get_backend(Translate_context * context)12528 Call_result_expression::do_get_backend(Translate_context* context)
12529 {
12530   Call_expression* ce = this->call_->call_expression();
12531   if (ce == NULL)
12532     {
12533       go_assert(this->call_->is_error_expression());
12534       return context->backend()->error_expression();
12535     }
12536   Temporary_statement* ts = ce->results();
12537   if (ts == NULL)
12538     {
12539       go_assert(saw_errors());
12540       return context->backend()->error_expression();
12541     }
12542   Expression* ref = Expression::make_temporary_reference(ts, this->location());
12543   ref = Expression::make_field_reference(ref, this->index_, this->location());
12544   return ref->get_backend(context);
12545 }
12546 
12547 // Dump ast representation for a call result expression.
12548 
12549 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12550 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12551     const
12552 {
12553   // FIXME: Wouldn't it be better if the call is assigned to a temporary
12554   // (struct) and the fields are referenced instead.
12555   ast_dump_context->ostream() << this->index_ << "@(";
12556   ast_dump_context->dump_expression(this->call_);
12557   ast_dump_context->ostream() << ")";
12558 }
12559 
12560 // Make a reference to a single result of a call which returns
12561 // multiple results.
12562 
12563 Expression*
make_call_result(Call_expression * call,unsigned int index)12564 Expression::make_call_result(Call_expression* call, unsigned int index)
12565 {
12566   return new Call_result_expression(call, index);
12567 }
12568 
12569 // Class Index_expression.
12570 
12571 // Traversal.
12572 
12573 int
do_traverse(Traverse * traverse)12574 Index_expression::do_traverse(Traverse* traverse)
12575 {
12576   if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
12577       || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
12578       || (this->end_ != NULL
12579 	  && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12580       || (this->cap_ != NULL
12581           && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
12582     return TRAVERSE_EXIT;
12583   return TRAVERSE_CONTINUE;
12584 }
12585 
12586 // Lower an index expression.  This converts the generic index
12587 // expression into an array index, a string index, or a map index.
12588 
12589 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)12590 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
12591 {
12592   Location location = this->location();
12593   Expression* left = this->left_;
12594   Expression* start = this->start_;
12595   Expression* end = this->end_;
12596   Expression* cap = this->cap_;
12597 
12598   Type* type = left->type();
12599   if (type->is_error())
12600     {
12601       go_assert(saw_errors());
12602       return Expression::make_error(location);
12603     }
12604   else if (left->is_type_expression())
12605     {
12606       go_error_at(location, "attempt to index type expression");
12607       return Expression::make_error(location);
12608     }
12609   else if (type->array_type() != NULL)
12610     return Expression::make_array_index(left, start, end, cap, location);
12611   else if (type->points_to() != NULL
12612 	   && type->points_to()->array_type() != NULL
12613 	   && !type->points_to()->is_slice_type())
12614     {
12615       Expression* deref =
12616           Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
12617 
12618       // For an ordinary index into the array, the pointer will be
12619       // dereferenced.  For a slice it will not--the resulting slice
12620       // will simply reuse the pointer, which is incorrect if that
12621       // pointer is nil.
12622       if (end != NULL || cap != NULL)
12623 	deref->issue_nil_check();
12624 
12625       return Expression::make_array_index(deref, start, end, cap, location);
12626     }
12627   else if (type->is_string_type())
12628     {
12629       if (cap != NULL)
12630         {
12631           go_error_at(location, "invalid 3-index slice of string");
12632           return Expression::make_error(location);
12633         }
12634       return Expression::make_string_index(left, start, end, location);
12635     }
12636   else if (type->map_type() != NULL)
12637     {
12638       if (end != NULL || cap != NULL)
12639 	{
12640 	  go_error_at(location, "invalid slice of map");
12641 	  return Expression::make_error(location);
12642 	}
12643       return Expression::make_map_index(left, start, location);
12644     }
12645   else if (cap != NULL)
12646     {
12647       go_error_at(location,
12648 		  "invalid 3-index slice of object that is not a slice");
12649       return Expression::make_error(location);
12650     }
12651   else if (end != NULL)
12652     {
12653       go_error_at(location,
12654 		  ("attempt to slice object that is not "
12655 		   "array, slice, or string"));
12656       return Expression::make_error(location);
12657     }
12658   else
12659     {
12660       go_error_at(location,
12661                   ("attempt to index object that is not "
12662 		   "array, slice, string, or map"));
12663       return Expression::make_error(location);
12664     }
12665 }
12666 
12667 // Write an indexed expression
12668 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
12669 
12670 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)12671 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
12672 					const Expression* expr,
12673 					const Expression* start,
12674 					const Expression* end,
12675 					const Expression* cap)
12676 {
12677   expr->dump_expression(ast_dump_context);
12678   ast_dump_context->ostream() << "[";
12679   start->dump_expression(ast_dump_context);
12680   if (end != NULL)
12681     {
12682       ast_dump_context->ostream() << ":";
12683       end->dump_expression(ast_dump_context);
12684     }
12685   if (cap != NULL)
12686     {
12687       ast_dump_context->ostream() << ":";
12688       cap->dump_expression(ast_dump_context);
12689     }
12690   ast_dump_context->ostream() << "]";
12691 }
12692 
12693 // Dump ast representation for an index expression.
12694 
12695 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12696 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12697     const
12698 {
12699   Index_expression::dump_index_expression(ast_dump_context, this->left_,
12700                                           this->start_, this->end_, this->cap_);
12701 }
12702 
12703 // Make an index expression.
12704 
12705 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)12706 Expression::make_index(Expression* left, Expression* start, Expression* end,
12707 		       Expression* cap, Location location)
12708 {
12709   return new Index_expression(left, start, end, cap, location);
12710 }
12711 
12712 // Class Array_index_expression.
12713 
12714 // Array index traversal.
12715 
12716 int
do_traverse(Traverse * traverse)12717 Array_index_expression::do_traverse(Traverse* traverse)
12718 {
12719   if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
12720     return TRAVERSE_EXIT;
12721   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
12722     return TRAVERSE_EXIT;
12723   if (this->end_ != NULL)
12724     {
12725       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12726 	return TRAVERSE_EXIT;
12727     }
12728   if (this->cap_ != NULL)
12729     {
12730       if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
12731         return TRAVERSE_EXIT;
12732     }
12733   return TRAVERSE_CONTINUE;
12734 }
12735 
12736 // Return the type of an array index.
12737 
12738 Type*
do_type()12739 Array_index_expression::do_type()
12740 {
12741   if (this->type_ == NULL)
12742     {
12743      Array_type* type = this->array_->type()->array_type();
12744       if (type == NULL)
12745 	this->type_ = Type::make_error_type();
12746       else if (this->end_ == NULL)
12747 	this->type_ = type->element_type();
12748       else if (type->is_slice_type())
12749 	{
12750 	  // A slice of a slice has the same type as the original
12751 	  // slice.
12752 	  this->type_ = this->array_->type()->deref();
12753 	}
12754       else
12755 	{
12756 	  // A slice of an array is a slice.
12757 	  this->type_ = Type::make_array_type(type->element_type(), NULL);
12758 	}
12759     }
12760   return this->type_;
12761 }
12762 
12763 // Set the type of an array index.
12764 
12765 void
do_determine_type(const Type_context *)12766 Array_index_expression::do_determine_type(const Type_context*)
12767 {
12768   this->array_->determine_type_no_context();
12769 
12770   Type_context index_context(Type::lookup_integer_type("int"), false);
12771   if (this->start_->is_constant())
12772     this->start_->determine_type(&index_context);
12773   else
12774     this->start_->determine_type_no_context();
12775   if (this->end_ != NULL)
12776     {
12777       if (this->end_->is_constant())
12778         this->end_->determine_type(&index_context);
12779       else
12780         this->end_->determine_type_no_context();
12781     }
12782   if (this->cap_ != NULL)
12783     {
12784       if (this->cap_->is_constant())
12785         this->cap_->determine_type(&index_context);
12786       else
12787         this->cap_->determine_type_no_context();
12788     }
12789 }
12790 
12791 // Check types of an array index.
12792 
12793 void
do_check_types(Gogo *)12794 Array_index_expression::do_check_types(Gogo*)
12795 {
12796   Numeric_constant nc;
12797   unsigned long v;
12798   if (this->start_->type()->integer_type() == NULL
12799       && !this->start_->type()->is_error()
12800       && (!this->start_->type()->is_abstract()
12801 	  || !this->start_->numeric_constant_value(&nc)
12802 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12803     this->report_error(_("index must be integer"));
12804   if (this->end_ != NULL
12805       && this->end_->type()->integer_type() == NULL
12806       && !this->end_->type()->is_error()
12807       && !this->end_->is_nil_expression()
12808       && !this->end_->is_error_expression()
12809       && (!this->end_->type()->is_abstract()
12810 	  || !this->end_->numeric_constant_value(&nc)
12811 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12812     this->report_error(_("slice end must be integer"));
12813   if (this->cap_ != NULL
12814       && this->cap_->type()->integer_type() == NULL
12815       && !this->cap_->type()->is_error()
12816       && !this->cap_->is_nil_expression()
12817       && !this->cap_->is_error_expression()
12818       && (!this->cap_->type()->is_abstract()
12819 	  || !this->cap_->numeric_constant_value(&nc)
12820 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12821     this->report_error(_("slice capacity must be integer"));
12822 
12823   Array_type* array_type = this->array_->type()->array_type();
12824   if (array_type == NULL)
12825     {
12826       go_assert(this->array_->type()->is_error());
12827       return;
12828     }
12829 
12830   unsigned int int_bits =
12831     Type::lookup_integer_type("int")->integer_type()->bits();
12832 
12833   Numeric_constant lvalnc;
12834   mpz_t lval;
12835   bool lval_valid = (array_type->length() != NULL
12836 		     && array_type->length()->numeric_constant_value(&lvalnc)
12837 		     && lvalnc.to_int(&lval));
12838   Numeric_constant inc;
12839   mpz_t ival;
12840   bool ival_valid = false;
12841   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
12842     {
12843       ival_valid = true;
12844       if (mpz_sgn(ival) < 0
12845 	  || mpz_sizeinbase(ival, 2) >= int_bits
12846 	  || (lval_valid
12847 	      && (this->end_ == NULL
12848 		  ? mpz_cmp(ival, lval) >= 0
12849 		  : mpz_cmp(ival, lval) > 0)))
12850 	{
12851 	  go_error_at(this->start_->location(), "array index out of bounds");
12852 	  this->set_is_error();
12853 	}
12854     }
12855   if (this->end_ != NULL && !this->end_->is_nil_expression())
12856     {
12857       Numeric_constant enc;
12858       mpz_t eval;
12859       bool eval_valid = false;
12860       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
12861 	{
12862 	  eval_valid = true;
12863 	  if (mpz_sgn(eval) < 0
12864 	      || mpz_sizeinbase(eval, 2) >= int_bits
12865 	      || (lval_valid && mpz_cmp(eval, lval) > 0))
12866 	    {
12867 	      go_error_at(this->end_->location(), "array index out of bounds");
12868 	      this->set_is_error();
12869 	    }
12870 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
12871 	    this->report_error(_("inverted slice range"));
12872 	}
12873 
12874       Numeric_constant cnc;
12875       mpz_t cval;
12876       if (this->cap_ != NULL
12877           && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
12878         {
12879           if (mpz_sgn(cval) < 0
12880               || mpz_sizeinbase(cval, 2) >= int_bits
12881               || (lval_valid && mpz_cmp(cval, lval) > 0))
12882             {
12883               go_error_at(this->cap_->location(), "array index out of bounds");
12884               this->set_is_error();
12885             }
12886 	  else if (ival_valid && mpz_cmp(ival, cval) > 0)
12887 	    {
12888 	      go_error_at(this->cap_->location(),
12889                           "invalid slice index: capacity less than start");
12890 	      this->set_is_error();
12891 	    }
12892           else if (eval_valid && mpz_cmp(eval, cval) > 0)
12893             {
12894               go_error_at(this->cap_->location(),
12895                           "invalid slice index: capacity less than length");
12896               this->set_is_error();
12897             }
12898           mpz_clear(cval);
12899         }
12900 
12901       if (eval_valid)
12902         mpz_clear(eval);
12903     }
12904   if (ival_valid)
12905     mpz_clear(ival);
12906   if (lval_valid)
12907     mpz_clear(lval);
12908 
12909   // A slice of an array requires an addressable array.  A slice of a
12910   // slice is always possible.
12911   if (this->end_ != NULL && !array_type->is_slice_type())
12912     {
12913       if (!this->array_->is_addressable())
12914 	this->report_error(_("slice of unaddressable value"));
12915       else
12916         // Set the array address taken but not escape. The escape
12917         // analysis will make it escape to heap when needed.
12918         this->array_->address_taken(false);
12919     }
12920 }
12921 
12922 // The subexpressions of an array index must be evaluated in order.
12923 // If this is indexing into an array, rather than a slice, then only
12924 // the index should be evaluated.  Since this is called for values on
12925 // the left hand side of an assigment, evaluating the array, meaning
12926 // copying the array, will cause a different array to be modified.
12927 
12928 bool
do_must_eval_subexpressions_in_order(int * skip) const12929 Array_index_expression::do_must_eval_subexpressions_in_order(
12930     int* skip) const
12931 {
12932   *skip = this->array_->type()->is_slice_type() ? 0 : 1;
12933   return true;
12934 }
12935 
12936 // Flatten array indexing: add temporary variables and bounds checks.
12937 
12938 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)12939 Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
12940                                    Statement_inserter* inserter)
12941 {
12942   if (this->is_flattened_)
12943     return this;
12944   this->is_flattened_ = true;
12945 
12946   Location loc = this->location();
12947 
12948   if (this->is_error_expression())
12949     return Expression::make_error(loc);
12950 
12951   Expression* array = this->array_;
12952   Expression* start = this->start_;
12953   Expression* end = this->end_;
12954   Expression* cap = this->cap_;
12955   if (array->is_error_expression()
12956       || array->type()->is_error_type()
12957       || start->is_error_expression()
12958       || start->type()->is_error_type()
12959       || (end != NULL
12960           && (end->is_error_expression() || end->type()->is_error_type()))
12961       || (cap != NULL
12962           && (cap->is_error_expression() || cap->type()->is_error_type())))
12963     {
12964       go_assert(saw_errors());
12965       return Expression::make_error(loc);
12966     }
12967 
12968   Array_type* array_type = this->array_->type()->array_type();
12969   if (array_type == NULL)
12970     {
12971       go_assert(saw_errors());
12972       return Expression::make_error(loc);
12973     }
12974 
12975   Temporary_statement* temp;
12976   if (array_type->is_slice_type() && !array->is_variable())
12977     {
12978       temp = Statement::make_temporary(NULL, array, loc);
12979       inserter->insert(temp);
12980       this->array_ = Expression::make_temporary_reference(temp, loc);
12981       array = this->array_;
12982     }
12983   if (!start->is_variable() && !start->is_constant())
12984     {
12985       temp = Statement::make_temporary(NULL, start, loc);
12986       inserter->insert(temp);
12987       this->start_ = Expression::make_temporary_reference(temp, loc);
12988       start = this->start_;
12989     }
12990   if (end != NULL
12991       && !end->is_nil_expression()
12992       && !end->is_variable()
12993       && !end->is_constant())
12994     {
12995       temp = Statement::make_temporary(NULL, end, loc);
12996       inserter->insert(temp);
12997       this->end_ = Expression::make_temporary_reference(temp, loc);
12998       end = this->end_;
12999     }
13000   if (cap != NULL && !cap->is_variable() && !cap->is_constant())
13001     {
13002       temp = Statement::make_temporary(NULL, cap, loc);
13003       inserter->insert(temp);
13004       this->cap_ = Expression::make_temporary_reference(temp, loc);
13005       cap = this->cap_;
13006     }
13007 
13008   if (!this->needs_bounds_check_)
13009     return this;
13010 
13011   Expression* len;
13012   if (!array_type->is_slice_type())
13013     {
13014       len = array_type->get_length(gogo, this->array_);
13015       go_assert(len->is_constant());
13016     }
13017   else
13018     {
13019       len = array_type->get_length(gogo, this->array_->copy());
13020       temp = Statement::make_temporary(NULL, len, loc);
13021       inserter->insert(temp);
13022       len = Expression::make_temporary_reference(temp, loc);
13023     }
13024 
13025   Expression* scap = NULL;
13026   if (array_type->is_slice_type())
13027     {
13028       scap = array_type->get_capacity(gogo, this->array_->copy());
13029       temp = Statement::make_temporary(NULL, scap, loc);
13030       inserter->insert(temp);
13031       scap = Expression::make_temporary_reference(temp, loc);
13032     }
13033 
13034   // The order of bounds checks here matches the order used by the gc
13035   // compiler, as tested by issue30116[u].go.
13036 
13037   if (cap != NULL)
13038     {
13039       if (array_type->is_slice_type())
13040 	Expression::check_bounds(cap, OPERATOR_LE, scap,
13041 				 Runtime::PANIC_SLICE3_ACAP,
13042 				 Runtime::PANIC_SLICE3_ACAP_U,
13043 				 Runtime::PANIC_EXTEND_SLICE3_ACAP,
13044 				 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
13045 				 inserter, loc);
13046       else
13047 	Expression::check_bounds(cap, OPERATOR_LE, len,
13048 				 Runtime::PANIC_SLICE3_ALEN,
13049 				 Runtime::PANIC_SLICE3_ALEN_U,
13050 				 Runtime::PANIC_EXTEND_SLICE3_ALEN,
13051 				 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
13052 				 inserter, loc);
13053 
13054       Expression* start_bound = cap;
13055       if (end != NULL && !end->is_nil_expression())
13056 	{
13057 	  Expression::check_bounds(end, OPERATOR_LE, cap,
13058 				   Runtime::PANIC_SLICE3_B,
13059 				   Runtime::PANIC_SLICE3_B_U,
13060 				   Runtime::PANIC_EXTEND_SLICE3_B,
13061 				   Runtime::PANIC_EXTEND_SLICE3_B_U,
13062 				   inserter, loc);
13063 	  start_bound = end;
13064 	}
13065 
13066       Expression::check_bounds(start, OPERATOR_LE, start_bound,
13067 			       Runtime::PANIC_SLICE3_C,
13068 			       Runtime::PANIC_SLICE3_C_U,
13069 			       Runtime::PANIC_EXTEND_SLICE3_C,
13070 			       Runtime::PANIC_EXTEND_SLICE3_C_U,
13071 			       inserter, loc);
13072     }
13073   else if (end != NULL && !end->is_nil_expression())
13074     {
13075       if (array_type->is_slice_type())
13076 	Expression::check_bounds(end, OPERATOR_LE, scap,
13077 				 Runtime::PANIC_SLICE_ACAP,
13078 				 Runtime::PANIC_SLICE_ACAP_U,
13079 				 Runtime::PANIC_EXTEND_SLICE_ACAP,
13080 				 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
13081 				 inserter, loc);
13082       else
13083 	Expression::check_bounds(end, OPERATOR_LE, len,
13084 				 Runtime::PANIC_SLICE_ALEN,
13085 				 Runtime::PANIC_SLICE_ALEN_U,
13086 				 Runtime::PANIC_EXTEND_SLICE_ALEN,
13087 				 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13088 				 inserter, loc);
13089 
13090       Expression::check_bounds(start, OPERATOR_LE, end,
13091 			       Runtime::PANIC_SLICE_B,
13092 			       Runtime::PANIC_SLICE_B_U,
13093 			       Runtime::PANIC_EXTEND_SLICE_B,
13094 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13095 			       inserter, loc);
13096     }
13097   else if (end != NULL)
13098     {
13099       Expression* start_bound;
13100       if (array_type->is_slice_type())
13101 	start_bound = scap;
13102       else
13103 	start_bound = len;
13104       Expression::check_bounds(start, OPERATOR_LE, start_bound,
13105 			       Runtime::PANIC_SLICE_B,
13106 			       Runtime::PANIC_SLICE_B_U,
13107 			       Runtime::PANIC_EXTEND_SLICE_B,
13108 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13109 			       inserter, loc);
13110     }
13111   else
13112     Expression::check_bounds(start, OPERATOR_LT, len,
13113 			     Runtime::PANIC_INDEX,
13114 			     Runtime::PANIC_INDEX_U,
13115 			     Runtime::PANIC_EXTEND_INDEX,
13116 			     Runtime::PANIC_EXTEND_INDEX_U,
13117 			     inserter, loc);
13118 
13119   return this;
13120 }
13121 
13122 // Return whether this expression is addressable.
13123 
13124 bool
do_is_addressable() const13125 Array_index_expression::do_is_addressable() const
13126 {
13127   // A slice expression is not addressable.
13128   if (this->end_ != NULL)
13129     return false;
13130 
13131   // An index into a slice is addressable.
13132   if (this->array_->type()->is_slice_type())
13133     return true;
13134 
13135   // An index into an array is addressable if the array is
13136   // addressable.
13137   return this->array_->is_addressable();
13138 }
13139 
13140 void
do_address_taken(bool escapes)13141 Array_index_expression::do_address_taken(bool escapes)
13142 {
13143   // In &x[0], if x is a slice, then x's address is not taken.
13144   if (!this->array_->type()->is_slice_type())
13145     this->array_->address_taken(escapes);
13146 }
13147 
13148 // Get the backend representation for an array index.
13149 
13150 Bexpression*
do_get_backend(Translate_context * context)13151 Array_index_expression::do_get_backend(Translate_context* context)
13152 {
13153   Array_type* array_type = this->array_->type()->array_type();
13154   if (array_type == NULL)
13155     {
13156       go_assert(this->array_->type()->is_error());
13157       return context->backend()->error_expression();
13158     }
13159   go_assert(!array_type->is_slice_type() || this->array_->is_variable());
13160 
13161   Location loc = this->location();
13162   Gogo* gogo = context->gogo();
13163 
13164   Type* int_type = Type::lookup_integer_type("int");
13165   Btype* int_btype = int_type->get_backend(gogo);
13166 
13167   // Convert the length and capacity to "int".  FIXME: Do we need to
13168   // do this?
13169   Bexpression* length = NULL;
13170   if (this->end_ == NULL || this->end_->is_nil_expression())
13171     {
13172       Expression* len = array_type->get_length(gogo, this->array_);
13173       length = len->get_backend(context);
13174       length = gogo->backend()->convert_expression(int_btype, length, loc);
13175     }
13176 
13177   Bexpression* capacity = NULL;
13178   if (this->end_ != NULL)
13179     {
13180       Expression* cap = array_type->get_capacity(gogo, this->array_);
13181       capacity = cap->get_backend(context);
13182       capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
13183     }
13184 
13185   Bexpression* cap_arg = capacity;
13186   if (this->cap_ != NULL)
13187     {
13188       cap_arg = this->cap_->get_backend(context);
13189       cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
13190     }
13191 
13192   if (length == NULL)
13193     length = cap_arg;
13194 
13195   if (this->start_->type()->integer_type() == NULL
13196       && !Type::are_convertible(int_type, this->start_->type(), NULL))
13197     {
13198       go_assert(saw_errors());
13199       return context->backend()->error_expression();
13200     }
13201 
13202   Bexpression* start = this->start_->get_backend(context);
13203   start = gogo->backend()->convert_expression(int_btype, start, loc);
13204 
13205   Bfunction* bfn = context->function()->func_value()->get_decl();
13206   if (this->end_ == NULL)
13207     {
13208       // Simple array indexing.
13209       Bexpression* ret;
13210       if (!array_type->is_slice_type())
13211 	{
13212 	  Bexpression* array = this->array_->get_backend(context);
13213 	  ret = gogo->backend()->array_index_expression(array, start, loc);
13214 	}
13215       else
13216 	{
13217 	  Expression* valptr =
13218               array_type->get_value_pointer(gogo, this->array_,
13219                                             this->is_lvalue_);
13220 	  Bexpression* ptr = valptr->get_backend(context);
13221           ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
13222 
13223 	  Type* ele_type = this->array_->type()->array_type()->element_type();
13224 	  Btype* ele_btype = ele_type->get_backend(gogo);
13225 	  ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
13226 	}
13227       return ret;
13228     }
13229 
13230   // Slice expression.
13231 
13232   Bexpression* end;
13233   if (this->end_->is_nil_expression())
13234     end = length;
13235   else
13236     {
13237       end = this->end_->get_backend(context);
13238       end = gogo->backend()->convert_expression(int_btype, end, loc);
13239     }
13240 
13241   Bexpression* result_length =
13242     gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
13243 
13244   Bexpression* result_capacity =
13245     gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
13246 
13247   // If the new capacity is zero, don't change val.  Otherwise we can
13248   // get a pointer to the next object in memory, keeping it live
13249   // unnecessarily.  When the capacity is zero, the actual pointer
13250   // value doesn't matter.
13251   Bexpression* zero =
13252     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13253   Bexpression* cond =
13254     gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
13255 				       loc);
13256   Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
13257 								cond, zero,
13258 								start, loc);
13259   Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
13260                                                      this->is_lvalue_);
13261   Bexpression* val = valptr->get_backend(context);
13262   val = gogo->backend()->pointer_offset_expression(val, offset, loc);
13263 
13264   Btype* struct_btype = this->type()->get_backend(gogo);
13265   std::vector<Bexpression*> init;
13266   init.push_back(val);
13267   init.push_back(result_length);
13268   init.push_back(result_capacity);
13269 
13270   return gogo->backend()->constructor_expression(struct_btype, init, loc);
13271 }
13272 
13273 // Export an array index expression.
13274 
13275 void
do_export(Export_function_body * efb) const13276 Array_index_expression::do_export(Export_function_body* efb) const
13277 {
13278   efb->write_c_string("(");
13279   this->array_->export_expression(efb);
13280   efb->write_c_string(")[");
13281 
13282   Type* old_context = efb->type_context();
13283   efb->set_type_context(Type::lookup_integer_type("int"));
13284 
13285   this->start_->export_expression(efb);
13286   if (this->end_ == NULL)
13287     go_assert(this->cap_ == NULL);
13288   else
13289     {
13290       efb->write_c_string(":");
13291       if (!this->end_->is_nil_expression())
13292 	this->end_->export_expression(efb);
13293       if (this->cap_ != NULL)
13294 	{
13295 	  efb->write_c_string(":");
13296 	  this->cap_->export_expression(efb);
13297 	}
13298     }
13299 
13300   efb->set_type_context(old_context);
13301 
13302   efb->write_c_string("]");
13303 }
13304 
13305 // Dump ast representation for an array index expression.
13306 
13307 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13308 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13309     const
13310 {
13311   Index_expression::dump_index_expression(ast_dump_context, this->array_,
13312                                           this->start_, this->end_, this->cap_);
13313 }
13314 
13315 // Make an array index expression.  END and CAP may be NULL.
13316 
13317 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)13318 Expression::make_array_index(Expression* array, Expression* start,
13319                              Expression* end, Expression* cap,
13320                              Location location)
13321 {
13322   return new Array_index_expression(array, start, end, cap, location);
13323 }
13324 
13325 // Class String_index_expression.
13326 
13327 // String index traversal.
13328 
13329 int
do_traverse(Traverse * traverse)13330 String_index_expression::do_traverse(Traverse* traverse)
13331 {
13332   if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
13333     return TRAVERSE_EXIT;
13334   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
13335     return TRAVERSE_EXIT;
13336   if (this->end_ != NULL)
13337     {
13338       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13339 	return TRAVERSE_EXIT;
13340     }
13341   return TRAVERSE_CONTINUE;
13342 }
13343 
13344 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13345 String_index_expression::do_flatten(Gogo*, Named_object*,
13346                                     Statement_inserter* inserter)
13347 {
13348   if (this->is_flattened_)
13349     return this;
13350   this->is_flattened_ = true;
13351 
13352   Location loc = this->location();
13353 
13354   if (this->is_error_expression())
13355     return Expression::make_error(loc);
13356 
13357   Expression* string = this->string_;
13358   Expression* start = this->start_;
13359   Expression* end = this->end_;
13360   if (string->is_error_expression()
13361       || string->type()->is_error_type()
13362       || start->is_error_expression()
13363       || start->type()->is_error_type()
13364       || (end != NULL
13365           && (end->is_error_expression() || end->type()->is_error_type())))
13366     {
13367       go_assert(saw_errors());
13368       return Expression::make_error(loc);
13369     }
13370 
13371   Temporary_statement* temp;
13372   if (!string->is_variable())
13373     {
13374       temp = Statement::make_temporary(NULL, string, loc);
13375       inserter->insert(temp);
13376       this->string_ = Expression::make_temporary_reference(temp, loc);
13377       string = this->string_;
13378     }
13379   if (!start->is_variable())
13380     {
13381       temp = Statement::make_temporary(NULL, start, loc);
13382       inserter->insert(temp);
13383       this->start_ = Expression::make_temporary_reference(temp, loc);
13384       start = this->start_;
13385     }
13386   if (end != NULL
13387       && !end->is_nil_expression()
13388       && !end->is_variable())
13389     {
13390       temp = Statement::make_temporary(NULL, end, loc);
13391       inserter->insert(temp);
13392       this->end_ = Expression::make_temporary_reference(temp, loc);
13393       end = this->end_;
13394     }
13395 
13396   Expression* len = Expression::make_string_info(string->copy(),
13397 						 STRING_INFO_LENGTH, loc);
13398   temp = Statement::make_temporary(NULL, len, loc);
13399   inserter->insert(temp);
13400   len = Expression::make_temporary_reference(temp, loc);
13401 
13402   // The order of bounds checks here matches the order used by the gc
13403   // compiler, as tested by issue30116[u].go.
13404 
13405   if (end != NULL && !end->is_nil_expression())
13406     {
13407       Expression::check_bounds(end, OPERATOR_LE, len,
13408 			       Runtime::PANIC_SLICE_ALEN,
13409 			       Runtime::PANIC_SLICE_ALEN_U,
13410 			       Runtime::PANIC_EXTEND_SLICE_ALEN,
13411 			       Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13412 			       inserter, loc);
13413       Expression::check_bounds(start, OPERATOR_LE, end,
13414 			       Runtime::PANIC_SLICE_B,
13415 			       Runtime::PANIC_SLICE_B_U,
13416 			       Runtime::PANIC_EXTEND_SLICE_B,
13417 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13418 			       inserter, loc);
13419     }
13420   else if (end != NULL)
13421     Expression::check_bounds(start, OPERATOR_LE, len,
13422 			     Runtime::PANIC_SLICE_B,
13423 			     Runtime::PANIC_SLICE_B_U,
13424 			     Runtime::PANIC_EXTEND_SLICE_B,
13425 			     Runtime::PANIC_EXTEND_SLICE_B_U,
13426 			     inserter, loc);
13427   else
13428     Expression::check_bounds(start, OPERATOR_LT, len,
13429 			     Runtime::PANIC_INDEX,
13430 			     Runtime::PANIC_INDEX_U,
13431 			     Runtime::PANIC_EXTEND_INDEX,
13432 			     Runtime::PANIC_EXTEND_INDEX_U,
13433 			     inserter, loc);
13434 
13435   return this;
13436 }
13437 
13438 // Return the type of a string index.
13439 
13440 Type*
do_type()13441 String_index_expression::do_type()
13442 {
13443   if (this->end_ == NULL)
13444     return Type::lookup_integer_type("uint8");
13445   else
13446     return this->string_->type();
13447 }
13448 
13449 // Determine the type of a string index.
13450 
13451 void
do_determine_type(const Type_context *)13452 String_index_expression::do_determine_type(const Type_context*)
13453 {
13454   this->string_->determine_type_no_context();
13455 
13456   Type_context index_context(Type::lookup_integer_type("int"), false);
13457   if (this->start_->is_constant())
13458     this->start_->determine_type(&index_context);
13459   else
13460     this->start_->determine_type_no_context();
13461   if (this->end_ != NULL)
13462     {
13463       if (this->end_->is_constant())
13464         this->end_->determine_type(&index_context);
13465       else
13466         this->end_->determine_type_no_context();
13467     }
13468 }
13469 
13470 // Check types of a string index.
13471 
13472 void
do_check_types(Gogo *)13473 String_index_expression::do_check_types(Gogo*)
13474 {
13475   Numeric_constant nc;
13476   unsigned long v;
13477   if (this->start_->type()->integer_type() == NULL
13478       && !this->start_->type()->is_error()
13479       && (!this->start_->type()->is_abstract()
13480 	  || !this->start_->numeric_constant_value(&nc)
13481 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13482     this->report_error(_("index must be integer"));
13483   if (this->end_ != NULL
13484       && this->end_->type()->integer_type() == NULL
13485       && !this->end_->type()->is_error()
13486       && !this->end_->is_nil_expression()
13487       && !this->end_->is_error_expression()
13488       && (!this->end_->type()->is_abstract()
13489 	  || !this->end_->numeric_constant_value(&nc)
13490 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13491     this->report_error(_("slice end must be integer"));
13492 
13493   std::string sval;
13494   bool sval_valid = this->string_->string_constant_value(&sval);
13495 
13496   Numeric_constant inc;
13497   mpz_t ival;
13498   bool ival_valid = false;
13499   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
13500     {
13501       ival_valid = true;
13502       if (mpz_sgn(ival) < 0
13503 	  || (sval_valid
13504 	      && (this->end_ == NULL
13505 		  ? mpz_cmp_ui(ival, sval.length()) >= 0
13506 		  : mpz_cmp_ui(ival, sval.length()) > 0)))
13507 	{
13508 	  go_error_at(this->start_->location(), "string index out of bounds");
13509 	  this->set_is_error();
13510 	}
13511     }
13512   if (this->end_ != NULL && !this->end_->is_nil_expression())
13513     {
13514       Numeric_constant enc;
13515       mpz_t eval;
13516       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
13517 	{
13518 	  if (mpz_sgn(eval) < 0
13519 	      || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
13520 	    {
13521 	      go_error_at(this->end_->location(), "string index out of bounds");
13522 	      this->set_is_error();
13523 	    }
13524 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
13525 	    this->report_error(_("inverted slice range"));
13526 	  mpz_clear(eval);
13527 	}
13528     }
13529   if (ival_valid)
13530     mpz_clear(ival);
13531 }
13532 
13533 // Get the backend representation for a string index.
13534 
13535 Bexpression*
do_get_backend(Translate_context * context)13536 String_index_expression::do_get_backend(Translate_context* context)
13537 {
13538   Location loc = this->location();
13539   Gogo* gogo = context->gogo();
13540 
13541   Type* int_type = Type::lookup_integer_type("int");
13542 
13543   // It is possible that an error occurred earlier because the start index
13544   // cannot be represented as an integer type.  In this case, we shouldn't
13545   // try casting the starting index into an integer since
13546   // Type_conversion_expression will fail to get the backend representation.
13547   // FIXME.
13548   if (this->start_->type()->integer_type() == NULL
13549       && !Type::are_convertible(int_type, this->start_->type(), NULL))
13550     {
13551       go_assert(saw_errors());
13552       return context->backend()->error_expression();
13553     }
13554 
13555   go_assert(this->string_->is_variable());
13556   go_assert(this->start_->is_variable());
13557 
13558   Expression* start = Expression::make_cast(int_type, this->start_, loc);
13559   Bfunction* bfn = context->function()->func_value()->get_decl();
13560 
13561   Expression* length =
13562     Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
13563   Expression* bytes =
13564     Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
13565 
13566   Bexpression* bstart = start->get_backend(context);
13567   Bexpression* ptr = bytes->get_backend(context);
13568 
13569   if (this->end_ == NULL)
13570     {
13571       ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
13572       Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
13573       return gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
13574     }
13575 
13576   Expression* end = NULL;
13577   if (this->end_->is_nil_expression())
13578     end = length;
13579   else
13580     {
13581       go_assert(this->end_->is_variable());
13582       end = Expression::make_cast(int_type, this->end_, loc);
13583     }
13584 
13585   end = end->copy();
13586   Bexpression* bend = end->get_backend(context);
13587   Bexpression* new_length =
13588     gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
13589 
13590   // If the new length is zero, don't change pointer.  Otherwise we can
13591   // get a pointer to the next object in memory, keeping it live
13592   // unnecessarily.  When the length is zero, the actual pointer
13593   // value doesn't matter.
13594   Btype* int_btype = int_type->get_backend(gogo);
13595   Bexpression* zero =
13596     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13597   Bexpression* cond =
13598     gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
13599                                        loc);
13600   Bexpression* offset =
13601     gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
13602                                             bstart, loc);
13603 
13604   ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
13605 
13606   Btype* str_btype = this->type()->get_backend(gogo);
13607   std::vector<Bexpression*> init;
13608   init.push_back(ptr);
13609   init.push_back(new_length);
13610   return gogo->backend()->constructor_expression(str_btype, init, loc);
13611 }
13612 
13613 // Export a string index expression.
13614 
13615 void
do_export(Export_function_body * efb) const13616 String_index_expression::do_export(Export_function_body* efb) const
13617 {
13618   efb->write_c_string("(");
13619   this->string_->export_expression(efb);
13620   efb->write_c_string(")[");
13621 
13622   Type* old_context = efb->type_context();
13623   efb->set_type_context(Type::lookup_integer_type("int"));
13624 
13625   this->start_->export_expression(efb);
13626   if (this->end_ != NULL)
13627     {
13628       efb->write_c_string(":");
13629       if (!this->end_->is_nil_expression())
13630 	this->end_->export_expression(efb);
13631     }
13632 
13633   efb->set_type_context(old_context);
13634 
13635   efb->write_c_string("]");
13636 }
13637 
13638 // Dump ast representation for a string index expression.
13639 
13640 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13641 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13642     const
13643 {
13644   Index_expression::dump_index_expression(ast_dump_context, this->string_,
13645                                           this->start_, this->end_, NULL);
13646 }
13647 
13648 // Make a string index expression.  END may be NULL.
13649 
13650 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)13651 Expression::make_string_index(Expression* string, Expression* start,
13652 			      Expression* end, Location location)
13653 {
13654   return new String_index_expression(string, start, end, location);
13655 }
13656 
13657 // Class Map_index.
13658 
13659 // Get the type of the map.
13660 
13661 Map_type*
get_map_type() const13662 Map_index_expression::get_map_type() const
13663 {
13664   Map_type* mt = this->map_->type()->map_type();
13665   if (mt == NULL)
13666     go_assert(saw_errors());
13667   return mt;
13668 }
13669 
13670 // Map index traversal.
13671 
13672 int
do_traverse(Traverse * traverse)13673 Map_index_expression::do_traverse(Traverse* traverse)
13674 {
13675   if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
13676     return TRAVERSE_EXIT;
13677   return Expression::traverse(&this->index_, traverse);
13678 }
13679 
13680 // We need to pass in a pointer to the key, so flatten the index into a
13681 // temporary variable if it isn't already.  The value pointer will be
13682 // dereferenced and checked for nil, so flatten into a temporary to avoid
13683 // recomputation.
13684 
13685 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13686 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
13687 				 Statement_inserter* inserter)
13688 {
13689   Location loc = this->location();
13690   Map_type* mt = this->get_map_type();
13691   if (this->index()->is_error_expression()
13692       || this->index()->type()->is_error_type()
13693       || mt->is_error_type())
13694     {
13695       go_assert(saw_errors());
13696       return Expression::make_error(loc);
13697     }
13698 
13699   // Avoid copy for string([]byte) conversions used in map keys.
13700   // mapaccess doesn't keep the reference, so this is safe.
13701   Type_conversion_expression* ce = this->index_->conversion_expression();
13702   if (ce != NULL && ce->type()->is_string_type()
13703       && ce->expr()->type()->is_slice_type())
13704     ce->set_no_copy(true);
13705 
13706   if (!Type::are_identical(mt->key_type(), this->index_->type(),
13707 			   Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
13708 			   NULL))
13709     {
13710       if (this->index_->type()->interface_type() != NULL
13711 	  && !this->index_->is_variable())
13712 	{
13713 	  Temporary_statement* temp =
13714 	    Statement::make_temporary(NULL, this->index_, loc);
13715 	  inserter->insert(temp);
13716 	  this->index_ = Expression::make_temporary_reference(temp, loc);
13717 	}
13718       this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
13719 							this->index_, loc);
13720     }
13721 
13722   if (!this->index_->is_variable())
13723     {
13724       Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
13725                                                             loc);
13726       inserter->insert(temp);
13727       this->index_ = Expression::make_temporary_reference(temp, loc);
13728     }
13729 
13730   if (this->value_pointer_ == NULL)
13731     this->get_value_pointer(gogo);
13732   if (this->value_pointer_->is_error_expression()
13733       || this->value_pointer_->type()->is_error_type())
13734     return Expression::make_error(loc);
13735   if (!this->value_pointer_->is_variable())
13736     {
13737       Temporary_statement* temp =
13738 	Statement::make_temporary(NULL, this->value_pointer_, loc);
13739       inserter->insert(temp);
13740       this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
13741     }
13742 
13743   return this;
13744 }
13745 
13746 // Return the type of a map index.
13747 
13748 Type*
do_type()13749 Map_index_expression::do_type()
13750 {
13751   Map_type* mt = this->get_map_type();
13752   if (mt == NULL)
13753     return Type::make_error_type();
13754   return mt->val_type();
13755 }
13756 
13757 // Fix the type of a map index.
13758 
13759 void
do_determine_type(const Type_context *)13760 Map_index_expression::do_determine_type(const Type_context*)
13761 {
13762   this->map_->determine_type_no_context();
13763   Map_type* mt = this->get_map_type();
13764   Type* key_type = mt == NULL ? NULL : mt->key_type();
13765   Type_context subcontext(key_type, false);
13766   this->index_->determine_type(&subcontext);
13767 }
13768 
13769 // Check types of a map index.
13770 
13771 void
do_check_types(Gogo *)13772 Map_index_expression::do_check_types(Gogo*)
13773 {
13774   std::string reason;
13775   Map_type* mt = this->get_map_type();
13776   if (mt == NULL)
13777     return;
13778   if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
13779     {
13780       if (reason.empty())
13781 	this->report_error(_("incompatible type for map index"));
13782       else
13783 	{
13784 	  go_error_at(this->location(), "incompatible type for map index (%s)",
13785                       reason.c_str());
13786 	  this->set_is_error();
13787 	}
13788     }
13789 }
13790 
13791 // Add explicit type conversions.
13792 
13793 void
do_add_conversions()13794 Map_index_expression::do_add_conversions()
13795 {
13796   Map_type* mt = this->get_map_type();
13797   if (mt == NULL)
13798     return;
13799   Type* lt = mt->key_type();
13800   Type* rt = this->index_->type();
13801   if (!Type::are_identical(lt, rt, 0, NULL)
13802       && lt->interface_type() != NULL)
13803     this->index_ = Expression::make_cast(lt, this->index_, this->location());
13804 }
13805 
13806 // Get the backend representation for a map index.
13807 
13808 Bexpression*
do_get_backend(Translate_context * context)13809 Map_index_expression::do_get_backend(Translate_context* context)
13810 {
13811   Map_type* type = this->get_map_type();
13812   if (type == NULL)
13813     {
13814       go_assert(saw_errors());
13815       return context->backend()->error_expression();
13816     }
13817 
13818   go_assert(this->value_pointer_ != NULL
13819             && this->value_pointer_->is_variable());
13820 
13821   Expression* val = Expression::make_dereference(this->value_pointer_,
13822                                                  NIL_CHECK_NOT_NEEDED,
13823                                                  this->location());
13824   return val->get_backend(context);
13825 }
13826 
13827 // Get an expression for the map index.  This returns an expression
13828 // that evaluates to a pointer to a value.  If the key is not in the
13829 // map, the pointer will point to a zero value.
13830 
13831 Expression*
get_value_pointer(Gogo * gogo)13832 Map_index_expression::get_value_pointer(Gogo* gogo)
13833 {
13834   if (this->value_pointer_ == NULL)
13835     {
13836       Map_type* type = this->get_map_type();
13837       if (type == NULL)
13838 	{
13839 	  go_assert(saw_errors());
13840 	  return Expression::make_error(this->location());
13841 	}
13842 
13843       Location loc = this->location();
13844       Expression* map_ref = this->map_;
13845 
13846       Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
13847 						     this->index_,
13848                                                      loc);
13849 
13850       Expression* type_expr = Expression::make_type_descriptor(type, loc);
13851       Expression* zero = type->fat_zero_value(gogo);
13852       Expression* map_index;
13853       if (zero == NULL)
13854         {
13855           Runtime::Function code;
13856           Expression* key;
13857           switch (type->algorithm(gogo))
13858             {
13859               case Map_type::MAP_ALG_FAST32:
13860               case Map_type::MAP_ALG_FAST32PTR:
13861                 {
13862                   Type* uint32_type = Type::lookup_integer_type("uint32");
13863                   Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
13864                   key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
13865                                                      loc);
13866                   key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13867                                                      loc);
13868                   code = Runtime::MAPACCESS1_FAST32;
13869                   break;
13870                 }
13871               case Map_type::MAP_ALG_FAST64:
13872               case Map_type::MAP_ALG_FAST64PTR:
13873                 {
13874                   Type* uint64_type = Type::lookup_integer_type("uint64");
13875                   Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
13876                   key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
13877                                                      loc);
13878                   key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13879                                                      loc);
13880                   code = Runtime::MAPACCESS1_FAST64;
13881                   break;
13882                 }
13883               case Map_type::MAP_ALG_FASTSTR:
13884                 key = this->index_;
13885                 code = Runtime::MAPACCESS1_FASTSTR;
13886                 break;
13887               default:
13888                 key = index_ptr;
13889                 code = Runtime::MAPACCESS1;
13890                 break;
13891             }
13892           map_index = Runtime::make_call(code, loc, 3,
13893                                          type_expr, map_ref, key);
13894         }
13895       else
13896         map_index = Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
13897                                        type_expr, map_ref, index_ptr, zero);
13898 
13899       Type* val_type = type->val_type();
13900       this->value_pointer_ =
13901           Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
13902                                        map_index, this->location());
13903     }
13904 
13905   return this->value_pointer_;
13906 }
13907 
13908 // Export a map index expression.
13909 
13910 void
do_export(Export_function_body * efb) const13911 Map_index_expression::do_export(Export_function_body* efb) const
13912 {
13913   efb->write_c_string("(");
13914   this->map_->export_expression(efb);
13915   efb->write_c_string(")[");
13916 
13917   Type* old_context = efb->type_context();
13918   efb->set_type_context(this->get_map_type()->key_type());
13919 
13920   this->index_->export_expression(efb);
13921 
13922   efb->set_type_context(old_context);
13923 
13924   efb->write_c_string("]");
13925 }
13926 
13927 // Dump ast representation for a map index expression
13928 
13929 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13930 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13931     const
13932 {
13933   Index_expression::dump_index_expression(ast_dump_context, this->map_,
13934                                           this->index_, NULL, NULL);
13935 }
13936 
13937 // Make a map index expression.
13938 
13939 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)13940 Expression::make_map_index(Expression* map, Expression* index,
13941 			   Location location)
13942 {
13943   return new Map_index_expression(map, index, location);
13944 }
13945 
13946 // Class Field_reference_expression.
13947 
13948 // Lower a field reference expression.  There is nothing to lower, but
13949 // this is where we generate the tracking information for fields with
13950 // the magic go:"track" tag.
13951 
13952 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)13953 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
13954 				     Statement_inserter* inserter, int)
13955 {
13956   Struct_type* struct_type = this->expr_->type()->struct_type();
13957   if (struct_type == NULL)
13958     {
13959       // Error will be reported elsewhere.
13960       return this;
13961     }
13962   const Struct_field* field = struct_type->field(this->field_index_);
13963   if (field == NULL)
13964     return this;
13965   if (!field->has_tag())
13966     return this;
13967   if (field->tag().find("go:\"track\"") == std::string::npos)
13968     return this;
13969 
13970   // References from functions generated by the compiler don't count.
13971   if (function != NULL && function->func_value()->is_type_specific_function())
13972     return this;
13973 
13974   // We have found a reference to a tracked field.  Build a call to
13975   // the runtime function __go_fieldtrack with a string that describes
13976   // the field.  FIXME: We should only call this once per referenced
13977   // field per function, not once for each reference to the field.
13978 
13979   if (this->called_fieldtrack_)
13980     return this;
13981   this->called_fieldtrack_ = true;
13982 
13983   Location loc = this->location();
13984 
13985   std::string s = "fieldtrack \"";
13986   Named_type* nt = this->expr_->type()->unalias()->named_type();
13987   if (nt == NULL || nt->named_object()->package() == NULL)
13988     s.append(gogo->pkgpath());
13989   else
13990     s.append(nt->named_object()->package()->pkgpath());
13991   s.push_back('.');
13992   if (nt != NULL)
13993     s.append(Gogo::unpack_hidden_name(nt->name()));
13994   s.push_back('.');
13995   s.append(Gogo::unpack_hidden_name(field->field_name()));
13996   s.push_back('"');
13997 
13998   // We can't use a string here, because internally a string holds a
13999   // pointer to the actual bytes; when the linker garbage collects the
14000   // string, it won't garbage collect the bytes.  So we use a
14001   // [...]byte.
14002 
14003   Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
14004 
14005   Type* byte_type = gogo->lookup_global("byte")->type_value();
14006   Array_type* array_type = Type::make_array_type(byte_type, length_expr);
14007   array_type->set_is_array_incomparable();
14008 
14009   Expression_list* bytes = new Expression_list();
14010   for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
14011     {
14012       unsigned char c = static_cast<unsigned char>(*p);
14013       bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
14014     }
14015 
14016   Expression* e = Expression::make_composite_literal(array_type, 0, false,
14017 						     bytes, false, loc);
14018 
14019   Variable* var = new Variable(array_type, e, true, false, false, loc);
14020 
14021   static int count;
14022   char buf[50];
14023   snprintf(buf, sizeof buf, "fieldtrack.%d", count);
14024   ++count;
14025 
14026   Named_object* no = gogo->add_variable(buf, var);
14027   e = Expression::make_var_reference(no, loc);
14028   e = Expression::make_unary(OPERATOR_AND, e, loc);
14029 
14030   Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
14031   gogo->lower_expression(function, inserter, &call);
14032   inserter->insert(Statement::make_statement(call, false));
14033 
14034   // Put this function, and the global variable we just created, into
14035   // unique sections.  This will permit the linker to garbage collect
14036   // them if they are not referenced.  The effect is that the only
14037   // strings, indicating field references, that will wind up in the
14038   // executable will be those for functions that are actually needed.
14039   if (function != NULL)
14040     function->func_value()->set_in_unique_section();
14041   var->set_in_unique_section();
14042 
14043   return this;
14044 }
14045 
14046 // Return the type of a field reference.
14047 
14048 Type*
do_type()14049 Field_reference_expression::do_type()
14050 {
14051   Type* type = this->expr_->type();
14052   if (type->is_error())
14053     return type;
14054   Struct_type* struct_type = type->struct_type();
14055   go_assert(struct_type != NULL);
14056   return struct_type->field(this->field_index_)->type();
14057 }
14058 
14059 // Check the types for a field reference.
14060 
14061 void
do_check_types(Gogo *)14062 Field_reference_expression::do_check_types(Gogo*)
14063 {
14064   Type* type = this->expr_->type();
14065   if (type->is_error())
14066     return;
14067   Struct_type* struct_type = type->struct_type();
14068   go_assert(struct_type != NULL);
14069   go_assert(struct_type->field(this->field_index_) != NULL);
14070 }
14071 
14072 // Get the backend representation for a field reference.
14073 
14074 Bexpression*
do_get_backend(Translate_context * context)14075 Field_reference_expression::do_get_backend(Translate_context* context)
14076 {
14077   Bexpression* bstruct = this->expr_->get_backend(context);
14078   return context->gogo()->backend()->struct_field_expression(bstruct,
14079 							     this->field_index_,
14080 							     this->location());
14081 }
14082 
14083 // Dump ast representation for a field reference expression.
14084 
14085 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14086 Field_reference_expression::do_dump_expression(
14087     Ast_dump_context* ast_dump_context) const
14088 {
14089   this->expr_->dump_expression(ast_dump_context);
14090   ast_dump_context->ostream() << "." <<  this->field_index_;
14091 }
14092 
14093 // Make a reference to a qualified identifier in an expression.
14094 
14095 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)14096 Expression::make_field_reference(Expression* expr, unsigned int field_index,
14097 				 Location location)
14098 {
14099   return new Field_reference_expression(expr, field_index, location);
14100 }
14101 
14102 // Class Interface_field_reference_expression.
14103 
14104 // Return an expression for the pointer to the function to call.
14105 
14106 Expression*
get_function()14107 Interface_field_reference_expression::get_function()
14108 {
14109   Expression* ref = this->expr_;
14110   Location loc = this->location();
14111   if (ref->type()->points_to() != NULL)
14112     ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
14113 
14114   Expression* mtable =
14115       Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
14116   Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
14117 
14118   std::string name = Gogo::unpack_hidden_name(this->name_);
14119   unsigned int index;
14120   const Struct_field* field = mtable_type->find_local_field(name, &index);
14121   go_assert(field != NULL);
14122 
14123   mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
14124   return Expression::make_field_reference(mtable, index, loc);
14125 }
14126 
14127 // Return an expression for the first argument to pass to the interface
14128 // function.
14129 
14130 Expression*
get_underlying_object()14131 Interface_field_reference_expression::get_underlying_object()
14132 {
14133   Expression* expr = this->expr_;
14134   if (expr->type()->points_to() != NULL)
14135     expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
14136                                         this->location());
14137   return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
14138                                          this->location());
14139 }
14140 
14141 // Traversal.
14142 
14143 int
do_traverse(Traverse * traverse)14144 Interface_field_reference_expression::do_traverse(Traverse* traverse)
14145 {
14146   return Expression::traverse(&this->expr_, traverse);
14147 }
14148 
14149 // Lower the expression.  If this expression is not called, we need to
14150 // evaluate the expression twice when converting to the backend
14151 // interface.  So introduce a temporary variable if necessary.
14152 
14153 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14154 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
14155 						 Statement_inserter* inserter)
14156 {
14157   if (this->expr_->is_error_expression()
14158       || this->expr_->type()->is_error_type())
14159     {
14160       go_assert(saw_errors());
14161       return Expression::make_error(this->location());
14162     }
14163 
14164   if (!this->expr_->is_variable())
14165     {
14166       Temporary_statement* temp =
14167 	Statement::make_temporary(NULL, this->expr_, this->location());
14168       inserter->insert(temp);
14169       this->expr_ = Expression::make_temporary_reference(temp, this->location());
14170     }
14171   return this;
14172 }
14173 
14174 // Return the type of an interface field reference.
14175 
14176 Type*
do_type()14177 Interface_field_reference_expression::do_type()
14178 {
14179   Type* expr_type = this->expr_->type();
14180 
14181   Type* points_to = expr_type->points_to();
14182   if (points_to != NULL)
14183     expr_type = points_to;
14184 
14185   Interface_type* interface_type = expr_type->interface_type();
14186   if (interface_type == NULL)
14187     return Type::make_error_type();
14188 
14189   const Typed_identifier* method = interface_type->find_method(this->name_);
14190   if (method == NULL)
14191     return Type::make_error_type();
14192 
14193   return method->type();
14194 }
14195 
14196 // Determine types.
14197 
14198 void
do_determine_type(const Type_context *)14199 Interface_field_reference_expression::do_determine_type(const Type_context*)
14200 {
14201   this->expr_->determine_type_no_context();
14202 }
14203 
14204 // Check the types for an interface field reference.
14205 
14206 void
do_check_types(Gogo *)14207 Interface_field_reference_expression::do_check_types(Gogo*)
14208 {
14209   Type* type = this->expr_->type();
14210 
14211   Type* points_to = type->points_to();
14212   if (points_to != NULL)
14213     type = points_to;
14214 
14215   Interface_type* interface_type = type->interface_type();
14216   if (interface_type == NULL)
14217     {
14218       if (!type->is_error_type())
14219 	this->report_error(_("expected interface or pointer to interface"));
14220     }
14221   else
14222     {
14223       const Typed_identifier* method =
14224 	interface_type->find_method(this->name_);
14225       if (method == NULL)
14226 	{
14227 	  go_error_at(this->location(), "method %qs not in interface",
14228                       Gogo::message_name(this->name_).c_str());
14229 	  this->set_is_error();
14230 	}
14231     }
14232 }
14233 
14234 // If an interface field reference is not simply called, then it is
14235 // represented as a closure.  The closure will hold a single variable,
14236 // the value of the interface on which the method should be called.
14237 // The function will be a simple thunk that pulls the value from the
14238 // closure and calls the method with the remaining arguments.
14239 
14240 // Because method values are not common, we don't build all thunks for
14241 // all possible interface methods, but instead only build them as we
14242 // need them.  In particular, we even build them on demand for
14243 // interface methods defined in other packages.
14244 
14245 Interface_field_reference_expression::Interface_method_thunks
14246   Interface_field_reference_expression::interface_method_thunks;
14247 
14248 // Find or create the thunk to call method NAME on TYPE.
14249 
14250 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)14251 Interface_field_reference_expression::create_thunk(Gogo* gogo,
14252 						   Interface_type* type,
14253 						   const std::string& name)
14254 {
14255   std::pair<Interface_type*, Method_thunks*> val(type, NULL);
14256   std::pair<Interface_method_thunks::iterator, bool> ins =
14257     Interface_field_reference_expression::interface_method_thunks.insert(val);
14258   if (ins.second)
14259     {
14260       // This is the first time we have seen this interface.
14261       ins.first->second = new Method_thunks();
14262     }
14263 
14264   for (Method_thunks::const_iterator p = ins.first->second->begin();
14265        p != ins.first->second->end();
14266        p++)
14267     if (p->first == name)
14268       return p->second;
14269 
14270   Location loc = type->location();
14271 
14272   const Typed_identifier* method_id = type->find_method(name);
14273   if (method_id == NULL)
14274     return Named_object::make_erroneous_name(gogo->thunk_name());
14275 
14276   Function_type* orig_fntype = method_id->type()->function_type();
14277   if (orig_fntype == NULL)
14278     return Named_object::make_erroneous_name(gogo->thunk_name());
14279 
14280   Struct_field_list* sfl = new Struct_field_list();
14281   // The type here is wrong--it should be the C function type.  But it
14282   // doesn't really matter.
14283   Type* vt = Type::make_pointer_type(Type::make_void_type());
14284   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
14285   sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
14286   Struct_type* st = Type::make_struct_type(sfl, loc);
14287   st->set_is_struct_incomparable();
14288   Type* closure_type = Type::make_pointer_type(st);
14289 
14290   Function_type* new_fntype = orig_fntype->copy_with_names();
14291 
14292   std::string thunk_name = gogo->thunk_name();
14293   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
14294 					      false, loc);
14295 
14296   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
14297   cvar->set_is_used();
14298   cvar->set_is_closure();
14299   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
14300 						 NULL, cvar);
14301   new_no->func_value()->set_closure_var(cp);
14302 
14303   gogo->start_block(loc);
14304 
14305   // Field 0 of the closure is the function code pointer, field 1 is
14306   // the value on which to invoke the method.
14307   Expression* arg = Expression::make_var_reference(cp, loc);
14308   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
14309   arg = Expression::make_field_reference(arg, 1, loc);
14310 
14311   Expression *ifre = Expression::make_interface_field_reference(arg, name,
14312 								loc);
14313 
14314   const Typed_identifier_list* orig_params = orig_fntype->parameters();
14315   Expression_list* args;
14316   if (orig_params == NULL || orig_params->empty())
14317     args = NULL;
14318   else
14319     {
14320       const Typed_identifier_list* new_params = new_fntype->parameters();
14321       args = new Expression_list();
14322       for (Typed_identifier_list::const_iterator p = new_params->begin();
14323 	   p != new_params->end();
14324 	   ++p)
14325 	{
14326 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
14327 	  go_assert(p_no != NULL
14328 		    && p_no->is_variable()
14329 		    && p_no->var_value()->is_parameter());
14330 	  args->push_back(Expression::make_var_reference(p_no, loc));
14331 	}
14332     }
14333 
14334   Call_expression* call = Expression::make_call(ifre, args,
14335 						orig_fntype->is_varargs(),
14336 						loc);
14337   call->set_varargs_are_lowered();
14338 
14339   Statement* s = Statement::make_return_from_call(call, loc);
14340   gogo->add_statement(s);
14341   Block* b = gogo->finish_block(loc);
14342   gogo->add_block(b, loc);
14343   gogo->lower_block(new_no, b);
14344   gogo->flatten_block(new_no, b);
14345   gogo->finish_function(loc);
14346 
14347   ins.first->second->push_back(std::make_pair(name, new_no));
14348   return new_no;
14349 }
14350 
14351 // Get the backend representation for a method value.
14352 
14353 Bexpression*
do_get_backend(Translate_context * context)14354 Interface_field_reference_expression::do_get_backend(Translate_context* context)
14355 {
14356   Interface_type* type = this->expr_->type()->interface_type();
14357   if (type == NULL)
14358     {
14359       go_assert(saw_errors());
14360       return context->backend()->error_expression();
14361     }
14362 
14363   Named_object* thunk =
14364     Interface_field_reference_expression::create_thunk(context->gogo(),
14365 						       type, this->name_);
14366   if (thunk->is_erroneous())
14367     {
14368       go_assert(saw_errors());
14369       return context->backend()->error_expression();
14370     }
14371 
14372   // FIXME: We should lower this earlier, but we can't it lower it in
14373   // the lowering pass because at that point we don't know whether we
14374   // need to create the thunk or not.  If the expression is called, we
14375   // don't need the thunk.
14376 
14377   Location loc = this->location();
14378 
14379   Struct_field_list* fields = new Struct_field_list();
14380   fields->push_back(Struct_field(Typed_identifier("fn",
14381 						  thunk->func_value()->type(),
14382 						  loc)));
14383   fields->push_back(Struct_field(Typed_identifier("val",
14384 						  this->expr_->type(),
14385 						  loc)));
14386   Struct_type* st = Type::make_struct_type(fields, loc);
14387   st->set_is_struct_incomparable();
14388 
14389   Expression_list* vals = new Expression_list();
14390   vals->push_back(Expression::make_func_code_reference(thunk, loc));
14391   vals->push_back(this->expr_);
14392 
14393   Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
14394   Bexpression* bclosure =
14395     Expression::make_heap_expression(expr, loc)->get_backend(context);
14396 
14397   Gogo* gogo = context->gogo();
14398   Btype* btype = this->type()->get_backend(gogo);
14399   bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
14400 
14401   Expression* nil_check =
14402       Expression::make_binary(OPERATOR_EQEQ, this->expr_,
14403                               Expression::make_nil(loc), loc);
14404   Bexpression* bnil_check = nil_check->get_backend(context);
14405 
14406   Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
14407   Bexpression* bcrash = crash->get_backend(context);
14408 
14409   Bfunction* bfn = context->function()->func_value()->get_decl();
14410   Bexpression* bcond =
14411       gogo->backend()->conditional_expression(bfn, NULL,
14412                                               bnil_check, bcrash, NULL, loc);
14413   Bfunction* bfunction = context->function()->func_value()->get_decl();
14414   Bstatement* cond_statement =
14415       gogo->backend()->expression_statement(bfunction, bcond);
14416   return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
14417 }
14418 
14419 // Dump ast representation for an interface field reference.
14420 
14421 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14422 Interface_field_reference_expression::do_dump_expression(
14423     Ast_dump_context* ast_dump_context) const
14424 {
14425   this->expr_->dump_expression(ast_dump_context);
14426   ast_dump_context->ostream() << "." << this->name_;
14427 }
14428 
14429 // Make a reference to a field in an interface.
14430 
14431 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)14432 Expression::make_interface_field_reference(Expression* expr,
14433 					   const std::string& field,
14434 					   Location location)
14435 {
14436   return new Interface_field_reference_expression(expr, field, location);
14437 }
14438 
14439 // A general selector.  This is a Parser_expression for LEFT.NAME.  It
14440 // is lowered after we know the type of the left hand side.
14441 
14442 class Selector_expression : public Parser_expression
14443 {
14444  public:
Selector_expression(Expression * left,const std::string & name,Location location)14445   Selector_expression(Expression* left, const std::string& name,
14446 		      Location location)
14447     : Parser_expression(EXPRESSION_SELECTOR, location),
14448       left_(left), name_(name)
14449   { }
14450 
14451  protected:
14452   int
do_traverse(Traverse * traverse)14453   do_traverse(Traverse* traverse)
14454   { return Expression::traverse(&this->left_, traverse); }
14455 
14456   Expression*
14457   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
14458 
14459   Expression*
do_copy()14460   do_copy()
14461   {
14462     return new Selector_expression(this->left_->copy(), this->name_,
14463 				   this->location());
14464   }
14465 
14466   void
14467   do_dump_expression(Ast_dump_context* ast_dump_context) const;
14468 
14469  private:
14470   Expression*
14471   lower_method_expression(Gogo*);
14472 
14473   // The expression on the left hand side.
14474   Expression* left_;
14475   // The name on the right hand side.
14476   std::string name_;
14477 };
14478 
14479 // Lower a selector expression once we know the real type of the left
14480 // hand side.
14481 
14482 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)14483 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
14484 			      int)
14485 {
14486   Expression* left = this->left_;
14487   if (left->is_type_expression())
14488     return this->lower_method_expression(gogo);
14489   return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
14490 				    this->location());
14491 }
14492 
14493 // Lower a method expression T.M or (*T).M.  We turn this into a
14494 // function literal.
14495 
14496 Expression*
lower_method_expression(Gogo * gogo)14497 Selector_expression::lower_method_expression(Gogo* gogo)
14498 {
14499   Location location = this->location();
14500   Type* left_type = this->left_->type();
14501   Type* type = left_type;
14502   const std::string& name(this->name_);
14503 
14504   bool is_pointer;
14505   if (type->points_to() == NULL)
14506     is_pointer = false;
14507   else
14508     {
14509       is_pointer = true;
14510       type = type->points_to();
14511     }
14512   Named_type* nt = type->named_type();
14513   if (nt == NULL)
14514     {
14515       go_error_at(location,
14516                   ("method expression requires named type or "
14517                    "pointer to named type"));
14518       return Expression::make_error(location);
14519     }
14520 
14521   bool is_ambiguous;
14522   Method* method = nt->method_function(name, &is_ambiguous);
14523   const Typed_identifier* imethod = NULL;
14524   if (method == NULL && !is_pointer)
14525     {
14526       Interface_type* it = nt->interface_type();
14527       if (it != NULL)
14528 	imethod = it->find_method(name);
14529     }
14530 
14531   if ((method == NULL && imethod == NULL)
14532       || (left_type->named_type() != NULL && left_type->points_to() != NULL))
14533     {
14534       if (!is_ambiguous)
14535 	go_error_at(location, "type %<%s%s%> has no method %<%s%>",
14536                     is_pointer ? "*" : "",
14537                     nt->message_name().c_str(),
14538                     Gogo::message_name(name).c_str());
14539       else
14540 	go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
14541                     Gogo::message_name(name).c_str(),
14542                     is_pointer ? "*" : "",
14543                     nt->message_name().c_str());
14544       return Expression::make_error(location);
14545     }
14546 
14547   if (method != NULL && !is_pointer && !method->is_value_method())
14548     {
14549       go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
14550                   nt->message_name().c_str(),
14551                   Gogo::message_name(name).c_str());
14552       return Expression::make_error(location);
14553     }
14554 
14555   // Build a new function type in which the receiver becomes the first
14556   // argument.
14557   Function_type* method_type;
14558   if (method != NULL)
14559     {
14560       method_type = method->type();
14561       go_assert(method_type->is_method());
14562     }
14563   else
14564     {
14565       method_type = imethod->type()->function_type();
14566       go_assert(method_type != NULL && !method_type->is_method());
14567     }
14568 
14569   const char* const receiver_name = "$this";
14570   Typed_identifier_list* parameters = new Typed_identifier_list();
14571   parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
14572 					 location));
14573 
14574   const Typed_identifier_list* method_parameters = method_type->parameters();
14575   if (method_parameters != NULL)
14576     {
14577       int i = 0;
14578       for (Typed_identifier_list::const_iterator p = method_parameters->begin();
14579 	   p != method_parameters->end();
14580 	   ++p, ++i)
14581 	{
14582 	  if (!p->name().empty())
14583 	    parameters->push_back(*p);
14584 	  else
14585 	    {
14586 	      char buf[20];
14587 	      snprintf(buf, sizeof buf, "$param%d", i);
14588 	      parameters->push_back(Typed_identifier(buf, p->type(),
14589 						     p->location()));
14590 	    }
14591 	}
14592     }
14593 
14594   const Typed_identifier_list* method_results = method_type->results();
14595   Typed_identifier_list* results;
14596   if (method_results == NULL)
14597     results = NULL;
14598   else
14599     {
14600       results = new Typed_identifier_list();
14601       for (Typed_identifier_list::const_iterator p = method_results->begin();
14602 	   p != method_results->end();
14603 	   ++p)
14604 	results->push_back(*p);
14605     }
14606 
14607   Function_type* fntype = Type::make_function_type(NULL, parameters, results,
14608 						   location);
14609   if (method_type->is_varargs())
14610     fntype->set_is_varargs();
14611 
14612   // We generate methods which always takes a pointer to the receiver
14613   // as their first argument.  If this is for a pointer type, we can
14614   // simply reuse the existing function.  We use an internal hack to
14615   // get the right type.
14616   // FIXME: This optimization is disabled because it doesn't yet work
14617   // with function descriptors when the method expression is not
14618   // directly called.
14619   if (method != NULL && is_pointer && false)
14620     {
14621       Named_object* mno = (method->needs_stub_method()
14622 			   ? method->stub_object()
14623 			   : method->named_object());
14624       Expression* f = Expression::make_func_reference(mno, NULL, location);
14625       f = Expression::make_cast(fntype, f, location);
14626       Type_conversion_expression* tce =
14627 	static_cast<Type_conversion_expression*>(f);
14628       tce->set_may_convert_function_types();
14629       return f;
14630     }
14631 
14632   Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
14633 					  location);
14634 
14635   Named_object* vno = gogo->lookup(receiver_name, NULL);
14636   go_assert(vno != NULL);
14637   Expression* ve = Expression::make_var_reference(vno, location);
14638   Expression* bm;
14639   if (method != NULL)
14640     bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
14641   else
14642     bm = Expression::make_interface_field_reference(ve, name, location);
14643 
14644   // Even though we found the method above, if it has an error type we
14645   // may see an error here.
14646   if (bm->is_error_expression())
14647     {
14648       gogo->finish_function(location);
14649       return bm;
14650     }
14651 
14652   Expression_list* args;
14653   if (parameters->size() <= 1)
14654     args = NULL;
14655   else
14656     {
14657       args = new Expression_list();
14658       Typed_identifier_list::const_iterator p = parameters->begin();
14659       ++p;
14660       for (; p != parameters->end(); ++p)
14661 	{
14662 	  vno = gogo->lookup(p->name(), NULL);
14663 	  go_assert(vno != NULL);
14664 	  args->push_back(Expression::make_var_reference(vno, location));
14665 	}
14666     }
14667 
14668   gogo->start_block(location);
14669 
14670   Call_expression* call = Expression::make_call(bm, args,
14671 						method_type->is_varargs(),
14672 						location);
14673 
14674   Statement* s = Statement::make_return_from_call(call, location);
14675   gogo->add_statement(s);
14676 
14677   Block* b = gogo->finish_block(location);
14678 
14679   gogo->add_block(b, location);
14680 
14681   // Lower the call in case there are multiple results.
14682   gogo->lower_block(no, b);
14683   gogo->flatten_block(no, b);
14684 
14685   gogo->finish_function(location);
14686 
14687   return Expression::make_func_reference(no, NULL, location);
14688 }
14689 
14690 // Dump the ast for a selector expression.
14691 
14692 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14693 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14694     const
14695 {
14696   ast_dump_context->dump_expression(this->left_);
14697   ast_dump_context->ostream() << ".";
14698   ast_dump_context->ostream() << this->name_;
14699 }
14700 
14701 // Make a selector expression.
14702 
14703 Expression*
make_selector(Expression * left,const std::string & name,Location location)14704 Expression::make_selector(Expression* left, const std::string& name,
14705 			  Location location)
14706 {
14707   return new Selector_expression(left, name, location);
14708 }
14709 
14710 // Class Allocation_expression.
14711 
14712 int
do_traverse(Traverse * traverse)14713 Allocation_expression::do_traverse(Traverse* traverse)
14714 {
14715   return Type::traverse(this->type_, traverse);
14716 }
14717 
14718 Type*
do_type()14719 Allocation_expression::do_type()
14720 {
14721   return Type::make_pointer_type(this->type_);
14722 }
14723 
14724 void
do_check_types(Gogo *)14725 Allocation_expression::do_check_types(Gogo*)
14726 {
14727   if (!this->type_->in_heap())
14728     go_error_at(this->location(), "cannot heap allocate go:notinheap type");
14729 }
14730 
14731 // Make a copy of an allocation expression.
14732 
14733 Expression*
do_copy()14734 Allocation_expression::do_copy()
14735 {
14736   Allocation_expression* alloc =
14737     new Allocation_expression(this->type_->copy_expressions(),
14738 			      this->location());
14739   if (this->allocate_on_stack_)
14740     alloc->set_allocate_on_stack();
14741   if (this->no_zero_)
14742     alloc->set_no_zero();
14743   return alloc;
14744 }
14745 
14746 // Return the backend representation for an allocation expression.
14747 
14748 Bexpression*
do_get_backend(Translate_context * context)14749 Allocation_expression::do_get_backend(Translate_context* context)
14750 {
14751   Gogo* gogo = context->gogo();
14752   Location loc = this->location();
14753   Btype* btype = this->type_->get_backend(gogo);
14754 
14755   if (this->allocate_on_stack_)
14756     {
14757       int64_t size;
14758       bool ok = this->type_->backend_type_size(gogo, &size);
14759       if (!ok)
14760         {
14761           go_assert(saw_errors());
14762           return gogo->backend()->error_expression();
14763         }
14764       Bstatement* decl;
14765       Named_object* fn = context->function();
14766       go_assert(fn != NULL);
14767       Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14768       Bexpression* init = (this->no_zero_
14769                            ? NULL
14770                            : gogo->backend()->zero_expression(btype));
14771       Bvariable* temp =
14772         gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14773                                             init, true, loc, &decl);
14774       Bexpression* ret = gogo->backend()->var_expression(temp, loc);
14775       ret = gogo->backend()->address_expression(ret, loc);
14776       ret = gogo->backend()->compound_expression(decl, ret, loc);
14777       return ret;
14778     }
14779 
14780   Bexpression* space =
14781     gogo->allocate_memory(this->type_, loc)->get_backend(context);
14782   Btype* pbtype = gogo->backend()->pointer_type(btype);
14783   return gogo->backend()->convert_expression(pbtype, space, loc);
14784 }
14785 
14786 // Dump ast representation for an allocation expression.
14787 
14788 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14789 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14790     const
14791 {
14792   ast_dump_context->ostream() << "new(";
14793   ast_dump_context->dump_type(this->type_);
14794   ast_dump_context->ostream() << ")";
14795 }
14796 
14797 // Make an allocation expression.
14798 
14799 Expression*
make_allocation(Type * type,Location location)14800 Expression::make_allocation(Type* type, Location location)
14801 {
14802   return new Allocation_expression(type, location);
14803 }
14804 
14805 // Class Ordered_value_list.
14806 
14807 int
traverse_vals(Traverse * traverse)14808 Ordered_value_list::traverse_vals(Traverse* traverse)
14809 {
14810   if (this->vals_ != NULL)
14811     {
14812       if (this->traverse_order_ == NULL)
14813 	{
14814 	  if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
14815 	    return TRAVERSE_EXIT;
14816 	}
14817       else
14818 	{
14819 	  for (std::vector<unsigned long>::const_iterator p =
14820 		   this->traverse_order_->begin();
14821 	       p != this->traverse_order_->end();
14822 	       ++p)
14823 	    {
14824 	      if (Expression::traverse(&this->vals_->at(*p), traverse)
14825 		  == TRAVERSE_EXIT)
14826 		return TRAVERSE_EXIT;
14827 	    }
14828 	}
14829     }
14830   return TRAVERSE_CONTINUE;
14831 }
14832 
14833 // Class Struct_construction_expression.
14834 
14835 // Traversal.
14836 
14837 int
do_traverse(Traverse * traverse)14838 Struct_construction_expression::do_traverse(Traverse* traverse)
14839 {
14840   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
14841     return TRAVERSE_EXIT;
14842   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14843     return TRAVERSE_EXIT;
14844   return TRAVERSE_CONTINUE;
14845 }
14846 
14847 // Return whether this is a constant initializer.
14848 
14849 bool
is_constant_struct() const14850 Struct_construction_expression::is_constant_struct() const
14851 {
14852   if (this->vals() == NULL)
14853     return true;
14854   for (Expression_list::const_iterator pv = this->vals()->begin();
14855        pv != this->vals()->end();
14856        ++pv)
14857     {
14858       if (*pv != NULL
14859 	  && !(*pv)->is_constant()
14860 	  && (!(*pv)->is_composite_literal()
14861 	      || (*pv)->is_nonconstant_composite_literal()))
14862 	return false;
14863     }
14864 
14865   const Struct_field_list* fields = this->type_->struct_type()->fields();
14866   for (Struct_field_list::const_iterator pf = fields->begin();
14867        pf != fields->end();
14868        ++pf)
14869     {
14870       // There are no constant constructors for interfaces.
14871       if (pf->type()->interface_type() != NULL)
14872 	return false;
14873     }
14874 
14875   return true;
14876 }
14877 
14878 // Return whether this is a zero value.
14879 
14880 bool
do_is_zero_value() const14881 Struct_construction_expression::do_is_zero_value() const
14882 {
14883   if (this->vals() == NULL)
14884     return true;
14885   for (Expression_list::const_iterator pv = this->vals()->begin();
14886        pv != this->vals()->end();
14887        ++pv)
14888     if (*pv != NULL && !(*pv)->is_zero_value())
14889       return false;
14890 
14891   const Struct_field_list* fields = this->type_->struct_type()->fields();
14892   for (Struct_field_list::const_iterator pf = fields->begin();
14893        pf != fields->end();
14894        ++pf)
14895     {
14896       // Interface conversion may cause a zero value being converted
14897       // to a non-zero value, like interface{}(0).  Be conservative.
14898       if (pf->type()->interface_type() != NULL)
14899         return false;
14900     }
14901 
14902   return true;
14903 }
14904 
14905 // Return whether this struct can be used as a constant initializer.
14906 
14907 bool
do_is_static_initializer() const14908 Struct_construction_expression::do_is_static_initializer() const
14909 {
14910   if (this->vals() == NULL)
14911     return true;
14912   for (Expression_list::const_iterator pv = this->vals()->begin();
14913        pv != this->vals()->end();
14914        ++pv)
14915     {
14916       if (*pv != NULL && !(*pv)->is_static_initializer())
14917 	return false;
14918     }
14919 
14920   const Struct_field_list* fields = this->type_->struct_type()->fields();
14921   for (Struct_field_list::const_iterator pf = fields->begin();
14922        pf != fields->end();
14923        ++pf)
14924     {
14925       // There are no constant constructors for interfaces.
14926       if (pf->type()->interface_type() != NULL)
14927 	return false;
14928     }
14929 
14930   return true;
14931 }
14932 
14933 // Final type determination.
14934 
14935 void
do_determine_type(const Type_context *)14936 Struct_construction_expression::do_determine_type(const Type_context*)
14937 {
14938   if (this->vals() == NULL)
14939     return;
14940   const Struct_field_list* fields = this->type_->struct_type()->fields();
14941   Expression_list::const_iterator pv = this->vals()->begin();
14942   for (Struct_field_list::const_iterator pf = fields->begin();
14943        pf != fields->end();
14944        ++pf, ++pv)
14945     {
14946       if (pv == this->vals()->end())
14947 	return;
14948       if (*pv != NULL)
14949 	{
14950 	  Type_context subcontext(pf->type(), false);
14951 	  (*pv)->determine_type(&subcontext);
14952 	}
14953     }
14954   // Extra values are an error we will report elsewhere; we still want
14955   // to determine the type to avoid knockon errors.
14956   for (; pv != this->vals()->end(); ++pv)
14957     (*pv)->determine_type_no_context();
14958 }
14959 
14960 // Check types.
14961 
14962 void
do_check_types(Gogo *)14963 Struct_construction_expression::do_check_types(Gogo*)
14964 {
14965   if (this->vals() == NULL)
14966     return;
14967 
14968   Struct_type* st = this->type_->struct_type();
14969   if (this->vals()->size() > st->field_count())
14970     {
14971       this->report_error(_("too many expressions for struct"));
14972       return;
14973     }
14974 
14975   const Struct_field_list* fields = st->fields();
14976   Expression_list::const_iterator pv = this->vals()->begin();
14977   int i = 0;
14978   for (Struct_field_list::const_iterator pf = fields->begin();
14979        pf != fields->end();
14980        ++pf, ++pv, ++i)
14981     {
14982       if (pv == this->vals()->end())
14983 	{
14984 	  this->report_error(_("too few expressions for struct"));
14985 	  break;
14986 	}
14987 
14988       if (*pv == NULL)
14989 	continue;
14990 
14991       std::string reason;
14992       if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
14993 	{
14994 	  if (reason.empty())
14995 	    go_error_at((*pv)->location(),
14996                         "incompatible type for field %d in struct construction",
14997                         i + 1);
14998 	  else
14999 	    go_error_at((*pv)->location(),
15000                         ("incompatible type for field %d in "
15001                          "struct construction (%s)"),
15002                         i + 1, reason.c_str());
15003 	  this->set_is_error();
15004 	}
15005     }
15006   go_assert(pv == this->vals()->end());
15007 }
15008 
15009 // Copy.
15010 
15011 Expression*
do_copy()15012 Struct_construction_expression::do_copy()
15013 {
15014   Struct_construction_expression* ret =
15015     new Struct_construction_expression(this->type_->copy_expressions(),
15016 				       (this->vals() == NULL
15017 					? NULL
15018 					: this->vals()->copy()),
15019 				       this->location());
15020   if (this->traverse_order() != NULL)
15021     ret->set_traverse_order(this->traverse_order());
15022   return ret;
15023 }
15024 
15025 // Flatten a struct construction expression.  Store the values into
15026 // temporaries in case they need interface conversion.
15027 
15028 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15029 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
15030 					   Statement_inserter* inserter)
15031 {
15032   if (this->vals() == NULL)
15033     return this;
15034 
15035   // If this is a constant struct, we don't need temporaries.
15036   if (this->is_constant_struct() || this->is_static_initializer())
15037     return this;
15038 
15039   Location loc = this->location();
15040   for (Expression_list::iterator pv = this->vals()->begin();
15041        pv != this->vals()->end();
15042        ++pv)
15043     {
15044       if (*pv != NULL)
15045 	{
15046           if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15047             {
15048               go_assert(saw_errors());
15049               return Expression::make_error(loc);
15050             }
15051 	  if (!(*pv)->is_variable())
15052 	    {
15053 	      Temporary_statement* temp =
15054 		Statement::make_temporary(NULL, *pv, loc);
15055 	      inserter->insert(temp);
15056 	      *pv = Expression::make_temporary_reference(temp, loc);
15057 	    }
15058 	}
15059     }
15060   return this;
15061 }
15062 
15063 // Make implicit type conversions explicit.
15064 
15065 void
do_add_conversions()15066 Struct_construction_expression::do_add_conversions()
15067 {
15068   if (this->vals() == NULL)
15069     return;
15070 
15071   Location loc = this->location();
15072   const Struct_field_list* fields = this->type_->struct_type()->fields();
15073   Expression_list::iterator pv = this->vals()->begin();
15074   for (Struct_field_list::const_iterator pf = fields->begin();
15075        pf != fields->end();
15076        ++pf, ++pv)
15077     {
15078       if (pv == this->vals()->end())
15079         break;
15080       if (*pv != NULL)
15081         {
15082           Type* ft = pf->type();
15083           if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
15084               && ft->interface_type() != NULL)
15085            *pv = Expression::make_cast(ft, *pv, loc);
15086         }
15087     }
15088 }
15089 
15090 // Return the backend representation for constructing a struct.
15091 
15092 Bexpression*
do_get_backend(Translate_context * context)15093 Struct_construction_expression::do_get_backend(Translate_context* context)
15094 {
15095   Gogo* gogo = context->gogo();
15096 
15097   Btype* btype = this->type_->get_backend(gogo);
15098   if (this->vals() == NULL)
15099     return gogo->backend()->zero_expression(btype);
15100 
15101   const Struct_field_list* fields = this->type_->struct_type()->fields();
15102   Expression_list::const_iterator pv = this->vals()->begin();
15103   std::vector<Bexpression*> init;
15104   for (Struct_field_list::const_iterator pf = fields->begin();
15105        pf != fields->end();
15106        ++pf)
15107     {
15108       Btype* fbtype = pf->type()->get_backend(gogo);
15109       if (pv == this->vals()->end())
15110         init.push_back(gogo->backend()->zero_expression(fbtype));
15111       else if (*pv == NULL)
15112 	{
15113           init.push_back(gogo->backend()->zero_expression(fbtype));
15114 	  ++pv;
15115 	}
15116       else
15117 	{
15118           Expression* val =
15119               Expression::convert_for_assignment(gogo, pf->type(),
15120                                                  *pv, this->location());
15121           init.push_back(val->get_backend(context));
15122 	  ++pv;
15123 	}
15124     }
15125   if (this->type_->struct_type()->has_padding())
15126     {
15127       // Feed an extra value if there is a padding field.
15128       Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
15129       init.push_back(gogo->backend()->zero_expression(fbtype));
15130     }
15131   return gogo->backend()->constructor_expression(btype, init, this->location());
15132 }
15133 
15134 // Export a struct construction.
15135 
15136 void
do_export(Export_function_body * efb) const15137 Struct_construction_expression::do_export(Export_function_body* efb) const
15138 {
15139   efb->write_c_string("$convert(");
15140   efb->write_type(this->type_);
15141   for (Expression_list::const_iterator pv = this->vals()->begin();
15142        pv != this->vals()->end();
15143        ++pv)
15144     {
15145       efb->write_c_string(", ");
15146       if (*pv != NULL)
15147 	(*pv)->export_expression(efb);
15148     }
15149   efb->write_c_string(")");
15150 }
15151 
15152 // Dump ast representation of a struct construction expression.
15153 
15154 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15155 Struct_construction_expression::do_dump_expression(
15156     Ast_dump_context* ast_dump_context) const
15157 {
15158   ast_dump_context->dump_type(this->type_);
15159   ast_dump_context->ostream() << "{";
15160   ast_dump_context->dump_expression_list(this->vals());
15161   ast_dump_context->ostream() << "}";
15162 }
15163 
15164 // Make a struct composite literal.  This used by the thunk code.
15165 
15166 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)15167 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
15168 					  Location location)
15169 {
15170   go_assert(type->struct_type() != NULL);
15171   return new Struct_construction_expression(type, vals, location);
15172 }
15173 
15174 // Class Array_construction_expression.
15175 
15176 // Traversal.
15177 
15178 int
do_traverse(Traverse * traverse)15179 Array_construction_expression::do_traverse(Traverse* traverse)
15180 {
15181   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
15182     return TRAVERSE_EXIT;
15183   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15184     return TRAVERSE_EXIT;
15185   return TRAVERSE_CONTINUE;
15186 }
15187 
15188 // Return whether this is a constant initializer.
15189 
15190 bool
is_constant_array() const15191 Array_construction_expression::is_constant_array() const
15192 {
15193   if (this->vals() == NULL)
15194     return true;
15195 
15196   // There are no constant constructors for interfaces.
15197   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15198     return false;
15199 
15200   for (Expression_list::const_iterator pv = this->vals()->begin();
15201        pv != this->vals()->end();
15202        ++pv)
15203     {
15204       if (*pv != NULL
15205 	  && !(*pv)->is_constant()
15206 	  && (!(*pv)->is_composite_literal()
15207 	      || (*pv)->is_nonconstant_composite_literal()))
15208 	return false;
15209     }
15210   return true;
15211 }
15212 
15213 // Return whether this is a zero value.
15214 
15215 bool
do_is_zero_value() const15216 Array_construction_expression::do_is_zero_value() const
15217 {
15218   if (this->vals() == NULL)
15219     return true;
15220 
15221   // Interface conversion may cause a zero value being converted
15222   // to a non-zero value, like interface{}(0).  Be conservative.
15223   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15224     return false;
15225 
15226   for (Expression_list::const_iterator pv = this->vals()->begin();
15227        pv != this->vals()->end();
15228        ++pv)
15229     if (*pv != NULL && !(*pv)->is_zero_value())
15230       return false;
15231 
15232   return true;
15233 }
15234 
15235 // Return whether this can be used a constant initializer.
15236 
15237 bool
do_is_static_initializer() const15238 Array_construction_expression::do_is_static_initializer() const
15239 {
15240   if (this->vals() == NULL)
15241     return true;
15242 
15243   // There are no constant constructors for interfaces.
15244   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15245     return false;
15246 
15247   for (Expression_list::const_iterator pv = this->vals()->begin();
15248        pv != this->vals()->end();
15249        ++pv)
15250     {
15251       if (*pv != NULL && !(*pv)->is_static_initializer())
15252 	return false;
15253     }
15254   return true;
15255 }
15256 
15257 // Final type determination.
15258 
15259 void
do_determine_type(const Type_context *)15260 Array_construction_expression::do_determine_type(const Type_context*)
15261 {
15262   if (this->vals() == NULL)
15263     return;
15264   Type_context subcontext(this->type_->array_type()->element_type(), false);
15265   for (Expression_list::const_iterator pv = this->vals()->begin();
15266        pv != this->vals()->end();
15267        ++pv)
15268     {
15269       if (*pv != NULL)
15270 	(*pv)->determine_type(&subcontext);
15271     }
15272 }
15273 
15274 // Check types.
15275 
15276 void
do_check_types(Gogo *)15277 Array_construction_expression::do_check_types(Gogo*)
15278 {
15279   if (this->vals() == NULL)
15280     return;
15281 
15282   Array_type* at = this->type_->array_type();
15283   int i = 0;
15284   Type* element_type = at->element_type();
15285   for (Expression_list::const_iterator pv = this->vals()->begin();
15286        pv != this->vals()->end();
15287        ++pv, ++i)
15288     {
15289       if (*pv != NULL
15290 	  && !Type::are_assignable(element_type, (*pv)->type(), NULL))
15291 	{
15292 	  go_error_at((*pv)->location(),
15293                       "incompatible type for element %d in composite literal",
15294                       i + 1);
15295 	  this->set_is_error();
15296 	}
15297     }
15298 }
15299 
15300 // Flatten an array construction expression.  Store the values into
15301 // temporaries in case they need interface conversion.
15302 
15303 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15304 Array_construction_expression::do_flatten(Gogo*, Named_object*,
15305 					   Statement_inserter* inserter)
15306 {
15307   if (this->vals() == NULL)
15308     return this;
15309 
15310   // If this is a constant array, we don't need temporaries.
15311   if (this->is_constant_array() || this->is_static_initializer())
15312     return this;
15313 
15314   Location loc = this->location();
15315   for (Expression_list::iterator pv = this->vals()->begin();
15316        pv != this->vals()->end();
15317        ++pv)
15318     {
15319       if (*pv != NULL)
15320 	{
15321           if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15322             {
15323               go_assert(saw_errors());
15324               return Expression::make_error(loc);
15325             }
15326 	  if (!(*pv)->is_variable())
15327 	    {
15328 	      Temporary_statement* temp =
15329 		Statement::make_temporary(NULL, *pv, loc);
15330 	      inserter->insert(temp);
15331 	      *pv = Expression::make_temporary_reference(temp, loc);
15332 	    }
15333 	}
15334     }
15335   return this;
15336 }
15337 
15338 // Make implicit type conversions explicit.
15339 
15340 void
do_add_conversions()15341 Array_construction_expression::do_add_conversions()
15342 {
15343   if (this->vals() == NULL)
15344     return;
15345 
15346   Type* et = this->type_->array_type()->element_type();
15347   if (et->interface_type() == NULL)
15348     return;
15349 
15350   Location loc = this->location();
15351   for (Expression_list::iterator pv = this->vals()->begin();
15352        pv != this->vals()->end();
15353        ++pv)
15354     if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
15355       *pv = Expression::make_cast(et, *pv, loc);
15356 }
15357 
15358 // Get a constructor expression for the array values.
15359 
15360 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)15361 Array_construction_expression::get_constructor(Translate_context* context,
15362                                                Btype* array_btype)
15363 {
15364   Type* element_type = this->type_->array_type()->element_type();
15365 
15366   std::vector<unsigned long> indexes;
15367   std::vector<Bexpression*> vals;
15368   Gogo* gogo = context->gogo();
15369   if (this->vals() != NULL)
15370     {
15371       size_t i = 0;
15372       std::vector<unsigned long>::const_iterator pi;
15373       if (this->indexes_ != NULL)
15374 	pi = this->indexes_->begin();
15375       for (Expression_list::const_iterator pv = this->vals()->begin();
15376 	   pv != this->vals()->end();
15377 	   ++pv, ++i)
15378 	{
15379 	  if (this->indexes_ != NULL)
15380 	    go_assert(pi != this->indexes_->end());
15381 
15382 	  if (this->indexes_ == NULL)
15383 	    indexes.push_back(i);
15384 	  else
15385 	    indexes.push_back(*pi);
15386 	  if (*pv == NULL)
15387 	    {
15388 	      Btype* ebtype = element_type->get_backend(gogo);
15389 	      Bexpression *zv = gogo->backend()->zero_expression(ebtype);
15390 	      vals.push_back(zv);
15391 	    }
15392 	  else
15393 	    {
15394               Expression* val_expr =
15395                   Expression::convert_for_assignment(gogo, element_type, *pv,
15396                                                      this->location());
15397 	      vals.push_back(val_expr->get_backend(context));
15398 	    }
15399 	  if (this->indexes_ != NULL)
15400 	    ++pi;
15401 	}
15402       if (this->indexes_ != NULL)
15403 	go_assert(pi == this->indexes_->end());
15404     }
15405   return gogo->backend()->array_constructor_expression(array_btype, indexes,
15406                                                        vals, this->location());
15407 }
15408 
15409 // Export an array construction.
15410 
15411 void
do_export(Export_function_body * efb) const15412 Array_construction_expression::do_export(Export_function_body* efb) const
15413 {
15414   efb->write_c_string("$convert(");
15415   efb->write_type(this->type_);
15416   if (this->vals() != NULL)
15417     {
15418       std::vector<unsigned long>::const_iterator pi;
15419       if (this->indexes_ != NULL)
15420 	pi = this->indexes_->begin();
15421       for (Expression_list::const_iterator pv = this->vals()->begin();
15422 	   pv != this->vals()->end();
15423 	   ++pv)
15424 	{
15425 	  efb->write_c_string(", ");
15426 
15427 	  if (this->indexes_ != NULL)
15428 	    {
15429 	      char buf[100];
15430 	      snprintf(buf, sizeof buf, "%lu", *pi);
15431 	      efb->write_c_string(buf);
15432 	      efb->write_c_string(":");
15433 	    }
15434 
15435 	  if (*pv != NULL)
15436 	    (*pv)->export_expression(efb);
15437 
15438 	  if (this->indexes_ != NULL)
15439 	    ++pi;
15440 	}
15441     }
15442   efb->write_c_string(")");
15443 }
15444 
15445 // Dump ast representation of an array construction expression.
15446 
15447 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15448 Array_construction_expression::do_dump_expression(
15449     Ast_dump_context* ast_dump_context) const
15450 {
15451   Expression* length = this->type_->array_type()->length();
15452 
15453   ast_dump_context->ostream() << "[" ;
15454   if (length != NULL)
15455     {
15456       ast_dump_context->dump_expression(length);
15457     }
15458   ast_dump_context->ostream() << "]" ;
15459   ast_dump_context->dump_type(this->type_);
15460   this->dump_slice_storage_expression(ast_dump_context);
15461   ast_dump_context->ostream() << "{" ;
15462   if (this->indexes_ == NULL)
15463     ast_dump_context->dump_expression_list(this->vals());
15464   else
15465     {
15466       Expression_list::const_iterator pv = this->vals()->begin();
15467       for (std::vector<unsigned long>::const_iterator pi =
15468 	     this->indexes_->begin();
15469 	   pi != this->indexes_->end();
15470 	   ++pi, ++pv)
15471 	{
15472 	  if (pi != this->indexes_->begin())
15473 	    ast_dump_context->ostream() << ", ";
15474 	  ast_dump_context->ostream() << *pi << ':';
15475 	  ast_dump_context->dump_expression(*pv);
15476 	}
15477     }
15478   ast_dump_context->ostream() << "}" ;
15479 
15480 }
15481 
15482 // Class Fixed_array_construction_expression.
15483 
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15484 Fixed_array_construction_expression::Fixed_array_construction_expression(
15485     Type* type, const std::vector<unsigned long>* indexes,
15486     Expression_list* vals, Location location)
15487   : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
15488 				  type, indexes, vals, location)
15489 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
15490 
15491 
15492 // Copy.
15493 
15494 Expression*
do_copy()15495 Fixed_array_construction_expression::do_copy()
15496 {
15497   Type* t = this->type()->copy_expressions();
15498   return new Fixed_array_construction_expression(t, this->indexes(),
15499 						 (this->vals() == NULL
15500 						  ? NULL
15501 						  : this->vals()->copy()),
15502 						 this->location());
15503 }
15504 
15505 // Return the backend representation for constructing a fixed array.
15506 
15507 Bexpression*
do_get_backend(Translate_context * context)15508 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
15509 {
15510   Type* type = this->type();
15511   Btype* btype = type->get_backend(context->gogo());
15512   return this->get_constructor(context, btype);
15513 }
15514 
15515 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)15516 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
15517                                          Location location)
15518 {
15519   go_assert(type->array_type() != NULL && !type->is_slice_type());
15520   return new Fixed_array_construction_expression(type, NULL, vals, location);
15521 }
15522 
15523 // Class Slice_construction_expression.
15524 
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15525 Slice_construction_expression::Slice_construction_expression(
15526   Type* type, const std::vector<unsigned long>* indexes,
15527   Expression_list* vals, Location location)
15528   : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
15529 				  type, indexes, vals, location),
15530     valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
15531     storage_escapes_(true)
15532 {
15533   go_assert(type->is_slice_type());
15534 
15535   unsigned long lenval;
15536   Expression* length;
15537   if (vals == NULL || vals->empty())
15538     lenval = 0;
15539   else
15540     {
15541       if (this->indexes() == NULL)
15542 	lenval = vals->size();
15543       else
15544 	lenval = indexes->back() + 1;
15545     }
15546   Type* int_type = Type::lookup_integer_type("int");
15547   length = Expression::make_integer_ul(lenval, int_type, location);
15548   Type* element_type = type->array_type()->element_type();
15549   Array_type* array_type = Type::make_array_type(element_type, length);
15550   array_type->set_is_array_incomparable();
15551   this->valtype_ = array_type;
15552 }
15553 
15554 // Traversal.
15555 
15556 int
do_traverse(Traverse * traverse)15557 Slice_construction_expression::do_traverse(Traverse* traverse)
15558 {
15559   if (this->Array_construction_expression::do_traverse(traverse)
15560       == TRAVERSE_EXIT)
15561     return TRAVERSE_EXIT;
15562   if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
15563     return TRAVERSE_EXIT;
15564   if (this->array_val_ != NULL
15565       && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
15566     return TRAVERSE_EXIT;
15567   if (this->slice_storage_ != NULL
15568       && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
15569     return TRAVERSE_EXIT;
15570   return TRAVERSE_CONTINUE;
15571 }
15572 
15573 // Helper routine to create fixed array value underlying the slice literal.
15574 // May be called during flattening, or later during do_get_backend().
15575 
15576 Expression*
create_array_val()15577 Slice_construction_expression::create_array_val()
15578 {
15579   Array_type* array_type = this->type()->array_type();
15580   if (array_type == NULL)
15581     {
15582       go_assert(this->type()->is_error());
15583       return NULL;
15584     }
15585 
15586   Location loc = this->location();
15587   go_assert(this->valtype_ != NULL);
15588 
15589   Expression_list* vals = this->vals();
15590   return new Fixed_array_construction_expression(
15591       this->valtype_, this->indexes(), vals, loc);
15592 }
15593 
15594 // If we're previous established that the slice storage does not
15595 // escape, then create a separate array temp val here for it. We
15596 // need to do this as part of flattening so as to be able to insert
15597 // the new temp statement.
15598 
15599 Expression*
do_flatten(Gogo * gogo,Named_object * no,Statement_inserter * inserter)15600 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
15601                                           Statement_inserter* inserter)
15602 {
15603   if (this->type()->array_type() == NULL)
15604     return NULL;
15605 
15606   // Base class flattening first
15607   this->Array_construction_expression::do_flatten(gogo, no, inserter);
15608 
15609   // Create a stack-allocated storage temp if storage won't escape
15610   if (!this->storage_escapes_
15611       && this->slice_storage_ == NULL
15612       && this->element_count() > 0)
15613     {
15614       Location loc = this->location();
15615       this->array_val_ = this->create_array_val();
15616       go_assert(this->array_val_);
15617       Temporary_statement* temp =
15618           Statement::make_temporary(this->valtype_, this->array_val_, loc);
15619       inserter->insert(temp);
15620       this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
15621     }
15622   return this;
15623 }
15624 
15625 // When dumping a slice construction expression that has an explicit
15626 // storeage temp, emit the temp here (if we don't do this the storage
15627 // temp appears unused in the AST dump).
15628 
15629 void
15630 Slice_construction_expression::
dump_slice_storage_expression(Ast_dump_context * ast_dump_context) const15631 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
15632 {
15633   if (this->slice_storage_ == NULL)
15634     return;
15635   ast_dump_context->ostream() << "storage=" ;
15636   ast_dump_context->dump_expression(this->slice_storage_);
15637 }
15638 
15639 // Copy.
15640 
15641 Expression*
do_copy()15642 Slice_construction_expression::do_copy()
15643 {
15644   return new Slice_construction_expression(this->type()->copy_expressions(),
15645 					   this->indexes(),
15646 					   (this->vals() == NULL
15647 					    ? NULL
15648 					    : this->vals()->copy()),
15649 					   this->location());
15650 }
15651 
15652 // Return the backend representation for constructing a slice.
15653 
15654 Bexpression*
do_get_backend(Translate_context * context)15655 Slice_construction_expression::do_get_backend(Translate_context* context)
15656 {
15657   if (this->array_val_ == NULL)
15658     this->array_val_ = this->create_array_val();
15659   if (this->array_val_ == NULL)
15660     {
15661       go_assert(this->type()->is_error());
15662       return context->backend()->error_expression();
15663     }
15664 
15665   Location loc = this->location();
15666 
15667   bool is_static_initializer = this->array_val_->is_static_initializer();
15668 
15669   // We have to copy the initial values into heap memory if we are in
15670   // a function or if the values are not constants.
15671   bool copy_to_heap = context->function() != NULL || !is_static_initializer;
15672 
15673   Expression* space;
15674 
15675   if (this->slice_storage_ != NULL)
15676     {
15677       go_assert(!this->storage_escapes_);
15678       space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
15679     }
15680   else if (!copy_to_heap)
15681     {
15682       // The initializer will only run once.
15683       space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
15684       space->unary_expression()->set_is_slice_init();
15685     }
15686   else
15687     {
15688       go_assert(this->storage_escapes_ || this->element_count() == 0);
15689       space = Expression::make_heap_expression(this->array_val_, loc);
15690     }
15691   Array_type* at = this->valtype_->array_type();
15692   Type* et = at->element_type();
15693   space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
15694 				       space, loc);
15695 
15696   // Build a constructor for the slice.
15697   Expression* len = at->length();
15698   Expression* slice_val =
15699     Expression::make_slice_value(this->type(), space, len, len, loc);
15700   return slice_val->get_backend(context);
15701 }
15702 
15703 // Make a slice composite literal.  This is used by the type
15704 // descriptor code.
15705 
15706 Slice_construction_expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)15707 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
15708 					 Location location)
15709 {
15710   go_assert(type->is_slice_type());
15711   return new Slice_construction_expression(type, NULL, vals, location);
15712 }
15713 
15714 // Class Map_construction_expression.
15715 
15716 // Traversal.
15717 
15718 int
do_traverse(Traverse * traverse)15719 Map_construction_expression::do_traverse(Traverse* traverse)
15720 {
15721   if (this->vals_ != NULL
15722       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
15723     return TRAVERSE_EXIT;
15724   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15725     return TRAVERSE_EXIT;
15726   return TRAVERSE_CONTINUE;
15727 }
15728 
15729 // Flatten constructor initializer into a temporary variable since
15730 // we need to take its address for __go_construct_map.
15731 
15732 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)15733 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
15734                                         Statement_inserter* inserter)
15735 {
15736   if (!this->is_error_expression()
15737       && this->vals_ != NULL
15738       && !this->vals_->empty()
15739       && this->constructor_temp_ == NULL)
15740     {
15741       Map_type* mt = this->type_->map_type();
15742       Type* key_type = mt->key_type();
15743       Type* val_type = mt->val_type();
15744       this->element_type_ = Type::make_builtin_struct_type(2,
15745                                                            "__key", key_type,
15746                                                            "__val", val_type);
15747 
15748       Expression_list* value_pairs = new Expression_list();
15749       Location loc = this->location();
15750 
15751       size_t i = 0;
15752       for (Expression_list::const_iterator pv = this->vals_->begin();
15753            pv != this->vals_->end();
15754            ++pv, ++i)
15755         {
15756           Expression_list* key_value_pair = new Expression_list();
15757           Expression* key = *pv;
15758           if (key->is_error_expression() || key->type()->is_error_type())
15759             {
15760               go_assert(saw_errors());
15761               return Expression::make_error(loc);
15762             }
15763 	  if (key->type()->interface_type() != NULL && !key->is_variable())
15764 	    {
15765 	      Temporary_statement* temp =
15766 		Statement::make_temporary(NULL, key, loc);
15767 	      inserter->insert(temp);
15768 	      key = Expression::make_temporary_reference(temp, loc);
15769 	    }
15770 	  key = Expression::convert_for_assignment(gogo, key_type, key, loc);
15771 
15772           ++pv;
15773           Expression* val = *pv;
15774           if (val->is_error_expression() || val->type()->is_error_type())
15775             {
15776               go_assert(saw_errors());
15777               return Expression::make_error(loc);
15778             }
15779 	  if (val->type()->interface_type() != NULL && !val->is_variable())
15780 	    {
15781 	      Temporary_statement* temp =
15782 		Statement::make_temporary(NULL, val, loc);
15783 	      inserter->insert(temp);
15784 	      val = Expression::make_temporary_reference(temp, loc);
15785 	    }
15786 	  val = Expression::convert_for_assignment(gogo, val_type, val, loc);
15787 
15788           key_value_pair->push_back(key);
15789           key_value_pair->push_back(val);
15790           value_pairs->push_back(
15791               Expression::make_struct_composite_literal(this->element_type_,
15792                                                         key_value_pair, loc));
15793         }
15794 
15795       Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
15796       Array_type* ctor_type =
15797           Type::make_array_type(this->element_type_, element_count);
15798       ctor_type->set_is_array_incomparable();
15799       Expression* constructor =
15800           new Fixed_array_construction_expression(ctor_type, NULL,
15801                                                   value_pairs, loc);
15802 
15803       this->constructor_temp_ =
15804           Statement::make_temporary(NULL, constructor, loc);
15805       constructor->issue_nil_check();
15806       this->constructor_temp_->set_is_address_taken();
15807       inserter->insert(this->constructor_temp_);
15808     }
15809 
15810   return this;
15811 }
15812 
15813 // Final type determination.
15814 
15815 void
do_determine_type(const Type_context *)15816 Map_construction_expression::do_determine_type(const Type_context*)
15817 {
15818   if (this->vals_ == NULL)
15819     return;
15820 
15821   Map_type* mt = this->type_->map_type();
15822   Type_context key_context(mt->key_type(), false);
15823   Type_context val_context(mt->val_type(), false);
15824   for (Expression_list::const_iterator pv = this->vals_->begin();
15825        pv != this->vals_->end();
15826        ++pv)
15827     {
15828       (*pv)->determine_type(&key_context);
15829       ++pv;
15830       (*pv)->determine_type(&val_context);
15831     }
15832 }
15833 
15834 // Check types.
15835 
15836 void
do_check_types(Gogo *)15837 Map_construction_expression::do_check_types(Gogo*)
15838 {
15839   if (this->vals_ == NULL)
15840     return;
15841 
15842   Map_type* mt = this->type_->map_type();
15843   int i = 0;
15844   Type* key_type = mt->key_type();
15845   Type* val_type = mt->val_type();
15846   for (Expression_list::const_iterator pv = this->vals_->begin();
15847        pv != this->vals_->end();
15848        ++pv, ++i)
15849     {
15850       if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
15851 	{
15852 	  go_error_at((*pv)->location(),
15853                       "incompatible type for element %d key in map construction",
15854                       i + 1);
15855 	  this->set_is_error();
15856 	}
15857       ++pv;
15858       if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
15859 	{
15860 	  go_error_at((*pv)->location(),
15861                       ("incompatible type for element %d value "
15862                        "in map construction"),
15863 		   i + 1);
15864 	  this->set_is_error();
15865 	}
15866     }
15867 }
15868 
15869 // Copy.
15870 
15871 Expression*
do_copy()15872 Map_construction_expression::do_copy()
15873 {
15874   return new Map_construction_expression(this->type_->copy_expressions(),
15875 					 (this->vals_ == NULL
15876 					  ? NULL
15877 					  : this->vals_->copy()),
15878 					 this->location());
15879 }
15880 
15881 // Make implicit type conversions explicit.
15882 
15883 void
do_add_conversions()15884 Map_construction_expression::do_add_conversions()
15885 {
15886   if (this->vals_ == NULL || this->vals_->empty())
15887     return;
15888 
15889   Map_type* mt = this->type_->map_type();
15890   Type* kt = mt->key_type();
15891   Type* vt = mt->val_type();
15892   bool key_is_interface = (kt->interface_type() != NULL);
15893   bool val_is_interface = (vt->interface_type() != NULL);
15894   if (!key_is_interface && !val_is_interface)
15895     return;
15896 
15897   Location loc = this->location();
15898   for (Expression_list::iterator pv = this->vals_->begin();
15899        pv != this->vals_->end();
15900        ++pv)
15901     {
15902       if (key_is_interface &&
15903           !Type::are_identical(kt, (*pv)->type(), 0, NULL))
15904         *pv = Expression::make_cast(kt, *pv, loc);
15905       ++pv;
15906       if (val_is_interface &&
15907           !Type::are_identical(vt, (*pv)->type(), 0, NULL))
15908         *pv = Expression::make_cast(vt, *pv, loc);
15909     }
15910 }
15911 
15912 // Return the backend representation for constructing a map.
15913 
15914 Bexpression*
do_get_backend(Translate_context * context)15915 Map_construction_expression::do_get_backend(Translate_context* context)
15916 {
15917   if (this->is_error_expression())
15918     return context->backend()->error_expression();
15919   Location loc = this->location();
15920 
15921   size_t i = 0;
15922   Expression* ventries;
15923   if (this->vals_ == NULL || this->vals_->empty())
15924     ventries = Expression::make_nil(loc);
15925   else
15926     {
15927       go_assert(this->constructor_temp_ != NULL);
15928       i = this->vals_->size() / 2;
15929 
15930       Expression* ctor_ref =
15931           Expression::make_temporary_reference(this->constructor_temp_, loc);
15932       ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
15933     }
15934 
15935   Map_type* mt = this->type_->map_type();
15936   if (this->element_type_ == NULL)
15937       this->element_type_ =
15938           Type::make_builtin_struct_type(2,
15939                                          "__key", mt->key_type(),
15940                                          "__val", mt->val_type());
15941   Expression* descriptor = Expression::make_type_descriptor(mt, loc);
15942 
15943   Type* uintptr_t = Type::lookup_integer_type("uintptr");
15944   Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
15945 
15946   Expression* entry_size =
15947       Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
15948 
15949   unsigned int field_index;
15950   const Struct_field* valfield =
15951       this->element_type_->find_local_field("__val", &field_index);
15952   Expression* val_offset =
15953       Expression::make_struct_field_offset(this->element_type_, valfield);
15954 
15955   Expression* map_ctor =
15956       Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
15957                          entry_size, val_offset, ventries);
15958   return map_ctor->get_backend(context);
15959 }
15960 
15961 // Export an array construction.
15962 
15963 void
do_export(Export_function_body * efb) const15964 Map_construction_expression::do_export(Export_function_body* efb) const
15965 {
15966   efb->write_c_string("$convert(");
15967   efb->write_type(this->type_);
15968   for (Expression_list::const_iterator pv = this->vals_->begin();
15969        pv != this->vals_->end();
15970        ++pv)
15971     {
15972       efb->write_c_string(", ");
15973       (*pv)->export_expression(efb);
15974     }
15975   efb->write_c_string(")");
15976 }
15977 
15978 // Dump ast representation for a map construction expression.
15979 
15980 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15981 Map_construction_expression::do_dump_expression(
15982     Ast_dump_context* ast_dump_context) const
15983 {
15984   ast_dump_context->ostream() << "{" ;
15985   ast_dump_context->dump_expression_list(this->vals_, true);
15986   ast_dump_context->ostream() << "}";
15987 }
15988 
15989 // A composite literal key.  This is seen during parsing, but is not
15990 // resolved to a named_object in case this is a composite literal of
15991 // struct type.
15992 
15993 class Composite_literal_key_expression : public Parser_expression
15994 {
15995  public:
Composite_literal_key_expression(const std::string & name,Location location)15996   Composite_literal_key_expression(const std::string& name, Location location)
15997     : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
15998       name_(name)
15999   { }
16000 
16001   const std::string&
name() const16002   name() const
16003   { return this->name_; }
16004 
16005  protected:
16006   Expression*
16007   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
16008 
16009   Expression*
do_copy()16010   do_copy()
16011   {
16012     return new Composite_literal_key_expression(this->name_, this->location());
16013   }
16014 
16015   void
16016   do_dump_expression(Ast_dump_context*) const;
16017 
16018  private:
16019   // The name.
16020   std::string name_;
16021 };
16022 
16023 // Lower a composite literal key.  We will never get here for keys in
16024 // composite literals of struct types, because that is prevented by
16025 // Composite_literal_expression::do_traverse.  So if we do get here,
16026 // this must be a regular name reference after all.
16027 
16028 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)16029 Composite_literal_key_expression::do_lower(Gogo* gogo, Named_object*,
16030 					   Statement_inserter*, int)
16031 {
16032   Named_object* no = gogo->lookup(this->name_, NULL);
16033   if (no == NULL)
16034     {
16035       // Gogo::lookup doesn't look in the global namespace, and names
16036       // used in composite literal keys aren't seen by
16037       // Gogo::define_global_names, so we have to look in the global
16038       // namespace ourselves.
16039       no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
16040       if (no == NULL)
16041 	{
16042 	  go_error_at(this->location(), "reference to undefined name %qs",
16043 		      Gogo::message_name(this->name_).c_str());
16044 	  return Expression::make_error(this->location());
16045 	}
16046     }
16047   return Expression::make_unknown_reference(no, this->location());
16048 }
16049 
16050 // Dump a composite literal key.
16051 
16052 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16053 Composite_literal_key_expression::do_dump_expression(
16054     Ast_dump_context* ast_dump_context) const
16055 {
16056   ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
16057 }
16058 
16059 // Make a composite literal key.
16060 
16061 Expression*
make_composite_literal_key(const std::string & name,Location location)16062 Expression::make_composite_literal_key(const std::string& name,
16063 				       Location location)
16064 {
16065   return new Composite_literal_key_expression(name, location);
16066 }
16067 
16068 // Class Composite_literal_expression.
16069 
16070 // Traversal.
16071 
16072 int
do_traverse(Traverse * traverse)16073 Composite_literal_expression::do_traverse(Traverse* traverse)
16074 {
16075   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16076     return TRAVERSE_EXIT;
16077 
16078   // If this is a struct composite literal with keys, then the keys
16079   // are field names, not expressions.  We don't want to traverse them
16080   // in that case.  If we do, we can give an erroneous error "variable
16081   // initializer refers to itself."  See bug482.go in the testsuite.
16082   if (this->has_keys_ && this->vals_ != NULL)
16083     {
16084       // The type may not be resolvable at this point.
16085       Type* type = this->type_;
16086 
16087       for (int depth = 0; depth < this->depth_; ++depth)
16088         {
16089 	  type = type->deref();
16090           if (type->array_type() != NULL)
16091             type = type->array_type()->element_type();
16092           else if (type->map_type() != NULL)
16093             {
16094               if (this->key_path_[depth])
16095                 type = type->map_type()->key_type();
16096               else
16097                 type = type->map_type()->val_type();
16098             }
16099           else
16100             {
16101               // This error will be reported during lowering.
16102               return TRAVERSE_CONTINUE;
16103             }
16104         }
16105       type = type->deref();
16106 
16107       while (true)
16108 	{
16109 	  if (type->classification() == Type::TYPE_NAMED)
16110 	    type = type->named_type()->real_type();
16111 	  else if (type->classification() == Type::TYPE_FORWARD)
16112 	    {
16113 	      Type* t = type->forwarded();
16114 	      if (t == type)
16115 		break;
16116 	      type = t;
16117 	    }
16118 	  else
16119 	    break;
16120 	}
16121 
16122       if (type->classification() == Type::TYPE_STRUCT)
16123 	{
16124 	  Expression_list::iterator p = this->vals_->begin();
16125 	  while (p != this->vals_->end())
16126 	    {
16127 	      // Skip key.
16128 	      ++p;
16129 	      go_assert(p != this->vals_->end());
16130 	      if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16131 		return TRAVERSE_EXIT;
16132 	      ++p;
16133 	    }
16134 	  return TRAVERSE_CONTINUE;
16135 	}
16136     }
16137 
16138   if (this->vals_ != NULL)
16139     return this->vals_->traverse(traverse);
16140 
16141   return TRAVERSE_CONTINUE;
16142 }
16143 
16144 // Lower a generic composite literal into a specific version based on
16145 // the type.
16146 
16147 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)16148 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
16149 				       Statement_inserter* inserter, int)
16150 {
16151   Type* type = this->type_;
16152 
16153   for (int depth = 0; depth < this->depth_; ++depth)
16154     {
16155       type = type->deref();
16156       if (type->array_type() != NULL)
16157 	type = type->array_type()->element_type();
16158       else if (type->map_type() != NULL)
16159         {
16160           if (this->key_path_[depth])
16161             type = type->map_type()->key_type();
16162           else
16163             type = type->map_type()->val_type();
16164         }
16165       else
16166 	{
16167 	  if (!type->is_error())
16168 	    go_error_at(this->location(),
16169                         ("may only omit types within composite literals "
16170                          "of slice, array, or map type"));
16171 	  return Expression::make_error(this->location());
16172 	}
16173     }
16174 
16175   Type *pt = type->points_to();
16176   bool is_pointer = false;
16177   if (pt != NULL)
16178     {
16179       is_pointer = true;
16180       type = pt;
16181     }
16182 
16183   Expression* ret;
16184   if (type->is_error())
16185     return Expression::make_error(this->location());
16186   else if (type->struct_type() != NULL)
16187     ret = this->lower_struct(gogo, type);
16188   else if (type->array_type() != NULL)
16189     ret = this->lower_array(type);
16190   else if (type->map_type() != NULL)
16191     ret = this->lower_map(gogo, function, inserter, type);
16192   else
16193     {
16194       go_error_at(this->location(),
16195                   ("expected struct, slice, array, or map type "
16196                    "for composite literal"));
16197       return Expression::make_error(this->location());
16198     }
16199 
16200   if (is_pointer)
16201     ret = Expression::make_heap_expression(ret, this->location());
16202 
16203   return ret;
16204 }
16205 
16206 // Lower a struct composite literal.
16207 
16208 Expression*
lower_struct(Gogo * gogo,Type * type)16209 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
16210 {
16211   Location location = this->location();
16212   Struct_type* st = type->struct_type();
16213   if (this->vals_ == NULL || !this->has_keys_)
16214     {
16215       if (this->vals_ != NULL
16216 	  && !this->vals_->empty()
16217 	  && type->named_type() != NULL
16218 	  && type->named_type()->named_object()->package() != NULL)
16219 	{
16220 	  for (Struct_field_list::const_iterator pf = st->fields()->begin();
16221 	       pf != st->fields()->end();
16222 	       ++pf)
16223 	    {
16224 	      if (Gogo::is_hidden_name(pf->field_name())
16225 		  || pf->is_embedded_builtin(gogo))
16226 		go_error_at(this->location(),
16227                             "assignment of unexported field %qs in %qs literal",
16228                             Gogo::message_name(pf->field_name()).c_str(),
16229                             type->named_type()->message_name().c_str());
16230 	    }
16231 	}
16232 
16233       return new Struct_construction_expression(type, this->vals_, location);
16234     }
16235 
16236   size_t field_count = st->field_count();
16237   std::vector<Expression*> vals(field_count);
16238   std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
16239   Expression_list::const_iterator p = this->vals_->begin();
16240   Expression* external_expr = NULL;
16241   const Named_object* external_no = NULL;
16242   while (p != this->vals_->end())
16243     {
16244       Expression* name_expr = *p;
16245 
16246       ++p;
16247       go_assert(p != this->vals_->end());
16248       Expression* val = *p;
16249 
16250       ++p;
16251 
16252       if (name_expr == NULL)
16253 	{
16254 	  go_error_at(val->location(),
16255                       "mixture of field and value initializers");
16256 	  return Expression::make_error(location);
16257 	}
16258 
16259       bool bad_key = false;
16260       std::string name;
16261       const Named_object* no = NULL;
16262       switch (name_expr->classification())
16263 	{
16264 	case EXPRESSION_COMPOSITE_LITERAL_KEY:
16265 	  name =
16266 	    static_cast<Composite_literal_key_expression*>(name_expr)->name();
16267 	  break;
16268 
16269 	case EXPRESSION_UNKNOWN_REFERENCE:
16270 	  name = name_expr->unknown_expression()->name();
16271 	  if (type->named_type() != NULL)
16272 	    {
16273 	      // If the named object found for this field name comes from a
16274 	      // different package than the struct it is a part of, do not count
16275 	      // this incorrect lookup as a usage of the object's package.
16276 	      no = name_expr->unknown_expression()->named_object();
16277 	      if (no->package() != NULL
16278 		  && no->package() != type->named_type()->named_object()->package())
16279 		no->package()->forget_usage(name_expr);
16280 	    }
16281 	  break;
16282 
16283 	case EXPRESSION_CONST_REFERENCE:
16284 	  no = static_cast<Const_expression*>(name_expr)->named_object();
16285 	  break;
16286 
16287 	case EXPRESSION_TYPE:
16288 	  {
16289 	    Type* t = name_expr->type();
16290 	    Named_type* nt = t->named_type();
16291 	    if (nt == NULL)
16292 	      bad_key = true;
16293 	    else
16294 	      no = nt->named_object();
16295 	  }
16296 	  break;
16297 
16298 	case EXPRESSION_VAR_REFERENCE:
16299 	  no = name_expr->var_expression()->named_object();
16300 	  break;
16301 
16302 	case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16303 	  no = name_expr->enclosed_var_expression()->variable();
16304 	  break;
16305 
16306 	case EXPRESSION_FUNC_REFERENCE:
16307 	  no = name_expr->func_expression()->named_object();
16308 	  break;
16309 
16310 	default:
16311 	  bad_key = true;
16312 	  break;
16313 	}
16314       if (bad_key)
16315 	{
16316 	  go_error_at(name_expr->location(), "expected struct field name");
16317 	  return Expression::make_error(location);
16318 	}
16319 
16320       if (no != NULL)
16321 	{
16322 	  if (no->package() != NULL && external_expr == NULL)
16323 	    {
16324 	      external_expr = name_expr;
16325 	      external_no = no;
16326 	    }
16327 
16328 	  name = no->name();
16329 
16330 	  // A predefined name won't be packed.  If it starts with a
16331 	  // lower case letter we need to check for that case, because
16332 	  // the field name will be packed.  FIXME.
16333 	  if (!Gogo::is_hidden_name(name)
16334 	      && name[0] >= 'a'
16335 	      && name[0] <= 'z')
16336 	    {
16337 	      Named_object* gno = gogo->lookup_global(name.c_str());
16338 	      if (gno == no)
16339 		name = gogo->pack_hidden_name(name, false);
16340 	    }
16341 	}
16342 
16343       unsigned int index;
16344       const Struct_field* sf = st->find_local_field(name, &index);
16345       if (sf == NULL)
16346 	{
16347 	  go_error_at(name_expr->location(), "unknown field %qs in %qs",
16348                       Gogo::message_name(name).c_str(),
16349                       (type->named_type() != NULL
16350                        ? type->named_type()->message_name().c_str()
16351                        : "unnamed struct"));
16352 	  return Expression::make_error(location);
16353 	}
16354       if (vals[index] != NULL)
16355 	{
16356 	  go_error_at(name_expr->location(),
16357                       "duplicate value for field %qs in %qs",
16358                       Gogo::message_name(name).c_str(),
16359                       (type->named_type() != NULL
16360                        ? type->named_type()->message_name().c_str()
16361                        : "unnamed struct"));
16362 	  return Expression::make_error(location);
16363 	}
16364 
16365       if (type->named_type() != NULL
16366 	  && type->named_type()->named_object()->package() != NULL
16367 	  && (Gogo::is_hidden_name(sf->field_name())
16368 	      || sf->is_embedded_builtin(gogo)))
16369 	go_error_at(name_expr->location(),
16370                     "assignment of unexported field %qs in %qs literal",
16371                     Gogo::message_name(sf->field_name()).c_str(),
16372                     type->named_type()->message_name().c_str());
16373 
16374       vals[index] = val;
16375       traverse_order->push_back(static_cast<unsigned long>(index));
16376     }
16377 
16378   if (!this->all_are_names_)
16379     {
16380       // This is a weird case like bug462 in the testsuite.
16381       if (external_expr == NULL)
16382 	go_error_at(this->location(), "unknown field in %qs literal",
16383                     (type->named_type() != NULL
16384                      ? type->named_type()->message_name().c_str()
16385                      : "unnamed struct"));
16386       else
16387 	go_error_at(external_expr->location(), "unknown field %qs in %qs",
16388                     external_no->message_name().c_str(),
16389                     (type->named_type() != NULL
16390                      ? type->named_type()->message_name().c_str()
16391                      : "unnamed struct"));
16392       return Expression::make_error(location);
16393     }
16394 
16395   Expression_list* list = new Expression_list;
16396   list->reserve(field_count);
16397   for (size_t i = 0; i < field_count; ++i)
16398     list->push_back(vals[i]);
16399 
16400   Struct_construction_expression* ret =
16401     new Struct_construction_expression(type, list, location);
16402   ret->set_traverse_order(traverse_order);
16403   return ret;
16404 }
16405 
16406 // Index/value/traversal-order triple.
16407 
16408 struct IVT_triple {
16409   unsigned long index;
16410   unsigned long traversal_order;
16411   Expression* expr;
IVT_tripleIVT_triple16412   IVT_triple(unsigned long i, unsigned long to, Expression *e)
16413       : index(i), traversal_order(to), expr(e) { }
operator <IVT_triple16414   bool operator<(const IVT_triple& other) const
16415   { return this->index < other.index; }
16416 };
16417 
16418 // Lower an array composite literal.
16419 
16420 Expression*
lower_array(Type * type)16421 Composite_literal_expression::lower_array(Type* type)
16422 {
16423   Location location = this->location();
16424   if (this->vals_ == NULL || !this->has_keys_)
16425     return this->make_array(type, NULL, this->vals_);
16426 
16427   std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
16428   indexes->reserve(this->vals_->size());
16429   bool indexes_out_of_order = false;
16430   Expression_list* vals = new Expression_list();
16431   vals->reserve(this->vals_->size());
16432   unsigned long index = 0;
16433   Expression_list::const_iterator p = this->vals_->begin();
16434   while (p != this->vals_->end())
16435     {
16436       Expression* index_expr = *p;
16437 
16438       ++p;
16439       go_assert(p != this->vals_->end());
16440       Expression* val = *p;
16441 
16442       ++p;
16443 
16444       if (index_expr == NULL)
16445 	{
16446 	  if (std::find(indexes->begin(), indexes->end(), index)
16447 	      != indexes->end())
16448 	    {
16449 	      go_error_at(val->location(),
16450 			  "duplicate value for index %lu", index);
16451 	      return Expression::make_error(location);
16452 	    }
16453 	  if (!indexes->empty())
16454 	    indexes->push_back(index);
16455 	}
16456       else
16457 	{
16458 	  if (indexes->empty() && !vals->empty())
16459 	    {
16460 	      for (size_t i = 0; i < vals->size(); ++i)
16461 		indexes->push_back(i);
16462 	    }
16463 
16464 	  Numeric_constant nc;
16465 	  if (!index_expr->numeric_constant_value(&nc))
16466 	    {
16467 	      go_error_at(index_expr->location(),
16468                           "index expression is not integer constant");
16469 	      return Expression::make_error(location);
16470 	    }
16471 
16472 	  switch (nc.to_unsigned_long(&index))
16473 	    {
16474 	    case Numeric_constant::NC_UL_VALID:
16475 	      break;
16476 	    case Numeric_constant::NC_UL_NOTINT:
16477 	      go_error_at(index_expr->location(),
16478                           "index expression is not integer constant");
16479 	      return Expression::make_error(location);
16480 	    case Numeric_constant::NC_UL_NEGATIVE:
16481 	      go_error_at(index_expr->location(),
16482                           "index expression is negative");
16483 	      return Expression::make_error(location);
16484 	    case Numeric_constant::NC_UL_BIG:
16485 	      go_error_at(index_expr->location(), "index value overflow");
16486 	      return Expression::make_error(location);
16487 	    default:
16488 	      go_unreachable();
16489 	    }
16490 
16491 	  Named_type* ntype = Type::lookup_integer_type("int");
16492 	  Integer_type* inttype = ntype->integer_type();
16493 	  if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
16494 	      && index >> (inttype->bits() - 1) != 0)
16495 	    {
16496 	      go_error_at(index_expr->location(), "index value overflow");
16497 	      return Expression::make_error(location);
16498 	    }
16499 
16500 	  if (std::find(indexes->begin(), indexes->end(), index)
16501 	      != indexes->end())
16502 	    {
16503 	      go_error_at(index_expr->location(),
16504                           "duplicate value for index %lu",
16505                           index);
16506 	      return Expression::make_error(location);
16507 	    }
16508 
16509 	  if (!indexes->empty() && index < indexes->back())
16510 	    indexes_out_of_order = true;
16511 
16512 	  indexes->push_back(index);
16513 	}
16514 
16515       vals->push_back(val);
16516 
16517       ++index;
16518     }
16519 
16520   if (indexes->empty())
16521     {
16522       delete indexes;
16523       indexes = NULL;
16524     }
16525 
16526   std::vector<unsigned long>* traverse_order = NULL;
16527   if (indexes_out_of_order)
16528     {
16529       typedef std::vector<IVT_triple> V;
16530 
16531       V v;
16532       v.reserve(indexes->size());
16533       std::vector<unsigned long>::const_iterator pi = indexes->begin();
16534       unsigned long torder = 0;
16535       for (Expression_list::const_iterator pe = vals->begin();
16536 	   pe != vals->end();
16537 	   ++pe, ++pi, ++torder)
16538 	v.push_back(IVT_triple(*pi, torder, *pe));
16539 
16540       std::sort(v.begin(), v.end());
16541 
16542       delete indexes;
16543       delete vals;
16544 
16545       indexes = new std::vector<unsigned long>();
16546       indexes->reserve(v.size());
16547       vals = new Expression_list();
16548       vals->reserve(v.size());
16549       traverse_order = new std::vector<unsigned long>();
16550       traverse_order->reserve(v.size());
16551 
16552       for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
16553 	{
16554 	  indexes->push_back(pv->index);
16555 	  vals->push_back(pv->expr);
16556 	  traverse_order->push_back(pv->traversal_order);
16557 	}
16558     }
16559 
16560   Expression* ret = this->make_array(type, indexes, vals);
16561   Array_construction_expression* ace = ret->array_literal();
16562   if (ace != NULL && traverse_order != NULL)
16563     ace->set_traverse_order(traverse_order);
16564   return ret;
16565 }
16566 
16567 // Actually build the array composite literal. This handles
16568 // [...]{...}.
16569 
16570 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)16571 Composite_literal_expression::make_array(
16572     Type* type,
16573     const std::vector<unsigned long>* indexes,
16574     Expression_list* vals)
16575 {
16576   Location location = this->location();
16577   Array_type* at = type->array_type();
16578 
16579   if (at->length() != NULL && at->length()->is_nil_expression())
16580     {
16581       size_t size;
16582       if (vals == NULL)
16583 	size = 0;
16584       else if (indexes != NULL)
16585 	size = indexes->back() + 1;
16586       else
16587 	{
16588 	  size = vals->size();
16589 	  Integer_type* it = Type::lookup_integer_type("int")->integer_type();
16590 	  if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
16591 	      && size >> (it->bits() - 1) != 0)
16592 	    {
16593 	      go_error_at(location, "too many elements in composite literal");
16594 	      return Expression::make_error(location);
16595 	    }
16596 	}
16597 
16598       Expression* elen = Expression::make_integer_ul(size, NULL, location);
16599       at = Type::make_array_type(at->element_type(), elen);
16600       type = at;
16601     }
16602   else if (at->length() != NULL
16603 	   && !at->length()->is_error_expression()
16604 	   && this->vals_ != NULL)
16605     {
16606       Numeric_constant nc;
16607       unsigned long val;
16608       if (at->length()->numeric_constant_value(&nc)
16609 	  && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
16610 	{
16611 	  if (indexes == NULL)
16612 	    {
16613 	      if (this->vals_->size() > val)
16614 		{
16615 		  go_error_at(location,
16616                               "too many elements in composite literal");
16617 		  return Expression::make_error(location);
16618 		}
16619 	    }
16620 	  else
16621 	    {
16622 	      unsigned long max = indexes->back();
16623 	      if (max >= val)
16624 		{
16625 		  go_error_at(location,
16626                               ("some element keys in composite literal "
16627                                "are out of range"));
16628 		  return Expression::make_error(location);
16629 		}
16630 	    }
16631 	}
16632     }
16633 
16634   if (at->length() != NULL)
16635     return new Fixed_array_construction_expression(type, indexes, vals,
16636 						   location);
16637   else
16638     return new Slice_construction_expression(type, indexes, vals, location);
16639 }
16640 
16641 // Lower a map composite literal.
16642 
16643 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)16644 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
16645 					Statement_inserter* inserter,
16646 					Type* type)
16647 {
16648   Location location = this->location();
16649   Unordered_map(unsigned int, std::vector<Expression*>) st;
16650   Unordered_map(unsigned int, std::vector<Expression*>) nt;
16651   if (this->vals_ != NULL)
16652     {
16653       if (!this->has_keys_)
16654 	{
16655 	  go_error_at(location, "map composite literal must have keys");
16656 	  return Expression::make_error(location);
16657 	}
16658 
16659       for (Expression_list::iterator p = this->vals_->begin();
16660 	   p != this->vals_->end();
16661 	   p += 2)
16662 	{
16663 	  if (*p == NULL)
16664 	    {
16665 	      ++p;
16666 	      go_error_at((*p)->location(),
16667                           ("map composite literal must "
16668                            "have keys for every value"));
16669 	      return Expression::make_error(location);
16670 	    }
16671 	  // Make sure we have lowered the key; it may not have been
16672 	  // lowered in order to handle keys for struct composite
16673 	  // literals.  Lower it now to get the right error message.
16674 	  if ((*p)->unknown_expression() != NULL)
16675 	    {
16676 	      gogo->lower_expression(function, inserter, &*p);
16677 	      go_assert((*p)->is_error_expression());
16678 	      return Expression::make_error(location);
16679 	    }
16680 	  // Check if there are duplicate constant keys.
16681 	  if (!(*p)->is_constant())
16682 	    continue;
16683 	  std::string sval;
16684 	  Numeric_constant nval;
16685 	  if ((*p)->string_constant_value(&sval)) // Check string keys.
16686 	    {
16687 	      unsigned int h = Gogo::hash_string(sval, 0);
16688 	      // Search the index h in the hash map.
16689 	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16690 	      mit = st.find(h);
16691 	      if (mit == st.end())
16692 		{
16693 		  // No duplicate since h is a new index.
16694 		  // Create a new vector indexed by h and add it to the hash map.
16695 		  std::vector<Expression*> l;
16696 		  l.push_back(*p);
16697 		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16698 		  st.insert(val);
16699 		}
16700 	      else
16701 		{
16702 		  // Do further check since index h already exists.
16703 		  for (std::vector<Expression*>::iterator lit =
16704 			   mit->second.begin();
16705 		       lit != mit->second.end();
16706 		       lit++)
16707 		    {
16708 		      std::string s;
16709 		      bool ok = (*lit)->string_constant_value(&s);
16710 		      go_assert(ok);
16711 		      if (s == sval)
16712 			{
16713 			  go_error_at((*p)->location(), ("duplicate key "
16714 				      "in map literal"));
16715 			  return Expression::make_error(location);
16716 			}
16717 		    }
16718 		  // Add this new string key to the vector indexed by h.
16719 		  mit->second.push_back(*p);
16720 		}
16721 	    }
16722 	  else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
16723 	    {
16724 	      unsigned int h = nval.hash(0);
16725 	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16726 	      mit = nt.find(h);
16727 	      if (mit == nt.end())
16728 		{
16729 		  // No duplicate since h is a new code.
16730 		  // Create a new vector indexed by h and add it to the hash map.
16731 		  std::vector<Expression*> l;
16732 		  l.push_back(*p);
16733 		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16734 		  nt.insert(val);
16735 		}
16736 	      else
16737 		{
16738 		  // Do further check since h already exists.
16739 		  for (std::vector<Expression*>::iterator lit =
16740 			   mit->second.begin();
16741 		       lit != mit->second.end();
16742 		       lit++)
16743 		    {
16744 		      Numeric_constant rval;
16745 		      bool ok = (*lit)->numeric_constant_value(&rval);
16746 		      go_assert(ok);
16747 		      if (nval.equals(rval))
16748 			{
16749 			  go_error_at((*p)->location(),
16750 				      "duplicate key in map literal");
16751 			  return Expression::make_error(location);
16752 			}
16753 		    }
16754 		  // Add this new numeric key to the vector indexed by h.
16755 		  mit->second.push_back(*p);
16756 		}
16757 	    }
16758 	}
16759     }
16760 
16761   return new Map_construction_expression(type, this->vals_, location);
16762 }
16763 
16764 // Copy.
16765 
16766 Expression*
do_copy()16767 Composite_literal_expression::do_copy()
16768 {
16769   Composite_literal_expression* ret =
16770     new Composite_literal_expression(this->type_->copy_expressions(),
16771 				     this->depth_, this->has_keys_,
16772 				     (this->vals_ == NULL
16773 				      ? NULL
16774 				      : this->vals_->copy()),
16775 				     this->all_are_names_,
16776 				     this->location());
16777   ret->key_path_ = this->key_path_;
16778   return ret;
16779 }
16780 
16781 // Dump ast representation for a composite literal expression.
16782 
16783 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16784 Composite_literal_expression::do_dump_expression(
16785                                Ast_dump_context* ast_dump_context) const
16786 {
16787   ast_dump_context->ostream() << "composite(";
16788   ast_dump_context->dump_type(this->type_);
16789   ast_dump_context->ostream() << ", {";
16790   ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
16791   ast_dump_context->ostream() << "})";
16792 }
16793 
16794 // Make a composite literal expression.
16795 
16796 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)16797 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
16798 				   Expression_list* vals, bool all_are_names,
16799 				   Location location)
16800 {
16801   return new Composite_literal_expression(type, depth, has_keys, vals,
16802 					  all_are_names, location);
16803 }
16804 
16805 // Return whether this expression is a composite literal.
16806 
16807 bool
is_composite_literal() const16808 Expression::is_composite_literal() const
16809 {
16810   switch (this->classification_)
16811     {
16812     case EXPRESSION_COMPOSITE_LITERAL:
16813     case EXPRESSION_STRUCT_CONSTRUCTION:
16814     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16815     case EXPRESSION_SLICE_CONSTRUCTION:
16816     case EXPRESSION_MAP_CONSTRUCTION:
16817       return true;
16818     default:
16819       return false;
16820     }
16821 }
16822 
16823 // Return whether this expression is a composite literal which is not
16824 // constant.
16825 
16826 bool
is_nonconstant_composite_literal() const16827 Expression::is_nonconstant_composite_literal() const
16828 {
16829   switch (this->classification_)
16830     {
16831     case EXPRESSION_STRUCT_CONSTRUCTION:
16832       {
16833 	const Struct_construction_expression *psce =
16834 	  static_cast<const Struct_construction_expression*>(this);
16835 	return !psce->is_constant_struct();
16836       }
16837     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16838       {
16839 	const Fixed_array_construction_expression *pace =
16840 	  static_cast<const Fixed_array_construction_expression*>(this);
16841 	return !pace->is_constant_array();
16842       }
16843     case EXPRESSION_SLICE_CONSTRUCTION:
16844       {
16845 	const Slice_construction_expression *pace =
16846 	  static_cast<const Slice_construction_expression*>(this);
16847 	return !pace->is_constant_array();
16848       }
16849     case EXPRESSION_MAP_CONSTRUCTION:
16850       return true;
16851     default:
16852       return false;
16853     }
16854 }
16855 
16856 // Return true if this is a variable or temporary_variable.
16857 
16858 bool
is_variable() const16859 Expression::is_variable() const
16860 {
16861   switch (this->classification_)
16862     {
16863     case EXPRESSION_VAR_REFERENCE:
16864     case EXPRESSION_TEMPORARY_REFERENCE:
16865     case EXPRESSION_SET_AND_USE_TEMPORARY:
16866     case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16867       return true;
16868     default:
16869       return false;
16870     }
16871 }
16872 
16873 // Return true if this is a reference to a local variable.
16874 
16875 bool
is_local_variable() const16876 Expression::is_local_variable() const
16877 {
16878   const Var_expression* ve = this->var_expression();
16879   if (ve == NULL)
16880     return false;
16881   const Named_object* no = ve->named_object();
16882   return (no->is_result_variable()
16883 	  || (no->is_variable() && !no->var_value()->is_global()));
16884 }
16885 
16886 const Named_object*
named_constant() const16887 Expression::named_constant() const
16888 {
16889   if (this->classification() != EXPRESSION_CONST_REFERENCE)
16890     return NULL;
16891   const Const_expression* ce = static_cast<const Const_expression*>(this);
16892   return ce->named_object();
16893 }
16894 
16895 // Class Type_guard_expression.
16896 
16897 // Traversal.
16898 
16899 int
do_traverse(Traverse * traverse)16900 Type_guard_expression::do_traverse(Traverse* traverse)
16901 {
16902   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
16903       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16904     return TRAVERSE_EXIT;
16905   return TRAVERSE_CONTINUE;
16906 }
16907 
16908 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)16909 Type_guard_expression::do_flatten(Gogo*, Named_object*,
16910                                   Statement_inserter* inserter)
16911 {
16912   if (this->expr_->is_error_expression()
16913       || this->expr_->type()->is_error_type())
16914     {
16915       go_assert(saw_errors());
16916       return Expression::make_error(this->location());
16917     }
16918 
16919   if (!this->expr_->is_variable())
16920     {
16921       Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
16922                                                             this->location());
16923       inserter->insert(temp);
16924       this->expr_ =
16925           Expression::make_temporary_reference(temp, this->location());
16926     }
16927   return this;
16928 }
16929 
16930 // Check types of a type guard expression.  The expression must have
16931 // an interface type, but the actual type conversion is checked at run
16932 // time.
16933 
16934 void
do_check_types(Gogo *)16935 Type_guard_expression::do_check_types(Gogo*)
16936 {
16937   Type* expr_type = this->expr_->type();
16938   if (expr_type->interface_type() == NULL)
16939     {
16940       if (!expr_type->is_error() && !this->type_->is_error())
16941 	this->report_error(_("type assertion only valid for interface types"));
16942       this->set_is_error();
16943     }
16944   else if (this->type_->interface_type() == NULL)
16945     {
16946       std::string reason;
16947       if (!expr_type->interface_type()->implements_interface(this->type_,
16948 							     &reason))
16949 	{
16950 	  if (!this->type_->is_error())
16951 	    {
16952 	      if (reason.empty())
16953 		this->report_error(_("impossible type assertion: "
16954 				     "type does not implement interface"));
16955 	      else
16956 		go_error_at(this->location(),
16957                             ("impossible type assertion: "
16958                              "type does not implement interface (%s)"),
16959                             reason.c_str());
16960 	    }
16961 	  this->set_is_error();
16962 	}
16963     }
16964 }
16965 
16966 // Copy.
16967 
16968 Expression*
do_copy()16969 Type_guard_expression::do_copy()
16970 {
16971   return new Type_guard_expression(this->expr_->copy(),
16972 				   this->type_->copy_expressions(),
16973 				   this->location());
16974 }
16975 
16976 // Return the backend representation for a type guard expression.
16977 
16978 Bexpression*
do_get_backend(Translate_context * context)16979 Type_guard_expression::do_get_backend(Translate_context* context)
16980 {
16981   Expression* conversion;
16982   if (this->type_->interface_type() != NULL)
16983     conversion =
16984         Expression::convert_interface_to_interface(this->type_, this->expr_,
16985                                                    true, this->location());
16986   else
16987     conversion =
16988         Expression::convert_for_assignment(context->gogo(), this->type_,
16989                                            this->expr_, this->location());
16990 
16991   Gogo* gogo = context->gogo();
16992   Btype* bt = this->type_->get_backend(gogo);
16993   Bexpression* bexpr = conversion->get_backend(context);
16994   return gogo->backend()->convert_expression(bt, bexpr, this->location());
16995 }
16996 
16997 // Dump ast representation for a type guard expression.
16998 
16999 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17000 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
17001     const
17002 {
17003   this->expr_->dump_expression(ast_dump_context);
17004   ast_dump_context->ostream() <<  ".";
17005   ast_dump_context->dump_type(this->type_);
17006 }
17007 
17008 // Make a type guard expression.
17009 
17010 Expression*
make_type_guard(Expression * expr,Type * type,Location location)17011 Expression::make_type_guard(Expression* expr, Type* type,
17012 			    Location location)
17013 {
17014   return new Type_guard_expression(expr, type, location);
17015 }
17016 
17017 // Class Heap_expression.
17018 
17019 // Return the type of the expression stored on the heap.
17020 
17021 Type*
do_type()17022 Heap_expression::do_type()
17023 { return Type::make_pointer_type(this->expr_->type()); }
17024 
17025 // Return the backend representation for allocating an expression on the heap.
17026 
17027 Bexpression*
do_get_backend(Translate_context * context)17028 Heap_expression::do_get_backend(Translate_context* context)
17029 {
17030   Type* etype = this->expr_->type();
17031   if (this->expr_->is_error_expression() || etype->is_error())
17032     return context->backend()->error_expression();
17033 
17034   Location loc = this->location();
17035   Gogo* gogo = context->gogo();
17036   Btype* btype = this->type()->get_backend(gogo);
17037 
17038   Expression* alloc = Expression::make_allocation(etype, loc);
17039   if (this->allocate_on_stack_)
17040     alloc->allocation_expression()->set_allocate_on_stack();
17041   Bexpression* space = alloc->get_backend(context);
17042 
17043   Bstatement* decl;
17044   Named_object* fn = context->function();
17045   go_assert(fn != NULL);
17046   Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
17047   Bvariable* space_temp =
17048     gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
17049 					space, true, loc, &decl);
17050   Btype* expr_btype = etype->get_backend(gogo);
17051 
17052   Bexpression* bexpr = this->expr_->get_backend(context);
17053 
17054   // If this assignment needs a write barrier, call typedmemmove.  We
17055   // don't do this in the write barrier pass because in some cases
17056   // backend conversion can introduce new Heap_expression values.
17057   Bstatement* assn;
17058   if (!etype->has_pointer() || this->allocate_on_stack_)
17059     {
17060       space = gogo->backend()->var_expression(space_temp, loc);
17061       Bexpression* ref =
17062 	gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17063       assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
17064     }
17065   else
17066     {
17067       Bstatement* edecl;
17068       Bvariable* btemp =
17069 	gogo->backend()->temporary_variable(fndecl, context->bblock(),
17070 					    expr_btype, bexpr, true, loc,
17071 					    &edecl);
17072       Bexpression* btempref = gogo->backend()->var_expression(btemp,
17073 							      loc);
17074       space = gogo->backend()->var_expression(space_temp, loc);
17075       Type* etype_ptr = Type::make_pointer_type(etype);
17076       Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
17077       Expression* erhs;
17078       Expression* call;
17079       if (etype->is_direct_iface_type())
17080         {
17081           // Single pointer.
17082           Type* uintptr_type = Type::lookup_integer_type("uintptr");
17083           erhs = Expression::make_backend(btempref, etype, loc);
17084           erhs = Expression::unpack_direct_iface(erhs, loc);
17085           erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
17086           call = Runtime::make_call(Runtime::GCWRITEBARRIER, loc, 2,
17087                                     elhs, erhs);
17088         }
17089       else
17090         {
17091           Expression* td = Expression::make_type_descriptor(etype, loc);
17092           Bexpression* addr =
17093             gogo->backend()->address_expression(btempref, loc);
17094           erhs = Expression::make_backend(addr, etype_ptr, loc);
17095           call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
17096                                     td, elhs, erhs);
17097         }
17098       Statement* cs = Statement::make_statement(call, false);
17099 
17100       space = gogo->backend()->var_expression(space_temp, loc);
17101       Bexpression* ref =
17102         gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17103       Expression* eref = Expression::make_backend(ref, etype, loc);
17104       btempref = gogo->backend()->var_expression(btemp, loc);
17105       erhs = Expression::make_backend(btempref, etype, loc);
17106       Statement* as = Statement::make_assignment(eref, erhs, loc);
17107 
17108       as = gogo->check_write_barrier(context->block(), as, cs);
17109       Bstatement* s = as->get_backend(context);
17110 
17111       assn = gogo->backend()->compound_statement(edecl, s);
17112     }
17113   decl = gogo->backend()->compound_statement(decl, assn);
17114   space = gogo->backend()->var_expression(space_temp, loc);
17115   return gogo->backend()->compound_expression(decl, space, loc);
17116 }
17117 
17118 // Dump ast representation for a heap expression.
17119 
17120 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17121 Heap_expression::do_dump_expression(
17122     Ast_dump_context* ast_dump_context) const
17123 {
17124   ast_dump_context->ostream() << "&(";
17125   ast_dump_context->dump_expression(this->expr_);
17126   ast_dump_context->ostream() << ")";
17127 }
17128 
17129 // Allocate an expression on the heap.
17130 
17131 Expression*
make_heap_expression(Expression * expr,Location location)17132 Expression::make_heap_expression(Expression* expr, Location location)
17133 {
17134   return new Heap_expression(expr, location);
17135 }
17136 
17137 // Class Receive_expression.
17138 
17139 // Return the type of a receive expression.
17140 
17141 Type*
do_type()17142 Receive_expression::do_type()
17143 {
17144   if (this->is_error_expression())
17145     return Type::make_error_type();
17146   Channel_type* channel_type = this->channel_->type()->channel_type();
17147   if (channel_type == NULL)
17148     {
17149       this->report_error(_("expected channel"));
17150       return Type::make_error_type();
17151     }
17152   return channel_type->element_type();
17153 }
17154 
17155 // Check types for a receive expression.
17156 
17157 void
do_check_types(Gogo *)17158 Receive_expression::do_check_types(Gogo*)
17159 {
17160   Type* type = this->channel_->type();
17161   if (type->is_error())
17162     {
17163       go_assert(saw_errors());
17164       this->set_is_error();
17165       return;
17166     }
17167   if (type->channel_type() == NULL)
17168     {
17169       this->report_error(_("expected channel"));
17170       return;
17171     }
17172   if (!type->channel_type()->may_receive())
17173     {
17174       this->report_error(_("invalid receive on send-only channel"));
17175       return;
17176     }
17177 }
17178 
17179 // Flattening for receive expressions creates a temporary variable to store
17180 // received data in for receives.
17181 
17182 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)17183 Receive_expression::do_flatten(Gogo*, Named_object*,
17184                                Statement_inserter* inserter)
17185 {
17186   Channel_type* channel_type = this->channel_->type()->channel_type();
17187   if (channel_type == NULL)
17188     {
17189       go_assert(saw_errors());
17190       return this;
17191     }
17192   else if (this->channel_->is_error_expression())
17193    {
17194      go_assert(saw_errors());
17195      return Expression::make_error(this->location());
17196    }
17197 
17198   Type* element_type = channel_type->element_type();
17199   if (this->temp_receiver_ == NULL)
17200     {
17201       this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
17202 						       this->location());
17203       this->temp_receiver_->set_is_address_taken();
17204       inserter->insert(this->temp_receiver_);
17205     }
17206 
17207   return this;
17208 }
17209 
17210 // Get the backend representation for a receive expression.
17211 
17212 Bexpression*
do_get_backend(Translate_context * context)17213 Receive_expression::do_get_backend(Translate_context* context)
17214 {
17215   Location loc = this->location();
17216 
17217   Channel_type* channel_type = this->channel_->type()->channel_type();
17218   if (channel_type == NULL)
17219     {
17220       go_assert(this->channel_->type()->is_error());
17221       return context->backend()->error_expression();
17222     }
17223 
17224   Expression* recv_ref =
17225     Expression::make_temporary_reference(this->temp_receiver_, loc);
17226   Expression* recv_addr =
17227     Expression::make_temporary_reference(this->temp_receiver_, loc);
17228   recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
17229   Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
17230 					this->channel_, recv_addr);
17231   return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
17232 }
17233 
17234 // Export a receive expression.
17235 
17236 void
do_export(Export_function_body * efb) const17237 Receive_expression::do_export(Export_function_body* efb) const
17238 {
17239   efb->write_c_string("<-");
17240   this->channel_->export_expression(efb);
17241 }
17242 
17243 // Dump ast representation for a receive expression.
17244 
17245 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17246 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
17247 {
17248   ast_dump_context->ostream() << " <- " ;
17249   ast_dump_context->dump_expression(channel_);
17250 }
17251 
17252 // Import a receive expression.
17253 
17254 Expression*
do_import(Import_expression * imp,Location loc)17255 Receive_expression::do_import(Import_expression* imp, Location loc)
17256 {
17257   imp->require_c_string("<-");
17258   Expression* expr = Expression::import_expression(imp, loc);
17259   return Expression::make_receive(expr, loc);
17260 }
17261 
17262 // Make a receive expression.
17263 
17264 Receive_expression*
make_receive(Expression * channel,Location location)17265 Expression::make_receive(Expression* channel, Location location)
17266 {
17267   return new Receive_expression(channel, location);
17268 }
17269 
17270 // An expression which evaluates to a pointer to the type descriptor
17271 // of a type.
17272 
17273 class Type_descriptor_expression : public Expression
17274 {
17275  public:
Type_descriptor_expression(Type * type,Location location)17276   Type_descriptor_expression(Type* type, Location location)
17277     : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
17278       type_(type)
17279   { }
17280 
17281  protected:
17282   int
17283   do_traverse(Traverse*);
17284 
17285   Type*
do_type()17286   do_type()
17287   { return Type::make_type_descriptor_ptr_type(); }
17288 
17289   bool
do_is_static_initializer() const17290   do_is_static_initializer() const
17291   { return true; }
17292 
17293   void
do_determine_type(const Type_context *)17294   do_determine_type(const Type_context*)
17295   { }
17296 
17297   Expression*
do_copy()17298   do_copy()
17299   { return this; }
17300 
17301   Bexpression*
do_get_backend(Translate_context * context)17302   do_get_backend(Translate_context* context)
17303   {
17304     return this->type_->type_descriptor_pointer(context->gogo(),
17305 						this->location());
17306   }
17307 
17308   void
17309   do_dump_expression(Ast_dump_context*) const;
17310 
17311  private:
17312   // The type for which this is the descriptor.
17313   Type* type_;
17314 };
17315 
17316 int
do_traverse(Traverse * traverse)17317 Type_descriptor_expression::do_traverse(Traverse* traverse)
17318 {
17319   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17320     return TRAVERSE_EXIT;
17321   return TRAVERSE_CONTINUE;
17322 }
17323 
17324 // Dump ast representation for a type descriptor expression.
17325 
17326 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17327 Type_descriptor_expression::do_dump_expression(
17328     Ast_dump_context* ast_dump_context) const
17329 {
17330   ast_dump_context->dump_type(this->type_);
17331 }
17332 
17333 // Make a type descriptor expression.
17334 
17335 Expression*
make_type_descriptor(Type * type,Location location)17336 Expression::make_type_descriptor(Type* type, Location location)
17337 {
17338   return new Type_descriptor_expression(type, location);
17339 }
17340 
17341 // An expression which evaluates to a pointer to the Garbage Collection symbol
17342 // of a type.
17343 
17344 class GC_symbol_expression : public Expression
17345 {
17346  public:
GC_symbol_expression(Type * type)17347   GC_symbol_expression(Type* type)
17348     : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
17349       type_(type)
17350   {}
17351 
17352  protected:
17353   Type*
do_type()17354   do_type()
17355   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17356 
17357   bool
do_is_static_initializer() const17358   do_is_static_initializer() const
17359   { return true; }
17360 
17361   void
do_determine_type(const Type_context *)17362   do_determine_type(const Type_context*)
17363   { }
17364 
17365   Expression*
do_copy()17366   do_copy()
17367   { return this; }
17368 
17369   Bexpression*
do_get_backend(Translate_context * context)17370   do_get_backend(Translate_context* context)
17371   { return this->type_->gc_symbol_pointer(context->gogo()); }
17372 
17373   void
17374   do_dump_expression(Ast_dump_context*) const;
17375 
17376  private:
17377   // The type which this gc symbol describes.
17378   Type* type_;
17379 };
17380 
17381 // Dump ast representation for a gc symbol expression.
17382 
17383 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17384 GC_symbol_expression::do_dump_expression(
17385     Ast_dump_context* ast_dump_context) const
17386 {
17387   ast_dump_context->ostream() << "gcdata(";
17388   ast_dump_context->dump_type(this->type_);
17389   ast_dump_context->ostream() << ")";
17390 }
17391 
17392 // Make a gc symbol expression.
17393 
17394 Expression*
make_gc_symbol(Type * type)17395 Expression::make_gc_symbol(Type* type)
17396 {
17397   return new GC_symbol_expression(type);
17398 }
17399 
17400 // An expression that evaluates to a pointer to a symbol holding the
17401 // ptrmask data of a type.
17402 
17403 class Ptrmask_symbol_expression : public Expression
17404 {
17405  public:
Ptrmask_symbol_expression(Type * type)17406   Ptrmask_symbol_expression(Type* type)
17407     : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
17408       type_(type)
17409   {}
17410 
17411  protected:
17412   Type*
do_type()17413   do_type()
17414   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17415 
17416   bool
do_is_static_initializer() const17417   do_is_static_initializer() const
17418   { return true; }
17419 
17420   void
do_determine_type(const Type_context *)17421   do_determine_type(const Type_context*)
17422   { }
17423 
17424   Expression*
do_copy()17425   do_copy()
17426   { return this; }
17427 
17428   Bexpression*
17429   do_get_backend(Translate_context*);
17430 
17431   void
17432   do_dump_expression(Ast_dump_context*) const;
17433 
17434  private:
17435   // The type that this ptrmask symbol describes.
17436   Type* type_;
17437 };
17438 
17439 // Return the ptrmask variable.
17440 
17441 Bexpression*
do_get_backend(Translate_context * context)17442 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
17443 {
17444   Gogo* gogo = context->gogo();
17445 
17446   // If this type does not need a gcprog, then we can use the standard
17447   // GC symbol.
17448   int64_t ptrsize, ptrdata;
17449   if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
17450     return this->type_->gc_symbol_pointer(gogo);
17451 
17452   // Otherwise we have to build a ptrmask variable, and return a
17453   // pointer to it.
17454 
17455   Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
17456   Location bloc = Linemap::predeclared_location();
17457   Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
17458   Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
17459 
17460   Type* uint8_type = Type::lookup_integer_type("uint8");
17461   Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
17462   Btype* ubtype = pointer_uint8_type->get_backend(gogo);
17463   return gogo->backend()->convert_expression(ubtype, baddr, bloc);
17464 }
17465 
17466 // Dump AST for a ptrmask symbol expression.
17467 
17468 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17469 Ptrmask_symbol_expression::do_dump_expression(
17470     Ast_dump_context* ast_dump_context) const
17471 {
17472   ast_dump_context->ostream() << "ptrmask(";
17473   ast_dump_context->dump_type(this->type_);
17474   ast_dump_context->ostream() << ")";
17475 }
17476 
17477 // Make a ptrmask symbol expression.
17478 
17479 Expression*
make_ptrmask_symbol(Type * type)17480 Expression::make_ptrmask_symbol(Type* type)
17481 {
17482   return new Ptrmask_symbol_expression(type);
17483 }
17484 
17485 // An expression which evaluates to some characteristic of a type.
17486 // This is only used to initialize fields of a type descriptor.  Using
17487 // a new expression class is slightly inefficient but gives us a good
17488 // separation between the frontend and the middle-end with regard to
17489 // how types are laid out.
17490 
17491 class Type_info_expression : public Expression
17492 {
17493  public:
Type_info_expression(Type * type,Type_info type_info)17494   Type_info_expression(Type* type, Type_info type_info)
17495     : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
17496       type_(type), type_info_(type_info)
17497   { }
17498 
17499  protected:
17500   bool
do_is_static_initializer() const17501   do_is_static_initializer() const
17502   { return true; }
17503 
17504   Type*
17505   do_type();
17506 
17507   void
do_determine_type(const Type_context *)17508   do_determine_type(const Type_context*)
17509   { }
17510 
17511   Expression*
do_copy()17512   do_copy()
17513   { return this; }
17514 
17515   Bexpression*
17516   do_get_backend(Translate_context* context);
17517 
17518   void
17519   do_dump_expression(Ast_dump_context*) const;
17520 
17521  private:
17522   // The type for which we are getting information.
17523   Type* type_;
17524   // What information we want.
17525   Type_info type_info_;
17526 };
17527 
17528 // The type is chosen to match what the type descriptor struct
17529 // expects.
17530 
17531 Type*
do_type()17532 Type_info_expression::do_type()
17533 {
17534   switch (this->type_info_)
17535     {
17536     case TYPE_INFO_SIZE:
17537     case TYPE_INFO_BACKEND_PTRDATA:
17538     case TYPE_INFO_DESCRIPTOR_PTRDATA:
17539       return Type::lookup_integer_type("uintptr");
17540     case TYPE_INFO_ALIGNMENT:
17541     case TYPE_INFO_FIELD_ALIGNMENT:
17542       return Type::lookup_integer_type("uint8");
17543     default:
17544       go_unreachable();
17545     }
17546 }
17547 
17548 // Return the backend representation for type information.
17549 
17550 Bexpression*
do_get_backend(Translate_context * context)17551 Type_info_expression::do_get_backend(Translate_context* context)
17552 {
17553   Gogo* gogo = context->gogo();
17554   bool ok = true;
17555   int64_t val;
17556   switch (this->type_info_)
17557     {
17558     case TYPE_INFO_SIZE:
17559       ok = this->type_->backend_type_size(gogo, &val);
17560       break;
17561     case TYPE_INFO_ALIGNMENT:
17562       ok = this->type_->backend_type_align(gogo, &val);
17563       break;
17564     case TYPE_INFO_FIELD_ALIGNMENT:
17565       ok = this->type_->backend_type_field_align(gogo, &val);
17566       break;
17567     case TYPE_INFO_BACKEND_PTRDATA:
17568       ok = this->type_->backend_type_ptrdata(gogo, &val);
17569       break;
17570     case TYPE_INFO_DESCRIPTOR_PTRDATA:
17571       ok = this->type_->descriptor_ptrdata(gogo, &val);
17572       break;
17573     default:
17574       go_unreachable();
17575     }
17576   if (!ok)
17577     {
17578       go_assert(saw_errors());
17579       return gogo->backend()->error_expression();
17580     }
17581   Expression* e = Expression::make_integer_int64(val, this->type(),
17582 						 this->location());
17583   return e->get_backend(context);
17584 }
17585 
17586 // Dump ast representation for a type info expression.
17587 
17588 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17589 Type_info_expression::do_dump_expression(
17590     Ast_dump_context* ast_dump_context) const
17591 {
17592   ast_dump_context->ostream() << "typeinfo(";
17593   ast_dump_context->dump_type(this->type_);
17594   ast_dump_context->ostream() << ",";
17595   ast_dump_context->ostream() <<
17596     (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
17597     : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
17598     : this->type_info_ == TYPE_INFO_SIZE ? "size"
17599     : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
17600     : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
17601     : "unknown");
17602   ast_dump_context->ostream() << ")";
17603 }
17604 
17605 // Make a type info expression.
17606 
17607 Expression*
make_type_info(Type * type,Type_info type_info)17608 Expression::make_type_info(Type* type, Type_info type_info)
17609 {
17610   return new Type_info_expression(type, type_info);
17611 }
17612 
17613 // An expression that evaluates to some characteristic of a slice.
17614 // This is used when indexing, bound-checking, or nil checking a slice.
17615 
17616 class Slice_info_expression : public Expression
17617 {
17618  public:
Slice_info_expression(Expression * slice,Slice_info slice_info,Location location)17619   Slice_info_expression(Expression* slice, Slice_info slice_info,
17620                         Location location)
17621     : Expression(EXPRESSION_SLICE_INFO, location),
17622       slice_(slice), slice_info_(slice_info)
17623   { }
17624 
17625  protected:
17626   Type*
17627   do_type();
17628 
17629   void
do_determine_type(const Type_context *)17630   do_determine_type(const Type_context*)
17631   { }
17632 
17633   Expression*
do_copy()17634   do_copy()
17635   {
17636     return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
17637                                      this->location());
17638   }
17639 
17640   Bexpression*
17641   do_get_backend(Translate_context* context);
17642 
17643   void
17644   do_dump_expression(Ast_dump_context*) const;
17645 
17646   void
do_issue_nil_check()17647   do_issue_nil_check()
17648   { this->slice_->issue_nil_check(); }
17649 
17650  private:
17651   // The slice for which we are getting information.
17652   Expression* slice_;
17653   // What information we want.
17654   Slice_info slice_info_;
17655 };
17656 
17657 // Return the type of the slice info.
17658 
17659 Type*
do_type()17660 Slice_info_expression::do_type()
17661 {
17662   switch (this->slice_info_)
17663     {
17664     case SLICE_INFO_VALUE_POINTER:
17665       return Type::make_pointer_type(
17666           this->slice_->type()->array_type()->element_type());
17667     case SLICE_INFO_LENGTH:
17668     case SLICE_INFO_CAPACITY:
17669         return Type::lookup_integer_type("int");
17670     default:
17671       go_unreachable();
17672     }
17673 }
17674 
17675 // Return the backend information for slice information.
17676 
17677 Bexpression*
do_get_backend(Translate_context * context)17678 Slice_info_expression::do_get_backend(Translate_context* context)
17679 {
17680   Gogo* gogo = context->gogo();
17681   Bexpression* bslice = this->slice_->get_backend(context);
17682   switch (this->slice_info_)
17683     {
17684     case SLICE_INFO_VALUE_POINTER:
17685     case SLICE_INFO_LENGTH:
17686     case SLICE_INFO_CAPACITY:
17687       return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
17688 						      this->location());
17689       break;
17690     default:
17691       go_unreachable();
17692     }
17693 }
17694 
17695 // Dump ast representation for a type info expression.
17696 
17697 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17698 Slice_info_expression::do_dump_expression(
17699     Ast_dump_context* ast_dump_context) const
17700 {
17701   ast_dump_context->ostream() << "sliceinfo(";
17702   this->slice_->dump_expression(ast_dump_context);
17703   ast_dump_context->ostream() << ",";
17704   ast_dump_context->ostream() <<
17705       (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
17706     : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
17707     : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
17708     : "unknown");
17709   ast_dump_context->ostream() << ")";
17710 }
17711 
17712 // Make a slice info expression.
17713 
17714 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)17715 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
17716                             Location location)
17717 {
17718   return new Slice_info_expression(slice, slice_info, location);
17719 }
17720 
17721 // Class Slice_value_expression.
17722 
17723 int
do_traverse(Traverse * traverse)17724 Slice_value_expression::do_traverse(Traverse* traverse)
17725 {
17726   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
17727       || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
17728       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
17729       || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
17730     return TRAVERSE_EXIT;
17731   return TRAVERSE_CONTINUE;
17732 }
17733 
17734 Expression*
do_copy()17735 Slice_value_expression::do_copy()
17736 {
17737   return new Slice_value_expression(this->type_->copy_expressions(),
17738 				    this->valmem_->copy(),
17739 				    this->len_->copy(), this->cap_->copy(),
17740 				    this->location());
17741 }
17742 
17743 Bexpression*
do_get_backend(Translate_context * context)17744 Slice_value_expression::do_get_backend(Translate_context* context)
17745 {
17746   std::vector<Bexpression*> vals(3);
17747   vals[0] = this->valmem_->get_backend(context);
17748   vals[1] = this->len_->get_backend(context);
17749   vals[2] = this->cap_->get_backend(context);
17750 
17751   Gogo* gogo = context->gogo();
17752   Btype* btype = this->type_->get_backend(gogo);
17753   return gogo->backend()->constructor_expression(btype, vals, this->location());
17754 }
17755 
17756 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17757 Slice_value_expression::do_dump_expression(
17758     Ast_dump_context* ast_dump_context) const
17759 {
17760   ast_dump_context->ostream() << "slicevalue(";
17761   ast_dump_context->ostream() << "values: ";
17762   this->valmem_->dump_expression(ast_dump_context);
17763   ast_dump_context->ostream() << ", length: ";
17764   this->len_->dump_expression(ast_dump_context);
17765   ast_dump_context->ostream() << ", capacity: ";
17766   this->cap_->dump_expression(ast_dump_context);
17767   ast_dump_context->ostream() << ")";
17768 }
17769 
17770 Expression*
make_slice_value(Type * at,Expression * valmem,Expression * len,Expression * cap,Location location)17771 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
17772                              Expression* cap, Location location)
17773 {
17774   go_assert(at->is_slice_type());
17775   go_assert(valmem->is_nil_expression()
17776 	    || (at->array_type()->element_type()
17777 		== valmem->type()->points_to()));
17778   return new Slice_value_expression(at, valmem, len, cap, location);
17779 }
17780 
17781 // Look through the expression of a Slice_value_expression's valmem to
17782 // find an call to makeslice.  If found, return the call expression and
17783 // the containing temporary statement (if any).
17784 
17785 std::pair<Call_expression*, Temporary_statement*>
find_makeslice_call(Expression * expr)17786 Expression::find_makeslice_call(Expression* expr)
17787 {
17788   Unsafe_type_conversion_expression* utce =
17789     expr->unsafe_conversion_expression();
17790   if (utce != NULL)
17791     expr = utce->expr();
17792 
17793   Slice_value_expression* sve = expr->slice_value_expression();
17794   if (sve == NULL)
17795     return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17796   expr = sve->valmem();
17797 
17798   utce = expr->unsafe_conversion_expression();
17799   if (utce != NULL)
17800     expr = utce->expr();
17801 
17802   Temporary_reference_expression* tre = expr->temporary_reference_expression();
17803   Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
17804   if (ts != NULL && ts->init() != NULL && !ts->assigned()
17805       && !ts->is_address_taken())
17806     expr = ts->init();
17807 
17808   Call_expression* call = expr->call_expression();
17809   if (call == NULL)
17810     return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17811 
17812   Func_expression* fe = call->fn()->func_expression();
17813   if (fe != NULL
17814       && fe->runtime_code() == Runtime::MAKESLICE)
17815     return std::make_pair(call, ts);
17816 
17817   return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17818 }
17819 
17820 // An expression that evaluates to some characteristic of a non-empty interface.
17821 // This is used to access the method table or underlying object of an interface.
17822 
17823 class Interface_info_expression : public Expression
17824 {
17825  public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)17826   Interface_info_expression(Expression* iface, Interface_info iface_info,
17827                             Location location)
17828     : Expression(EXPRESSION_INTERFACE_INFO, location),
17829       iface_(iface), iface_info_(iface_info)
17830   { }
17831 
17832  protected:
17833   Type*
17834   do_type();
17835 
17836   void
do_determine_type(const Type_context *)17837   do_determine_type(const Type_context*)
17838   { }
17839 
17840   Expression*
do_copy()17841   do_copy()
17842   {
17843     return new Interface_info_expression(this->iface_->copy(),
17844                                          this->iface_info_, this->location());
17845   }
17846 
17847   Bexpression*
17848   do_get_backend(Translate_context* context);
17849 
17850   void
17851   do_dump_expression(Ast_dump_context*) const;
17852 
17853   void
do_issue_nil_check()17854   do_issue_nil_check()
17855   { this->iface_->issue_nil_check(); }
17856 
17857  private:
17858   // The interface for which we are getting information.
17859   Expression* iface_;
17860   // What information we want.
17861   Interface_info iface_info_;
17862 };
17863 
17864 // Return the type of the interface info.
17865 
17866 Type*
do_type()17867 Interface_info_expression::do_type()
17868 {
17869   switch (this->iface_info_)
17870     {
17871     case INTERFACE_INFO_METHODS:
17872       {
17873         typedef Unordered_map(Interface_type*, Type*) Hashtable;
17874         static Hashtable result_types;
17875 
17876         Interface_type* itype = this->iface_->type()->interface_type();
17877 
17878         Hashtable::const_iterator pr = result_types.find(itype);
17879         if (pr != result_types.end())
17880           return pr->second;
17881 
17882         Type* pdt = Type::make_type_descriptor_ptr_type();
17883         if (itype->is_empty())
17884           {
17885             result_types[itype] = pdt;
17886             return pdt;
17887           }
17888 
17889         Location loc = this->location();
17890         Struct_field_list* sfl = new Struct_field_list();
17891         sfl->push_back(
17892             Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
17893 
17894         for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
17895              p != itype->methods()->end();
17896              ++p)
17897           {
17898             Function_type* ft = p->type()->function_type();
17899             go_assert(ft->receiver() == NULL);
17900 
17901             const Typed_identifier_list* params = ft->parameters();
17902             Typed_identifier_list* mparams = new Typed_identifier_list();
17903             if (params != NULL)
17904               mparams->reserve(params->size() + 1);
17905             Type* vt = Type::make_pointer_type(Type::make_void_type());
17906             mparams->push_back(Typed_identifier("", vt, ft->location()));
17907             if (params != NULL)
17908               {
17909                 for (Typed_identifier_list::const_iterator pp = params->begin();
17910                      pp != params->end();
17911                      ++pp)
17912                   mparams->push_back(*pp);
17913               }
17914 
17915             Typed_identifier_list* mresults = (ft->results() == NULL
17916                                                ? NULL
17917                                                : ft->results()->copy());
17918             Backend_function_type* mft =
17919                 Type::make_backend_function_type(NULL, mparams, mresults,
17920                                                  ft->location());
17921 
17922             std::string fname = Gogo::unpack_hidden_name(p->name());
17923             sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
17924           }
17925 
17926 	Struct_type* st = Type::make_struct_type(sfl, loc);
17927 	st->set_is_struct_incomparable();
17928 	Pointer_type *pt = Type::make_pointer_type(st);
17929         result_types[itype] = pt;
17930         return pt;
17931       }
17932     case INTERFACE_INFO_OBJECT:
17933       return Type::make_pointer_type(Type::make_void_type());
17934     default:
17935       go_unreachable();
17936     }
17937 }
17938 
17939 // Return the backend representation for interface information.
17940 
17941 Bexpression*
do_get_backend(Translate_context * context)17942 Interface_info_expression::do_get_backend(Translate_context* context)
17943 {
17944   Gogo* gogo = context->gogo();
17945   Bexpression* biface = this->iface_->get_backend(context);
17946   switch (this->iface_info_)
17947     {
17948     case INTERFACE_INFO_METHODS:
17949     case INTERFACE_INFO_OBJECT:
17950       return gogo->backend()->struct_field_expression(biface, this->iface_info_,
17951 						      this->location());
17952       break;
17953     default:
17954       go_unreachable();
17955     }
17956 }
17957 
17958 // Dump ast representation for an interface info expression.
17959 
17960 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17961 Interface_info_expression::do_dump_expression(
17962     Ast_dump_context* ast_dump_context) const
17963 {
17964   bool is_empty = this->iface_->type()->interface_type()->is_empty();
17965   ast_dump_context->ostream() << "interfaceinfo(";
17966   this->iface_->dump_expression(ast_dump_context);
17967   ast_dump_context->ostream() << ",";
17968   ast_dump_context->ostream() <<
17969       (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
17970     : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
17971     : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
17972     : "unknown");
17973   ast_dump_context->ostream() << ")";
17974 }
17975 
17976 // Make an interface info expression.
17977 
17978 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)17979 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
17980                                 Location location)
17981 {
17982   return new Interface_info_expression(iface, iface_info, location);
17983 }
17984 
17985 // An expression that represents an interface value.  The first field is either
17986 // a type descriptor for an empty interface or a pointer to the interface method
17987 // table for a non-empty interface.  The second field is always the object.
17988 
17989 class Interface_value_expression : public Expression
17990 {
17991  public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)17992   Interface_value_expression(Type* type, Expression* first_field,
17993                              Expression* obj, Location location)
17994       : Expression(EXPRESSION_INTERFACE_VALUE, location),
17995         type_(type), first_field_(first_field), obj_(obj)
17996   { }
17997 
17998  protected:
17999   int
18000   do_traverse(Traverse*);
18001 
18002   Type*
do_type()18003   do_type()
18004   { return this->type_; }
18005 
18006   void
do_determine_type(const Type_context *)18007   do_determine_type(const Type_context*)
18008   { go_unreachable(); }
18009 
18010   Expression*
do_copy()18011   do_copy()
18012   {
18013     return new Interface_value_expression(this->type_->copy_expressions(),
18014                                           this->first_field_->copy(),
18015                                           this->obj_->copy(), this->location());
18016   }
18017 
18018   Bexpression*
18019   do_get_backend(Translate_context* context);
18020 
18021   void
18022   do_dump_expression(Ast_dump_context*) const;
18023 
18024  private:
18025   // The type of the interface value.
18026   Type* type_;
18027   // The first field of the interface (either a type descriptor or a pointer
18028   // to the method table.
18029   Expression* first_field_;
18030   // The underlying object of the interface.
18031   Expression* obj_;
18032 };
18033 
18034 int
do_traverse(Traverse * traverse)18035 Interface_value_expression::do_traverse(Traverse* traverse)
18036 {
18037   if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
18038       || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
18039     return TRAVERSE_EXIT;
18040   return TRAVERSE_CONTINUE;
18041 }
18042 
18043 Bexpression*
do_get_backend(Translate_context * context)18044 Interface_value_expression::do_get_backend(Translate_context* context)
18045 {
18046   std::vector<Bexpression*> vals(2);
18047   vals[0] = this->first_field_->get_backend(context);
18048   vals[1] = this->obj_->get_backend(context);
18049 
18050   Gogo* gogo = context->gogo();
18051   Btype* btype = this->type_->get_backend(gogo);
18052   return gogo->backend()->constructor_expression(btype, vals, this->location());
18053 }
18054 
18055 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18056 Interface_value_expression::do_dump_expression(
18057     Ast_dump_context* ast_dump_context) const
18058 {
18059   ast_dump_context->ostream() << "interfacevalue(";
18060   ast_dump_context->ostream() <<
18061       (this->type_->interface_type()->is_empty()
18062        ? "type_descriptor: "
18063        : "methods: ");
18064   this->first_field_->dump_expression(ast_dump_context);
18065   ast_dump_context->ostream() << ", object: ";
18066   this->obj_->dump_expression(ast_dump_context);
18067   ast_dump_context->ostream() << ")";
18068 }
18069 
18070 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)18071 Expression::make_interface_value(Type* type, Expression* first_value,
18072                                  Expression* object, Location location)
18073 {
18074   return new Interface_value_expression(type, first_value, object, location);
18075 }
18076 
18077 // An interface method table for a pair of types: an interface type and a type
18078 // that implements that interface.
18079 
18080 class Interface_mtable_expression : public Expression
18081 {
18082  public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)18083   Interface_mtable_expression(Interface_type* itype, Type* type,
18084                               bool is_pointer, Location location)
18085       : Expression(EXPRESSION_INTERFACE_MTABLE, location),
18086         itype_(itype), type_(type), is_pointer_(is_pointer),
18087 	method_table_type_(NULL), bvar_(NULL)
18088   { }
18089 
18090  protected:
18091   int
18092   do_traverse(Traverse*);
18093 
18094   Type*
18095   do_type();
18096 
18097   bool
do_is_static_initializer() const18098   do_is_static_initializer() const
18099   { return true; }
18100 
18101   void
do_determine_type(const Type_context *)18102   do_determine_type(const Type_context*)
18103   { go_unreachable(); }
18104 
18105   Expression*
do_copy()18106   do_copy()
18107   {
18108     Interface_type* itype = this->itype_->copy_expressions()->interface_type();
18109     return new Interface_mtable_expression(itype,
18110 					   this->type_->copy_expressions(),
18111                                            this->is_pointer_, this->location());
18112   }
18113 
18114   bool
do_is_addressable() const18115   do_is_addressable() const
18116   { return true; }
18117 
18118   Bexpression*
18119   do_get_backend(Translate_context* context);
18120 
18121   void
18122   do_dump_expression(Ast_dump_context*) const;
18123 
18124  private:
18125   // The interface type for which the methods are defined.
18126   Interface_type* itype_;
18127   // The type to construct the interface method table for.
18128   Type* type_;
18129   // Whether this table contains the method set for the receiver type or the
18130   // pointer receiver type.
18131   bool is_pointer_;
18132   // The type of the method table.
18133   Type* method_table_type_;
18134   // The backend variable that refers to the interface method table.
18135   Bvariable* bvar_;
18136 };
18137 
18138 int
do_traverse(Traverse * traverse)18139 Interface_mtable_expression::do_traverse(Traverse* traverse)
18140 {
18141   if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
18142       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
18143     return TRAVERSE_EXIT;
18144   return TRAVERSE_CONTINUE;
18145 }
18146 
18147 Type*
do_type()18148 Interface_mtable_expression::do_type()
18149 {
18150   if (this->method_table_type_ != NULL)
18151     return this->method_table_type_;
18152 
18153   const Typed_identifier_list* interface_methods = this->itype_->methods();
18154   go_assert(!interface_methods->empty());
18155 
18156   Struct_field_list* sfl = new Struct_field_list;
18157   Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
18158                        this->location());
18159   sfl->push_back(Struct_field(tid));
18160   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
18161   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18162        p != interface_methods->end();
18163        ++p)
18164     {
18165       // We want C function pointers here, not func descriptors; model
18166       // using void* pointers.
18167       Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
18168       sfl->push_back(Struct_field(method));
18169     }
18170   Struct_type* st = Type::make_struct_type(sfl, this->location());
18171   st->set_is_struct_incomparable();
18172   this->method_table_type_ = st;
18173   return this->method_table_type_;
18174 }
18175 
18176 Bexpression*
do_get_backend(Translate_context * context)18177 Interface_mtable_expression::do_get_backend(Translate_context* context)
18178 {
18179   Gogo* gogo = context->gogo();
18180   Location loc = Linemap::predeclared_location();
18181   if (this->bvar_ != NULL)
18182     return gogo->backend()->var_expression(this->bvar_, this->location());
18183 
18184   const Typed_identifier_list* interface_methods = this->itype_->methods();
18185   go_assert(!interface_methods->empty());
18186 
18187   std::string mangled_name =
18188     gogo->interface_method_table_name(this->itype_, this->type_,
18189 				      this->is_pointer_);
18190 
18191   // Set is_public if we are converting a named type to an interface
18192   // type that is defined in the same package as the named type, and
18193   // the interface has hidden methods.  In that case the interface
18194   // method table will be defined by the package that defines the
18195   // types.
18196   bool is_public = false;
18197   if (this->type_->named_type() != NULL
18198       && (this->type_->named_type()->named_object()->package()
18199 	  == this->itype_->package()))
18200     {
18201       for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18202 	   p != interface_methods->end();
18203 	   ++p)
18204 	{
18205 	  if (Gogo::is_hidden_name(p->name()))
18206 	    {
18207 	      is_public = true;
18208 	      break;
18209 	    }
18210 	}
18211     }
18212 
18213   if (is_public
18214       && this->type_->named_type()->named_object()->package() != NULL)
18215     {
18216       // The interface conversion table is defined elsewhere.
18217       Btype* btype = this->type()->get_backend(gogo);
18218       std::string asm_name(go_selectively_encode_id(mangled_name));
18219       this->bvar_ =
18220           gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
18221                                                       btype, loc);
18222       return gogo->backend()->var_expression(this->bvar_, this->location());
18223     }
18224 
18225   // The first element is the type descriptor.
18226   Type* td_type;
18227   if (!this->is_pointer_)
18228     td_type = this->type_;
18229   else
18230     td_type = Type::make_pointer_type(this->type_);
18231 
18232   std::vector<Backend::Btyped_identifier> bstructfields;
18233 
18234   // Build an interface method table for a type: a type descriptor followed by a
18235   // list of function pointers, one for each interface method.  This is used for
18236   // interfaces.
18237   Expression_list* svals = new Expression_list();
18238   Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
18239   svals->push_back(tdescriptor);
18240 
18241   Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
18242   Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
18243   bstructfields.push_back(btd);
18244 
18245   Named_type* nt = this->type_->named_type();
18246   Struct_type* st = this->type_->struct_type();
18247   go_assert(nt != NULL || st != NULL);
18248 
18249   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18250        p != interface_methods->end();
18251        ++p)
18252     {
18253       bool is_ambiguous;
18254       Method* m;
18255       if (nt != NULL)
18256 	m = nt->method_function(p->name(), &is_ambiguous);
18257       else
18258 	m = st->method_function(p->name(), &is_ambiguous);
18259       go_assert(m != NULL);
18260       Named_object* no =
18261         (this->is_pointer_
18262          && this->type_->is_direct_iface_type()
18263          && m->is_value_method()
18264          ? m->iface_stub_object()
18265          : m->named_object());
18266 
18267       go_assert(no->is_function() || no->is_function_declaration());
18268 
18269       Function_type* fcn_type = (no->is_function()
18270                                  ? no->func_value()->type()
18271                                  : no->func_declaration_value()->type());
18272       Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
18273       Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
18274       bstructfields.push_back(bmtype);
18275 
18276       svals->push_back(Expression::make_func_code_reference(no, loc));
18277     }
18278 
18279   Btype *btype = gogo->backend()->struct_type(bstructfields);
18280   std::vector<Bexpression*> ctor_bexprs;
18281   for (Expression_list::const_iterator pe = svals->begin();
18282        pe != svals->end();
18283        ++pe)
18284     {
18285       ctor_bexprs.push_back((*pe)->get_backend(context));
18286     }
18287   Bexpression* ctor =
18288       gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
18289 
18290   std::string asm_name(go_selectively_encode_id(mangled_name));
18291   this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
18292 						  !is_public, btype, loc);
18293   gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
18294                                              !is_public, btype, loc, ctor);
18295   return gogo->backend()->var_expression(this->bvar_, loc);
18296 }
18297 
18298 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18299 Interface_mtable_expression::do_dump_expression(
18300     Ast_dump_context* ast_dump_context) const
18301 {
18302   ast_dump_context->ostream() << "__go_"
18303                               << (this->is_pointer_ ? "pimt__" : "imt_");
18304   ast_dump_context->dump_type(this->itype_);
18305   ast_dump_context->ostream() << "__";
18306   ast_dump_context->dump_type(this->type_);
18307 }
18308 
18309 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)18310 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
18311                                       bool is_pointer, Location location)
18312 {
18313   return new Interface_mtable_expression(itype, type, is_pointer, location);
18314 }
18315 
18316 // An expression which evaluates to the offset of a field within a
18317 // struct.  This, like Type_info_expression, q.v., is only used to
18318 // initialize fields of a type descriptor.
18319 
18320 class Struct_field_offset_expression : public Expression
18321 {
18322  public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)18323   Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
18324     : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
18325 		 Linemap::predeclared_location()),
18326       type_(type), field_(field)
18327   { }
18328 
18329  protected:
18330   bool
do_is_static_initializer() const18331   do_is_static_initializer() const
18332   { return true; }
18333 
18334   Type*
do_type()18335   do_type()
18336   { return Type::lookup_integer_type("uintptr"); }
18337 
18338   void
do_determine_type(const Type_context *)18339   do_determine_type(const Type_context*)
18340   { }
18341 
18342   Expression*
do_copy()18343   do_copy()
18344   { return this; }
18345 
18346   Bexpression*
18347   do_get_backend(Translate_context* context);
18348 
18349   void
18350   do_dump_expression(Ast_dump_context*) const;
18351 
18352  private:
18353   // The type of the struct.
18354   Struct_type* type_;
18355   // The field.
18356   const Struct_field* field_;
18357 };
18358 
18359 // Return the backend representation for a struct field offset.
18360 
18361 Bexpression*
do_get_backend(Translate_context * context)18362 Struct_field_offset_expression::do_get_backend(Translate_context* context)
18363 {
18364   const Struct_field_list* fields = this->type_->fields();
18365   Struct_field_list::const_iterator p;
18366   unsigned i = 0;
18367   for (p = fields->begin();
18368        p != fields->end();
18369        ++p, ++i)
18370     if (&*p == this->field_)
18371       break;
18372   go_assert(&*p == this->field_);
18373 
18374   Gogo* gogo = context->gogo();
18375   Btype* btype = this->type_->get_backend(gogo);
18376 
18377   int64_t offset = gogo->backend()->type_field_offset(btype, i);
18378   Type* uptr_type = Type::lookup_integer_type("uintptr");
18379   Expression* ret =
18380     Expression::make_integer_int64(offset, uptr_type,
18381 				   Linemap::predeclared_location());
18382   return ret->get_backend(context);
18383 }
18384 
18385 // Dump ast representation for a struct field offset expression.
18386 
18387 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18388 Struct_field_offset_expression::do_dump_expression(
18389     Ast_dump_context* ast_dump_context) const
18390 {
18391   ast_dump_context->ostream() <<  "unsafe.Offsetof(";
18392   ast_dump_context->dump_type(this->type_);
18393   ast_dump_context->ostream() << '.';
18394   ast_dump_context->ostream() <<
18395     Gogo::message_name(this->field_->field_name());
18396   ast_dump_context->ostream() << ")";
18397 }
18398 
18399 // Make an expression for a struct field offset.
18400 
18401 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)18402 Expression::make_struct_field_offset(Struct_type* type,
18403 				     const Struct_field* field)
18404 {
18405   return new Struct_field_offset_expression(type, field);
18406 }
18407 
18408 // An expression which evaluates to the address of an unnamed label.
18409 
18410 class Label_addr_expression : public Expression
18411 {
18412  public:
Label_addr_expression(Label * label,Location location)18413   Label_addr_expression(Label* label, Location location)
18414     : Expression(EXPRESSION_LABEL_ADDR, location),
18415       label_(label)
18416   { }
18417 
18418  protected:
18419   Type*
do_type()18420   do_type()
18421   { return Type::make_pointer_type(Type::make_void_type()); }
18422 
18423   void
do_determine_type(const Type_context *)18424   do_determine_type(const Type_context*)
18425   { }
18426 
18427   Expression*
do_copy()18428   do_copy()
18429   { return new Label_addr_expression(this->label_, this->location()); }
18430 
18431   Bexpression*
do_get_backend(Translate_context * context)18432   do_get_backend(Translate_context* context)
18433   { return this->label_->get_addr(context, this->location()); }
18434 
18435   void
do_dump_expression(Ast_dump_context * ast_dump_context) const18436   do_dump_expression(Ast_dump_context* ast_dump_context) const
18437   { ast_dump_context->ostream() << this->label_->name(); }
18438 
18439  private:
18440   // The label whose address we are taking.
18441   Label* label_;
18442 };
18443 
18444 // Make an expression for the address of an unnamed label.
18445 
18446 Expression*
make_label_addr(Label * label,Location location)18447 Expression::make_label_addr(Label* label, Location location)
18448 {
18449   return new Label_addr_expression(label, location);
18450 }
18451 
18452 // Class Conditional_expression.
18453 
18454 // Traversal.
18455 
18456 int
do_traverse(Traverse * traverse)18457 Conditional_expression::do_traverse(Traverse* traverse)
18458 {
18459   if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
18460       || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
18461       || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
18462     return TRAVERSE_EXIT;
18463   return TRAVERSE_CONTINUE;
18464 }
18465 
18466 // Return the type of the conditional expression.
18467 
18468 Type*
do_type()18469 Conditional_expression::do_type()
18470 {
18471   Type* result_type = Type::make_void_type();
18472   if (Type::are_identical(this->then_->type(), this->else_->type(),
18473 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
18474                           NULL))
18475     result_type = this->then_->type();
18476   else if (this->then_->is_nil_expression()
18477            || this->else_->is_nil_expression())
18478     result_type = (!this->then_->is_nil_expression()
18479                    ? this->then_->type()
18480                    : this->else_->type());
18481   return result_type;
18482 }
18483 
18484 // Determine type for a conditional expression.
18485 
18486 void
do_determine_type(const Type_context * context)18487 Conditional_expression::do_determine_type(const Type_context* context)
18488 {
18489   this->cond_->determine_type_no_context();
18490   this->then_->determine_type(context);
18491   this->else_->determine_type(context);
18492 }
18493 
18494 // Get the backend representation of a conditional expression.
18495 
18496 Bexpression*
do_get_backend(Translate_context * context)18497 Conditional_expression::do_get_backend(Translate_context* context)
18498 {
18499   Gogo* gogo = context->gogo();
18500   Btype* result_btype = this->type()->get_backend(gogo);
18501   Bexpression* cond = this->cond_->get_backend(context);
18502   Bexpression* then = this->then_->get_backend(context);
18503   Bexpression* belse = this->else_->get_backend(context);
18504   Bfunction* bfn = context->function()->func_value()->get_decl();
18505   return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
18506 						 belse, this->location());
18507 }
18508 
18509 // Dump ast representation of a conditional expression.
18510 
18511 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18512 Conditional_expression::do_dump_expression(
18513     Ast_dump_context* ast_dump_context) const
18514 {
18515   ast_dump_context->ostream() << "(";
18516   ast_dump_context->dump_expression(this->cond_);
18517   ast_dump_context->ostream() << " ? ";
18518   ast_dump_context->dump_expression(this->then_);
18519   ast_dump_context->ostream() << " : ";
18520   ast_dump_context->dump_expression(this->else_);
18521   ast_dump_context->ostream() << ") ";
18522 }
18523 
18524 // Make a conditional expression.
18525 
18526 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)18527 Expression::make_conditional(Expression* cond, Expression* then,
18528                              Expression* else_expr, Location location)
18529 {
18530   return new Conditional_expression(cond, then, else_expr, location);
18531 }
18532 
18533 // Class Compound_expression.
18534 
18535 // Traversal.
18536 
18537 int
do_traverse(Traverse * traverse)18538 Compound_expression::do_traverse(Traverse* traverse)
18539 {
18540   if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
18541       || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
18542     return TRAVERSE_EXIT;
18543   return TRAVERSE_CONTINUE;
18544 }
18545 
18546 // Return the type of the compound expression.
18547 
18548 Type*
do_type()18549 Compound_expression::do_type()
18550 {
18551   return this->expr_->type();
18552 }
18553 
18554 // Determine type for a compound expression.
18555 
18556 void
do_determine_type(const Type_context * context)18557 Compound_expression::do_determine_type(const Type_context* context)
18558 {
18559   this->init_->determine_type_no_context();
18560   this->expr_->determine_type(context);
18561 }
18562 
18563 // Get the backend representation of a compound expression.
18564 
18565 Bexpression*
do_get_backend(Translate_context * context)18566 Compound_expression::do_get_backend(Translate_context* context)
18567 {
18568   Gogo* gogo = context->gogo();
18569   Bexpression* binit = this->init_->get_backend(context);
18570   Bfunction* bfunction = context->function()->func_value()->get_decl();
18571   Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
18572                                                                 binit);
18573   Bexpression* bexpr = this->expr_->get_backend(context);
18574   return gogo->backend()->compound_expression(init_stmt, bexpr,
18575 					      this->location());
18576 }
18577 
18578 // Dump ast representation of a conditional expression.
18579 
18580 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18581 Compound_expression::do_dump_expression(
18582     Ast_dump_context* ast_dump_context) const
18583 {
18584   ast_dump_context->ostream() << "(";
18585   ast_dump_context->dump_expression(this->init_);
18586   ast_dump_context->ostream() << ",";
18587   ast_dump_context->dump_expression(this->expr_);
18588   ast_dump_context->ostream() << ") ";
18589 }
18590 
18591 // Make a compound expression.
18592 
18593 Expression*
make_compound(Expression * init,Expression * expr,Location location)18594 Expression::make_compound(Expression* init, Expression* expr, Location location)
18595 {
18596   return new Compound_expression(init, expr, location);
18597 }
18598 
18599 // Class Backend_expression.
18600 
18601 int
do_traverse(Traverse *)18602 Backend_expression::do_traverse(Traverse*)
18603 {
18604   return TRAVERSE_CONTINUE;
18605 }
18606 
18607 Expression*
do_copy()18608 Backend_expression::do_copy()
18609 {
18610   return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
18611 				this->location());
18612 }
18613 
18614 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18615 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
18616 {
18617   ast_dump_context->ostream() << "backend_expression<";
18618   ast_dump_context->dump_type(this->type_);
18619   ast_dump_context->ostream() << ">";
18620 }
18621 
18622 Expression*
make_backend(Bexpression * bexpr,Type * type,Location location)18623 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
18624 {
18625   return new Backend_expression(bexpr, type, location);
18626 }
18627 
18628 // Import an expression.  This comes at the end in order to see the
18629 // various class definitions.
18630 
18631 Expression*
import_expression(Import_expression * imp,Location loc)18632 Expression::import_expression(Import_expression* imp, Location loc)
18633 {
18634   Expression* expr = Expression::import_expression_without_suffix(imp, loc);
18635   while (true)
18636     {
18637       if (imp->match_c_string("("))
18638 	{
18639 	  imp->advance(1);
18640 	  Expression_list* args = new Expression_list();
18641 	  bool is_varargs = false;
18642 	  while (!imp->match_c_string(")"))
18643 	    {
18644 	      Expression* arg = Expression::import_expression(imp, loc);
18645 	      if (arg->is_error_expression())
18646 		return arg;
18647 	      args->push_back(arg);
18648 	      if (imp->match_c_string(")"))
18649 		break;
18650 	      else if (imp->match_c_string("...)"))
18651 		{
18652 		  imp->advance(3);
18653 		  is_varargs = true;
18654 		  break;
18655 		}
18656 	      imp->require_c_string(", ");
18657 	    }
18658 	  imp->require_c_string(")");
18659 	  expr = Expression::make_call(expr, args, is_varargs, loc);
18660           expr->call_expression()->set_varargs_are_lowered();
18661 	}
18662       else if (imp->match_c_string("["))
18663 	{
18664 	  imp->advance(1);
18665 	  Expression* start = Expression::import_expression(imp, loc);
18666 	  Expression* end = NULL;
18667 	  Expression* cap = NULL;
18668 	  if (imp->match_c_string(":"))
18669 	    {
18670 	      imp->advance(1);
18671 	      int c = imp->peek_char();
18672 	      if (c == ':' || c == ']')
18673 		end = Expression::make_nil(loc);
18674 	      else
18675 		end = Expression::import_expression(imp, loc);
18676 	      if (imp->match_c_string(":"))
18677 		{
18678 		  imp->advance(1);
18679 		  cap = Expression::import_expression(imp, loc);
18680 		}
18681 	    }
18682 	  imp->require_c_string("]");
18683 	  expr = Expression::make_index(expr, start, end, cap, loc);
18684 	}
18685       else
18686 	break;
18687     }
18688 
18689   return expr;
18690 }
18691 
18692 // Import an expression without considering a suffix (function
18693 // arguments, index operations, etc.).
18694 
18695 Expression*
import_expression_without_suffix(Import_expression * imp,Location loc)18696 Expression::import_expression_without_suffix(Import_expression* imp,
18697 					     Location loc)
18698 {
18699   int c = imp->peek_char();
18700   if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
18701     return Unary_expression::do_import(imp, loc);
18702   else if (c == '(')
18703     return Binary_expression::do_import(imp, loc);
18704   else if (imp->match_c_string("$true")
18705 	   || imp->match_c_string("$false")
18706 	   || (imp->version() < EXPORT_FORMAT_V3
18707 	       && (imp->match_c_string("true")
18708 		   || imp->match_c_string("false"))))
18709     return Boolean_expression::do_import(imp, loc);
18710   else if (c == '"')
18711     return String_expression::do_import(imp, loc);
18712   else if (c == '-' || (c >= '0' && c <= '9'))
18713     {
18714       // This handles integers, floats and complex constants.
18715       return Integer_expression::do_import(imp, loc);
18716     }
18717   else if (imp->match_c_string("<-"))
18718     return Receive_expression::do_import(imp, loc);
18719   else if (imp->match_c_string("$nil")
18720 	   || (imp->version() < EXPORT_FORMAT_V3
18721 	       && imp->match_c_string("nil")))
18722     return Nil_expression::do_import(imp, loc);
18723   else if (imp->match_c_string("$convert")
18724 	   || (imp->version() < EXPORT_FORMAT_V3
18725 	       && imp->match_c_string("convert")))
18726     return Type_conversion_expression::do_import(imp, loc);
18727 
18728   Import_function_body* ifb = imp->ifb();
18729   if (ifb == NULL)
18730     {
18731       go_error_at(imp->location(), "import error: expected expression");
18732       return Expression::make_error(loc);
18733     }
18734   if (ifb->saw_error())
18735     return Expression::make_error(loc);
18736 
18737   if (ifb->match_c_string("$t"))
18738     return Temporary_reference_expression::do_import(ifb, loc);
18739 
18740   return Expression::import_identifier(ifb, loc);
18741 }
18742 
18743 // Import an identifier in an expression.  This is a reference to a
18744 // variable or function.
18745 
18746 Expression*
import_identifier(Import_function_body * ifb,Location loc)18747 Expression::import_identifier(Import_function_body* ifb, Location loc)
18748 {
18749   std::string id;
18750   Package* pkg;
18751   bool is_exported;
18752   if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
18753     {
18754       if (!ifb->saw_error())
18755 	go_error_at(ifb->location(),
18756 		    "import error for %qs: bad qualified identifier at %lu",
18757 		    ifb->name().c_str(),
18758 		    static_cast<unsigned long>(ifb->off()));
18759       ifb->set_saw_error();
18760       return Expression::make_error(loc);
18761     }
18762 
18763   Named_object* no = NULL;
18764   if (pkg == NULL && is_exported)
18765     no = ifb->block()->bindings()->lookup(id);
18766   if (no == NULL)
18767     {
18768       const Package* ipkg = pkg;
18769       if (ipkg == NULL)
18770 	ipkg = ifb->function()->package();
18771       if (!is_exported)
18772 	id = '.' + ipkg->pkgpath() + '.' + id;
18773       no = ipkg->bindings()->lookup(id);
18774     }
18775   if (no == NULL)
18776     no = ifb->gogo()->lookup_global(id.c_str());
18777 
18778   if (no == NULL)
18779     {
18780       if (!ifb->saw_error())
18781 	go_error_at(ifb->location(),
18782 		    "import error for %qs: lookup of %qs failed",
18783 		    ifb->name().c_str(), id.c_str());
18784       ifb->set_saw_error();
18785       return Expression::make_error(loc);
18786     }
18787 
18788   if (no->is_variable() || no->is_result_variable())
18789     return Expression::make_var_reference(no, loc);
18790   else if (no->is_function() || no->is_function_declaration())
18791     return Expression::make_func_reference(no, NULL, loc);
18792   else
18793     {
18794       if (!ifb->saw_error())
18795 	go_error_at(ifb->location(),
18796 		    ("import error for %qs: "
18797 		     "unexpected type of identifier %qs (%d)"),
18798 		    ifb->name().c_str(),
18799 		    id.c_str(), no->classification());
18800       ifb->set_saw_error();
18801       return Expression::make_error(loc);
18802     }
18803 }
18804 
18805 // Class Expression_list.
18806 
18807 // Traverse the list.
18808 
18809 int
traverse(Traverse * traverse)18810 Expression_list::traverse(Traverse* traverse)
18811 {
18812   for (Expression_list::iterator p = this->begin();
18813        p != this->end();
18814        ++p)
18815     {
18816       if (*p != NULL)
18817 	{
18818 	  if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
18819 	    return TRAVERSE_EXIT;
18820 	}
18821     }
18822   return TRAVERSE_CONTINUE;
18823 }
18824 
18825 // Copy the list.
18826 
18827 Expression_list*
copy()18828 Expression_list::copy()
18829 {
18830   Expression_list* ret = new Expression_list();
18831   for (Expression_list::iterator p = this->begin();
18832        p != this->end();
18833        ++p)
18834     {
18835       if (*p == NULL)
18836 	ret->push_back(NULL);
18837       else
18838 	ret->push_back((*p)->copy());
18839     }
18840   return ret;
18841 }
18842 
18843 // Return whether an expression list has an error expression.
18844 
18845 bool
contains_error() const18846 Expression_list::contains_error() const
18847 {
18848   for (Expression_list::const_iterator p = this->begin();
18849        p != this->end();
18850        ++p)
18851     if (*p != NULL && (*p)->is_error_expression())
18852       return true;
18853   return false;
18854 }
18855 
18856 // Class Numeric_constant.
18857 
18858 // Destructor.
18859 
~Numeric_constant()18860 Numeric_constant::~Numeric_constant()
18861 {
18862   this->clear();
18863 }
18864 
18865 // Copy constructor.
18866 
Numeric_constant(const Numeric_constant & a)18867 Numeric_constant::Numeric_constant(const Numeric_constant& a)
18868   : classification_(a.classification_), type_(a.type_)
18869 {
18870   switch (a.classification_)
18871     {
18872     case NC_INVALID:
18873       break;
18874     case NC_INT:
18875     case NC_RUNE:
18876       mpz_init_set(this->u_.int_val, a.u_.int_val);
18877       break;
18878     case NC_FLOAT:
18879       mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
18880       break;
18881     case NC_COMPLEX:
18882       mpc_init2(this->u_.complex_val, mpc_precision);
18883       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
18884       break;
18885     default:
18886       go_unreachable();
18887     }
18888 }
18889 
18890 // Assignment operator.
18891 
18892 Numeric_constant&
operator =(const Numeric_constant & a)18893 Numeric_constant::operator=(const Numeric_constant& a)
18894 {
18895   this->clear();
18896   this->classification_ = a.classification_;
18897   this->type_ = a.type_;
18898   switch (a.classification_)
18899     {
18900     case NC_INVALID:
18901       break;
18902     case NC_INT:
18903     case NC_RUNE:
18904       mpz_init_set(this->u_.int_val, a.u_.int_val);
18905       break;
18906     case NC_FLOAT:
18907       mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
18908       break;
18909     case NC_COMPLEX:
18910       mpc_init2(this->u_.complex_val, mpc_precision);
18911       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
18912       break;
18913     default:
18914       go_unreachable();
18915     }
18916   return *this;
18917 }
18918 
18919 // Check equality with another numeric constant.
18920 
18921 bool
equals(const Numeric_constant & a) const18922 Numeric_constant::equals(const Numeric_constant& a) const
18923 {
18924   if (this->classification_ != a.classification_)
18925     return false;
18926 
18927   if (this->type_ != NULL && a.type_ != NULL
18928       && !Type::are_identical(this->type_, a.type_,
18929 			      Type::COMPARE_ALIASES, NULL))
18930     return false;
18931 
18932   switch (a.classification_)
18933     {
18934     case NC_INVALID:
18935       break;
18936     case NC_INT:
18937     case NC_RUNE:
18938       return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
18939     case NC_FLOAT:
18940       return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
18941     case NC_COMPLEX:
18942       return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
18943     default:
18944       go_unreachable();
18945     }
18946   return false;
18947 }
18948 
18949 // Clear the contents.
18950 
18951 void
clear()18952 Numeric_constant::clear()
18953 {
18954   switch (this->classification_)
18955     {
18956     case NC_INVALID:
18957       break;
18958     case NC_INT:
18959     case NC_RUNE:
18960       mpz_clear(this->u_.int_val);
18961       break;
18962     case NC_FLOAT:
18963       mpfr_clear(this->u_.float_val);
18964       break;
18965     case NC_COMPLEX:
18966       mpc_clear(this->u_.complex_val);
18967       break;
18968     default:
18969       go_unreachable();
18970     }
18971   this->classification_ = NC_INVALID;
18972 }
18973 
18974 // Set to an unsigned long value.
18975 
18976 void
set_unsigned_long(Type * type,unsigned long val)18977 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
18978 {
18979   this->clear();
18980   this->classification_ = NC_INT;
18981   this->type_ = type;
18982   mpz_init_set_ui(this->u_.int_val, val);
18983 }
18984 
18985 // Set to an integer value.
18986 
18987 void
set_int(Type * type,const mpz_t val)18988 Numeric_constant::set_int(Type* type, const mpz_t val)
18989 {
18990   this->clear();
18991   this->classification_ = NC_INT;
18992   this->type_ = type;
18993   mpz_init_set(this->u_.int_val, val);
18994 }
18995 
18996 // Set to a rune value.
18997 
18998 void
set_rune(Type * type,const mpz_t val)18999 Numeric_constant::set_rune(Type* type, const mpz_t val)
19000 {
19001   this->clear();
19002   this->classification_ = NC_RUNE;
19003   this->type_ = type;
19004   mpz_init_set(this->u_.int_val, val);
19005 }
19006 
19007 // Set to a floating point value.
19008 
19009 void
set_float(Type * type,const mpfr_t val)19010 Numeric_constant::set_float(Type* type, const mpfr_t val)
19011 {
19012   this->clear();
19013   this->classification_ = NC_FLOAT;
19014   this->type_ = type;
19015 
19016   // Numeric constants do not have negative zero values, so remove
19017   // them here.  They also don't have infinity or NaN values, but we
19018   // should never see them here.
19019   int bits = 0;
19020   if (type != NULL
19021       && type->float_type() != NULL
19022       && !type->float_type()->is_abstract())
19023     bits = type->float_type()->bits();
19024   if (Numeric_constant::is_float_neg_zero(val, bits))
19025     mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
19026   else
19027     mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
19028 }
19029 
19030 // Set to a complex value.
19031 
19032 void
set_complex(Type * type,const mpc_t val)19033 Numeric_constant::set_complex(Type* type, const mpc_t val)
19034 {
19035   this->clear();
19036   this->classification_ = NC_COMPLEX;
19037   this->type_ = type;
19038 
19039   // Avoid negative zero as in set_float.
19040   int bits = 0;
19041   if (type != NULL
19042       && type->complex_type() != NULL
19043       && !type->complex_type()->is_abstract())
19044     bits = type->complex_type()->bits() / 2;
19045 
19046   mpfr_t real;
19047   mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
19048   if (Numeric_constant::is_float_neg_zero(real, bits))
19049     mpfr_set_ui(real, 0, MPFR_RNDN);
19050 
19051   mpfr_t imag;
19052   mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
19053   if (Numeric_constant::is_float_neg_zero(imag, bits))
19054     mpfr_set_ui(imag, 0, MPFR_RNDN);
19055 
19056   mpc_init2(this->u_.complex_val, mpc_precision);
19057   mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
19058 
19059   mpfr_clear(real);
19060   mpfr_clear(imag);
19061 }
19062 
19063 // Return whether VAL, at a precision of BITS, is a negative zero.
19064 // BITS may be zero in which case it is ignored.
19065 
19066 bool
is_float_neg_zero(const mpfr_t val,int bits)19067 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
19068 {
19069   if (!mpfr_signbit(val))
19070     return false;
19071   if (mpfr_zero_p(val))
19072     return true;
19073   mpfr_exp_t min_exp;
19074   switch (bits)
19075     {
19076     case 0:
19077       return false;
19078     case 32:
19079       // In a denormalized float32 the exponent is -126, and there are
19080       // 24 bits of which at least the last must be 1, so the smallest
19081       // representable non-zero exponent is -126 - (24 - 1) == -149.
19082       min_exp = -149;
19083       break;
19084     case 64:
19085       // Minimum exponent is -1022, there are 53 bits.
19086       min_exp = -1074;
19087       break;
19088     default:
19089       go_unreachable();
19090     }
19091   return mpfr_get_exp(val) < min_exp;
19092 }
19093 
19094 // Get an int value.
19095 
19096 void
get_int(mpz_t * val) const19097 Numeric_constant::get_int(mpz_t* val) const
19098 {
19099   go_assert(this->is_int());
19100   mpz_init_set(*val, this->u_.int_val);
19101 }
19102 
19103 // Get a rune value.
19104 
19105 void
get_rune(mpz_t * val) const19106 Numeric_constant::get_rune(mpz_t* val) const
19107 {
19108   go_assert(this->is_rune());
19109   mpz_init_set(*val, this->u_.int_val);
19110 }
19111 
19112 // Get a floating point value.
19113 
19114 void
get_float(mpfr_t * val) const19115 Numeric_constant::get_float(mpfr_t* val) const
19116 {
19117   go_assert(this->is_float());
19118   mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19119 }
19120 
19121 // Get a complex value.
19122 
19123 void
get_complex(mpc_t * val) const19124 Numeric_constant::get_complex(mpc_t* val) const
19125 {
19126   go_assert(this->is_complex());
19127   mpc_init2(*val, mpc_precision);
19128   mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19129 }
19130 
19131 // Express value as unsigned long if possible.
19132 
19133 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const19134 Numeric_constant::to_unsigned_long(unsigned long* val) const
19135 {
19136   switch (this->classification_)
19137     {
19138     case NC_INT:
19139     case NC_RUNE:
19140       return this->mpz_to_unsigned_long(this->u_.int_val, val);
19141     case NC_FLOAT:
19142       return this->mpfr_to_unsigned_long(this->u_.float_val, val);
19143     case NC_COMPLEX:
19144       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19145 	return NC_UL_NOTINT;
19146       return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
19147 					 val);
19148     default:
19149       go_unreachable();
19150     }
19151 }
19152 
19153 // Express integer value as unsigned long if possible.
19154 
19155 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const19156 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
19157 				       unsigned long *val) const
19158 {
19159   if (mpz_sgn(ival) < 0)
19160     return NC_UL_NEGATIVE;
19161   unsigned long ui = mpz_get_ui(ival);
19162   if (mpz_cmp_ui(ival, ui) != 0)
19163     return NC_UL_BIG;
19164   *val = ui;
19165   return NC_UL_VALID;
19166 }
19167 
19168 // Express floating point value as unsigned long if possible.
19169 
19170 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const19171 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
19172 					unsigned long *val) const
19173 {
19174   if (!mpfr_integer_p(fval))
19175     return NC_UL_NOTINT;
19176   mpz_t ival;
19177   mpz_init(ival);
19178   mpfr_get_z(ival, fval, MPFR_RNDN);
19179   To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
19180   mpz_clear(ival);
19181   return ret;
19182 }
19183 
19184 // Express value as memory size if possible.
19185 
19186 bool
to_memory_size(int64_t * val) const19187 Numeric_constant::to_memory_size(int64_t* val) const
19188 {
19189   switch (this->classification_)
19190     {
19191     case NC_INT:
19192     case NC_RUNE:
19193       return this->mpz_to_memory_size(this->u_.int_val, val);
19194     case NC_FLOAT:
19195       return this->mpfr_to_memory_size(this->u_.float_val, val);
19196     case NC_COMPLEX:
19197       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19198 	return false;
19199       return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
19200     default:
19201       go_unreachable();
19202     }
19203 }
19204 
19205 // Express integer as memory size if possible.
19206 
19207 bool
mpz_to_memory_size(const mpz_t ival,int64_t * val) const19208 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
19209 {
19210   if (mpz_sgn(ival) < 0)
19211     return false;
19212   if (mpz_fits_slong_p(ival))
19213     {
19214       *val = static_cast<int64_t>(mpz_get_si(ival));
19215       return true;
19216     }
19217 
19218   // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
19219   // positive value.
19220   if (mpz_sizeinbase(ival, 2) >= 64)
19221     return false;
19222 
19223   mpz_t q, r;
19224   mpz_init(q);
19225   mpz_init(r);
19226   mpz_tdiv_q_2exp(q, ival, 32);
19227   mpz_tdiv_r_2exp(r, ival, 32);
19228   go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
19229   *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
19230 	  + static_cast<int64_t>(mpz_get_ui(r)));
19231   mpz_clear(r);
19232   mpz_clear(q);
19233   return true;
19234 }
19235 
19236 // Express floating point value as memory size if possible.
19237 
19238 bool
mpfr_to_memory_size(const mpfr_t fval,int64_t * val) const19239 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
19240 {
19241   if (!mpfr_integer_p(fval))
19242     return false;
19243   mpz_t ival;
19244   mpz_init(ival);
19245   mpfr_get_z(ival, fval, MPFR_RNDN);
19246   bool ret = this->mpz_to_memory_size(ival, val);
19247   mpz_clear(ival);
19248   return ret;
19249 }
19250 
19251 // Convert value to integer if possible.
19252 
19253 bool
to_int(mpz_t * val) const19254 Numeric_constant::to_int(mpz_t* val) const
19255 {
19256   switch (this->classification_)
19257     {
19258     case NC_INT:
19259     case NC_RUNE:
19260       mpz_init_set(*val, this->u_.int_val);
19261       return true;
19262     case NC_FLOAT:
19263       if (!mpfr_integer_p(this->u_.float_val))
19264 	return false;
19265       mpz_init(*val);
19266       mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
19267       return true;
19268     case NC_COMPLEX:
19269       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
19270 	  || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
19271 	return false;
19272       mpz_init(*val);
19273       mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19274       return true;
19275     default:
19276       go_unreachable();
19277     }
19278 }
19279 
19280 // Convert value to floating point if possible.
19281 
19282 bool
to_float(mpfr_t * val) const19283 Numeric_constant::to_float(mpfr_t* val) const
19284 {
19285   switch (this->classification_)
19286     {
19287     case NC_INT:
19288     case NC_RUNE:
19289       mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
19290       return true;
19291     case NC_FLOAT:
19292       mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19293       return true;
19294     case NC_COMPLEX:
19295       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19296 	return false;
19297       mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19298       return true;
19299     default:
19300       go_unreachable();
19301     }
19302 }
19303 
19304 // Convert value to complex.
19305 
19306 bool
to_complex(mpc_t * val) const19307 Numeric_constant::to_complex(mpc_t* val) const
19308 {
19309   mpc_init2(*val, mpc_precision);
19310   switch (this->classification_)
19311     {
19312     case NC_INT:
19313     case NC_RUNE:
19314       mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
19315       return true;
19316     case NC_FLOAT:
19317       mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
19318       return true;
19319     case NC_COMPLEX:
19320       mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19321       return true;
19322     default:
19323       go_unreachable();
19324     }
19325 }
19326 
19327 // Get the type.
19328 
19329 Type*
type() const19330 Numeric_constant::type() const
19331 {
19332   if (this->type_ != NULL)
19333     return this->type_;
19334   switch (this->classification_)
19335     {
19336     case NC_INT:
19337       return Type::make_abstract_integer_type();
19338     case NC_RUNE:
19339       return Type::make_abstract_character_type();
19340     case NC_FLOAT:
19341       return Type::make_abstract_float_type();
19342     case NC_COMPLEX:
19343       return Type::make_abstract_complex_type();
19344     default:
19345       go_unreachable();
19346     }
19347 }
19348 
19349 // If the constant can be expressed in TYPE, then set the type of the
19350 // constant to TYPE and return true.  Otherwise return false, and, if
19351 // ISSUE_ERROR is true, report an appropriate error message.
19352 
19353 bool
set_type(Type * type,bool issue_error,Location loc)19354 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
19355 {
19356   bool ret;
19357   if (type == NULL || type->is_error())
19358     ret = true;
19359   else if (type->integer_type() != NULL)
19360     ret = this->check_int_type(type->integer_type(), issue_error, loc);
19361   else if (type->float_type() != NULL)
19362     ret = this->check_float_type(type->float_type(), issue_error, loc);
19363   else if (type->complex_type() != NULL)
19364     ret = this->check_complex_type(type->complex_type(), issue_error, loc);
19365   else
19366     {
19367       ret = false;
19368       if (issue_error)
19369         go_assert(saw_errors());
19370     }
19371   if (ret)
19372     this->type_ = type;
19373   return ret;
19374 }
19375 
19376 // Check whether the constant can be expressed in an integer type.
19377 
19378 bool
check_int_type(Integer_type * type,bool issue_error,Location location)19379 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
19380 				 Location location)
19381 {
19382   mpz_t val;
19383   switch (this->classification_)
19384     {
19385     case NC_INT:
19386     case NC_RUNE:
19387       mpz_init_set(val, this->u_.int_val);
19388       break;
19389 
19390     case NC_FLOAT:
19391       if (!mpfr_integer_p(this->u_.float_val))
19392 	{
19393 	  if (issue_error)
19394             {
19395               go_error_at(location,
19396                           "floating-point constant truncated to integer");
19397               this->set_invalid();
19398             }
19399 	  return false;
19400 	}
19401       mpz_init(val);
19402       mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
19403       break;
19404 
19405     case NC_COMPLEX:
19406       if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
19407 	  || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19408 	{
19409 	  if (issue_error)
19410             {
19411               go_error_at(location, "complex constant truncated to integer");
19412               this->set_invalid();
19413             }
19414 	  return false;
19415 	}
19416       mpz_init(val);
19417       mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19418       break;
19419 
19420     default:
19421       go_unreachable();
19422     }
19423 
19424   bool ret;
19425   if (type->is_abstract())
19426     ret = true;
19427   else
19428     {
19429       int bits = mpz_sizeinbase(val, 2);
19430       if (type->is_unsigned())
19431 	{
19432 	  // For an unsigned type we can only accept a nonnegative
19433 	  // number, and we must be able to represents at least BITS.
19434 	  ret = mpz_sgn(val) >= 0 && bits <= type->bits();
19435 	}
19436       else
19437 	{
19438 	  // For a signed type we need an extra bit to indicate the
19439 	  // sign.  We have to handle the most negative integer
19440 	  // specially.
19441 	  ret = (bits + 1 <= type->bits()
19442 		 || (bits <= type->bits()
19443 		     && mpz_sgn(val) < 0
19444 		     && (mpz_scan1(val, 0)
19445 			 == static_cast<unsigned long>(type->bits() - 1))
19446 		     && mpz_scan0(val, type->bits()) == ULONG_MAX));
19447 	}
19448     }
19449 
19450   if (!ret && issue_error)
19451     {
19452       go_error_at(location, "integer constant overflow");
19453       this->set_invalid();
19454     }
19455 
19456   return ret;
19457 }
19458 
19459 // Check whether the constant can be expressed in a floating point
19460 // type.
19461 
19462 bool
check_float_type(Float_type * type,bool issue_error,Location location)19463 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
19464 				   Location location)
19465 {
19466   mpfr_t val;
19467   switch (this->classification_)
19468     {
19469     case NC_INT:
19470     case NC_RUNE:
19471       mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
19472       break;
19473 
19474     case NC_FLOAT:
19475       mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
19476       break;
19477 
19478     case NC_COMPLEX:
19479       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19480 	{
19481 	  if (issue_error)
19482             {
19483               this->set_invalid();
19484               go_error_at(location,
19485 			  "complex constant truncated to floating-point");
19486             }
19487 	  return false;
19488 	}
19489       mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19490       break;
19491 
19492     default:
19493       go_unreachable();
19494     }
19495 
19496   bool ret;
19497   if (type->is_abstract())
19498     ret = true;
19499   else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
19500     {
19501       // A NaN or Infinity always fits in the range of the type.
19502       ret = true;
19503     }
19504   else
19505     {
19506       mpfr_exp_t exp = mpfr_get_exp(val);
19507       mpfr_exp_t max_exp;
19508       switch (type->bits())
19509 	{
19510 	case 32:
19511 	  max_exp = 128;
19512 	  break;
19513 	case 64:
19514 	  max_exp = 1024;
19515 	  break;
19516 	default:
19517 	  go_unreachable();
19518 	}
19519 
19520       ret = exp <= max_exp;
19521 
19522       if (ret)
19523 	{
19524 	  // Round the constant to the desired type.
19525 	  mpfr_t t;
19526 	  mpfr_init(t);
19527 	  switch (type->bits())
19528 	    {
19529 	    case 32:
19530 	      mpfr_set_prec(t, 24);
19531 	      break;
19532 	    case 64:
19533 	      mpfr_set_prec(t, 53);
19534 	      break;
19535 	    default:
19536 	      go_unreachable();
19537 	    }
19538 	  mpfr_set(t, val, MPFR_RNDN);
19539 	  mpfr_set(val, t, MPFR_RNDN);
19540 	  mpfr_clear(t);
19541 
19542 	  this->set_float(type, val);
19543 	}
19544     }
19545 
19546   mpfr_clear(val);
19547 
19548   if (!ret && issue_error)
19549     {
19550       go_error_at(location, "floating-point constant overflow");
19551       this->set_invalid();
19552     }
19553 
19554   return ret;
19555 }
19556 
19557 // Check whether the constant can be expressed in a complex type.
19558 
19559 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)19560 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
19561 				     Location location)
19562 {
19563   if (type->is_abstract())
19564     return true;
19565 
19566   mpfr_exp_t max_exp;
19567   switch (type->bits())
19568     {
19569     case 64:
19570       max_exp = 128;
19571       break;
19572     case 128:
19573       max_exp = 1024;
19574       break;
19575     default:
19576       go_unreachable();
19577     }
19578 
19579   mpc_t val;
19580   mpc_init2(val, mpc_precision);
19581   switch (this->classification_)
19582     {
19583     case NC_INT:
19584     case NC_RUNE:
19585       mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
19586       break;
19587 
19588     case NC_FLOAT:
19589       mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
19590       break;
19591 
19592     case NC_COMPLEX:
19593       mpc_set(val, this->u_.complex_val, MPC_RNDNN);
19594       break;
19595 
19596     default:
19597       go_unreachable();
19598     }
19599 
19600   bool ret = true;
19601   if (!mpfr_nan_p(mpc_realref(val))
19602       && !mpfr_inf_p(mpc_realref(val))
19603       && !mpfr_zero_p(mpc_realref(val))
19604       && mpfr_get_exp(mpc_realref(val)) > max_exp)
19605     {
19606       if (issue_error)
19607         {
19608           go_error_at(location, "complex real part overflow");
19609           this->set_invalid();
19610         }
19611       ret = false;
19612     }
19613 
19614   if (!mpfr_nan_p(mpc_imagref(val))
19615       && !mpfr_inf_p(mpc_imagref(val))
19616       && !mpfr_zero_p(mpc_imagref(val))
19617       && mpfr_get_exp(mpc_imagref(val)) > max_exp)
19618     {
19619       if (issue_error)
19620         {
19621           go_error_at(location, "complex imaginary part overflow");
19622           this->set_invalid();
19623         }
19624       ret = false;
19625     }
19626 
19627   if (ret)
19628     {
19629       // Round the constant to the desired type.
19630       mpc_t t;
19631       switch (type->bits())
19632 	{
19633 	case 64:
19634 	  mpc_init2(t, 24);
19635 	  break;
19636 	case 128:
19637 	  mpc_init2(t, 53);
19638 	  break;
19639 	default:
19640 	  go_unreachable();
19641 	}
19642       mpc_set(t, val, MPC_RNDNN);
19643       mpc_set(val, t, MPC_RNDNN);
19644       mpc_clear(t);
19645 
19646       this->set_complex(type, val);
19647     }
19648 
19649   mpc_clear(val);
19650 
19651   return ret;
19652 }
19653 
19654 // Return an Expression for this value.
19655 
19656 Expression*
expression(Location loc) const19657 Numeric_constant::expression(Location loc) const
19658 {
19659   switch (this->classification_)
19660     {
19661     case NC_INT:
19662       return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
19663     case NC_RUNE:
19664       return Expression::make_character(&this->u_.int_val, this->type_, loc);
19665     case NC_FLOAT:
19666       return Expression::make_float(&this->u_.float_val, this->type_, loc);
19667     case NC_COMPLEX:
19668       return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
19669     case NC_INVALID:
19670       go_assert(saw_errors());
19671       return Expression::make_error(loc);
19672     default:
19673       go_unreachable();
19674     }
19675 }
19676 
19677 // Calculate a hash code with a given seed.
19678 
19679 unsigned int
hash(unsigned int seed) const19680 Numeric_constant::hash(unsigned int seed) const
19681 {
19682   unsigned long val;
19683   const unsigned int PRIME = 97;
19684   long e = 0;
19685   double f = 1.0;
19686   mpfr_t m;
19687 
19688   switch (this->classification_)
19689     {
19690     case NC_INVALID:
19691       return PRIME;
19692     case NC_INT:
19693     case NC_RUNE:
19694       val = mpz_get_ui(this->u_.int_val);
19695       break;
19696     case NC_COMPLEX:
19697       mpfr_init(m);
19698       mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
19699       val = mpfr_get_ui(m, MPFR_RNDN);
19700       mpfr_clear(m);
19701       break;
19702     case NC_FLOAT:
19703       f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
19704       val = static_cast<unsigned long>(e + static_cast<long>(f));
19705       break;
19706     default:
19707       go_unreachable();
19708     }
19709 
19710   return (static_cast<unsigned int>(val) + seed) * PRIME;
19711 }
19712