github.com/kidsbmilk/gofrontend_all@v0.0.0-20220701224323-6479d5976c5d/go/types.cc (about)

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