OSDN Git Service

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