OSDN Git Service

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