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