OSDN Git Service

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