OSDN Git Service

* ir.texi: Correct typo.
[pf3gnuchains/gcc-fork.git] / gcc / cp / mangle.c
1 /* Name mangling for the new standard C++ ABI.
2    Copyright (C) 2000 Free Software Foundation, Inc.
3    Written by Alex Samuel <sameul@codesourcery.com>
4
5    This file is part of GNU CC.
6
7    GNU CC 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    GNU CC 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 GNU CC; 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 "tree.h"
53 #include "cp-tree.h"
54 #include "obstack.h"
55 #include "toplev.h"
56 #include "varray.h"
57
58 /* Debugging support.  */
59
60 /* Define DEBUG_MANGLE to enable very verbose trace messages.  */
61 #ifndef DEBUG_MANGLE
62 #define DEBUG_MANGLE 0
63 #endif
64
65 /* Macros for tracing the write_* functions.  */
66 #if DEBUG_MANGLE
67 # define MANGLE_TRACE(FN, INPUT) \
68   fprintf (stderr, "  %-24s: %-24s\n", FN, INPUT)
69 # define MANGLE_TRACE_TREE(FN, NODE) \
70   fprintf (stderr, "  %-24s: %-24s (%p)\n", \
71            FN, tree_code_name[TREE_CODE (NODE)], (void *) NODE)
72 #else
73 # define MANGLE_TRACE(FN, INPUT)
74 # define MANGLE_TRACE_TREE(FN, NODE)
75 #endif
76
77 /* Non-zero if NODE is a template-id.  */
78 #define DECL_TEMPLATE_ID_P(NODE)                                \
79   (DECL_LANG_SPECIFIC (NODE) != NULL                            \
80    && DECL_USE_TEMPLATE (NODE)                                  \
81    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (NODE)))
82
83 /* Non-zero if NODE is a class template-id.  */
84 #define CLASSTYPE_TEMPLATE_ID_P(NODE)                           \
85   (TYPE_LANG_SPECIFIC (NODE) != NULL                            \
86    && CLASSTYPE_USE_TEMPLATE (NODE)                             \
87    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (NODE)))
88
89 /* Things we only need one of.  This module is not reentrant.  */
90 static struct globals
91 {
92   /* The name in which we're building the mangled name.  */
93   struct obstack name_obstack;
94
95   /* The current innermost template args.  */
96   tree template_args;
97
98   /* An array of the current substitution candidates, in the order
99      we've seen them.  */
100   varray_type substitutions;
101 } G;
102
103 /* Indices into subst_identifiers.  These are identifiers used in
104    special substitution rules.  */
105 typedef enum
106 {
107   SUBID_ALLOCATOR,
108   SUBID_BASIC_STRING,
109   SUBID_CHAR_TRAITS,
110   SUBID_BASIC_ISTREAM,
111   SUBID_BASIC_OSTREAM,
112   SUBID_BASIC_IOSTREAM,
113   SUBID_MAX
114 }
115 substitution_identifier_index_t;
116
117 /* For quick substitution checks, look up these common identifiers
118    once only.  */
119 static tree subst_identifiers[SUBID_MAX];
120
121 /* Single-letter codes for builtin integer types, defined in
122    <builtin-type>.  These are indexed by integer_type_kind values.  */
123 static char
124 integer_type_codes[itk_none] =
125 {
126   'c',  /* itk_char */
127   'a',  /* itk_signed_char */
128   'h',  /* itk_unsigned_char */
129   's',  /* itk_short */
130   't',  /* itk_unsigned_short */
131   'i',  /* itk_int */
132   'j',  /* itk_unsigned_int */
133   'l',  /* itk_long */
134   'm',  /* itk_unsigned_long */
135   'x',  /* itk_long_long */
136   'y'   /* itk_unsigned_long_long */
137 };
138
139 /* Functions for handling substitutions.  */
140
141 static inline tree canonicalize_for_substitution PARAMS ((tree));
142 static void add_substitution PARAMS ((tree));
143 static inline int is_std_substitution PARAMS ((tree, substitution_identifier_index_t));
144 static inline int is_std_substitution_char PARAMS ((tree, substitution_identifier_index_t));
145 static int find_substitution PARAMS ((tree));
146
147 /* Functions for emitting mangled representations of things.  */
148
149 static void write_mangled_name PARAMS ((tree));
150 static void write_encoding PARAMS ((tree));
151 static void write_name PARAMS ((tree));
152 static void write_unscoped_name PARAMS ((tree));
153 static void write_unscoped_template_name PARAMS ((tree));
154 static void write_nested_name PARAMS ((tree));
155 static void write_prefix PARAMS ((tree));
156 static void write_template_prefix PARAMS ((tree));
157 static void write_component PARAMS ((tree));
158 static void write_unqualified_name PARAMS ((tree));
159 static void write_source_name PARAMS ((tree));
160 static void write_number PARAMS ((int, int));
161 static void write_integer_cst PARAMS ((tree));
162 static void write_identifier PARAMS ((char *));
163 static void write_special_name_constructor PARAMS ((tree));
164 static void write_special_name_destructor PARAMS ((tree));
165 static void write_type PARAMS ((tree));
166 static int write_CV_qualifiers_for_type PARAMS ((tree));
167 static void write_builtin_type PARAMS ((tree));
168 static void write_function_type PARAMS ((tree, int));
169 static void write_bare_function_type PARAMS ((tree, int));
170 static void write_method_parms PARAMS ((tree, int));
171 static void write_class_enum_type PARAMS ((tree));
172 static void write_template_args PARAMS ((tree));
173 static void write_expression PARAMS ((tree));
174 static void write_template_arg_literal PARAMS ((tree));
175 static void write_template_arg PARAMS ((tree));
176 static void write_template_template_arg PARAMS ((tree));
177 static void write_array_type PARAMS ((tree));
178 static void write_pointer_to_member_type PARAMS ((tree));
179 static void write_template_param PARAMS ((tree));
180 static void write_template_template_param PARAMS ((tree));
181 static void write_substitution PARAMS ((int));
182 static int discriminator_for_local_entity PARAMS ((tree));
183 static int discriminator_for_string_literal PARAMS ((tree, tree));
184 static void write_discriminator PARAMS ((int));
185 static void write_local_name PARAMS ((tree, tree));
186 static void dump_substitution_candidates PARAMS ((void));
187 static const char *mangle_decl_string PARAMS ((tree));
188
189 /* Control functions.  */
190
191 static inline void start_mangling PARAMS ((void));
192 static inline const char *finish_mangling PARAMS ((void));
193 static tree mangle_special_for_type PARAMS ((tree, const char *));
194
195 /* Append a single character to the end of the mangled
196    representation.  */
197 #define write_char(CHAR)                                              \
198   obstack_1grow (&G.name_obstack, (CHAR))
199
200 /* Append a NUL-terminated string to the end of the mangled
201    representation.  */
202 #define write_string(STRING)                                          \
203   obstack_grow (&G.name_obstack, (STRING), strlen (STRING))
204
205 /* Return the position at which the next character will be appended to
206    the mangled representation.  */
207 #define mangled_position()                                              \
208   obstack_object_size (&G.name_obstack)
209
210 /* Non-zero if NODE1__ and NODE2__ are both TREE_LIST nodes and have
211    the same purpose (context, which may be a type) and value (template
212    decl).  See write_template_prefix for more information on what this
213    is used for.  */
214 #define NESTED_TEMPLATE_MATCH(NODE1, NODE2)                         \
215   (TREE_CODE (NODE1) == TREE_LIST                                     \
216    && TREE_CODE (NODE2) == TREE_LIST                                  \
217    && ((TYPE_P (TREE_PURPOSE (NODE1))                                 \
218         && same_type_p (TREE_PURPOSE (NODE1), TREE_PURPOSE (NODE2)))\
219        || TREE_PURPOSE (NODE1) == TREE_PURPOSE (NODE2))             \
220    && TREE_VALUE (NODE1) == TREE_VALUE (NODE2))
221
222 /* Produce debugging output of current substitution candidates.  */
223
224 static void
225 dump_substitution_candidates ()
226 {
227   unsigned i;
228
229   fprintf (stderr, "  ++ substitutions  ");
230   for (i = 0; i < VARRAY_ACTIVE_SIZE (G.substitutions); ++i)
231     {
232       tree el = VARRAY_TREE (G.substitutions, i);
233       const char *name = "???";
234
235       if (i > 0)
236         fprintf (stderr, "                    ");
237       if (DECL_P (el))
238         name = IDENTIFIER_POINTER (DECL_NAME (el));
239       else if (TREE_CODE (el) == TREE_LIST)
240         name = IDENTIFIER_POINTER (DECL_NAME (TREE_VALUE (el)));
241       else if (TYPE_NAME (el))
242         name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (el)));
243       fprintf (stderr, " S%d_ = ", i - 1);
244       if (TYPE_P (el) && 
245           (CP_TYPE_RESTRICT_P (el) 
246            || CP_TYPE_VOLATILE_P (el) 
247            || CP_TYPE_CONST_P (el)))
248         fprintf (stderr, "CV-");
249       fprintf (stderr, "%s (%s at %p)\n", 
250                name, tree_code_name[TREE_CODE (el)], (void *) el);
251     }
252 }
253
254 /* Both decls and types can be substitution candidates, but sometimes
255    they refer to the same thing.  For instance, a TYPE_DECL and
256    RECORD_TYPE for the same class refer to the same thing, and should
257    be treated accordinginly in substitutions.  This function returns a
258    canonicalized tree node representing NODE that is used when adding
259    and substitution candidates and finding matches.  */
260
261 static inline tree
262 canonicalize_for_substitution (node)
263      tree node;
264 {
265   /* For a TYPE_DECL, use the type instead.  */
266   if (TREE_CODE (node) == TYPE_DECL)
267     node = TREE_TYPE (node);
268
269   return node;
270 }
271
272 /* Add NODE as a substitution candidate.  NODE must not already be on
273    the list of candidates.  */
274
275 static void
276 add_substitution (node)
277      tree node;
278 {
279   tree c;
280
281   if (DEBUG_MANGLE)
282     fprintf (stderr, "  ++ add_substitution (%s at %10p)\n", 
283              tree_code_name[TREE_CODE (node)], (void *) node);
284
285   /* Get the canonicalized substitution candidate for NODE.  */
286   c = canonicalize_for_substitution (node);
287   if (DEBUG_MANGLE && c != node)
288     fprintf (stderr, "  ++ using candidate (%s at %10p)\n",
289              tree_code_name[TREE_CODE (node)], (void *) node);
290   node = c;
291
292 #if ENABLE_CHECKING
293   /* Make sure NODE isn't already a candidate.  */
294   {
295     int i;
296     for (i = VARRAY_ACTIVE_SIZE (G.substitutions); --i >= 0; )
297       {
298         tree candidate = VARRAY_TREE (G.substitutions, i);
299         if ((DECL_P (node) 
300              && node == candidate)
301             || (TYPE_P (node) 
302                 && TYPE_P (candidate) 
303                 && same_type_p (node, candidate)))
304           my_friendly_abort (20000524);
305       }
306   }
307 #endif /* ENABLE_CHECKING */
308
309   /* Put the decl onto the varray of substitution candidates.  */
310   VARRAY_PUSH_TREE (G.substitutions, node);
311
312   if (DEBUG_MANGLE)
313     dump_substitution_candidates ();
314 }
315
316 /* Helper function for find_substitution.  Returns non-zero if NODE,
317    which may be a decl or a CLASS_TYPE, is a template-id with template
318    name of substitution_index[INDEX] in the ::std namespace.  */
319
320 static inline int 
321 is_std_substitution (node, index)
322      tree node;
323      substitution_identifier_index_t index;
324 {
325   tree type = NULL;
326   tree decl = NULL;
327
328   if (DECL_P (node))
329     {
330       type = TREE_TYPE (node);
331       decl = node;
332     }
333   else if (CLASS_TYPE_P (node))
334     {
335       type = node;
336       decl = TYPE_NAME (node);
337     }
338   else 
339     /* These are not the droids you're looking for.  */
340     return 0;
341
342   return 
343     DECL_NAMESPACE_STD_P (CP_DECL_CONTEXT (decl))
344     && TYPE_LANG_SPECIFIC (type) 
345     && CLASSTYPE_USE_TEMPLATE (type)
346     && (DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) 
347         == subst_identifiers[index]);
348 }
349
350 /* Helper function for find_substitution.  Returns non-zero if NODE,
351    which may be a decl or a CLASS_TYPE, is the template-id
352    ::std::identifier<char>, where identifier is
353    substitution_index[INDEX].  */
354
355 static inline int
356 is_std_substitution_char (node, index)
357      tree node;
358      substitution_identifier_index_t index;
359 {
360   tree args;
361   /* Check NODE's name is ::std::identifier.  */
362   if (!is_std_substitution (node, index))
363     return 0;
364   /* Figure out its template args.  */
365   if (DECL_P (node))
366     args = DECL_TI_ARGS (node);  
367   else if (CLASS_TYPE_P (node))
368     args = CLASSTYPE_TI_ARGS (node);
369   else
370     /* Oops, not a template.  */
371     return 0;
372   /* NODE's template arg list should be <char>.  */
373   return 
374     TREE_VEC_LENGTH (args) == 1
375     && TREE_VEC_ELT (args, 0) == char_type_node;
376 }
377
378 /* Check whether a substitution should be used to represent NODE in
379    the mangling.
380
381    First, check standard special-case substitutions.
382
383      <substitution> ::= St     
384          # ::std
385
386                     ::= Sa     
387          # ::std::allocator
388
389                     ::= Sb     
390          # ::std::basic_string
391
392                     ::= Ss 
393          # ::std::basic_string<char,
394                                ::std::char_traits<char>,
395                                ::std::allocator<char> >
396
397                     ::= Si 
398          # ::std::basic_istream<char, ::std::char_traits<char> >
399
400                     ::= So 
401          # ::std::basic_ostream<char, ::std::char_traits<char> >
402
403                     ::= Sd 
404          # ::std::basic_iostream<char, ::std::char_traits<char> >   
405
406    Then examine the stack of currently available substitution
407    candidates for entities appearing earlier in the same mangling
408
409    If a substitution is found, write its mangled representation and
410    return non-zero.  If none is found, just return zero.  */
411
412 static int
413 find_substitution (node)
414      tree node;
415 {
416   int i;
417   int size = VARRAY_ACTIVE_SIZE (G.substitutions);
418   tree decl;
419   tree type;
420
421   if (DEBUG_MANGLE)
422     fprintf (stderr, "  ++ find_substitution (%s at %p)\n",
423              tree_code_name[TREE_CODE (node)], (void *) node);
424
425   /* Obtain the canonicalized substitution representation for NODE.
426      This is what we'll compare against.  */
427   node = canonicalize_for_substitution (node);
428
429   /* Check for builtin substitutions.  */
430
431   decl = TYPE_P (node) ? TYPE_NAME (node) : node;
432   type = TYPE_P (node) ? node : TREE_TYPE (node);
433
434   /* Check for std::allocator.  */
435   if (decl && is_std_substitution (decl, SUBID_ALLOCATOR))
436     {
437       write_string ("Sa");
438       return 1;
439     }
440
441   /* Check for std::basic_string.  */
442   if (decl && is_std_substitution (decl, SUBID_BASIC_STRING))
443     {
444       if (type)
445         {
446           /* If this is a type (i.e. a fully-qualified template-id), 
447              check for 
448                  std::basic_string <char,
449                                     std::char_traits<char>,
450                                     std::allocator<char> > .  */
451           if (CP_TYPE_QUALS (type) == TYPE_UNQUALIFIED
452               && CLASSTYPE_USE_TEMPLATE (type))
453             {
454               tree args = CLASSTYPE_TI_ARGS (type);
455               if (TREE_VEC_LENGTH (args) == 3
456                   && TREE_VEC_ELT (args, 0) == char_type_node
457                   && is_std_substitution_char (TREE_VEC_ELT (args, 1),
458                                                SUBID_CHAR_TRAITS)
459                   && is_std_substitution_char (TREE_VEC_ELT (args, 2),
460                                                SUBID_ALLOCATOR))
461                 {
462                   write_string ("Ss");
463                   return 1;
464                 }
465             }
466         }
467       else
468         /* Substitute for the template name only if this isn't a type.  */
469         {
470           write_string ("Sb");
471           return 1;
472         }
473     }
474
475   /* Check for basic_{i,o,io}stream.  */
476   if (type
477       && CP_TYPE_QUALS (type) == TYPE_UNQUALIFIED
478       && CLASS_TYPE_P (type)
479       && CLASSTYPE_USE_TEMPLATE (type)
480       && CLASSTYPE_TEMPLATE_INFO (type) != NULL)
481     {
482       /* First, check for the template 
483          args <char, std::char_traits<char> > .  */
484       tree args = CLASSTYPE_TI_ARGS (type);
485       if (TREE_VEC_LENGTH (args) == 2
486           && TREE_VEC_ELT (args, 0) == char_type_node
487           && is_std_substitution_char (TREE_VEC_ELT (args, 1),
488                                        SUBID_CHAR_TRAITS))
489         {
490           /* Got them.  Is this basic_istream?  */
491           tree name = DECL_NAME (CLASSTYPE_TI_TEMPLATE (type));
492           if (name == subst_identifiers[SUBID_BASIC_ISTREAM])
493             {
494               write_string ("Si");
495               return 1;
496             }
497           /* Or basic_ostream?  */
498           else if (name == subst_identifiers[SUBID_BASIC_OSTREAM])
499             {
500               write_string ("So");
501               return 1;
502             }
503           /* Or basic_iostream?  */
504           else if (name == subst_identifiers[SUBID_BASIC_IOSTREAM])
505             {
506               write_string ("Sd");
507               return 1;
508             }
509         }
510     }
511
512   /* Check for namespace std.  */
513   if (decl&& DECL_NAMESPACE_STD_P (decl))
514     {
515       write_string ("St");
516       return 1;
517     }
518
519   /* Now check the list of available substitutions for this mangling
520      operation.    */
521
522   for (i = 0; i < size; ++i)
523     {
524       tree candidate = VARRAY_TREE (G.substitutions, i);
525       /* NODE is a matched to a candidate if it's the same decl node or
526          if it's the same type.  */
527       if (decl == candidate
528           || (TYPE_P (candidate) && type && TYPE_P (type)
529               && same_type_p (type, candidate))
530           || NESTED_TEMPLATE_MATCH (node, candidate))
531         {
532           write_substitution (i);
533           return 1;
534         }
535     }
536
537   /* No substitution found.  */
538   return 0;
539 }
540
541
542 /*  <mangled-name>      ::= _Z <encoding>  */
543
544 static inline void
545 write_mangled_name (decl)
546      tree decl;
547 {
548   MANGLE_TRACE_TREE ("mangled-name", decl);
549
550   if (DECL_LANG_SPECIFIC (decl) && DECL_EXTERN_C_FUNCTION_P (decl))
551     /* The standard notes:
552          "The <encoding> of an extern "C" function is treated like
553          global-scope data, i.e. as its <source-name> without a type."  */
554     write_source_name (DECL_NAME (decl));
555   else
556     /* C++ name; needs to be mangled.  */
557     {
558       write_string ("_Z");
559       write_encoding (decl);
560     }
561 }
562
563 /*   <encoding>         ::= <function name> <bare-function-type>
564                         ::= <data name>
565                         ::= <substitution>  */
566
567 static void
568 write_encoding (decl)
569      tree decl;
570 {
571   MANGLE_TRACE_TREE ("encoding", decl);
572
573   if (find_substitution (decl))
574     return;
575
576   if (DECL_LANG_SPECIFIC (decl) && DECL_EXTERN_C_FUNCTION_P (decl))
577     {
578       write_source_name (DECL_NAME (decl));
579       return;
580     }
581
582   write_name (decl);
583   if (TREE_CODE (decl) == FUNCTION_DECL)
584     {
585       tree fn_type;
586
587       if (DECL_TEMPLATE_ID_P (decl))
588         fn_type = get_mostly_instantiated_function_type (decl, NULL, NULL);
589       else
590         fn_type = TREE_TYPE (decl);
591
592       write_bare_function_type (fn_type, DECL_TEMPLATE_ID_P (decl));
593     }
594
595   add_substitution (decl);
596 }
597
598 /* <name> ::= <unscoped-name>
599           ::= <unscoped-template-name> <template-args>
600           ::= <nested-name>
601           ::= <local-name>  */
602
603 static void
604 write_name (decl)
605      tree decl;
606 {
607   tree context = CP_DECL_CONTEXT (decl);
608
609   MANGLE_TRACE_TREE ("name", decl);
610
611   /* Decls in :: or ::std scope are treated specially.  */
612   if (context == global_namespace || DECL_NAMESPACE_STD_P (context))
613     {
614       if (decl && DECL_TEMPLATE_ID_P (decl))
615         {
616           /* Templated decls get an <unqualified-template-name>.  */
617           write_unscoped_template_name (DECL_TI_TEMPLATE (decl));
618           write_template_args (DECL_TI_ARGS (decl));
619         }
620       else if (TREE_CODE (decl) == TYPE_DECL 
621                && CLASSTYPE_TEMPLATE_ID_P (TREE_TYPE (decl)))
622         {
623           tree type;
624
625           /* Templated decls get an <unqualified-template-name>.  */
626           type = TREE_TYPE (decl);
627           write_unscoped_template_name (TYPE_TI_TEMPLATE (type));
628           write_template_args (TYPE_TI_ARGS (type));
629         }
630       else
631         /* Everything else gets an <unqualified-name>.  */
632         write_unscoped_name (decl);
633     }
634   /* Handle local names.  */
635   else if (TREE_CODE (context) == FUNCTION_DECL)
636     write_local_name (context, decl);
637   /* Other decls get a <nested-name> to encode their scope.  */
638   else
639     write_nested_name (decl);
640 }
641
642 /* <unscoped-name> ::= <unqualified-name>
643                    ::= St <unqualified-name>   # ::std::  */
644
645 static void
646 write_unscoped_name (decl)
647      tree decl;
648 {
649   tree context = CP_DECL_CONTEXT (decl);
650
651   MANGLE_TRACE_TREE ("unscoped-name", decl);
652
653   /* Is DECL in ::std?  */
654   if (DECL_NAMESPACE_STD_P (context))
655     {
656       write_string ("St");
657       write_unqualified_name (decl);
658     }
659   /* If not, it should be in the global namespace.  */
660   else if (context == global_namespace || context == NULL)
661     write_unqualified_name (decl);
662   else 
663     my_friendly_abort (20000521);
664 }
665
666 /* <unscoped-template-name> ::= <unscoped-name>
667                             ::= <substitution>  */
668
669 static void
670 write_unscoped_template_name (decl)
671      tree decl;
672 {
673   MANGLE_TRACE_TREE ("unscoped-template-name", decl);
674
675   if (find_substitution (decl))
676     return;
677   write_unscoped_name (decl);
678   add_substitution (decl);
679 }
680
681 /* Write the nested name, including CV-qualifiers, of DECL.
682
683    <nested-name> ::= N [<CV-qualifiers>] <prefix> <component> E  
684                  ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
685
686    <CV-qualifiers> ::= [r] [V] [K]  */
687
688 static void
689 write_nested_name (decl)
690      tree decl;
691 {
692   MANGLE_TRACE_TREE ("nested-name", decl);
693
694   write_char ('N');
695   
696   /* Write CV-qualifiers, if this is a member function.  */
697   if (TREE_CODE (decl) == FUNCTION_DECL 
698       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
699     {
700       if (DECL_VOLATILE_MEMFUNC_P (decl))
701         write_char ('V');
702       if (DECL_CONST_MEMFUNC_P (decl))
703         write_char ('K');
704     }
705
706   if (DECL_TEMPLATE_ID_P (decl))
707     {
708       write_template_prefix (decl);
709       write_template_args (DECL_TI_ARGS (decl));
710     }
711   else if (CLASSTYPE_TEMPLATE_ID_P (TREE_TYPE (decl)))
712     {
713       write_template_prefix (decl);
714       write_template_args (CLASSTYPE_TI_ARGS (TREE_TYPE (decl)));
715     }
716   else
717     {
718       write_prefix (DECL_CONTEXT (decl));
719       write_component (decl);
720     }
721   write_char ('E');
722 }
723
724 /* <prefix> ::= <prefix> <component>
725             ::= <template-prefix> <template-args>
726             ::= # empty
727             ::= <substitution>  */
728
729 static void
730 write_prefix (node)
731      tree node;
732 {
733   tree decl;
734   tree type;
735   tree context;
736
737   if (node == NULL
738       || node == global_namespace)
739     return;
740
741   MANGLE_TRACE_TREE ("prefix", node);
742
743   decl = DECL_P (node) ? node : TYPE_NAME (node);
744   type = DECL_P (node) ? TREE_TYPE (node) : node;
745   context = CP_DECL_CONTEXT (decl);
746
747   if (find_substitution (node))
748     return;
749
750   /* Check if this is a template-id.  For a template member, the
751      template info will be hanging off the decl.  */
752   if (DECL_TEMPLATE_ID_P (decl))
753     {
754       write_template_prefix (decl);
755       write_template_args (DECL_TI_ARGS (decl));
756     }
757   /* For a template class, the template info will be hanging off the
758      type.  */
759   else if (type && CLASSTYPE_TEMPLATE_ID_P (type))
760     {
761       write_template_prefix (type);
762       write_template_args (CLASSTYPE_TI_ARGS (type));
763     }
764   else
765     /* Not templated.  */
766     {
767       write_prefix (context);
768       write_component (decl);
769     }
770
771   add_substitution (node);
772 }
773
774 /* <template-prefix> ::= <prefix> <template component>
775                      ::= <substitution>  
776
777    Names of templates are substitution candidates.  For a nested
778    template, though, the template name for the innermost name must
779    have all the outer template levels instantiated.  For instance,
780    consider
781
782      template<typename T> struct Outer
783      {
784        template<typename U> struct Inner {};
785      };
786
787    The template name for `Inner' in `Outer<int>::Inner<float>' is
788    `Outer<int>::Inner<U>'.  In g++, we don't instantiate the template
789    levels separately, so there's no TEMPLATE_DECL available for this
790    (there's only `Outer<T>::Inner<U>').
791
792    In order to get the substitutions right, we create a special
793    TREE_LIST to represent the substitution candidate for a nested
794    template.  The TREE_PURPOSE is the tempate's context, fully
795    instantiated, and the TREE_VALUE is the TEMPLATE_DECL for the inner
796    template.  
797
798    So, for the example above, `Inner' is represented as a substitution
799    candidate by a TREE_LIST whose purpose is `Outer<int>' and whose
800    value is `Outer<T>::Inner<U>'.  */
801
802 static void
803 write_template_prefix (node)
804      tree node;
805 {
806   tree decl = DECL_P (node) ? node : TYPE_NAME (node);
807   tree type = DECL_P (node) ? TREE_TYPE (node) : node;
808   tree context = CP_DECL_CONTEXT (decl);
809   tree template;
810   tree substitution;
811
812   MANGLE_TRACE_TREE ("template-prefix", node);
813
814   /* Find the template decl.  */
815   if (DECL_TEMPLATE_ID_P (decl))
816     template = DECL_TI_TEMPLATE (decl);
817   else if (CLASSTYPE_TEMPLATE_ID_P (type))
818     template = CLASSTYPE_TI_TEMPLATE (type);
819   else
820     /* Oops, not a template.  */
821     my_friendly_abort (20000524);
822
823   /* Build the substitution candidate TREE_LIST.  */
824   substitution = build_tree_list (context, template);
825
826   if (find_substitution (substitution))
827     return;
828
829   write_prefix (context);
830   write_component (decl);
831
832   add_substitution (substitution);
833 }
834
835 /* <component> ::= <unqualified-name>
836                ::= <local-name> */
837
838 static void
839 write_component (decl)
840      tree decl;
841 {
842   MANGLE_TRACE_TREE ("component", decl);
843
844   switch (TREE_CODE (decl))
845     {
846     case TEMPLATE_DECL:
847     case NAMESPACE_DECL:
848     case VAR_DECL:
849     case TYPE_DECL:
850     case FUNCTION_DECL:
851     case FIELD_DECL:
852       if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
853         write_local_name (CP_DECL_CONTEXT (decl), decl);
854       else
855         write_unqualified_name (decl);
856       break;
857
858     default:
859       my_friendly_abort (2000509);
860     }
861 }
862
863 /* We don't need to handle thunks, vtables, or VTTs here.  Those are
864    mangled through special entry points.  
865
866     <unqualified-name>  ::= <operator-name>
867                         ::= <special-name>  
868                         ::= <source-name>  */
869
870 static void
871 write_unqualified_name (decl)
872      tree decl;
873 {
874   MANGLE_TRACE_TREE ("unqualified-name", decl);
875
876   if (DECL_LANG_SPECIFIC (decl) != NULL && DECL_CONSTRUCTOR_P (decl))
877     write_special_name_constructor (decl);
878   else if (DECL_LANG_SPECIFIC (decl) != NULL && DECL_DESTRUCTOR_P (decl))
879     write_special_name_destructor (decl);
880   else if (DECL_CONV_FN_P (decl)) 
881     {
882       /* Conversion operator. Handle it right here.  
883            <operator> ::= cv <type>  */
884       write_string ("cv");
885       write_type (TREE_TYPE (DECL_NAME (decl)));
886     }
887   else if (DECL_OVERLOADED_OPERATOR_P (decl))
888     {
889       operator_name_info_t *oni;
890       if (DECL_ASSIGNMENT_OPERATOR_P (decl))
891         oni = assignment_operator_name_info;
892       else
893         oni = operator_name_info;
894       
895       write_string (oni[DECL_OVERLOADED_OPERATOR_P (decl)].mangled_name);
896     }
897   else
898     write_source_name (DECL_NAME (decl));
899 }
900
901 /* Non-termial <source-name>.  IDENTIFIER is an IDENTIFIER_NODE.  
902
903      <source-name> ::= </length/ number> <identifier>  */
904
905 static void
906 write_source_name (identifier)
907      tree identifier;
908 {
909   MANGLE_TRACE_TREE ("source-name", identifier);
910
911   /* Never write the whole template-id name including the template
912      arguments; we only want the template name.  */
913   if (IDENTIFIER_TEMPLATE (identifier))
914     identifier = IDENTIFIER_TEMPLATE (identifier);
915
916   write_number (IDENTIFIER_LENGTH (identifier), 10);
917   write_identifier (IDENTIFIER_POINTER (identifier));
918 }
919
920 /* Non-terminal <number>.
921
922      <number> ::= [n] </decimal integer/>  */
923
924 static void
925 write_number (number, base)
926      int number;
927      int base;
928 {
929   static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
930   int n;
931   int m = 1;
932
933   if (number < 0)
934     {
935       write_char ('n');
936       number = -number;
937     }
938   
939   n = number;
940   while (n >= base)
941     {
942       n /= base;
943       m *= base;
944     }
945
946   while (m > 0)
947     {
948       int digit = number / m;
949       write_char (digits[digit]);
950       number -= digit * m;
951       m /= base;
952     }
953
954   my_friendly_assert (number == 0, 20000407);
955 }
956
957 /* Write out an integeral CST in decimal.  */
958
959 static inline void
960 write_integer_cst (cst)
961      tree cst;
962 {
963   write_number (tree_low_cst (cst, TREE_UNSIGNED (TREE_TYPE (cst))), 10);
964 }
965
966 /* Non-terminal <identifier>.
967
968      <identifier> ::= </unqualified source code identifier>  */
969
970 static void
971 write_identifier (identifier)
972      char *identifier;
973 {
974   MANGLE_TRACE ("identifier", identifier);
975   write_string (identifier);
976 }
977
978 /* Handle constructor productions of non-terminal <special-name>.
979    CTOR is a constructor FUNCTION_DECL. 
980
981      <special-name> ::= C1   # complete object constructor
982                     ::= C2   # base object constructor
983                     ::= C3   # complete object allocating constructor
984                     ::= C4   # base object allocating constructor  
985
986    Currently, allocating constructors are never used. 
987
988    We also need to provide unique mangled names (which should never be
989    exported) for the constructor that takes an in-charge parameter,
990    and for a constructor whose name is the same as its class's name.
991    We use "C*INTERNAL*" for these.  */
992
993 static void
994 write_special_name_constructor (ctor)
995      tree ctor;
996 {
997   if (DECL_COMPLETE_CONSTRUCTOR_P (ctor))
998     write_string ("C1");
999   else if (DECL_BASE_CONSTRUCTOR_P (ctor))
1000     write_string ("C2");
1001   else
1002     write_string ("C*INTERNAL*");
1003 }
1004
1005 /* Handle destructor productions of non-terminal <special-name>.
1006    DTOR is a denstructor FUNCTION_DECL. 
1007
1008      <special-name> ::= D0 # deleting (in-charge) destructor
1009                     ::= D1 # complete object (in-charge) destructor
1010                     ::= D2 # base object (not-in-charge) destructor 
1011
1012    We also need to provide unique mngled names for old-ABI
1013    destructors, sometimes.  These should only be used internally.  We
1014    use "D*INTERNAL*" for these.  */
1015
1016 static void
1017 write_special_name_destructor (dtor)
1018      tree dtor;
1019 {
1020   if (DECL_DELETING_DESTRUCTOR_P (dtor))
1021     write_string ("D0");
1022   else if (DECL_COMPLETE_DESTRUCTOR_P (dtor))
1023     write_string ("D1");
1024   else if (DECL_BASE_DESTRUCTOR_P (dtor))
1025     write_string ("D2");
1026   else
1027     /* Old-ABI destructor.   */
1028     write_string ("D*INTERNAL*");
1029 }
1030
1031 /* Return the discriminator for ENTITY appearing inside
1032    FUNCTION.  The discriminator is the lexical ordinal of VAR among
1033    entities with the same name in the same FUNCTION.  */
1034
1035 static int
1036 discriminator_for_local_entity (entity)
1037      tree entity;
1038 {
1039   tree *type;
1040   int discriminator;
1041
1042   /* Assume this is the only local entity with this name.  */
1043   discriminator = 0;
1044
1045   /* For now, we don't discriminate amongst local variables.  */
1046   if (TREE_CODE (entity) != TYPE_DECL)
1047     return 0;
1048
1049   /* Scan the list of local classes.  */
1050   entity = TREE_TYPE (entity);
1051   for (type = &VARRAY_TREE (local_classes, 0); *type != entity; ++type)
1052     if (TYPE_IDENTIFIER (*type) == TYPE_IDENTIFIER (entity)
1053         && TYPE_CONTEXT (*type) == TYPE_CONTEXT (entity))
1054       ++discriminator;
1055
1056   return discriminator;
1057 }
1058
1059 /* Return the discriminator for STRING, a string literal used inside
1060    FUNCTION.  The disciminator is the lexical ordinal of STRING among
1061    string literals used in FUNCTION.  */
1062
1063 static int
1064 discriminator_for_string_literal (function, string)
1065      tree function ATTRIBUTE_UNUSED;
1066      tree string ATTRIBUTE_UNUSED;
1067 {
1068   /* For now, we don't discriminate amongst string literals.  */
1069   return 0;
1070 }
1071
1072 /*   <discriminator> := _ <number>   
1073
1074    The discriminator is used only for the second and later occurrences
1075    of the same name within a single function. In this case <number> is
1076    n - 2, if this is the nth occurrence, in lexical order.  */
1077
1078 static void
1079 write_discriminator (discriminator)
1080      int discriminator;
1081 {
1082   /* If discriminator is zero, don't write anything.  Otherwise... */
1083   if (discriminator > 0)
1084     {
1085       write_char ('_');
1086       /* The number is omitted for discriminator == 1.  Beyond 1, the
1087          numbering starts at 0.  */
1088       if (discriminator > 1)
1089         write_number (discriminator - 2, 10);
1090     }
1091 }
1092
1093 /* Mangle the name of a function-scope entity.  FUNCTION is the
1094    FUNCTION_DECL for the enclosing function.  ENTITY is the decl for
1095    the entity itself.
1096
1097      <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1098                   := Z <function encoding> E s [<discriminator>]  */
1099
1100 static void
1101 write_local_name (function, entity)
1102      tree function;
1103      tree entity;
1104 {
1105   MANGLE_TRACE_TREE ("local-name", entity);
1106
1107   write_char ('Z');
1108   write_encoding (function);
1109   write_char ('E');
1110   if (TREE_CODE (entity) == STRING_CST)
1111     {
1112       write_char ('s');
1113       write_discriminator (discriminator_for_string_literal (function, 
1114                                                              entity));
1115     }
1116   else
1117     {
1118       write_unqualified_name (entity);
1119       write_discriminator (discriminator_for_local_entity (entity));
1120     }
1121 }
1122
1123 /* Non-terminals <type> and <CV-qualifier>.  
1124
1125      <type> ::= <builtin-type>
1126             ::= <function-type>
1127             ::= <class-enum-type>
1128             ::= <array-type>
1129             ::= <pointer-to-member-type>
1130             ::= <template-param>
1131             ::= <substitution>
1132             ::= <CV-qualifier>
1133             ::= P <type>    # pointer-to
1134             ::= R <type>    # reference-to
1135             ::= C <type>    # complex pair (C 2000)  [not supported]
1136             ::= G <type>    # imaginary (C 2000)     [not supported]
1137             ::= U <source-name> <type>   # vendor extended type qualifier 
1138                                                      [not supported]
1139
1140    TYPE is a type node.  */
1141
1142 static void 
1143 write_type (type)
1144      tree type;
1145 {
1146   /* This gets set to non-zero if TYPE turns out to be a (possibly
1147      CV-qualified) builtin type.  */
1148   int is_builtin_type = 0;
1149
1150   MANGLE_TRACE_TREE ("type", type);
1151
1152   if (find_substitution (type))
1153     return;
1154
1155   if (write_CV_qualifiers_for_type (type) > 0)
1156     /* If TYPE was CV-qualified, we just wrote the qualifiers; now
1157        mangle the unqualified type.  The recursive call is needed here
1158        since both the qualified and uqualified types are substitution
1159        candidates.  */
1160     write_type (TYPE_MAIN_VARIANT (type));
1161   else
1162     switch (TREE_CODE (type))
1163       {
1164       case VOID_TYPE:
1165       case BOOLEAN_TYPE:
1166       case INTEGER_TYPE:  /* Includes wchar_t.  */
1167       case REAL_TYPE:
1168         /* If this is a typedef, TYPE may not be one of
1169            the standard builtin type nodes, but an alias of one.  Use
1170            TYPE_MAIN_VARIANT to get to the underlying builtin type.  */
1171         write_builtin_type (TYPE_MAIN_VARIANT (type));
1172         ++is_builtin_type;
1173         break;
1174
1175       case COMPLEX_TYPE:
1176         write_char ('C');
1177         write_type (TREE_TYPE (type));
1178         break;
1179
1180       case FUNCTION_TYPE:
1181       case METHOD_TYPE:
1182         write_function_type (type, 1);
1183         break;
1184
1185       case UNION_TYPE:
1186       case RECORD_TYPE:
1187       case ENUMERAL_TYPE:
1188         /* A pointer-to-member function is represented as a special
1189            RECORD_TYPE, so check for this first.  */
1190         if (TYPE_PTRMEMFUNC_P (type))
1191           write_pointer_to_member_type (type);
1192         else
1193           write_class_enum_type (type);
1194         break;
1195
1196       case TYPENAME_TYPE:
1197         /* We handle TYPENAME_TYPEs like ordinary nested names.  */
1198         write_nested_name (TYPE_STUB_DECL (type));
1199         break;
1200
1201       case ARRAY_TYPE:
1202         write_array_type (type);
1203         break;
1204
1205       case POINTER_TYPE:
1206         /* A pointer-to-member variable is represented by a POINTER_TYPE
1207            to an OFFSET_TYPE, so check for this first.  */
1208         if (TYPE_PTRMEM_P (type))
1209           write_pointer_to_member_type (type);
1210         else
1211           {
1212             write_char ('P');
1213             write_type (TREE_TYPE (type));
1214           }
1215         break;
1216
1217       case REFERENCE_TYPE:
1218         write_char ('R');
1219         write_type (TREE_TYPE (type));
1220         break;
1221
1222       case TEMPLATE_TYPE_PARM:
1223       case TEMPLATE_PARM_INDEX:
1224         write_template_param (type);
1225         break;
1226
1227       case TEMPLATE_TEMPLATE_PARM:
1228         write_template_template_param (type);
1229         if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (type))
1230           write_template_args 
1231             (TI_ARGS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (type)));
1232         break;
1233
1234       case OFFSET_TYPE:
1235         write_pointer_to_member_type (build_pointer_type (type));
1236         break;
1237
1238       default:
1239         my_friendly_abort (20000409);
1240       }
1241
1242   /* Types other than builtin types are substitution candidates.  */
1243   if (!is_builtin_type)
1244     add_substitution (type);
1245 }
1246
1247 /* Non-terminal <CV-qualifiers> for type nodes.  Returns the number of
1248    CV-qualifiers written for TYPE.
1249
1250      <CV-qualifiers> ::= [r] [V] [K]  */
1251
1252 static int
1253 write_CV_qualifiers_for_type (type)
1254      tree type;
1255 {
1256   int num_qualifiers = 0;
1257
1258   /* The order is specified by:
1259
1260        "In cases where multiple order-insensitive qualifiers are
1261        present, they should be ordered 'K' (closest to the base type),
1262        'V', 'r', and 'U' (farthest from the base type) ..."  */
1263
1264   if (CP_TYPE_RESTRICT_P (type))
1265     {
1266       write_char ('r');
1267       ++num_qualifiers;
1268     }
1269   if (CP_TYPE_VOLATILE_P (type))
1270     {
1271       write_char ('V');
1272       ++num_qualifiers;
1273     }
1274   if (CP_TYPE_CONST_P (type))
1275     {
1276       write_char ('K');
1277       ++num_qualifiers;
1278     }
1279
1280   return num_qualifiers;
1281 }
1282
1283 /* Non-terminal <builtin-type>. 
1284
1285      <builtin-type> ::= v   # void 
1286                     ::= b   # bool
1287                     ::= w   # wchar_t
1288                     ::= c   # char
1289                     ::= a   # signed char
1290                     ::= h   # unsigned char
1291                     ::= s   # short
1292                     ::= t   # unsigned short
1293                     ::= i   # int
1294                     ::= j   # unsigned int
1295                     ::= l   # long
1296                     ::= m   # unsigned long
1297                     ::= x   # long long, __int64
1298                     ::= y   # unsigned long long, __int64  
1299                     ::= n   # __int128            [not supported]
1300                     ::= o   # unsigned __int128   [not supported] 
1301                     ::= f   # float
1302                     ::= d   # double
1303                     ::= e   # long double, __float80 
1304                     ::= g   # __float128          [not supported]  */
1305
1306 static void 
1307 write_builtin_type (type)
1308      tree type;
1309 {
1310   switch (TREE_CODE (type))
1311     {
1312     case VOID_TYPE:
1313       write_char ('v');
1314       break;
1315
1316     case BOOLEAN_TYPE:
1317       write_char ('b');
1318       break;
1319
1320     case INTEGER_TYPE:
1321       /* If this is size_t, get the underlying int type.  */
1322       if (TYPE_IS_SIZETYPE (type))
1323         type = TYPE_DOMAIN (type);
1324
1325       /* TYPE may still be wchar_t, since that isn't in
1326          integer_type_nodes.  */
1327       if (type == wchar_type_node)
1328         write_char ('w');
1329       else
1330         {
1331           size_t itk;
1332           /* Assume TYPE is one of the shared integer type nodes.  Find
1333              it in the array of these nodes.  */
1334           for (itk = 0; itk < itk_none; ++itk)
1335             if (type == integer_types[itk])
1336               {
1337                 /* Print the corresponding single-letter code.  */
1338                 write_char (integer_type_codes[itk]);
1339                 break;
1340               }
1341           
1342           if (itk == itk_none)
1343             /* Couldn't find this type.  */
1344             my_friendly_abort (20000408);
1345         }
1346       break;
1347
1348     case REAL_TYPE:
1349       if (type == float_type_node)
1350         write_char ('f');
1351       else if (type == double_type_node)
1352         write_char ('d');
1353       else if (type == long_double_type_node)
1354         write_char ('e');
1355       else
1356         my_friendly_abort (20000409);
1357       break;
1358
1359     default:
1360       my_friendly_abort (20000509);
1361     }
1362 }
1363
1364 /* Non-terminal <function-type>.  NODE is a FUNCTION_TYPE or
1365    METHOD_TYPE.  If INCLUDE_RETURN_TYPE is non-zero, the return type
1366    is mangled before the parameter types.
1367
1368      <function-type> ::= F [Y] <bare-function-type> E   */
1369
1370 static void
1371 write_function_type (type, include_return_type)
1372      tree type;
1373      int include_return_type;
1374 {
1375   MANGLE_TRACE_TREE ("function-type", type);
1376
1377   write_char ('F');
1378   /* We don't track whether or not a type is `extern "C"'.  Note that
1379      you can have an `extern "C"' function that does not have
1380      `extern "C"' type, and vice versa:
1381
1382        extern "C" typedef void function_t();
1383        function_t f; // f has C++ linkage, but its type is
1384                      // `extern "C"'
1385
1386        typedef void function_t();
1387        extern "C" function_t f; // Vice versa.
1388
1389      See [dcl.link].  */
1390   write_bare_function_type (type, include_return_type);
1391   write_char ('E');
1392 }
1393
1394 /* Non-terminal <bare-function-type>.  NODE is a FUNCTION_DECL or a
1395    METHOD_TYPE.  If INCLUDE_RETURN_TYPE is non-zero, the return value
1396    is mangled before the parameter types.
1397
1398      <bare-function-type> ::= </signature/ type>+  */
1399
1400 static void
1401 write_bare_function_type (type, include_return_type_p)
1402      tree type;
1403      int include_return_type_p;
1404 {
1405   MANGLE_TRACE_TREE ("bare-function-type", type);
1406
1407   /* Mangle the return type, if requested.  */
1408   if (include_return_type_p)
1409     write_type (TREE_TYPE (type));
1410
1411   /* Now mangle the types of the arguments.  */
1412   write_method_parms (TYPE_ARG_TYPES (type), 
1413                       TREE_CODE (type) == METHOD_TYPE);
1414 }
1415
1416 /* Write the mangled representation of a method parameter list of
1417    types given in PARM_LIST.  If METHOD_P is non-zero, the function is 
1418    considered a non-static method, and the this parameter is omitted.
1419    If VARARGS_P is non-zero, an additional token designating varargs
1420    is appended.  */
1421
1422 static void
1423 write_method_parms (parm_list, method_p)
1424      tree parm_list;
1425      int method_p;
1426 {
1427   tree first_parm;
1428   /* Assume this parameter type list is variable-length.  If it ends
1429      with a void type, then it's not.  */
1430   int varargs_p = 1;
1431
1432   /* If this is a member function, skip the first arg, which is the
1433      this pointer.  
1434        "Member functions do not encode the type of their implicit this
1435        parameter."  */
1436   if (method_p)
1437     parm_list = TREE_CHAIN (parm_list);
1438
1439   for (first_parm = parm_list; 
1440        parm_list; 
1441        parm_list = TREE_CHAIN (parm_list))
1442     {
1443       tree parm = TREE_VALUE (parm_list);
1444
1445       if (same_type_p (parm, void_type_node))
1446         {
1447           /* "Empty parameter lists, whether declared as () or
1448              conventionally as (void), are encoded with a void parameter
1449              (v)."  */
1450           if (parm_list == first_parm)
1451             write_type (parm);
1452           /* If the parm list is terminated with a void type, it's
1453              fixed-length.  */
1454           varargs_p = 0;
1455           /* A void type better be the last one.  */
1456           my_friendly_assert (TREE_CHAIN (parm_list) == NULL, 20000523);
1457         }
1458       else
1459         write_type (parm);
1460     }
1461
1462   if (varargs_p)
1463     /* <builtin-type> ::= z  # ellipsis  */
1464     write_char ('z');
1465 }
1466
1467 /* <class-enum-type> ::= <name>  */
1468
1469 static void 
1470 write_class_enum_type (type)
1471      tree type;
1472 {
1473   write_name (TYPE_NAME (type));
1474 }
1475
1476 /* Non-terminal <template-args>.  ARGS is a TREE_VEC of template
1477    arguments.
1478
1479      <template-args> ::= I <template-arg>+ E  */
1480
1481 static void
1482 write_template_args (args)
1483      tree args;
1484 {
1485   int i;
1486   int length = TREE_VEC_LENGTH (args);
1487
1488   MANGLE_TRACE_TREE ("template-args", args);
1489
1490   my_friendly_assert (length > 0, 20000422);
1491
1492   if (TREE_CODE (TREE_VEC_ELT (args, 0)) == TREE_VEC)
1493     {
1494       /* We have nested template args.  We want the innermost template
1495          argument list.  */
1496       args = TREE_VEC_ELT (args, length - 1);
1497       length = TREE_VEC_LENGTH (args);
1498     }
1499
1500   write_char ('I');
1501   for (i = 0; i < length; ++i)
1502     write_template_arg (TREE_VEC_ELT (args, i));
1503   write_char ('E');
1504 }
1505
1506 /* <expression> ::= <unary operator-name> <expression>
1507                 ::= <binary operator-name> <expression> <expression>
1508                 ::= <expr-primary>
1509
1510    <expr-primary> ::= <template-param>
1511                   ::= L <type> <value number> E  # literal
1512                   ::= L <mangled-name> E         # external name  */
1513
1514 static void
1515 write_expression (expr)
1516      tree expr;
1517 {
1518   enum tree_code code;
1519
1520   code = TREE_CODE (expr);
1521
1522   /* Handle pointers-to-members by making them look like expression
1523      nodes.  */
1524   if (code == PTRMEM_CST)
1525     {
1526       expr = build_nt (ADDR_EXPR,
1527                        build_nt (SCOPE_REF,
1528                                  PTRMEM_CST_CLASS (expr),
1529                                  PTRMEM_CST_MEMBER (expr)));
1530       code = TREE_CODE (expr);
1531     }
1532
1533   /* Handle template parameters. */
1534   if (code == TEMPLATE_TYPE_PARM 
1535       || code == TEMPLATE_TEMPLATE_PARM
1536       ||  code == TEMPLATE_PARM_INDEX)
1537     write_template_param (expr);
1538   /* Handle literals.  */
1539   else if (TREE_CODE_CLASS (code) == 'c')
1540     write_template_arg_literal (expr);
1541   else if (DECL_P (expr))
1542     {
1543       write_char ('L');
1544       write_mangled_name (expr);
1545       write_char ('E');
1546     }
1547   else
1548     {
1549       int i;
1550
1551       /* Skip NOP_EXPRs.  They can occur when (say) a pointer argument
1552          is converted (via qualification conversions) to another
1553          type.  */
1554       while (TREE_CODE (expr) == NOP_EXPR)
1555         {
1556           expr = TREE_OPERAND (expr, 0);
1557           code = TREE_CODE (expr);
1558         }
1559
1560       /* When we bind a variable or function to a non-type template
1561          argument with reference type, we create an ADDR_EXPR to show
1562          the fact that the entity's address has been taken.  But, we
1563          don't actually want to output a mangling code for the `&'.  */
1564       if (TREE_CODE (expr) == ADDR_EXPR
1565           && TREE_TYPE (expr)
1566           && TREE_CODE (TREE_TYPE (expr)) == REFERENCE_TYPE)
1567         expr = TREE_OPERAND (expr, 0);
1568
1569       /* If it wasn't any of those, recursively expand the expression.  */
1570       write_string (operator_name_info[(int) code].mangled_name);
1571
1572       /* Handle pointers-to-members specially.  */
1573       if (code == SCOPE_REF)
1574         {
1575           write_type (TREE_OPERAND (expr, 0));
1576           if (TREE_CODE (TREE_OPERAND (expr, 1)) == IDENTIFIER_NODE)
1577             write_source_name (TREE_OPERAND (expr, 1));
1578           else
1579             write_encoding (TREE_OPERAND (expr, 1));
1580         }
1581       else
1582         for (i = 0; i < TREE_CODE_LENGTH (code); ++i)
1583           write_expression (TREE_OPERAND (expr, i));
1584     }
1585 }
1586
1587 /* Literal subcase of non-terminal <template-arg>.  
1588
1589      "Literal arguments, e.g. "A<42L>", are encoded with their type
1590      and value. Negative integer values are preceded with "n"; for
1591      example, "A<-42L>" becomes "1AILln42EE". The bool value false is
1592      encoded as 0, true as 1. If floating-point arguments are accepted
1593      as an extension, their values should be encoded using a
1594      fixed-length lowercase hexadecimal string corresponding to the
1595      internal representation (IEEE on IA-64), high-order bytes first,
1596      without leading zeroes. For example: "Lfbff000000E" is -1.0f."  */
1597
1598 static void
1599 write_template_arg_literal (value)
1600      tree value;
1601 {
1602   tree type = TREE_TYPE (value);
1603   write_char ('L');
1604   write_type (type);
1605
1606   if (TREE_CODE (value) == CONST_DECL)
1607     write_integer_cst (DECL_INITIAL (value));
1608   else if (TREE_CODE (value) == INTEGER_CST)
1609     {
1610       if (same_type_p (type, boolean_type_node))
1611         {
1612           if (value == boolean_false_node || integer_zerop (value))
1613             write_number (0, 10);
1614           else if (value == boolean_true_node)
1615             write_number (1, 10);
1616           else 
1617             my_friendly_abort (20000412);
1618         }
1619       else
1620         write_integer_cst (value);
1621     }
1622   else if (TREE_CODE (value) == REAL_CST)
1623     {
1624 #ifdef CROSS_COMPILE
1625       static int explained;
1626
1627       if (!explained) 
1628         {
1629           sorry ("real-valued template parameters when cross-compiling");
1630           explained = 1;
1631         }
1632 #else
1633       size_t i;
1634       for (i = 0; i < sizeof (TREE_REAL_CST (value)); ++i)
1635         write_number (((unsigned char *) 
1636                        &TREE_REAL_CST (value))[i], 16);
1637 #endif
1638     }
1639   else
1640     my_friendly_abort (20000412);
1641
1642   write_char ('E');
1643 }
1644
1645 /* Non-terminal <tempalate-arg>.  
1646
1647      <template-arg> ::= <type>                        # type
1648                     ::= L <type> </value/ number> E   # literal
1649                     ::= LZ <name> E                   # external name
1650                     ::= X <expression> E              # expression  */
1651
1652 static void
1653 write_template_arg (node)
1654      tree node;
1655 {
1656   enum tree_code code = TREE_CODE (node);
1657
1658   MANGLE_TRACE_TREE ("template-arg", node);
1659
1660   /* A template template paramter's argument list contains TREE_LIST
1661      nodes of which the value field is the the actual argument.  */
1662   if (code == TREE_LIST)
1663     {
1664       node = TREE_VALUE (node);
1665       /* If it's a decl, deal with its type instead.  */
1666       if (DECL_P (node))
1667         {
1668           node = TREE_TYPE (node);
1669           code = TREE_CODE (node);
1670         }
1671     }
1672
1673   if (TYPE_P (node))
1674     write_type (node);
1675   else if (code == TEMPLATE_DECL)
1676     /* A template appearing as a template arg is a template template arg.  */
1677     write_template_template_arg (node);
1678   else if (DECL_P (node))
1679     {
1680       write_char ('L');
1681       write_char ('Z');
1682       write_encoding (node);
1683       write_char ('E');
1684     }
1685   else if (TREE_CODE_CLASS (code) == 'c' && code != PTRMEM_CST)
1686     write_template_arg_literal (node);
1687   else
1688     {
1689       /* Template arguments may be expressions.  */
1690       write_char ('X');
1691       write_expression (node);
1692       write_char ('E');
1693     }
1694 }
1695
1696 /*  <template-template-arg>
1697                         ::= <name>
1698                         ::= <substitution>  */
1699
1700 void
1701 write_template_template_arg (tree decl)
1702 {
1703   MANGLE_TRACE_TREE ("template-template-arg", decl);
1704
1705   if (find_substitution (decl))
1706     return;
1707   write_name (decl);
1708   add_substitution (decl);
1709 }
1710
1711
1712 /* Non-terminal <array-type>.  TYPE is an ARRAY_TYPE.  
1713
1714      <array-type> ::= A [</dimension/ number>] _ </element/ type>  
1715
1716      "Array types encode the dimension (number of elements) and the
1717      element type. For variable length arrays, the dimension (but not
1718      the '_' separator) is omitted."  */
1719
1720 static void 
1721 write_array_type (type)
1722   tree type;
1723 {
1724   write_char ('A');
1725   if (TYPE_DOMAIN (type))
1726     {
1727       tree index_type;
1728       tree max;
1729
1730       index_type = TYPE_DOMAIN (type);
1731       /* The INDEX_TYPE gives the upper and lower bounds of the
1732          array.  */
1733       max = TYPE_MAX_VALUE (index_type);
1734       if (TREE_CODE (max) == INTEGER_CST)
1735         write_number (TREE_INT_CST_LOW (max) + 1, 10);
1736       else
1737         write_expression (TREE_OPERAND (max, 0));
1738     }
1739   write_char ('_');
1740   write_type (TREE_TYPE (type));
1741 }
1742
1743 /* Non-terminal <pointer-to-member-type> for pointer-to-member
1744    variables.  TYPE is a pointer-to-member POINTER_TYPE.
1745
1746      <pointer-to-member-type> ::= M </class/ type> </member/ type>  */
1747
1748 static void
1749 write_pointer_to_member_type (type)
1750      tree type;
1751 {
1752   write_char ('M');
1753   write_type (TYPE_PTRMEM_CLASS_TYPE (type));
1754   write_type (TYPE_PTRMEM_POINTED_TO_TYPE (type));
1755 }
1756
1757 /* Non-terminal <template-param>.  PARM is a TEMPLATE_TYPE_PARM,
1758    TEMPLATE_TEMPLATE_PARM, or a TEMPLATE_PARM_INDEX.
1759
1760      <template-param> ::= T </parameter/ number> _  */
1761
1762 static void
1763 write_template_param (parm)
1764      tree parm;
1765 {
1766   int parm_index;
1767
1768   MANGLE_TRACE_TREE ("template-parm", parm);
1769
1770   switch (TREE_CODE (parm))
1771     {
1772     case TEMPLATE_TYPE_PARM:
1773     case TEMPLATE_TEMPLATE_PARM:
1774       parm_index = TEMPLATE_TYPE_IDX (parm);
1775       break;
1776
1777     case TEMPLATE_PARM_INDEX:
1778       parm_index = TEMPLATE_PARM_IDX (parm);
1779       break;
1780
1781     default:
1782       my_friendly_abort (20000523);
1783     }
1784
1785   write_char ('T');
1786   /* NUMBER as it appears in the mangling is (-1)-indexed, with the
1787      earliest template param denoted by `_'.  */
1788   if (parm_index > 0)
1789     write_number (parm_index - 1, 10);
1790   write_char ('_');
1791 }
1792
1793 /*  <template-template-param>
1794                         ::= <template-param> 
1795                         ::= <substitution>  */
1796
1797 static void
1798 write_template_template_param (parm)
1799      tree parm;
1800 {
1801   tree template = NULL_TREE;
1802
1803   /* PARM, a TEMPLATE_TEMPLATE_PARM, is an instantiation of the
1804      template template parameter.  The substitution candidate here is
1805      only the template.  */
1806   if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm))
1807     {
1808       template 
1809         = TI_TEMPLATE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm));
1810       if (find_substitution (template))
1811         return;
1812     }
1813
1814   /* <template-param> encodes only the template parameter position,
1815      not its template arguments, which is fine here.  */
1816   write_template_param (parm);
1817   if (template)
1818     add_substitution (template);
1819 }
1820
1821 /* Non-terminal <substitution>.  
1822
1823       <substitution> ::= S <seq-id> _
1824                      ::= S_  */
1825
1826 static void
1827 write_substitution (seq_id)
1828      int seq_id;
1829 {
1830   MANGLE_TRACE ("substitution", "");
1831
1832   write_char ('S');
1833   if (seq_id > 0)
1834     write_number (seq_id - 1, 36);
1835   write_char ('_');
1836 }
1837
1838 /* Start mangling a new name or type.  */
1839
1840 static inline void
1841 start_mangling ()
1842 {
1843   obstack_free (&G.name_obstack, obstack_base (&G.name_obstack));
1844 }
1845
1846 /* Done with mangling.  Return the generated mangled name.  */
1847
1848 static inline const char *
1849 finish_mangling ()
1850 {
1851   /* Clear all the substitutions.  */
1852   VARRAY_POP_ALL (G.substitutions);
1853
1854   /* Null-terminate the string.  */
1855   write_char ('\0');
1856
1857   return (const char *) obstack_base (&G.name_obstack);
1858 }
1859
1860 /* Initialize data structures for mangling.  */
1861
1862 void
1863 init_mangle ()
1864 {
1865   gcc_obstack_init (&G.name_obstack);
1866   VARRAY_TREE_INIT (G.substitutions, 1, "mangling substitutions");
1867
1868   /* Cache these identifiers for quick comparison when checking for
1869      standard substitutions.  */
1870   subst_identifiers[SUBID_ALLOCATOR] = get_identifier ("allocator");
1871   subst_identifiers[SUBID_BASIC_STRING] = get_identifier ("basic_string");
1872   subst_identifiers[SUBID_CHAR_TRAITS] = get_identifier ("char_traits");
1873   subst_identifiers[SUBID_BASIC_ISTREAM] = get_identifier ("basic_istream");
1874   subst_identifiers[SUBID_BASIC_OSTREAM] = get_identifier ("basic_ostream");
1875   subst_identifiers[SUBID_BASIC_IOSTREAM] = get_identifier ("basic_iostream");
1876 }
1877
1878 /* Generate the mangled name of DECL.  */
1879
1880 static const char *
1881 mangle_decl_string (decl)
1882      tree decl;
1883 {
1884   const char *result;
1885
1886   start_mangling ();
1887
1888   if (TREE_CODE (decl) == TYPE_DECL)
1889     write_type (TREE_TYPE (decl));
1890   else
1891     write_mangled_name (decl);
1892
1893   result = finish_mangling ();
1894   if (DEBUG_MANGLE)
1895     fprintf (stderr, "mangle_decl_string = '%s'\n\n", result);
1896   return result;
1897 }
1898
1899 /* Create an identifier for the external mangled name of DECL.  */
1900
1901 tree
1902 mangle_decl (decl)
1903      tree decl;
1904 {
1905   return get_identifier (mangle_decl_string (decl));
1906 }
1907
1908 /* Generate the mangled representation of TYPE.  */
1909
1910 const char *
1911 mangle_type_string (type)
1912      tree type;
1913 {
1914   const char *result;
1915
1916   start_mangling ();
1917   write_type (type);
1918   result = finish_mangling ();
1919   if (DEBUG_MANGLE)
1920     fprintf (stderr, "mangle_type_string = '%s'\n\n", result);
1921   return result;
1922 }
1923
1924 /* Create an identifier for the mangled representation of TYPE.  */
1925
1926 tree
1927 mangle_type (type)
1928      tree type;
1929 {
1930   return get_identifier (mangle_type_string (type));
1931 }
1932
1933 /* Create an identifier for the mangled name of a special component
1934    for belonging to TYPE.  CODE is the ABI-specified code for this
1935    component.  */
1936
1937 static tree
1938 mangle_special_for_type (type, code)
1939      tree type;
1940      const char *code;
1941 {
1942   const char *result;
1943
1944   /* We don't have an actual decl here for the special component, so
1945      we can't just process the <encoded-name>.  Instead, fake it.  */
1946   start_mangling ();
1947
1948   /* Start the mangling.  */
1949   write_string ("_Z");
1950   write_string (code);
1951
1952   /* Add the type.  */
1953   write_type (type);
1954   result = finish_mangling ();
1955
1956   if (DEBUG_MANGLE)
1957     fprintf (stderr, "mangle_special_for_type = %s\n\n", result);
1958
1959   return get_identifier (result);
1960 }
1961
1962 /* Create an identifier for the mangled representation of the typeinfo
1963    structure for TYPE.  */
1964
1965 tree
1966 mangle_typeinfo_for_type (type)
1967      tree type;
1968 {
1969   return mangle_special_for_type (type, "TI");
1970 }
1971
1972 /* Create an identifier for the mangled name of the NTBS containing
1973    the mangled name of TYPE.  */
1974
1975 tree
1976 mangle_typeinfo_string_for_type (type)
1977      tree type;
1978 {
1979   return mangle_special_for_type (type, "TS");
1980 }
1981
1982 /* Create an identifier for the mangled name of the vtable for TYPE.  */
1983
1984 tree
1985 mangle_vtbl_for_type (type)
1986      tree type;
1987 {
1988   return mangle_special_for_type (type, "TV");
1989 }
1990
1991 /* Returns an identifier for the mangled name of the VTT for TYPE.  */
1992
1993 tree
1994 mangle_vtt_for_type (type)
1995      tree type;
1996 {
1997   return mangle_special_for_type (type, "TT");
1998 }
1999
2000 /* Return an identifier for a construction vtable group.  TYPE is
2001    the most derived class in the hierarchy; BINFO is the base
2002    subobject for which this construction vtable group will be used.  
2003
2004    This mangling isn't part of the ABI specification; in the ABI
2005    specification, the vtable group is dumped in the same COMDAT as the
2006    main vtable, and is referenced only from that vtable, so it doesn't
2007    need an external name.  For binary formats without COMDAT sections,
2008    though, we need external names for the vtable groups.  
2009
2010    We use the production
2011
2012     <special-name> ::= CT <type> <offset number> _ <base type>  */
2013
2014 tree
2015 mangle_ctor_vtbl_for_type (type, binfo)
2016      tree type;
2017      tree binfo;
2018 {
2019   const char *result;
2020
2021   start_mangling ();
2022
2023   write_string ("_Z");
2024   write_string ("TC");
2025   write_type (type);
2026   write_integer_cst (BINFO_OFFSET (binfo));
2027   write_char ('_');
2028   write_type (BINFO_TYPE (binfo));
2029
2030   result = finish_mangling ();
2031   if (DEBUG_MANGLE)
2032     fprintf (stderr, "mangle_ctor_vtbl_for_type = %s\n\n", result);
2033   return get_identifier (result);
2034 }
2035
2036 /* Return an identifier for the mangled name of a thunk to FN_DECL.
2037    OFFSET is the initial adjustment to this used to find the vptr.  If
2038    VCALL_OFFSET is non-zero, this is a virtual thunk, and it is the
2039    vtbl offset in bytes.  
2040
2041     <special-name> ::= Th <offset number> _ <base encoding>
2042                    ::= Tv <offset number> _ <vcall offset number> _
2043                                                             <base encoding>
2044 */
2045
2046 tree
2047 mangle_thunk (fn_decl, offset, vcall_offset)
2048      tree fn_decl;
2049      int offset;
2050      int vcall_offset;
2051 {
2052   const char *result;
2053   
2054   start_mangling ();
2055
2056   write_string ("_Z");
2057   /* The <special-name> for virtual thunks is Tv, for non-virtual
2058      thunks Th.  */
2059   write_char ('T');
2060   if (vcall_offset != 0)
2061     write_char ('v');
2062   else
2063     write_char ('h');
2064
2065   /* For either flavor, write the offset to this.  */
2066   write_number (offset, 10);
2067   write_char ('_');
2068
2069   /* For a virtual thunk, add the vcall offset.  */
2070   if (vcall_offset != 0)
2071     {
2072       /* Virtual thunk.  Write the vcall offset and base type name.  */
2073       write_number (vcall_offset, 10);
2074       write_char ('_');
2075     }
2076
2077   /* Scoped name.  */
2078   write_encoding (fn_decl);
2079
2080   result = finish_mangling ();
2081   if (DEBUG_MANGLE)
2082     fprintf (stderr, "mangle_thunk = %s\n\n", result);
2083   return get_identifier (result);
2084 }
2085
2086 /* Return an identifier for the mangled unqualified name for a
2087    conversion operator to TYPE.  This mangling is not specified by the
2088    ABI spec; it is only used internally.
2089
2090    For compatibility with existing conversion operator mechanisms,
2091    the mangled form is `__op<type>' where <type> is the mangled
2092    representation of TYPE.  
2093
2094    FIXME: Though identifiers with starting with __op are reserved for
2095    the implementation, it would eventually be nice to use inaccessible
2096    names for these operators.  */
2097
2098 tree
2099 mangle_conv_op_name_for_type (type)
2100      tree type;
2101 {
2102   tree identifier;
2103
2104   /* Build the mangling for TYPE.  */
2105   const char *mangled_type = mangle_type_string (type);
2106   /* Allocate a temporary buffer for the complete name.  */
2107   char *op_name = (char *) xmalloc (strlen (OPERATOR_TYPENAME_FORMAT) 
2108                                     + strlen (mangled_type) + 1);
2109   /* Assemble the mangling.  */
2110   strcpy (op_name, OPERATOR_TYPENAME_FORMAT);
2111   strcat (op_name, mangled_type);
2112   /* Find or create an identifier.  */
2113   identifier = get_identifier (op_name);
2114   /* Done with the temporary buffer.  */
2115   free (op_name);
2116   /* Set bits on the identifier so we know later it's a conversion.  */
2117   IDENTIFIER_OPNAME_P (identifier) = 1;
2118   IDENTIFIER_TYPENAME_P (identifier) = 1;
2119   /* Hang TYPE off the identifier so it can be found easily later when
2120      performing conversions.  */
2121   TREE_TYPE (identifier) = type;
2122
2123   return identifier;
2124 }
2125
2126 /* Return an identifier for the name of an initialization guard
2127    variable for indicated VARIABLE.  */
2128
2129 tree
2130 mangle_guard_variable (variable)
2131      tree variable;
2132 {
2133   start_mangling ();
2134   write_string ("_ZGV");
2135   write_name (variable);
2136   return get_identifier (finish_mangling ());
2137 }