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