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