mangle.c revision 117395
1/* Name mangling for the 3.0 C++ ABI.
2   Copyright (C) 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3   Written by Alex Samuel <sameul@codesourcery.com>
4
5   This file is part of GNU CC.
6
7   GNU CC is free software; you can redistribute it and/or modify it
8   under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2, or (at your option)
10   any later version.
11
12   GNU CC is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with GNU CC; see the file COPYING.  If not, write to the Free
19   Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20   02111-1307, USA.  */
21
22/* This file implements mangling of C++ names according to the IA64
23   C++ ABI specification.  A mangled name encodes a function or
24   variable's name, scope, type, and/or template arguments into a text
25   identifier.  This identifier is used as the function's or
26   variable's linkage name, to preserve compatibility between C++'s
27   language features (templates, scoping, and overloading) and C
28   linkers.
29
30   Additionally, g++ uses mangled names internally.  To support this,
31   mangling of types is allowed, even though the mangled name of a
32   type should not appear by itself as an exported name.  Ditto for
33   uninstantiated templates.
34
35   The primary entry point for this module is mangle_decl, which
36   returns an identifier containing the mangled name for a decl.
37   Additional entry points are provided to build mangled names of
38   particular constructs when the appropriate decl for that construct
39   is not available.  These are:
40
41     mangle_typeinfo_for_type:        typeinfo data
42     mangle_typeinfo_string_for_type: typeinfo type name
43     mangle_vtbl_for_type:            virtual table data
44     mangle_vtt_for_type:             VTT data
45     mangle_ctor_vtbl_for_type:       `C-in-B' constructor virtual table data
46     mangle_thunk:                    thunk function or entry
47
48*/
49
50#include "config.h"
51#include "system.h"
52#include "tree.h"
53#include "tm_p.h"
54#include "cp-tree.h"
55#include "real.h"
56#include "obstack.h"
57#include "toplev.h"
58#include "varray.h"
59#include "ggc.h"
60
61/* Debugging support.  */
62
63/* Define DEBUG_MANGLE to enable very verbose trace messages.  */
64#ifndef DEBUG_MANGLE
65#define DEBUG_MANGLE 0
66#endif
67
68/* Macros for tracing the write_* functions.  */
69#if DEBUG_MANGLE
70# define MANGLE_TRACE(FN, INPUT) \
71  fprintf (stderr, "  %-24s: %-24s\n", (FN), (INPUT))
72# define MANGLE_TRACE_TREE(FN, NODE) \
73  fprintf (stderr, "  %-24s: %-24s (%p)\n", \
74           (FN), tree_code_name[TREE_CODE (NODE)], (void *) (NODE))
75#else
76# define MANGLE_TRACE(FN, INPUT)
77# define MANGLE_TRACE_TREE(FN, NODE)
78#endif
79
80/* Nonzero if NODE is a class template-id.  We can't rely on
81   CLASSTYPE_USE_TEMPLATE here because of tricky bugs in the parser
82   that hard to distinguish A<T> from A, where A<T> is the type as
83   instantiated outside of the template, and A is the type used
84   without parameters inside the template.  */
85#define CLASSTYPE_TEMPLATE_ID_P(NODE)					\
86  (TYPE_LANG_SPECIFIC (NODE) != NULL					\
87   && (TREE_CODE (NODE) == BOUND_TEMPLATE_TEMPLATE_PARM			\
88       || (CLASSTYPE_TEMPLATE_INFO (NODE) != NULL			\
89	   && (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (NODE))))))
90
91/* Things we only need one of.  This module is not reentrant.  */
92static struct globals
93{
94  /* The name in which we're building the mangled name.  */
95  struct obstack name_obstack;
96
97  /* An array of the current substitution candidates, in the order
98     we've seen them.  */
99  varray_type substitutions;
100
101  /* The entity that is being mangled.  */
102  tree entity;
103
104  /* True if the mangling will be different in a future version of the
105     ABI.  */
106  bool need_abi_warning;
107} G;
108
109/* Indices into subst_identifiers.  These are identifiers used in
110   special substitution rules.  */
111typedef enum
112{
113  SUBID_ALLOCATOR,
114  SUBID_BASIC_STRING,
115  SUBID_CHAR_TRAITS,
116  SUBID_BASIC_ISTREAM,
117  SUBID_BASIC_OSTREAM,
118  SUBID_BASIC_IOSTREAM,
119  SUBID_MAX
120}
121substitution_identifier_index_t;
122
123/* For quick substitution checks, look up these common identifiers
124   once only.  */
125static tree subst_identifiers[SUBID_MAX];
126
127/* Single-letter codes for builtin integer types, defined in
128   <builtin-type>.  These are indexed by integer_type_kind values.  */
129static const char
130integer_type_codes[itk_none] =
131{
132  'c',  /* itk_char */
133  'a',  /* itk_signed_char */
134  'h',  /* itk_unsigned_char */
135  's',  /* itk_short */
136  't',  /* itk_unsigned_short */
137  'i',  /* itk_int */
138  'j',  /* itk_unsigned_int */
139  'l',  /* itk_long */
140  'm',  /* itk_unsigned_long */
141  'x',  /* itk_long_long */
142  'y'   /* itk_unsigned_long_long */
143};
144
145static int decl_is_template_id PARAMS ((tree, tree*));
146
147/* Functions for handling substitutions.  */
148
149static inline tree canonicalize_for_substitution PARAMS ((tree));
150static void add_substitution PARAMS ((tree));
151static inline int is_std_substitution PARAMS ((tree, substitution_identifier_index_t));
152static inline int is_std_substitution_char PARAMS ((tree, substitution_identifier_index_t));
153static int find_substitution PARAMS ((tree));
154
155/* Functions for emitting mangled representations of things.  */
156
157static void write_mangled_name PARAMS ((tree));
158static void write_encoding PARAMS ((tree));
159static void write_name PARAMS ((tree, int));
160static void write_unscoped_name PARAMS ((tree));
161static void write_unscoped_template_name PARAMS ((tree));
162static void write_nested_name PARAMS ((tree));
163static void write_prefix PARAMS ((tree));
164static void write_template_prefix PARAMS ((tree));
165static void write_unqualified_name PARAMS ((tree));
166static void write_conversion_operator_name (tree);
167static void write_source_name PARAMS ((tree));
168static int hwint_to_ascii PARAMS ((unsigned HOST_WIDE_INT, unsigned int, char *, unsigned));
169static void write_number PARAMS ((unsigned HOST_WIDE_INT, int,
170				  unsigned int));
171static void write_integer_cst PARAMS ((tree));
172static void write_real_cst PARAMS ((tree));
173static void write_identifier PARAMS ((const char *));
174static void write_special_name_constructor PARAMS ((tree));
175static void write_special_name_destructor PARAMS ((tree));
176static void write_type PARAMS ((tree));
177static int write_CV_qualifiers_for_type PARAMS ((tree));
178static void write_builtin_type PARAMS ((tree));
179static void write_function_type PARAMS ((tree));
180static void write_bare_function_type PARAMS ((tree, int, tree));
181static void write_method_parms PARAMS ((tree, int, tree));
182static void write_class_enum_type PARAMS ((tree));
183static void write_template_args PARAMS ((tree));
184static void write_expression PARAMS ((tree));
185static void write_template_arg_literal PARAMS ((tree));
186static void write_template_arg PARAMS ((tree));
187static void write_template_template_arg PARAMS ((tree));
188static void write_array_type PARAMS ((tree));
189static void write_pointer_to_member_type PARAMS ((tree));
190static void write_template_param PARAMS ((tree));
191static void write_template_template_param PARAMS ((tree));
192static void write_substitution PARAMS ((int));
193static int discriminator_for_local_entity PARAMS ((tree));
194static int discriminator_for_string_literal PARAMS ((tree, tree));
195static void write_discriminator PARAMS ((int));
196static void write_local_name PARAMS ((tree, tree, tree));
197static void dump_substitution_candidates PARAMS ((void));
198static const char *mangle_decl_string PARAMS ((tree));
199
200/* Control functions.  */
201
202static inline void start_mangling (tree);
203static inline const char *finish_mangling (bool);
204static tree mangle_special_for_type PARAMS ((tree, const char *));
205
206/* Foreign language functions.  */
207
208static void write_java_integer_type_codes PARAMS ((tree));
209
210/* Append a single character to the end of the mangled
211   representation.  */
212#define write_char(CHAR)                                              \
213  obstack_1grow (&G.name_obstack, (CHAR))
214
215/* Append a sized buffer to the end of the mangled representation.  */
216#define write_chars(CHAR, LEN)                                        \
217  obstack_grow (&G.name_obstack, (CHAR), (LEN))
218
219/* Append a NUL-terminated string to the end of the mangled
220   representation.  */
221#define write_string(STRING)                                          \
222  obstack_grow (&G.name_obstack, (STRING), strlen (STRING))
223
224/* Nonzero if NODE1 and NODE2 are both TREE_LIST nodes and have the
225   same purpose (context, which may be a type) and value (template
226   decl).  See write_template_prefix for more information on what this
227   is used for.  */
228#define NESTED_TEMPLATE_MATCH(NODE1, NODE2)                         \
229  (TREE_CODE (NODE1) == TREE_LIST                                     \
230   && TREE_CODE (NODE2) == TREE_LIST                                  \
231   && ((TYPE_P (TREE_PURPOSE (NODE1))                                 \
232        && same_type_p (TREE_PURPOSE (NODE1), TREE_PURPOSE (NODE2)))\
233       || TREE_PURPOSE (NODE1) == TREE_PURPOSE (NODE2))             \
234   && TREE_VALUE (NODE1) == TREE_VALUE (NODE2))
235
236/* Write out an unsigned quantity in base 10.  */
237#define write_unsigned_number(NUMBER) \
238  write_number ((NUMBER), /*unsigned_p=*/1, 10)
239
240/* If DECL is a template instance, return nonzero and, if
241   TEMPLATE_INFO is non-NULL, set *TEMPLATE_INFO to its template info.
242   Otherwise return zero.  */
243
244static int
245decl_is_template_id (decl, template_info)
246     tree decl;
247     tree* template_info;
248{
249  if (TREE_CODE (decl) == TYPE_DECL)
250    {
251      /* TYPE_DECLs are handled specially.  Look at its type to decide
252	 if this is a template instantiation.  */
253      tree type = TREE_TYPE (decl);
254
255      if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_ID_P (type))
256	{
257	  if (template_info != NULL)
258	    /* For a templated TYPE_DECL, the template info is hanging
259	       off the type.  */
260	    *template_info = TYPE_TEMPLATE_INFO (type);
261	  return 1;
262	}
263    }
264  else
265    {
266      /* Check if this is a primary template.  */
267      if (DECL_LANG_SPECIFIC (decl) != NULL
268	  && DECL_USE_TEMPLATE (decl)
269	  && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
270	  && TREE_CODE (decl) != TEMPLATE_DECL)
271	{
272	  if (template_info != NULL)
273	    /* For most templated decls, the template info is hanging
274	       off the decl.  */
275	    *template_info = DECL_TEMPLATE_INFO (decl);
276	  return 1;
277	}
278    }
279
280  /* It's not a template id.  */
281  return 0;
282}
283
284/* Produce debugging output of current substitution candidates.  */
285
286static void
287dump_substitution_candidates ()
288{
289  unsigned i;
290
291  fprintf (stderr, "  ++ substitutions  ");
292  for (i = 0; i < VARRAY_ACTIVE_SIZE (G.substitutions); ++i)
293    {
294      tree el = VARRAY_TREE (G.substitutions, i);
295      const char *name = "???";
296
297      if (i > 0)
298	fprintf (stderr, "                    ");
299      if (DECL_P (el))
300	name = IDENTIFIER_POINTER (DECL_NAME (el));
301      else if (TREE_CODE (el) == TREE_LIST)
302	name = IDENTIFIER_POINTER (DECL_NAME (TREE_VALUE (el)));
303      else if (TYPE_NAME (el))
304	name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (el)));
305      fprintf (stderr, " S%d_ = ", i - 1);
306      if (TYPE_P (el) &&
307	  (CP_TYPE_RESTRICT_P (el)
308	   || CP_TYPE_VOLATILE_P (el)
309	   || CP_TYPE_CONST_P (el)))
310	fprintf (stderr, "CV-");
311      fprintf (stderr, "%s (%s at %p)\n",
312	       name, tree_code_name[TREE_CODE (el)], (void *) el);
313    }
314}
315
316/* Both decls and types can be substitution candidates, but sometimes
317   they refer to the same thing.  For instance, a TYPE_DECL and
318   RECORD_TYPE for the same class refer to the same thing, and should
319   be treated accordinginly in substitutions.  This function returns a
320   canonicalized tree node representing NODE that is used when adding
321   and substitution candidates and finding matches.  */
322
323static inline tree
324canonicalize_for_substitution (node)
325     tree node;
326{
327  /* For a TYPE_DECL, use the type instead.  */
328  if (TREE_CODE (node) == TYPE_DECL)
329    node = TREE_TYPE (node);
330  if (TYPE_P (node))
331    node = canonical_type_variant (node);
332
333  return node;
334}
335
336/* Add NODE as a substitution candidate.  NODE must not already be on
337   the list of candidates.  */
338
339static void
340add_substitution (node)
341     tree node;
342{
343  tree c;
344
345  if (DEBUG_MANGLE)
346    fprintf (stderr, "  ++ add_substitution (%s at %10p)\n",
347	     tree_code_name[TREE_CODE (node)], (void *) node);
348
349  /* Get the canonicalized substitution candidate for NODE.  */
350  c = canonicalize_for_substitution (node);
351  if (DEBUG_MANGLE && c != node)
352    fprintf (stderr, "  ++ using candidate (%s at %10p)\n",
353	     tree_code_name[TREE_CODE (node)], (void *) node);
354  node = c;
355
356#if ENABLE_CHECKING
357  /* Make sure NODE isn't already a candidate.  */
358  {
359    int i;
360    for (i = VARRAY_ACTIVE_SIZE (G.substitutions); --i >= 0; )
361      {
362	tree candidate = VARRAY_TREE (G.substitutions, i);
363	if ((DECL_P (node)
364	     && node == candidate)
365	    || (TYPE_P (node)
366		&& TYPE_P (candidate)
367		&& same_type_p (node, candidate)))
368	  abort ();
369      }
370  }
371#endif /* ENABLE_CHECKING */
372
373  /* Put the decl onto the varray of substitution candidates.  */
374  VARRAY_PUSH_TREE (G.substitutions, node);
375
376  if (DEBUG_MANGLE)
377    dump_substitution_candidates ();
378}
379
380/* Helper function for find_substitution.  Returns nonzero if NODE,
381   which may be a decl or a CLASS_TYPE, is a template-id with template
382   name of substitution_index[INDEX] in the ::std namespace.  */
383
384static inline int
385is_std_substitution (node, index)
386     tree node;
387     substitution_identifier_index_t index;
388{
389  tree type = NULL;
390  tree decl = NULL;
391
392  if (DECL_P (node))
393    {
394      type = TREE_TYPE (node);
395      decl = node;
396    }
397  else if (CLASS_TYPE_P (node))
398    {
399      type = node;
400      decl = TYPE_NAME (node);
401    }
402  else
403    /* These are not the droids you're looking for.  */
404    return 0;
405
406  return (DECL_NAMESPACE_STD_P (CP_DECL_CONTEXT (decl))
407	  && TYPE_LANG_SPECIFIC (type)
408	  && TYPE_TEMPLATE_INFO (type)
409	  && (DECL_NAME (TYPE_TI_TEMPLATE (type))
410	      == subst_identifiers[index]));
411}
412
413/* Helper function for find_substitution.  Returns nonzero if NODE,
414   which may be a decl or a CLASS_TYPE, is the template-id
415   ::std::identifier<char>, where identifier is
416   substitution_index[INDEX].  */
417
418static inline int
419is_std_substitution_char (node, index)
420     tree node;
421     substitution_identifier_index_t index;
422{
423  tree args;
424  /* Check NODE's name is ::std::identifier.  */
425  if (!is_std_substitution (node, index))
426    return 0;
427  /* Figure out its template args.  */
428  if (DECL_P (node))
429    args = DECL_TI_ARGS (node);
430  else if (CLASS_TYPE_P (node))
431    args = CLASSTYPE_TI_ARGS (node);
432  else
433    /* Oops, not a template.  */
434    return 0;
435  /* NODE's template arg list should be <char>.  */
436  return
437    TREE_VEC_LENGTH (args) == 1
438    && TREE_VEC_ELT (args, 0) == char_type_node;
439}
440
441/* Check whether a substitution should be used to represent NODE in
442   the mangling.
443
444   First, check standard special-case substitutions.
445
446     <substitution> ::= St
447         # ::std
448
449                    ::= Sa
450	 # ::std::allocator
451
452                    ::= Sb
453         # ::std::basic_string
454
455                    ::= Ss
456         # ::std::basic_string<char,
457			       ::std::char_traits<char>,
458			       ::std::allocator<char> >
459
460                    ::= Si
461         # ::std::basic_istream<char, ::std::char_traits<char> >
462
463                    ::= So
464         # ::std::basic_ostream<char, ::std::char_traits<char> >
465
466                    ::= Sd
467         # ::std::basic_iostream<char, ::std::char_traits<char> >
468
469   Then examine the stack of currently available substitution
470   candidates for entities appearing earlier in the same mangling
471
472   If a substitution is found, write its mangled representation and
473   return nonzero.  If none is found, just return zero.  */
474
475static int
476find_substitution (node)
477     tree node;
478{
479  int i;
480  int size = VARRAY_ACTIVE_SIZE (G.substitutions);
481  tree decl;
482  tree type;
483
484  if (DEBUG_MANGLE)
485    fprintf (stderr, "  ++ find_substitution (%s at %p)\n",
486	     tree_code_name[TREE_CODE (node)], (void *) node);
487
488  /* Obtain the canonicalized substitution representation for NODE.
489     This is what we'll compare against.  */
490  node = canonicalize_for_substitution (node);
491
492  /* Check for builtin substitutions.  */
493
494  decl = TYPE_P (node) ? TYPE_NAME (node) : node;
495  type = TYPE_P (node) ? node : TREE_TYPE (node);
496
497  /* Check for std::allocator.  */
498  if (decl
499      && is_std_substitution (decl, SUBID_ALLOCATOR)
500      && !CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
501    {
502      write_string ("Sa");
503      return 1;
504    }
505
506  /* Check for std::basic_string.  */
507  if (decl && is_std_substitution (decl, SUBID_BASIC_STRING))
508    {
509      if (TYPE_P (node))
510	{
511	  /* If this is a type (i.e. a fully-qualified template-id),
512	     check for
513  	         std::basic_string <char,
514		 		    std::char_traits<char>,
515				    std::allocator<char> > .  */
516	  if (cp_type_quals (type) == TYPE_UNQUALIFIED
517	      && CLASSTYPE_USE_TEMPLATE (type))
518	    {
519	      tree args = CLASSTYPE_TI_ARGS (type);
520	      if (TREE_VEC_LENGTH (args) == 3
521		  && same_type_p (TREE_VEC_ELT (args, 0), char_type_node)
522		  && is_std_substitution_char (TREE_VEC_ELT (args, 1),
523					       SUBID_CHAR_TRAITS)
524		  && is_std_substitution_char (TREE_VEC_ELT (args, 2),
525					       SUBID_ALLOCATOR))
526		{
527		  write_string ("Ss");
528		  return 1;
529		}
530	    }
531	}
532      else
533	/* Substitute for the template name only if this isn't a type.  */
534	{
535	  write_string ("Sb");
536	  return 1;
537	}
538    }
539
540  /* Check for basic_{i,o,io}stream.  */
541  if (TYPE_P (node)
542      && cp_type_quals (type) == TYPE_UNQUALIFIED
543      && CLASS_TYPE_P (type)
544      && CLASSTYPE_USE_TEMPLATE (type)
545      && CLASSTYPE_TEMPLATE_INFO (type) != NULL)
546    {
547      /* First, check for the template
548	 args <char, std::char_traits<char> > .  */
549      tree args = CLASSTYPE_TI_ARGS (type);
550      if (TREE_VEC_LENGTH (args) == 2
551	  && same_type_p (TREE_VEC_ELT (args, 0), char_type_node)
552	  && is_std_substitution_char (TREE_VEC_ELT (args, 1),
553				       SUBID_CHAR_TRAITS))
554	{
555	  /* Got them.  Is this basic_istream?  */
556	  tree name = DECL_NAME (CLASSTYPE_TI_TEMPLATE (type));
557	  if (name == subst_identifiers[SUBID_BASIC_ISTREAM])
558	    {
559	      write_string ("Si");
560	      return 1;
561	    }
562	  /* Or basic_ostream?  */
563	  else if (name == subst_identifiers[SUBID_BASIC_OSTREAM])
564	    {
565	      write_string ("So");
566	      return 1;
567	    }
568	  /* Or basic_iostream?  */
569	  else if (name == subst_identifiers[SUBID_BASIC_IOSTREAM])
570	    {
571	      write_string ("Sd");
572	      return 1;
573	    }
574	}
575    }
576
577  /* Check for namespace std.  */
578  if (decl && DECL_NAMESPACE_STD_P (decl))
579    {
580      write_string ("St");
581      return 1;
582    }
583
584  /* Now check the list of available substitutions for this mangling
585     operation.  */
586  for (i = 0; i < size; ++i)
587    {
588      tree candidate = VARRAY_TREE (G.substitutions, i);
589      /* NODE is a matched to a candidate if it's the same decl node or
590	 if it's the same type.  */
591      if (decl == candidate
592	  || (TYPE_P (candidate) && type && TYPE_P (type)
593	      && same_type_p (type, candidate))
594	  || NESTED_TEMPLATE_MATCH (node, candidate))
595	{
596	  write_substitution (i);
597	  return 1;
598	}
599    }
600
601  /* No substitution found.  */
602  return 0;
603}
604
605
606/*  <mangled-name>      ::= _Z <encoding>  */
607
608static inline void
609write_mangled_name (decl)
610     tree decl;
611{
612  MANGLE_TRACE_TREE ("mangled-name", decl);
613
614  if (DECL_LANG_SPECIFIC (decl)
615      && DECL_EXTERN_C_FUNCTION_P (decl)
616      && ! DECL_OVERLOADED_OPERATOR_P (decl))
617    /* The standard notes:
618         "The <encoding> of an extern "C" function is treated like
619	 global-scope data, i.e. as its <source-name> without a type."
620       We cannot write overloaded operators that way though,
621       because it contains characters invalid in assembler.  */
622    write_source_name (DECL_NAME (decl));
623  else
624    /* C++ name; needs to be mangled.  */
625    {
626      write_string ("_Z");
627      write_encoding (decl);
628    }
629}
630
631/*   <encoding>		::= <function name> <bare-function-type>
632			::= <data name>  */
633
634static void
635write_encoding (decl)
636     tree decl;
637{
638  MANGLE_TRACE_TREE ("encoding", decl);
639
640  if (DECL_LANG_SPECIFIC (decl) && DECL_EXTERN_C_FUNCTION_P (decl))
641    {
642      /* For overloaded operators write just the mangled name
643	 without arguments.  */
644      if (DECL_OVERLOADED_OPERATOR_P (decl))
645	write_name (decl, /*ignore_local_scope=*/0);
646      else
647	write_source_name (DECL_NAME (decl));
648      return;
649    }
650
651  write_name (decl, /*ignore_local_scope=*/0);
652  if (TREE_CODE (decl) == FUNCTION_DECL)
653    {
654      tree fn_type;
655
656      if (decl_is_template_id (decl, NULL))
657	fn_type = get_mostly_instantiated_function_type (decl);
658      else
659	fn_type = TREE_TYPE (decl);
660
661      write_bare_function_type (fn_type,
662				(!DECL_CONSTRUCTOR_P (decl)
663				 && !DECL_DESTRUCTOR_P (decl)
664				 && !DECL_CONV_FN_P (decl)
665				 && decl_is_template_id (decl, NULL)),
666				decl);
667    }
668}
669
670/* <name> ::= <unscoped-name>
671          ::= <unscoped-template-name> <template-args>
672	  ::= <nested-name>
673	  ::= <local-name>
674
675   If IGNORE_LOCAL_SCOPE is nonzero, this production of <name> is
676   called from <local-name>, which mangles the enclosing scope
677   elsewhere and then uses this function to mangle just the part
678   underneath the function scope.  So don't use the <local-name>
679   production, to avoid an infinite recursion.  */
680
681static void
682write_name (decl, ignore_local_scope)
683     tree decl;
684     int ignore_local_scope;
685{
686  tree context;
687
688  MANGLE_TRACE_TREE ("name", decl);
689
690  if (TREE_CODE (decl) == TYPE_DECL)
691    {
692      /* In case this is a typedef, fish out the corresponding
693	 TYPE_DECL for the main variant.  */
694      decl = TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl)));
695      context = TYPE_CONTEXT (TYPE_MAIN_VARIANT (TREE_TYPE (decl)));
696    }
697  else
698    context = (DECL_CONTEXT (decl) == NULL) ? NULL : CP_DECL_CONTEXT (decl);
699
700  /* A decl in :: or ::std scope is treated specially.  The former is
701     mangled using <unscoped-name> or <unscoped-template-name>, the
702     latter with a special substitution.  Also, a name that is
703     directly in a local function scope is also mangled with
704     <unscoped-name> rather than a full <nested-name>.  */
705  if (context == NULL
706      || context == global_namespace
707      || DECL_NAMESPACE_STD_P (context)
708      || (ignore_local_scope && TREE_CODE (context) == FUNCTION_DECL))
709    {
710      tree template_info;
711      /* Is this a template instance?  */
712      if (decl_is_template_id (decl, &template_info))
713	{
714	  /* Yes: use <unscoped-template-name>.  */
715	  write_unscoped_template_name (TI_TEMPLATE (template_info));
716	  write_template_args (TI_ARGS (template_info));
717	}
718      else
719	/* Everything else gets an <unqualified-name>.  */
720	write_unscoped_name (decl);
721    }
722  else
723    {
724      /* Handle local names, unless we asked not to (that is, invoked
725         under <local-name>, to handle only the part of the name under
726         the local scope).  */
727      if (!ignore_local_scope)
728        {
729	  /* Scan up the list of scope context, looking for a
730	     function.  If we find one, this entity is in local
731	     function scope.  local_entity tracks context one scope
732	     level down, so it will contain the element that's
733	     directly in that function's scope, either decl or one of
734	     its enclosing scopes.  */
735	  tree local_entity = decl;
736	  while (context != NULL && context != global_namespace)
737	    {
738	      /* Make sure we're always dealing with decls.  */
739	      if (context != NULL && TYPE_P (context))
740		context = TYPE_NAME (context);
741	      /* Is this a function?  */
742	      if (TREE_CODE (context) == FUNCTION_DECL)
743		{
744		  /* Yes, we have local scope.  Use the <local-name>
745		     production for the innermost function scope.  */
746		  write_local_name (context, local_entity, decl);
747		  return;
748		}
749	      /* Up one scope level.  */
750	      local_entity = context;
751	      context = CP_DECL_CONTEXT (context);
752	    }
753
754	  /* No local scope found?  Fall through to <nested-name>.  */
755	}
756
757      /* Other decls get a <nested-name> to encode their scope.  */
758      write_nested_name (decl);
759    }
760}
761
762/* <unscoped-name> ::= <unqualified-name>
763                   ::= St <unqualified-name>   # ::std::  */
764
765static void
766write_unscoped_name (decl)
767     tree decl;
768{
769  tree context = CP_DECL_CONTEXT (decl);
770
771  MANGLE_TRACE_TREE ("unscoped-name", decl);
772
773  /* Is DECL in ::std?  */
774  if (DECL_NAMESPACE_STD_P (context))
775    {
776      write_string ("St");
777      write_unqualified_name (decl);
778    }
779  /* If not, it should be either in the global namespace, or directly
780     in a local function scope.  */
781  else if (context == global_namespace
782	   || context == NULL
783	   || TREE_CODE (context) == FUNCTION_DECL)
784    write_unqualified_name (decl);
785  else
786    abort ();
787}
788
789/* <unscoped-template-name> ::= <unscoped-name>
790                            ::= <substitution>  */
791
792static void
793write_unscoped_template_name (decl)
794     tree decl;
795{
796  MANGLE_TRACE_TREE ("unscoped-template-name", decl);
797
798  if (find_substitution (decl))
799    return;
800  write_unscoped_name (decl);
801  add_substitution (decl);
802}
803
804/* Write the nested name, including CV-qualifiers, of DECL.
805
806   <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
807                 ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
808
809   <CV-qualifiers> ::= [r] [V] [K]  */
810
811static void
812write_nested_name (decl)
813     tree decl;
814{
815  tree template_info;
816
817  MANGLE_TRACE_TREE ("nested-name", decl);
818
819  write_char ('N');
820
821  /* Write CV-qualifiers, if this is a member function.  */
822  if (TREE_CODE (decl) == FUNCTION_DECL
823      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
824    {
825      if (DECL_VOLATILE_MEMFUNC_P (decl))
826	write_char ('V');
827      if (DECL_CONST_MEMFUNC_P (decl))
828	write_char ('K');
829    }
830
831  /* Is this a template instance?  */
832  if (decl_is_template_id (decl, &template_info))
833    {
834      /* Yes, use <template-prefix>.  */
835      write_template_prefix (decl);
836      write_template_args (TI_ARGS (template_info));
837    }
838  else
839    {
840      /* No, just use <prefix>  */
841      write_prefix (DECL_CONTEXT (decl));
842      write_unqualified_name (decl);
843    }
844  write_char ('E');
845}
846
847/* <prefix> ::= <prefix> <unqualified-name>
848            ::= <template-param>
849            ::= <template-prefix> <template-args>
850	    ::= # empty
851	    ::= <substitution>  */
852
853static void
854write_prefix (node)
855     tree node;
856{
857  tree decl;
858  /* Non-NULL if NODE represents a template-id.  */
859  tree template_info = NULL;
860
861  MANGLE_TRACE_TREE ("prefix", node);
862
863  if (node == NULL
864      || node == global_namespace)
865    return;
866
867  if (find_substitution (node))
868    return;
869
870  if (DECL_P (node))
871    {
872      /* If this is a function decl, that means we've hit function
873	 scope, so this prefix must be for a local name.  In this
874	 case, we're under the <local-name> production, which encodes
875	 the enclosing function scope elsewhere.  So don't continue
876	 here.  */
877      if (TREE_CODE (node) == FUNCTION_DECL)
878	return;
879
880      decl = node;
881      decl_is_template_id (decl, &template_info);
882    }
883  else
884    {
885      /* Node is a type.  */
886      decl = TYPE_NAME (node);
887      if (CLASSTYPE_TEMPLATE_ID_P (node))
888	template_info = TYPE_TEMPLATE_INFO (node);
889    }
890
891  /* In G++ 3.2, the name of the template parameter was used.  */
892  if (TREE_CODE (node) == TEMPLATE_TYPE_PARM
893      && !abi_version_at_least (2))
894    G.need_abi_warning = true;
895
896  if (TREE_CODE (node) == TEMPLATE_TYPE_PARM
897      && abi_version_at_least (2))
898    write_template_param (node);
899  else if (template_info != NULL)
900    /* Templated.  */
901    {
902      write_template_prefix (decl);
903      write_template_args (TI_ARGS (template_info));
904    }
905  else
906    /* Not templated.  */
907    {
908      write_prefix (CP_DECL_CONTEXT (decl));
909      write_unqualified_name (decl);
910    }
911
912  add_substitution (node);
913}
914
915/* <template-prefix> ::= <prefix> <template component>
916                     ::= <template-param>
917                     ::= <substitution>  */
918
919static void
920write_template_prefix (node)
921     tree node;
922{
923  tree decl = DECL_P (node) ? node : TYPE_NAME (node);
924  tree type = DECL_P (node) ? TREE_TYPE (node) : node;
925  tree context = CP_DECL_CONTEXT (decl);
926  tree template_info;
927  tree template;
928  tree substitution;
929
930  MANGLE_TRACE_TREE ("template-prefix", node);
931
932  /* Find the template decl.  */
933  if (decl_is_template_id (decl, &template_info))
934    template = TI_TEMPLATE (template_info);
935  else if (CLASSTYPE_TEMPLATE_ID_P (type))
936    template = TYPE_TI_TEMPLATE (type);
937  else
938    /* Oops, not a template.  */
939    abort ();
940
941  /* For a member template, though, the template name for the
942     innermost name must have all the outer template levels
943     instantiated.  For instance, consider
944
945       template<typename T> struct Outer {
946	 template<typename U> struct Inner {};
947       };
948
949     The template name for `Inner' in `Outer<int>::Inner<float>' is
950     `Outer<int>::Inner<U>'.  In g++, we don't instantiate the template
951     levels separately, so there's no TEMPLATE_DECL available for this
952     (there's only `Outer<T>::Inner<U>').
953
954     In order to get the substitutions right, we create a special
955     TREE_LIST to represent the substitution candidate for a nested
956     template.  The TREE_PURPOSE is the template's context, fully
957     instantiated, and the TREE_VALUE is the TEMPLATE_DECL for the inner
958     template.
959
960     So, for the example above, `Outer<int>::Inner' is represented as a
961     substitution candidate by a TREE_LIST whose purpose is `Outer<int>'
962     and whose value is `Outer<T>::Inner<U>'.  */
963  if (TYPE_P (context))
964    substitution = build_tree_list (context, template);
965  else
966    substitution = template;
967
968  if (find_substitution (substitution))
969    return;
970
971  /* In G++ 3.2, the name of the template template parameter was used.  */
972  if (TREE_CODE (TREE_TYPE (template)) == TEMPLATE_TEMPLATE_PARM
973      && !abi_version_at_least (2))
974    G.need_abi_warning = true;
975
976  if (TREE_CODE (TREE_TYPE (template)) == TEMPLATE_TEMPLATE_PARM
977      && abi_version_at_least (2))
978    write_template_param (TREE_TYPE (template));
979  else
980    {
981      write_prefix (context);
982      write_unqualified_name (decl);
983    }
984
985  add_substitution (substitution);
986}
987
988/* We don't need to handle thunks, vtables, or VTTs here.  Those are
989   mangled through special entry points.
990
991    <unqualified-name>  ::= <operator-name>
992			::= <special-name>
993			::= <source-name>  */
994
995static void
996write_unqualified_name (decl)
997     tree decl;
998{
999  MANGLE_TRACE_TREE ("unqualified-name", decl);
1000
1001  if (DECL_LANG_SPECIFIC (decl) != NULL && DECL_CONSTRUCTOR_P (decl))
1002    write_special_name_constructor (decl);
1003  else if (DECL_LANG_SPECIFIC (decl) != NULL && DECL_DESTRUCTOR_P (decl))
1004    write_special_name_destructor (decl);
1005  else if (DECL_CONV_FN_P (decl))
1006    {
1007      /* Conversion operator. Handle it right here.
1008           <operator> ::= cv <type>  */
1009      tree type;
1010      if (decl_is_template_id (decl, NULL))
1011	{
1012	  tree fn_type = get_mostly_instantiated_function_type (decl);
1013	  type = TREE_TYPE (fn_type);
1014	}
1015      else
1016	type = DECL_CONV_FN_TYPE (decl);
1017      write_conversion_operator_name (type);
1018    }
1019  else if (DECL_OVERLOADED_OPERATOR_P (decl))
1020    {
1021      operator_name_info_t *oni;
1022      if (DECL_ASSIGNMENT_OPERATOR_P (decl))
1023	oni = assignment_operator_name_info;
1024      else
1025	oni = operator_name_info;
1026
1027      write_string (oni[DECL_OVERLOADED_OPERATOR_P (decl)].mangled_name);
1028    }
1029  else
1030    write_source_name (DECL_NAME (decl));
1031}
1032
1033/* Write the unqualified-name for a conversion operator to TYPE.  */
1034
1035static void
1036write_conversion_operator_name (tree type)
1037{
1038  write_string ("cv");
1039  write_type (type);
1040}
1041
1042/* Non-termial <source-name>.  IDENTIFIER is an IDENTIFIER_NODE.
1043
1044     <source-name> ::= </length/ number> <identifier>  */
1045
1046static void
1047write_source_name (identifier)
1048     tree identifier;
1049{
1050  MANGLE_TRACE_TREE ("source-name", identifier);
1051
1052  /* Never write the whole template-id name including the template
1053     arguments; we only want the template name.  */
1054  if (IDENTIFIER_TEMPLATE (identifier))
1055    identifier = IDENTIFIER_TEMPLATE (identifier);
1056
1057  write_unsigned_number (IDENTIFIER_LENGTH (identifier));
1058  write_identifier (IDENTIFIER_POINTER (identifier));
1059}
1060
1061/* Convert NUMBER to ascii using base BASE and generating at least
1062   MIN_DIGITS characters. BUFFER points to the _end_ of the buffer
1063   into which to store the characters. Returns the number of
1064   characters generated (these will be layed out in advance of where
1065   BUFFER points).  */
1066
1067static int
1068hwint_to_ascii (number, base, buffer, min_digits)
1069     unsigned HOST_WIDE_INT number;
1070     unsigned int base;
1071     char *buffer;
1072     unsigned min_digits;
1073{
1074  static const char base_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1075  unsigned digits = 0;
1076
1077  while (number)
1078    {
1079      unsigned HOST_WIDE_INT d = number / base;
1080
1081      *--buffer = base_digits[number - d * base];
1082      digits++;
1083      number = d;
1084    }
1085  while (digits < min_digits)
1086    {
1087      *--buffer = base_digits[0];
1088      digits++;
1089    }
1090  return digits;
1091}
1092
1093/* Non-terminal <number>.
1094
1095     <number> ::= [n] </decimal integer/>  */
1096
1097static void
1098write_number (number, unsigned_p, base)
1099     unsigned HOST_WIDE_INT number;
1100     int unsigned_p;
1101     unsigned int base;
1102{
1103  char buffer[sizeof (HOST_WIDE_INT) * 8];
1104  unsigned count = 0;
1105
1106  if (!unsigned_p && (HOST_WIDE_INT) number < 0)
1107    {
1108      write_char ('n');
1109      number = -((HOST_WIDE_INT) number);
1110    }
1111  count = hwint_to_ascii (number, base, buffer + sizeof (buffer), 1);
1112  write_chars (buffer + sizeof (buffer) - count, count);
1113}
1114
1115/* Write out an integral CST in decimal. Most numbers are small, and
1116   representable in a HOST_WIDE_INT. Occasionally we'll have numbers
1117   bigger than that, which we must deal with.  */
1118
1119static inline void
1120write_integer_cst (cst)
1121     tree cst;
1122{
1123  int sign = tree_int_cst_sgn (cst);
1124
1125  if (TREE_INT_CST_HIGH (cst) + (sign < 0))
1126    {
1127      /* A bignum. We do this in chunks, each of which fits in a
1128	 HOST_WIDE_INT.  */
1129      char buffer[sizeof (HOST_WIDE_INT) * 8 * 2];
1130      unsigned HOST_WIDE_INT chunk;
1131      unsigned chunk_digits;
1132      char *ptr = buffer + sizeof (buffer);
1133      unsigned count = 0;
1134      tree n, base, type;
1135      int done;
1136
1137      /* HOST_WIDE_INT must be at least 32 bits, so 10^9 is
1138	 representable.  */
1139      chunk = 1000000000;
1140      chunk_digits = 9;
1141
1142      if (sizeof (HOST_WIDE_INT) >= 8)
1143	{
1144	  /* It is at least 64 bits, so 10^18 is representable.  */
1145	  chunk_digits = 18;
1146	  chunk *= chunk;
1147	}
1148
1149      type = c_common_signed_or_unsigned_type (1, TREE_TYPE (cst));
1150      base = build_int_2 (chunk, 0);
1151      n = build_int_2 (TREE_INT_CST_LOW (cst), TREE_INT_CST_HIGH (cst));
1152      TREE_TYPE (n) = TREE_TYPE (base) = type;
1153
1154      if (sign < 0)
1155	{
1156	  write_char ('n');
1157	  n = fold (build1 (NEGATE_EXPR, type, n));
1158	}
1159      do
1160	{
1161	  tree d = fold (build (FLOOR_DIV_EXPR, type, n, base));
1162	  tree tmp = fold (build (MULT_EXPR, type, d, base));
1163	  unsigned c;
1164
1165	  done = integer_zerop (d);
1166	  tmp = fold (build (MINUS_EXPR, type, n, tmp));
1167	  c = hwint_to_ascii (TREE_INT_CST_LOW (tmp), 10, ptr,
1168				done ? 1 : chunk_digits);
1169	  ptr -= c;
1170	  count += c;
1171	  n = d;
1172	}
1173      while (!done);
1174      write_chars (ptr, count);
1175    }
1176  else
1177    {
1178      /* A small num.  */
1179      unsigned HOST_WIDE_INT low = TREE_INT_CST_LOW (cst);
1180
1181      if (sign < 0)
1182	{
1183	  write_char ('n');
1184	  low = -low;
1185	}
1186      write_unsigned_number (low);
1187    }
1188}
1189
1190/* Write out a floating-point literal.
1191
1192    "Floating-point literals are encoded using the bit pattern of the
1193    target processor's internal representation of that number, as a
1194    fixed-length lowercase hexadecimal string, high-order bytes first
1195    (even if the target processor would store low-order bytes first).
1196    The "n" prefix is not used for floating-point literals; the sign
1197    bit is encoded with the rest of the number.
1198
1199    Here are some examples, assuming the IEEE standard representation
1200    for floating point numbers.  (Spaces are for readability, not
1201    part of the encoding.)
1202
1203        1.0f                    Lf 3f80 0000 E
1204       -1.0f                    Lf bf80 0000 E
1205        1.17549435e-38f         Lf 0080 0000 E
1206        1.40129846e-45f         Lf 0000 0001 E
1207        0.0f                    Lf 0000 0000 E"
1208
1209   Caller is responsible for the Lx and the E.  */
1210static void
1211write_real_cst (value)
1212     tree value;
1213{
1214  if (abi_version_at_least (2))
1215    {
1216      long target_real[4];  /* largest supported float */
1217      char buffer[9];       /* eight hex digits in a 32-bit number */
1218      int i, limit, dir;
1219
1220      tree type = TREE_TYPE (value);
1221      int words = GET_MODE_BITSIZE (TYPE_MODE (type)) / 32;
1222
1223      real_to_target (target_real, &TREE_REAL_CST (value),
1224		      TYPE_MODE (type));
1225
1226      /* The value in target_real is in the target word order,
1227         so we must write it out backward if that happens to be
1228	 little-endian.  write_number cannot be used, it will
1229	 produce uppercase.  */
1230      if (FLOAT_WORDS_BIG_ENDIAN)
1231	i = 0, limit = words, dir = 1;
1232      else
1233	i = words - 1, limit = -1, dir = -1;
1234
1235      for (; i != limit; i += dir)
1236	{
1237	  sprintf (buffer, "%08lx", target_real[i]);
1238	  write_chars (buffer, 8);
1239	}
1240    }
1241  else
1242    {
1243      /* In G++ 3.3 and before the REAL_VALUE_TYPE was written out
1244	 literally.  Note that compatibility with 3.2 is impossible,
1245	 because the old floating-point emulator used a different
1246	 format for REAL_VALUE_TYPE.  */
1247      size_t i;
1248      for (i = 0; i < sizeof (TREE_REAL_CST (value)); ++i)
1249	write_number (((unsigned char *) &TREE_REAL_CST (value))[i],
1250		      /*unsigned_p*/ 1,
1251		      /*base*/ 16);
1252      G.need_abi_warning = 1;
1253    }
1254}
1255
1256/* Non-terminal <identifier>.
1257
1258     <identifier> ::= </unqualified source code identifier>  */
1259
1260static void
1261write_identifier (identifier)
1262     const char *identifier;
1263{
1264  MANGLE_TRACE ("identifier", identifier);
1265  write_string (identifier);
1266}
1267
1268/* Handle constructor productions of non-terminal <special-name>.
1269   CTOR is a constructor FUNCTION_DECL.
1270
1271     <special-name> ::= C1   # complete object constructor
1272                    ::= C2   # base object constructor
1273                    ::= C3   # complete object allocating constructor
1274
1275   Currently, allocating constructors are never used.
1276
1277   We also need to provide mangled names for the maybe-in-charge
1278   constructor, so we treat it here too.  mangle_decl_string will
1279   append *INTERNAL* to that, to make sure we never emit it.  */
1280
1281static void
1282write_special_name_constructor (ctor)
1283     tree ctor;
1284{
1285  if (DECL_COMPLETE_CONSTRUCTOR_P (ctor)
1286      /* Even though we don't ever emit a definition of the
1287	 old-style destructor, we still have to consider entities
1288	 (like static variables) nested inside it.  */
1289      || DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (ctor))
1290    write_string ("C1");
1291  else if (DECL_BASE_CONSTRUCTOR_P (ctor))
1292    write_string ("C2");
1293  else
1294    abort ();
1295}
1296
1297/* Handle destructor productions of non-terminal <special-name>.
1298   DTOR is a destructor FUNCTION_DECL.
1299
1300     <special-name> ::= D0 # deleting (in-charge) destructor
1301                    ::= D1 # complete object (in-charge) destructor
1302                    ::= D2 # base object (not-in-charge) destructor
1303
1304   We also need to provide mangled names for the maybe-incharge
1305   destructor, so we treat it here too.  mangle_decl_string will
1306   append *INTERNAL* to that, to make sure we never emit it.  */
1307
1308static void
1309write_special_name_destructor (dtor)
1310     tree dtor;
1311{
1312  if (DECL_DELETING_DESTRUCTOR_P (dtor))
1313    write_string ("D0");
1314  else if (DECL_COMPLETE_DESTRUCTOR_P (dtor)
1315	   /* Even though we don't ever emit a definition of the
1316	      old-style destructor, we still have to consider entities
1317	      (like static variables) nested inside it.  */
1318	   || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (dtor))
1319    write_string ("D1");
1320  else if (DECL_BASE_DESTRUCTOR_P (dtor))
1321    write_string ("D2");
1322  else
1323    abort ();
1324}
1325
1326/* Return the discriminator for ENTITY appearing inside
1327   FUNCTION.  The discriminator is the lexical ordinal of VAR among
1328   entities with the same name in the same FUNCTION.  */
1329
1330static int
1331discriminator_for_local_entity (entity)
1332     tree entity;
1333{
1334  tree *type;
1335  int discriminator;
1336
1337  /* Assume this is the only local entity with this name.  */
1338  discriminator = 0;
1339
1340  if (DECL_DISCRIMINATOR_P (entity) && DECL_LANG_SPECIFIC (entity))
1341    discriminator = DECL_DISCRIMINATOR (entity);
1342  else if (TREE_CODE (entity) == TYPE_DECL)
1343    {
1344      /* Scan the list of local classes.  */
1345      entity = TREE_TYPE (entity);
1346      for (type = &VARRAY_TREE (local_classes, 0); *type != entity; ++type)
1347        if (TYPE_IDENTIFIER (*type) == TYPE_IDENTIFIER (entity)
1348            && TYPE_CONTEXT (*type) == TYPE_CONTEXT (entity))
1349	  ++discriminator;
1350    }
1351
1352  return discriminator;
1353}
1354
1355/* Return the discriminator for STRING, a string literal used inside
1356   FUNCTION.  The disciminator is the lexical ordinal of STRING among
1357   string literals used in FUNCTION.  */
1358
1359static int
1360discriminator_for_string_literal (function, string)
1361     tree function ATTRIBUTE_UNUSED;
1362     tree string ATTRIBUTE_UNUSED;
1363{
1364  /* For now, we don't discriminate amongst string literals.  */
1365  return 0;
1366}
1367
1368/*   <discriminator> := _ <number>
1369
1370   The discriminator is used only for the second and later occurrences
1371   of the same name within a single function. In this case <number> is
1372   n - 2, if this is the nth occurrence, in lexical order.  */
1373
1374static void
1375write_discriminator (discriminator)
1376     int discriminator;
1377{
1378  /* If discriminator is zero, don't write anything.  Otherwise...  */
1379  if (discriminator > 0)
1380    {
1381      write_char ('_');
1382      write_unsigned_number (discriminator - 1);
1383    }
1384}
1385
1386/* Mangle the name of a function-scope entity.  FUNCTION is the
1387   FUNCTION_DECL for the enclosing function.  ENTITY is the decl for
1388   the entity itself.  LOCAL_ENTITY is the entity that's directly
1389   scoped in FUNCTION_DECL, either ENTITY itself or an enclosing scope
1390   of ENTITY.
1391
1392     <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1393                  := Z <function encoding> E s [<discriminator>]  */
1394
1395static void
1396write_local_name (function, local_entity, entity)
1397     tree function;
1398     tree local_entity;
1399     tree entity;
1400{
1401  MANGLE_TRACE_TREE ("local-name", entity);
1402
1403  write_char ('Z');
1404  write_encoding (function);
1405  write_char ('E');
1406  if (TREE_CODE (entity) == STRING_CST)
1407    {
1408      write_char ('s');
1409      write_discriminator (discriminator_for_string_literal (function,
1410							     entity));
1411    }
1412  else
1413    {
1414      /* Now the <entity name>.  Let write_name know its being called
1415	 from <local-name>, so it doesn't try to process the enclosing
1416	 function scope again.  */
1417      write_name (entity, /*ignore_local_scope=*/1);
1418      write_discriminator (discriminator_for_local_entity (local_entity));
1419    }
1420}
1421
1422/* Non-terminals <type> and <CV-qualifier>.
1423
1424     <type> ::= <builtin-type>
1425            ::= <function-type>
1426            ::= <class-enum-type>
1427            ::= <array-type>
1428            ::= <pointer-to-member-type>
1429            ::= <template-param>
1430            ::= <substitution>
1431            ::= <CV-qualifier>
1432            ::= P <type>    # pointer-to
1433            ::= R <type>    # reference-to
1434            ::= C <type>    # complex pair (C 2000)
1435            ::= G <type>    # imaginary (C 2000)     [not supported]
1436            ::= U <source-name> <type>   # vendor extended type qualifier
1437
1438   TYPE is a type node.  */
1439
1440static void
1441write_type (type)
1442     tree type;
1443{
1444  /* This gets set to nonzero if TYPE turns out to be a (possibly
1445     CV-qualified) builtin type.  */
1446  int is_builtin_type = 0;
1447
1448  MANGLE_TRACE_TREE ("type", type);
1449
1450  if (type == error_mark_node)
1451    return;
1452
1453  if (find_substitution (type))
1454    return;
1455
1456  if (write_CV_qualifiers_for_type (type) > 0)
1457    /* If TYPE was CV-qualified, we just wrote the qualifiers; now
1458       mangle the unqualified type.  The recursive call is needed here
1459       since both the qualified and uqualified types are substitution
1460       candidates.  */
1461    write_type (TYPE_MAIN_VARIANT (type));
1462  else if (TREE_CODE (type) == ARRAY_TYPE)
1463    /* It is important not to use the TYPE_MAIN_VARIANT of TYPE here
1464       so that the cv-qualification of the element type is available
1465       in write_array_type.  */
1466    write_array_type (type);
1467  else
1468    {
1469      /* See through any typedefs.  */
1470      type = TYPE_MAIN_VARIANT (type);
1471
1472      switch (TREE_CODE (type))
1473	{
1474	case VOID_TYPE:
1475	case BOOLEAN_TYPE:
1476	case INTEGER_TYPE:  /* Includes wchar_t.  */
1477	case REAL_TYPE:
1478	  /* If this is a typedef, TYPE may not be one of
1479	     the standard builtin type nodes, but an alias of one.  Use
1480	     TYPE_MAIN_VARIANT to get to the underlying builtin type.  */
1481	  write_builtin_type (TYPE_MAIN_VARIANT (type));
1482	  ++is_builtin_type;
1483	  break;
1484
1485	case COMPLEX_TYPE:
1486	  write_char ('C');
1487	  write_type (TREE_TYPE (type));
1488	  break;
1489
1490	case FUNCTION_TYPE:
1491	case METHOD_TYPE:
1492	  write_function_type (type);
1493	  break;
1494
1495	case UNION_TYPE:
1496	case RECORD_TYPE:
1497	case ENUMERAL_TYPE:
1498	  /* A pointer-to-member function is represented as a special
1499	     RECORD_TYPE, so check for this first.  */
1500	  if (TYPE_PTRMEMFUNC_P (type))
1501	    write_pointer_to_member_type (type);
1502	  else
1503	    write_class_enum_type (type);
1504	  break;
1505
1506	case TYPENAME_TYPE:
1507	case UNBOUND_CLASS_TEMPLATE:
1508	  /* We handle TYPENAME_TYPEs and UNBOUND_CLASS_TEMPLATEs like
1509	     ordinary nested names.  */
1510	  write_nested_name (TYPE_STUB_DECL (type));
1511	  break;
1512
1513	case POINTER_TYPE:
1514	  /* A pointer-to-member variable is represented by a POINTER_TYPE
1515	     to an OFFSET_TYPE, so check for this first.  */
1516	  if (TYPE_PTRMEM_P (type))
1517	    write_pointer_to_member_type (type);
1518	  else
1519	    {
1520	      write_char ('P');
1521	      write_type (TREE_TYPE (type));
1522	    }
1523	  break;
1524
1525	case REFERENCE_TYPE:
1526	  write_char ('R');
1527	  write_type (TREE_TYPE (type));
1528	  break;
1529
1530	case TEMPLATE_TYPE_PARM:
1531	case TEMPLATE_PARM_INDEX:
1532	  write_template_param (type);
1533	  break;
1534
1535	case TEMPLATE_TEMPLATE_PARM:
1536	  write_template_template_param (type);
1537	  break;
1538
1539	case BOUND_TEMPLATE_TEMPLATE_PARM:
1540	  write_template_template_param (type);
1541	  write_template_args
1542	    (TI_ARGS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (type)));
1543	  break;
1544
1545	case OFFSET_TYPE:
1546	  write_pointer_to_member_type (build_pointer_type (type));
1547	  break;
1548
1549	case VECTOR_TYPE:
1550	  write_string ("U8__vector");
1551	  write_type (TREE_TYPE (type));
1552	  break;
1553
1554	default:
1555	  abort ();
1556	}
1557    }
1558
1559  /* Types other than builtin types are substitution candidates.  */
1560  if (!is_builtin_type)
1561    add_substitution (type);
1562}
1563
1564/* Non-terminal <CV-qualifiers> for type nodes.  Returns the number of
1565   CV-qualifiers written for TYPE.
1566
1567     <CV-qualifiers> ::= [r] [V] [K]  */
1568
1569static int
1570write_CV_qualifiers_for_type (type)
1571     tree type;
1572{
1573  int num_qualifiers = 0;
1574
1575  /* The order is specified by:
1576
1577       "In cases where multiple order-insensitive qualifiers are
1578       present, they should be ordered 'K' (closest to the base type),
1579       'V', 'r', and 'U' (farthest from the base type) ..."
1580
1581     Note that we do not use cp_type_quals below; given "const
1582     int[3]", the "const" is emitted with the "int", not with the
1583     array.  */
1584
1585  if (TYPE_QUALS (type) & TYPE_QUAL_RESTRICT)
1586    {
1587      write_char ('r');
1588      ++num_qualifiers;
1589    }
1590  if (TYPE_QUALS (type) & TYPE_QUAL_VOLATILE)
1591    {
1592      write_char ('V');
1593      ++num_qualifiers;
1594    }
1595  if (TYPE_QUALS (type) & TYPE_QUAL_CONST)
1596    {
1597      write_char ('K');
1598      ++num_qualifiers;
1599    }
1600
1601  return num_qualifiers;
1602}
1603
1604/* Non-terminal <builtin-type>.
1605
1606     <builtin-type> ::= v   # void
1607                    ::= b   # bool
1608                    ::= w   # wchar_t
1609                    ::= c   # char
1610                    ::= a   # signed char
1611                    ::= h   # unsigned char
1612                    ::= s   # short
1613                    ::= t   # unsigned short
1614                    ::= i   # int
1615                    ::= j   # unsigned int
1616                    ::= l   # long
1617                    ::= m   # unsigned long
1618                    ::= x   # long long, __int64
1619                    ::= y   # unsigned long long, __int64
1620                    ::= n   # __int128
1621                    ::= o   # unsigned __int128
1622                    ::= f   # float
1623                    ::= d   # double
1624                    ::= e   # long double, __float80
1625                    ::= g   # __float128          [not supported]
1626                    ::= u <source-name>  # vendor extended type */
1627
1628static void
1629write_builtin_type (type)
1630     tree type;
1631{
1632  switch (TREE_CODE (type))
1633    {
1634    case VOID_TYPE:
1635      write_char ('v');
1636      break;
1637
1638    case BOOLEAN_TYPE:
1639      write_char ('b');
1640      break;
1641
1642    case INTEGER_TYPE:
1643      /* If this is size_t, get the underlying int type.  */
1644      if (TYPE_IS_SIZETYPE (type))
1645	type = TYPE_DOMAIN (type);
1646
1647      /* TYPE may still be wchar_t, since that isn't in
1648	 integer_type_nodes.  */
1649      if (type == wchar_type_node)
1650	write_char ('w');
1651      else if (TYPE_FOR_JAVA (type))
1652	write_java_integer_type_codes (type);
1653      else
1654	{
1655	  size_t itk;
1656	  /* Assume TYPE is one of the shared integer type nodes.  Find
1657	     it in the array of these nodes.  */
1658	iagain:
1659	  for (itk = 0; itk < itk_none; ++itk)
1660	    if (type == integer_types[itk])
1661	      {
1662		/* Print the corresponding single-letter code.  */
1663		write_char (integer_type_codes[itk]);
1664		break;
1665	      }
1666
1667	  if (itk == itk_none)
1668	    {
1669	      tree t = c_common_type_for_mode (TYPE_MODE (type),
1670					       TREE_UNSIGNED (type));
1671	      if (type == t)
1672		{
1673		  if (TYPE_PRECISION (type) == 128)
1674		    write_char (TREE_UNSIGNED (type) ? 'o' : 'n');
1675		  else
1676		    /* Couldn't find this type.  */
1677		    abort ();
1678		}
1679	      else
1680		{
1681		  type = t;
1682		  goto iagain;
1683		}
1684	    }
1685	}
1686      break;
1687
1688    case REAL_TYPE:
1689      if (type == float_type_node
1690	  || type == java_float_type_node)
1691	write_char ('f');
1692      else if (type == double_type_node
1693	       || type == java_double_type_node)
1694	write_char ('d');
1695      else if (type == long_double_type_node)
1696	write_char ('e');
1697      else
1698	abort ();
1699      break;
1700
1701    default:
1702      abort ();
1703    }
1704}
1705
1706/* Non-terminal <function-type>.  NODE is a FUNCTION_TYPE or
1707   METHOD_TYPE.  The return type is mangled before the parameter
1708   types.
1709
1710     <function-type> ::= F [Y] <bare-function-type> E   */
1711
1712static void
1713write_function_type (type)
1714     tree type;
1715{
1716  MANGLE_TRACE_TREE ("function-type", type);
1717
1718  /* For a pointer to member function, the function type may have
1719     cv-qualifiers, indicating the quals for the artificial 'this'
1720     parameter.  */
1721  if (TREE_CODE (type) == METHOD_TYPE)
1722    {
1723      /* The first parameter must be a POINTER_TYPE pointing to the
1724	 `this' parameter.  */
1725      tree this_type = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (type)));
1726      write_CV_qualifiers_for_type (this_type);
1727    }
1728
1729  write_char ('F');
1730  /* We don't track whether or not a type is `extern "C"'.  Note that
1731     you can have an `extern "C"' function that does not have
1732     `extern "C"' type, and vice versa:
1733
1734       extern "C" typedef void function_t();
1735       function_t f; // f has C++ linkage, but its type is
1736                     // `extern "C"'
1737
1738       typedef void function_t();
1739       extern "C" function_t f; // Vice versa.
1740
1741     See [dcl.link].  */
1742  write_bare_function_type (type, /*include_return_type_p=*/1,
1743			    /*decl=*/NULL);
1744  write_char ('E');
1745}
1746
1747/* Non-terminal <bare-function-type>.  TYPE is a FUNCTION_TYPE or
1748   METHOD_TYPE.  If INCLUDE_RETURN_TYPE is nonzero, the return value
1749   is mangled before the parameter types.  If non-NULL, DECL is
1750   FUNCTION_DECL for the function whose type is being emitted.
1751
1752     <bare-function-type> ::= </signature/ type>+  */
1753
1754static void
1755write_bare_function_type (type, include_return_type_p, decl)
1756     tree type;
1757     int include_return_type_p;
1758     tree decl;
1759{
1760  MANGLE_TRACE_TREE ("bare-function-type", type);
1761
1762  /* Mangle the return type, if requested.  */
1763  if (include_return_type_p)
1764    write_type (TREE_TYPE (type));
1765
1766  /* Now mangle the types of the arguments.  */
1767  write_method_parms (TYPE_ARG_TYPES (type),
1768		      TREE_CODE (type) == METHOD_TYPE,
1769		      decl);
1770}
1771
1772/* Write the mangled representation of a method parameter list of
1773   types given in PARM_TYPES.  If METHOD_P is nonzero, the function is
1774   considered a non-static method, and the this parameter is omitted.
1775   If non-NULL, DECL is the FUNCTION_DECL for the function whose
1776   parameters are being emitted.  */
1777
1778static void
1779write_method_parms (parm_types, method_p, decl)
1780     tree decl;
1781     tree parm_types;
1782     int method_p;
1783{
1784  tree first_parm_type;
1785  tree parm_decl = decl ? DECL_ARGUMENTS (decl) : NULL_TREE;
1786
1787  /* Assume this parameter type list is variable-length.  If it ends
1788     with a void type, then it's not.  */
1789  int varargs_p = 1;
1790
1791  /* If this is a member function, skip the first arg, which is the
1792     this pointer.
1793       "Member functions do not encode the type of their implicit this
1794       parameter."
1795
1796     Similarly, there's no need to mangle artificial parameters, like
1797     the VTT parameters for constructors and destructors.  */
1798  if (method_p)
1799    {
1800      parm_types = TREE_CHAIN (parm_types);
1801      parm_decl = parm_decl ? TREE_CHAIN (parm_decl) : NULL_TREE;
1802
1803      while (parm_decl && DECL_ARTIFICIAL (parm_decl))
1804	{
1805	  parm_types = TREE_CHAIN (parm_types);
1806	  parm_decl = TREE_CHAIN (parm_decl);
1807	}
1808    }
1809
1810  for (first_parm_type = parm_types;
1811       parm_types;
1812       parm_types = TREE_CHAIN (parm_types))
1813    {
1814      tree parm = TREE_VALUE (parm_types);
1815      if (parm == void_type_node)
1816	{
1817	  /* "Empty parameter lists, whether declared as () or
1818	     conventionally as (void), are encoded with a void parameter
1819	     (v)."  */
1820	  if (parm_types == first_parm_type)
1821	    write_type (parm);
1822	  /* If the parm list is terminated with a void type, it's
1823	     fixed-length.  */
1824	  varargs_p = 0;
1825	  /* A void type better be the last one.  */
1826	  my_friendly_assert (TREE_CHAIN (parm_types) == NULL, 20000523);
1827	}
1828      else
1829	write_type (parm);
1830    }
1831
1832  if (varargs_p)
1833    /* <builtin-type> ::= z  # ellipsis  */
1834    write_char ('z');
1835}
1836
1837/* <class-enum-type> ::= <name>  */
1838
1839static void
1840write_class_enum_type (type)
1841     tree type;
1842{
1843  write_name (TYPE_NAME (type), /*ignore_local_scope=*/0);
1844}
1845
1846/* Non-terminal <template-args>.  ARGS is a TREE_VEC of template
1847   arguments.
1848
1849     <template-args> ::= I <template-arg>+ E  */
1850
1851static void
1852write_template_args (args)
1853     tree args;
1854{
1855  MANGLE_TRACE_TREE ("template-args", args);
1856
1857  write_char ('I');
1858
1859  if (TREE_CODE (args) == TREE_VEC)
1860    {
1861      int i;
1862      int length = TREE_VEC_LENGTH (args);
1863      my_friendly_assert (length > 0, 20000422);
1864
1865      if (TREE_CODE (TREE_VEC_ELT (args, 0)) == TREE_VEC)
1866	{
1867	  /* We have nested template args.  We want the innermost template
1868	     argument list.  */
1869	  args = TREE_VEC_ELT (args, length - 1);
1870	  length = TREE_VEC_LENGTH (args);
1871	}
1872      for (i = 0; i < length; ++i)
1873	write_template_arg (TREE_VEC_ELT (args, i));
1874    }
1875  else
1876    {
1877      my_friendly_assert (TREE_CODE (args) == TREE_LIST, 20021014);
1878
1879      while (args)
1880	{
1881	  write_template_arg (TREE_VALUE (args));
1882	  args = TREE_CHAIN (args);
1883	}
1884    }
1885
1886  write_char ('E');
1887}
1888
1889/* <expression> ::= <unary operator-name> <expression>
1890		::= <binary operator-name> <expression> <expression>
1891		::= <expr-primary>
1892
1893   <expr-primary> ::= <template-param>
1894		  ::= L <type> <value number> E  # literal
1895		  ::= L <mangled-name> E         # external name
1896                  ::= sr <type> <unqualified-name>
1897                  ::= sr <type> <unqualified-name> <template-args> */
1898
1899static void
1900write_expression (expr)
1901     tree expr;
1902{
1903  enum tree_code code;
1904
1905  code = TREE_CODE (expr);
1906
1907  /* Handle pointers-to-members by making them look like expression
1908     nodes.  */
1909  if (code == PTRMEM_CST)
1910    {
1911      expr = build_nt (ADDR_EXPR,
1912		       build_nt (SCOPE_REF,
1913				 PTRMEM_CST_CLASS (expr),
1914				 PTRMEM_CST_MEMBER (expr)));
1915      code = TREE_CODE (expr);
1916    }
1917
1918  /* Skip NOP_EXPRs.  They can occur when (say) a pointer argument
1919     is converted (via qualification conversions) to another
1920     type.  */
1921  while (TREE_CODE (expr) == NOP_EXPR
1922	 || TREE_CODE (expr) == NON_LVALUE_EXPR)
1923    {
1924      expr = TREE_OPERAND (expr, 0);
1925      code = TREE_CODE (expr);
1926    }
1927
1928  /* Handle template parameters.  */
1929  if (code == TEMPLATE_TYPE_PARM
1930      || code == TEMPLATE_TEMPLATE_PARM
1931      || code == BOUND_TEMPLATE_TEMPLATE_PARM
1932      || code == TEMPLATE_PARM_INDEX)
1933    write_template_param (expr);
1934  /* Handle literals.  */
1935  else if (TREE_CODE_CLASS (code) == 'c'
1936	   || (abi_version_at_least (2) && code == CONST_DECL))
1937    write_template_arg_literal (expr);
1938  else if (DECL_P (expr))
1939    {
1940      /* G++ 3.2 incorrectly mangled non-type template arguments of
1941	 enumeration type using their names.  */
1942      if (code == CONST_DECL)
1943	G.need_abi_warning = 1;
1944      write_char ('L');
1945      write_mangled_name (expr);
1946      write_char ('E');
1947    }
1948  else if (TREE_CODE (expr) == SIZEOF_EXPR
1949	   && TYPE_P (TREE_OPERAND (expr, 0)))
1950    {
1951      write_string ("st");
1952      write_type (TREE_OPERAND (expr, 0));
1953    }
1954  else if (abi_version_at_least (2) && TREE_CODE (expr) == SCOPE_REF)
1955    {
1956      tree scope = TREE_OPERAND (expr, 0);
1957      tree member = TREE_OPERAND (expr, 1);
1958
1959      /* If the MEMBER is a real declaration, then the qualifying
1960	 scope was not dependent.  Ideally, we would not have a
1961	 SCOPE_REF in those cases, but sometimes we do.  If the second
1962	 argument is a DECL, then the name must not have been
1963	 dependent.  */
1964      if (DECL_P (member))
1965	write_expression (member);
1966      else
1967	{
1968	  tree template_args;
1969
1970	  write_string ("sr");
1971	  write_type (scope);
1972	  /* If MEMBER is a template-id, separate the template
1973	     from the arguments.  */
1974	  if (TREE_CODE (member) == TEMPLATE_ID_EXPR)
1975	    {
1976	      template_args = TREE_OPERAND (member, 1);
1977	      member = TREE_OPERAND (member, 0);
1978	      if (TREE_CODE (member) == LOOKUP_EXPR)
1979		member = TREE_OPERAND (member, 0);
1980	    }
1981	  else
1982	    template_args = NULL_TREE;
1983	  /* Write out the name of the MEMBER.  */
1984	  if (IDENTIFIER_TYPENAME_P (member))
1985	    write_conversion_operator_name (TREE_TYPE (member));
1986	  else if (IDENTIFIER_OPNAME_P (member))
1987	    {
1988	      int i;
1989	      const char *mangled_name = NULL;
1990
1991	      /* Unfortunately, there is no easy way to go from the
1992		 name of the operator back to the corresponding tree
1993		 code.  */
1994	      for (i = 0; i < LAST_CPLUS_TREE_CODE; ++i)
1995		if (operator_name_info[i].identifier == member)
1996		  {
1997		    /* The ABI says that we prefer binary operator
1998		       names to unary operator names.  */
1999		    if (operator_name_info[i].arity == 2)
2000		      {
2001			mangled_name = operator_name_info[i].mangled_name;
2002			break;
2003		      }
2004		    else if (!mangled_name)
2005		      mangled_name = operator_name_info[i].mangled_name;
2006		  }
2007		else if (assignment_operator_name_info[i].identifier
2008			 == member)
2009		  {
2010		    mangled_name
2011		      = assignment_operator_name_info[i].mangled_name;
2012		    break;
2013		  }
2014	      write_string (mangled_name);
2015	    }
2016	  else
2017	    write_source_name (member);
2018	  /* Write out the template arguments.  */
2019	  if (template_args)
2020	    write_template_args (template_args);
2021	}
2022    }
2023  else
2024    {
2025      int i;
2026
2027      /* When we bind a variable or function to a non-type template
2028	 argument with reference type, we create an ADDR_EXPR to show
2029	 the fact that the entity's address has been taken.  But, we
2030	 don't actually want to output a mangling code for the `&'.  */
2031      if (TREE_CODE (expr) == ADDR_EXPR
2032	  && TREE_TYPE (expr)
2033	  && TREE_CODE (TREE_TYPE (expr)) == REFERENCE_TYPE)
2034	{
2035	  expr = TREE_OPERAND (expr, 0);
2036	  if (DECL_P (expr))
2037	    {
2038	      write_expression (expr);
2039	      return;
2040	    }
2041
2042	  code = TREE_CODE (expr);
2043	}
2044
2045      /* If it wasn't any of those, recursively expand the expression.  */
2046      write_string (operator_name_info[(int) code].mangled_name);
2047
2048      switch (code)
2049	{
2050        case CALL_EXPR:
2051          sorry ("call_expr cannot be mangled due to a defect in the C++ ABI");
2052          break;
2053
2054	case CAST_EXPR:
2055	  write_type (TREE_TYPE (expr));
2056	  write_expression (TREE_VALUE (TREE_OPERAND (expr, 0)));
2057	  break;
2058
2059	case STATIC_CAST_EXPR:
2060	case CONST_CAST_EXPR:
2061	  write_type (TREE_TYPE (expr));
2062	  write_expression (TREE_OPERAND (expr, 0));
2063	  break;
2064
2065
2066	/* Handle pointers-to-members specially.  */
2067	case SCOPE_REF:
2068	  write_type (TREE_OPERAND (expr, 0));
2069	  if (TREE_CODE (TREE_OPERAND (expr, 1)) == IDENTIFIER_NODE)
2070	    write_source_name (TREE_OPERAND (expr, 1));
2071	  else
2072	    {
2073	      /* G++ 3.2 incorrectly put out both the "sr" code and
2074		 the nested name of the qualified name.  */
2075	      G.need_abi_warning = 1;
2076	      write_encoding (TREE_OPERAND (expr, 1));
2077	    }
2078	  break;
2079
2080	default:
2081	  for (i = 0; i < TREE_CODE_LENGTH (code); ++i)
2082	    write_expression (TREE_OPERAND (expr, i));
2083	}
2084    }
2085}
2086
2087/* Literal subcase of non-terminal <template-arg>.
2088
2089     "Literal arguments, e.g. "A<42L>", are encoded with their type
2090     and value. Negative integer values are preceded with "n"; for
2091     example, "A<-42L>" becomes "1AILln42EE". The bool value false is
2092     encoded as 0, true as 1."  */
2093
2094static void
2095write_template_arg_literal (value)
2096     tree value;
2097{
2098  tree type = TREE_TYPE (value);
2099  write_char ('L');
2100  write_type (type);
2101
2102  if (TREE_CODE (value) == CONST_DECL)
2103    write_integer_cst (DECL_INITIAL (value));
2104  else if (TREE_CODE (value) == INTEGER_CST)
2105    {
2106      if (same_type_p (type, boolean_type_node))
2107	{
2108	  if (value == boolean_false_node || integer_zerop (value))
2109	    write_unsigned_number (0);
2110	  else if (value == boolean_true_node)
2111	    write_unsigned_number (1);
2112	  else
2113	    abort ();
2114	}
2115      else
2116	write_integer_cst (value);
2117    }
2118  else if (TREE_CODE (value) == REAL_CST)
2119    write_real_cst (value);
2120  else
2121    abort ();
2122
2123  write_char ('E');
2124}
2125
2126/* Non-terminal <tempalate-arg>.
2127
2128     <template-arg> ::= <type>                        # type
2129                    ::= L <type> </value/ number> E   # literal
2130                    ::= LZ <name> E                   # external name
2131                    ::= X <expression> E              # expression  */
2132
2133static void
2134write_template_arg (node)
2135     tree node;
2136{
2137  enum tree_code code = TREE_CODE (node);
2138
2139  MANGLE_TRACE_TREE ("template-arg", node);
2140
2141  /* A template template paramter's argument list contains TREE_LIST
2142     nodes of which the value field is the the actual argument.  */
2143  if (code == TREE_LIST)
2144    {
2145      node = TREE_VALUE (node);
2146      /* If it's a decl, deal with its type instead.  */
2147      if (DECL_P (node))
2148	{
2149	  node = TREE_TYPE (node);
2150	  code = TREE_CODE (node);
2151	}
2152    }
2153
2154  if (TYPE_P (node))
2155    write_type (node);
2156  else if (code == TEMPLATE_DECL)
2157    /* A template appearing as a template arg is a template template arg.  */
2158    write_template_template_arg (node);
2159  else if ((TREE_CODE_CLASS (code) == 'c' && code != PTRMEM_CST)
2160	   || (abi_version_at_least (2) && code == CONST_DECL))
2161    write_template_arg_literal (node);
2162  else if (DECL_P (node))
2163    {
2164      /* G++ 3.2 incorrectly mangled non-type template arguments of
2165	 enumeration type using their names.  */
2166      if (code == CONST_DECL)
2167	G.need_abi_warning = 1;
2168      write_char ('L');
2169      write_char ('Z');
2170      write_encoding (node);
2171      write_char ('E');
2172    }
2173  else
2174    {
2175      /* Template arguments may be expressions.  */
2176      write_char ('X');
2177      write_expression (node);
2178      write_char ('E');
2179    }
2180}
2181
2182/*  <template-template-arg>
2183			::= <name>
2184			::= <substitution>  */
2185
2186void
2187write_template_template_arg (tree decl)
2188{
2189  MANGLE_TRACE_TREE ("template-template-arg", decl);
2190
2191  if (find_substitution (decl))
2192    return;
2193  write_name (decl, /*ignore_local_scope=*/0);
2194  add_substitution (decl);
2195}
2196
2197
2198/* Non-terminal <array-type>.  TYPE is an ARRAY_TYPE.
2199
2200     <array-type> ::= A [</dimension/ number>] _ </element/ type>
2201                  ::= A <expression> _ </element/ type>
2202
2203     "Array types encode the dimension (number of elements) and the
2204     element type. For variable length arrays, the dimension (but not
2205     the '_' separator) is omitted."  */
2206
2207static void
2208write_array_type (type)
2209  tree type;
2210{
2211  write_char ('A');
2212  if (TYPE_DOMAIN (type))
2213    {
2214      tree index_type;
2215      tree max;
2216
2217      index_type = TYPE_DOMAIN (type);
2218      /* The INDEX_TYPE gives the upper and lower bounds of the
2219	 array.  */
2220      max = TYPE_MAX_VALUE (index_type);
2221      if (TREE_CODE (max) == INTEGER_CST)
2222	{
2223	  /* The ABI specifies that we should mangle the number of
2224	     elements in the array, not the largest allowed index.  */
2225	  max = size_binop (PLUS_EXPR, max, size_one_node);
2226	  write_unsigned_number (tree_low_cst (max, 1));
2227	}
2228      else
2229	write_expression (TREE_OPERAND (max, 0));
2230    }
2231  write_char ('_');
2232  write_type (TREE_TYPE (type));
2233}
2234
2235/* Non-terminal <pointer-to-member-type> for pointer-to-member
2236   variables.  TYPE is a pointer-to-member POINTER_TYPE.
2237
2238     <pointer-to-member-type> ::= M </class/ type> </member/ type>  */
2239
2240static void
2241write_pointer_to_member_type (type)
2242     tree type;
2243{
2244  write_char ('M');
2245  write_type (TYPE_PTRMEM_CLASS_TYPE (type));
2246  write_type (TYPE_PTRMEM_POINTED_TO_TYPE (type));
2247}
2248
2249/* Non-terminal <template-param>.  PARM is a TEMPLATE_TYPE_PARM,
2250   TEMPLATE_TEMPLATE_PARM, BOUND_TEMPLATE_TEMPLATE_PARM or a
2251   TEMPLATE_PARM_INDEX.
2252
2253     <template-param> ::= T </parameter/ number> _
2254
2255   If we are internally mangling then we distinguish level and, for
2256   non-type parms, type too. The mangling appends
2257
2258     </level/ number> _ </non-type type/ type> _
2259
2260   This is used by mangle_conv_op_name_for_type.  */
2261
2262static void
2263write_template_param (parm)
2264     tree parm;
2265{
2266  int parm_index;
2267  int parm_level;
2268  tree parm_type = NULL_TREE;
2269
2270  MANGLE_TRACE_TREE ("template-parm", parm);
2271
2272  switch (TREE_CODE (parm))
2273    {
2274    case TEMPLATE_TYPE_PARM:
2275    case TEMPLATE_TEMPLATE_PARM:
2276    case BOUND_TEMPLATE_TEMPLATE_PARM:
2277      parm_index = TEMPLATE_TYPE_IDX (parm);
2278      parm_level = TEMPLATE_TYPE_LEVEL (parm);
2279      break;
2280
2281    case TEMPLATE_PARM_INDEX:
2282      parm_index = TEMPLATE_PARM_IDX (parm);
2283      parm_level = TEMPLATE_PARM_LEVEL (parm);
2284      parm_type = TREE_TYPE (TEMPLATE_PARM_DECL (parm));
2285      break;
2286
2287    default:
2288      abort ();
2289    }
2290
2291  write_char ('T');
2292  /* NUMBER as it appears in the mangling is (-1)-indexed, with the
2293     earliest template param denoted by `_'.  */
2294  if (parm_index > 0)
2295    write_unsigned_number (parm_index - 1);
2296  write_char ('_');
2297}
2298
2299/*  <template-template-param>
2300                        ::= <template-param>
2301			::= <substitution>  */
2302
2303static void
2304write_template_template_param (parm)
2305     tree parm;
2306{
2307  tree template = NULL_TREE;
2308
2309  /* PARM, a TEMPLATE_TEMPLATE_PARM, is an instantiation of the
2310     template template parameter.  The substitution candidate here is
2311     only the template.  */
2312  if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
2313    {
2314      template
2315	= TI_TEMPLATE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm));
2316      if (find_substitution (template))
2317	return;
2318    }
2319
2320  /* <template-param> encodes only the template parameter position,
2321     not its template arguments, which is fine here.  */
2322  write_template_param (parm);
2323  if (template)
2324    add_substitution (template);
2325}
2326
2327/* Non-terminal <substitution>.
2328
2329      <substitution> ::= S <seq-id> _
2330                     ::= S_  */
2331
2332static void
2333write_substitution (seq_id)
2334     int seq_id;
2335{
2336  MANGLE_TRACE ("substitution", "");
2337
2338  write_char ('S');
2339  if (seq_id > 0)
2340    write_number (seq_id - 1, /*unsigned=*/1, 36);
2341  write_char ('_');
2342}
2343
2344/* Start mangling ENTITY.  */
2345
2346static inline void
2347start_mangling (tree entity)
2348{
2349  G.entity = entity;
2350  G.need_abi_warning = false;
2351  VARRAY_TREE_INIT (G.substitutions, 1, "mangling substitutions");
2352  obstack_free (&G.name_obstack, obstack_base (&G.name_obstack));
2353}
2354
2355/* Done with mangling.  Return the generated mangled name.  If WARN is
2356   true, and the name of G.entity will be mangled differently in a
2357   future version of the ABI, issue a warning.  */
2358
2359static inline const char *
2360finish_mangling (bool warn)
2361{
2362  if (warn_abi && warn && G.need_abi_warning)
2363    warning ("the mangled name of `%D' will change in a future "
2364	     "version of GCC",
2365	     G.entity);
2366
2367  /* Clear all the substitutions.  */
2368  G.substitutions = 0;
2369
2370  /* Null-terminate the string.  */
2371  write_char ('\0');
2372
2373  return (const char *) obstack_base (&G.name_obstack);
2374}
2375
2376/* Initialize data structures for mangling.  */
2377
2378void
2379init_mangle ()
2380{
2381  gcc_obstack_init (&G.name_obstack);
2382
2383  /* Cache these identifiers for quick comparison when checking for
2384     standard substitutions.  */
2385  subst_identifiers[SUBID_ALLOCATOR] = get_identifier ("allocator");
2386  subst_identifiers[SUBID_BASIC_STRING] = get_identifier ("basic_string");
2387  subst_identifiers[SUBID_CHAR_TRAITS] = get_identifier ("char_traits");
2388  subst_identifiers[SUBID_BASIC_ISTREAM] = get_identifier ("basic_istream");
2389  subst_identifiers[SUBID_BASIC_OSTREAM] = get_identifier ("basic_ostream");
2390  subst_identifiers[SUBID_BASIC_IOSTREAM] = get_identifier ("basic_iostream");
2391}
2392
2393/* Generate the mangled name of DECL.  */
2394
2395static const char *
2396mangle_decl_string (decl)
2397     tree decl;
2398{
2399  const char *result;
2400
2401  start_mangling (decl);
2402
2403  if (TREE_CODE (decl) == TYPE_DECL)
2404    write_type (TREE_TYPE (decl));
2405  else if (/* The names of `extern "C"' functions are not mangled.  */
2406	   (DECL_EXTERN_C_FUNCTION_P (decl)
2407	    /* But overloaded operator names *are* mangled.  */
2408	    && !DECL_OVERLOADED_OPERATOR_P (decl))
2409	   /* The names of global variables aren't mangled either.  */
2410	   || (TREE_CODE (decl) == VAR_DECL
2411	       && CP_DECL_CONTEXT (decl) == global_namespace)
2412	   /* And neither are `extern "C"' variables.  */
2413	   || (TREE_CODE (decl) == VAR_DECL
2414	       && DECL_EXTERN_C_P (decl)))
2415    write_string (IDENTIFIER_POINTER (DECL_NAME (decl)));
2416  else
2417    {
2418      write_mangled_name (decl);
2419      if (DECL_LANG_SPECIFIC (decl)
2420	  && (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl)
2421	      || DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)))
2422	/* We need a distinct mangled name for these entities, but
2423	   we should never actually output it.  So, we append some
2424	   characters the assembler won't like.  */
2425	write_string (" *INTERNAL* ");
2426    }
2427
2428  result = finish_mangling (/*warn=*/true);
2429  if (DEBUG_MANGLE)
2430    fprintf (stderr, "mangle_decl_string = '%s'\n\n", result);
2431  return result;
2432}
2433
2434/* Create an identifier for the external mangled name of DECL.  */
2435
2436void
2437mangle_decl (decl)
2438     tree decl;
2439{
2440  tree id = get_identifier (mangle_decl_string (decl));
2441
2442  SET_DECL_ASSEMBLER_NAME (decl, id);
2443}
2444
2445/* Generate the mangled representation of TYPE.  */
2446
2447const char *
2448mangle_type_string (type)
2449     tree type;
2450{
2451  const char *result;
2452
2453  start_mangling (type);
2454  write_type (type);
2455  result = finish_mangling (/*warn=*/false);
2456  if (DEBUG_MANGLE)
2457    fprintf (stderr, "mangle_type_string = '%s'\n\n", result);
2458  return result;
2459}
2460
2461/* Create an identifier for the mangled representation of TYPE.  */
2462
2463tree
2464mangle_type (type)
2465     tree type;
2466{
2467  return get_identifier (mangle_type_string (type));
2468}
2469
2470/* Create an identifier for the mangled name of a special component
2471   for belonging to TYPE.  CODE is the ABI-specified code for this
2472   component.  */
2473
2474static tree
2475mangle_special_for_type (type, code)
2476     tree type;
2477     const char *code;
2478{
2479  const char *result;
2480
2481  /* We don't have an actual decl here for the special component, so
2482     we can't just process the <encoded-name>.  Instead, fake it.  */
2483  start_mangling (type);
2484
2485  /* Start the mangling.  */
2486  write_string ("_Z");
2487  write_string (code);
2488
2489  /* Add the type.  */
2490  write_type (type);
2491  result = finish_mangling (/*warn=*/false);
2492
2493  if (DEBUG_MANGLE)
2494    fprintf (stderr, "mangle_special_for_type = %s\n\n", result);
2495
2496  return get_identifier (result);
2497}
2498
2499/* Create an identifier for the mangled representation of the typeinfo
2500   structure for TYPE.  */
2501
2502tree
2503mangle_typeinfo_for_type (type)
2504     tree type;
2505{
2506  return mangle_special_for_type (type, "TI");
2507}
2508
2509/* Create an identifier for the mangled name of the NTBS containing
2510   the mangled name of TYPE.  */
2511
2512tree
2513mangle_typeinfo_string_for_type (type)
2514     tree type;
2515{
2516  return mangle_special_for_type (type, "TS");
2517}
2518
2519/* Create an identifier for the mangled name of the vtable for TYPE.  */
2520
2521tree
2522mangle_vtbl_for_type (type)
2523     tree type;
2524{
2525  return mangle_special_for_type (type, "TV");
2526}
2527
2528/* Returns an identifier for the mangled name of the VTT for TYPE.  */
2529
2530tree
2531mangle_vtt_for_type (type)
2532     tree type;
2533{
2534  return mangle_special_for_type (type, "TT");
2535}
2536
2537/* Return an identifier for a construction vtable group.  TYPE is
2538   the most derived class in the hierarchy; BINFO is the base
2539   subobject for which this construction vtable group will be used.
2540
2541   This mangling isn't part of the ABI specification; in the ABI
2542   specification, the vtable group is dumped in the same COMDAT as the
2543   main vtable, and is referenced only from that vtable, so it doesn't
2544   need an external name.  For binary formats without COMDAT sections,
2545   though, we need external names for the vtable groups.
2546
2547   We use the production
2548
2549    <special-name> ::= CT <type> <offset number> _ <base type>  */
2550
2551tree
2552mangle_ctor_vtbl_for_type (type, binfo)
2553     tree type;
2554     tree binfo;
2555{
2556  const char *result;
2557
2558  start_mangling (type);
2559
2560  write_string ("_Z");
2561  write_string ("TC");
2562  write_type (type);
2563  write_integer_cst (BINFO_OFFSET (binfo));
2564  write_char ('_');
2565  write_type (BINFO_TYPE (binfo));
2566
2567  result = finish_mangling (/*warn=*/false);
2568  if (DEBUG_MANGLE)
2569    fprintf (stderr, "mangle_ctor_vtbl_for_type = %s\n\n", result);
2570  return get_identifier (result);
2571}
2572
2573/* Return an identifier for the mangled name of a thunk to FN_DECL.
2574   OFFSET is the initial adjustment to this used to find the vptr.  If
2575   VCALL_OFFSET is non-NULL, this is a virtual thunk, and it is the
2576   vtbl offset in bytes.
2577
2578    <special-name> ::= Th <offset number> _ <base encoding>
2579                   ::= Tv <offset number> _ <vcall offset number> _
2580		                                            <base encoding>
2581*/
2582
2583tree
2584mangle_thunk (fn_decl, offset, vcall_offset)
2585     tree fn_decl;
2586     tree offset;
2587     tree vcall_offset;
2588{
2589  const char *result;
2590
2591  start_mangling (fn_decl);
2592
2593  write_string ("_Z");
2594  /* The <special-name> for virtual thunks is Tv, for non-virtual
2595     thunks Th.  */
2596  write_char ('T');
2597  if (vcall_offset != 0)
2598    write_char ('v');
2599  else
2600    write_char ('h');
2601
2602  /* For either flavor, write the offset to this.  */
2603  write_integer_cst (offset);
2604  write_char ('_');
2605
2606  /* For a virtual thunk, add the vcall offset.  */
2607  if (vcall_offset)
2608    {
2609      /* Virtual thunk.  Write the vcall offset and base type name.  */
2610      write_integer_cst (vcall_offset);
2611      write_char ('_');
2612    }
2613
2614  /* Scoped name.  */
2615  write_encoding (fn_decl);
2616
2617  result = finish_mangling (/*warn=*/false);
2618  if (DEBUG_MANGLE)
2619    fprintf (stderr, "mangle_thunk = %s\n\n", result);
2620  return get_identifier (result);
2621}
2622
2623/* This hash table maps TYPEs to the IDENTIFIER for a conversion
2624   operator to TYPE.  The nodes are TREE_LISTs whose TREE_PURPOSE is
2625   the TYPE and whose TREE_VALUE is the IDENTIFIER.  */
2626
2627static GTY ((param_is (union tree_node))) htab_t conv_type_names;
2628
2629/* Hash a node (VAL1) in the table.  */
2630
2631static hashval_t
2632hash_type (const void *val)
2633{
2634  return htab_hash_pointer (TREE_PURPOSE ((tree) val));
2635}
2636
2637/* Compare VAL1 (a node in the table) with VAL2 (a TYPE).  */
2638
2639static int
2640compare_type (const void *val1, const void *val2)
2641{
2642  return TREE_PURPOSE ((tree) val1) == (tree) val2;
2643}
2644
2645/* Return an identifier for the mangled unqualified name for a
2646   conversion operator to TYPE.  This mangling is not specified by the
2647   ABI spec; it is only used internally.  */
2648
2649tree
2650mangle_conv_op_name_for_type (const tree type)
2651{
2652  void **slot;
2653  tree identifier;
2654  char buffer[64];
2655
2656  if (conv_type_names == NULL)
2657    conv_type_names = htab_create_ggc (31, &hash_type, &compare_type, NULL);
2658
2659  slot = htab_find_slot_with_hash (conv_type_names, type,
2660				   htab_hash_pointer (type), INSERT);
2661  if (*slot)
2662    return TREE_VALUE ((tree) *slot);
2663
2664  /* Create a unique name corresponding to TYPE.  */
2665  sprintf (buffer, "operator %lu",
2666	   (unsigned long) htab_elements (conv_type_names));
2667  identifier = get_identifier (buffer);
2668  *slot = build_tree_list (type, identifier);
2669
2670  /* Set bits on the identifier so we know later it's a conversion.  */
2671  IDENTIFIER_OPNAME_P (identifier) = 1;
2672  IDENTIFIER_TYPENAME_P (identifier) = 1;
2673  /* Hang TYPE off the identifier so it can be found easily later when
2674     performing conversions.  */
2675  TREE_TYPE (identifier) = type;
2676
2677  return identifier;
2678}
2679
2680/* Return an identifier for the name of an initialization guard
2681   variable for indicated VARIABLE.  */
2682
2683tree
2684mangle_guard_variable (variable)
2685     tree variable;
2686{
2687  start_mangling (variable);
2688  write_string ("_ZGV");
2689  if (strncmp (IDENTIFIER_POINTER (DECL_NAME (variable)), "_ZGR", 4) == 0)
2690    /* The name of a guard variable for a reference temporary should refer
2691       to the reference, not the temporary.  */
2692    write_string (IDENTIFIER_POINTER (DECL_NAME (variable)) + 4);
2693  else
2694    write_name (variable, /*ignore_local_scope=*/0);
2695  return get_identifier (finish_mangling (/*warn=*/false));
2696}
2697
2698/* Return an identifier for the name of a temporary variable used to
2699   initialize a static reference.  This isn't part of the ABI, but we might
2700   as well call them something readable.  */
2701
2702tree
2703mangle_ref_init_variable (variable)
2704     tree variable;
2705{
2706  start_mangling (variable);
2707  write_string ("_ZGR");
2708  write_name (variable, /*ignore_local_scope=*/0);
2709  return get_identifier (finish_mangling (/*warn=*/false));
2710}
2711
2712
2713/* Foreign language type mangling section.  */
2714
2715/* How to write the type codes for the integer Java type.  */
2716
2717static void
2718write_java_integer_type_codes (type)
2719     tree type;
2720{
2721  if (type == java_int_type_node)
2722    write_char ('i');
2723  else if (type == java_short_type_node)
2724    write_char ('s');
2725  else if (type == java_byte_type_node)
2726    write_char ('c');
2727  else if (type == java_char_type_node)
2728    write_char ('w');
2729  else if (type == java_long_type_node)
2730    write_char ('x');
2731  else if (type == java_boolean_type_node)
2732    write_char ('b');
2733  else
2734    abort ();
2735}
2736
2737#include "gt-cp-mangle.h"
2738