Import pre-release gcc-5.0 to new vendor branch
[dragonfly.git] / contrib / gcc-5.0 / gcc / cp / mangle.c
1 /* Name mangling for the 3.0 C++ ABI.
2    Copyright (C) 2000-2015 Free Software Foundation, Inc.
3    Written by Alex Samuel <samuel@codesourcery.com>
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11
12    GCC is distributed in the hope that it will be useful, but
13    WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 /* This file implements mangling of C++ names according to the IA64
22    C++ ABI specification.  A mangled name encodes a function or
23    variable's name, scope, type, and/or template arguments into a text
24    identifier.  This identifier is used as the function's or
25    variable's linkage name, to preserve compatibility between C++'s
26    language features (templates, scoping, and overloading) and C
27    linkers.
28
29    Additionally, g++ uses mangled names internally.  To support this,
30    mangling of types is allowed, even though the mangled name of a
31    type should not appear by itself as an exported name.  Ditto for
32    uninstantiated templates.
33
34    The primary entry point for this module is mangle_decl, which
35    returns an identifier containing the mangled name for a decl.
36    Additional entry points are provided to build mangled names of
37    particular constructs when the appropriate decl for that construct
38    is not available.  These are:
39
40      mangle_typeinfo_for_type:          typeinfo data
41      mangle_typeinfo_string_for_type:   typeinfo type name
42      mangle_vtbl_for_type:              virtual table data
43      mangle_vtt_for_type:               VTT data
44      mangle_ctor_vtbl_for_type:         `C-in-B' constructor virtual table data
45      mangle_thunk:                      thunk function or entry  */
46
47 #include "config.h"
48 #include "system.h"
49 #include "coretypes.h"
50 #include "tm.h"
51 #include "hash-set.h"
52 #include "machmode.h"
53 #include "vec.h"
54 #include "double-int.h"
55 #include "input.h"
56 #include "alias.h"
57 #include "symtab.h"
58 #include "wide-int.h"
59 #include "inchash.h"
60 #include "tree.h"
61 #include "tree-hasher.h"
62 #include "stor-layout.h"
63 #include "stringpool.h"
64 #include "tm_p.h"
65 #include "cp-tree.h"
66 #include "obstack.h"
67 #include "flags.h"
68 #include "target.h"
69 #include "hash-map.h"
70 #include "is-a.h"
71 #include "plugin-api.h"
72 #include "hard-reg-set.h"
73 #include "input.h"
74 #include "function.h"
75 #include "ipa-ref.h"
76 #include "cgraph.h"
77 #include "wide-int.h"
78
79 /* Debugging support.  */
80
81 /* Define DEBUG_MANGLE to enable very verbose trace messages.  */
82 #ifndef DEBUG_MANGLE
83 #define DEBUG_MANGLE 0
84 #endif
85
86 /* Macros for tracing the write_* functions.  */
87 #if DEBUG_MANGLE
88 # define MANGLE_TRACE(FN, INPUT) \
89   fprintf (stderr, "  %-24s: %-24s\n", (FN), (INPUT))
90 # define MANGLE_TRACE_TREE(FN, NODE) \
91   fprintf (stderr, "  %-24s: %-24s (%p)\n", \
92            (FN), get_tree_code_name (TREE_CODE (NODE)), (void *) (NODE))
93 #else
94 # define MANGLE_TRACE(FN, INPUT)
95 # define MANGLE_TRACE_TREE(FN, NODE)
96 #endif
97
98 /* Nonzero if NODE is a class template-id.  We can't rely on
99    CLASSTYPE_USE_TEMPLATE here because of tricky bugs in the parser
100    that hard to distinguish A<T> from A, where A<T> is the type as
101    instantiated outside of the template, and A is the type used
102    without parameters inside the template.  */
103 #define CLASSTYPE_TEMPLATE_ID_P(NODE)                                   \
104   (TYPE_LANG_SPECIFIC (NODE) != NULL                                    \
105    && (TREE_CODE (NODE) == BOUND_TEMPLATE_TEMPLATE_PARM                 \
106        || (CLASSTYPE_TEMPLATE_INFO (NODE) != NULL                       \
107            && (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (NODE))))))
108
109 /* Things we only need one of.  This module is not reentrant.  */
110 typedef struct GTY(()) globals {
111   /* An array of the current substitution candidates, in the order
112      we've seen them.  */
113   vec<tree, va_gc> *substitutions;
114
115   /* The entity that is being mangled.  */
116   tree GTY ((skip)) entity;
117
118   /* How many parameter scopes we are inside.  */
119   int parm_depth;
120
121   /* True if the mangling will be different in a future version of the
122      ABI.  */
123   bool need_abi_warning;
124 } globals;
125
126 static GTY (()) globals G;
127
128 /* The obstack on which we build mangled names.  */
129 static struct obstack *mangle_obstack;
130
131 /* The obstack on which we build mangled names that are not going to
132    be IDENTIFIER_NODEs.  */
133 static struct obstack name_obstack;
134
135 /* The first object on the name_obstack; we use this to free memory
136    allocated on the name_obstack.  */
137 static void *name_base;
138
139 /* Indices into subst_identifiers.  These are identifiers used in
140    special substitution rules.  */
141 typedef enum
142 {
143   SUBID_ALLOCATOR,
144   SUBID_BASIC_STRING,
145   SUBID_CHAR_TRAITS,
146   SUBID_BASIC_ISTREAM,
147   SUBID_BASIC_OSTREAM,
148   SUBID_BASIC_IOSTREAM,
149   SUBID_MAX
150 }
151 substitution_identifier_index_t;
152
153 /* For quick substitution checks, look up these common identifiers
154    once only.  */
155 static GTY(()) tree subst_identifiers[SUBID_MAX];
156
157 /* Single-letter codes for builtin integer types, defined in
158    <builtin-type>.  These are indexed by integer_type_kind values.  */
159 static const char
160 integer_type_codes[itk_none] =
161 {
162   'c',  /* itk_char */
163   'a',  /* itk_signed_char */
164   'h',  /* itk_unsigned_char */
165   's',  /* itk_short */
166   't',  /* itk_unsigned_short */
167   'i',  /* itk_int */
168   'j',  /* itk_unsigned_int */
169   'l',  /* itk_long */
170   'm',  /* itk_unsigned_long */
171   'x',  /* itk_long_long */
172   'y',  /* itk_unsigned_long_long */
173   /* __intN types are handled separately */
174   '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'
175 };
176
177 static int decl_is_template_id (const tree, tree* const);
178
179 /* Functions for handling substitutions.  */
180
181 static inline tree canonicalize_for_substitution (tree);
182 static void add_substitution (tree);
183 static inline int is_std_substitution (const tree,
184                                        const substitution_identifier_index_t);
185 static inline int is_std_substitution_char (const tree,
186                                             const substitution_identifier_index_t);
187 static int find_substitution (tree);
188 static void mangle_call_offset (const tree, const tree);
189
190 /* Functions for emitting mangled representations of things.  */
191
192 static void write_mangled_name (const tree, bool);
193 static void write_encoding (const tree);
194 static void write_name (tree, const int);
195 static void write_abi_tags (tree);
196 static void write_unscoped_name (const tree);
197 static void write_unscoped_template_name (const tree);
198 static void write_nested_name (const tree);
199 static void write_prefix (const tree);
200 static void write_template_prefix (const tree);
201 static void write_unqualified_name (tree);
202 static void write_conversion_operator_name (const tree);
203 static void write_source_name (tree);
204 static void write_literal_operator_name (tree);
205 static void write_unnamed_type_name (const tree);
206 static void write_closure_type_name (const tree);
207 static int hwint_to_ascii (unsigned HOST_WIDE_INT, const unsigned int, char *,
208                            const unsigned int);
209 static void write_number (unsigned HOST_WIDE_INT, const int,
210                           const unsigned int);
211 static void write_compact_number (int num);
212 static void write_integer_cst (const tree);
213 static void write_real_cst (const tree);
214 static void write_identifier (const char *);
215 static void write_special_name_constructor (const tree);
216 static void write_special_name_destructor (const tree);
217 static void write_type (tree);
218 static int write_CV_qualifiers_for_type (const tree);
219 static void write_builtin_type (tree);
220 static void write_function_type (const tree);
221 static void write_bare_function_type (const tree, const int, const tree);
222 static void write_method_parms (tree, const int, const tree);
223 static void write_class_enum_type (const tree);
224 static void write_template_args (tree);
225 static void write_expression (tree);
226 static void write_template_arg_literal (const tree);
227 static void write_template_arg (tree);
228 static void write_template_template_arg (const tree);
229 static void write_array_type (const tree);
230 static void write_pointer_to_member_type (const tree);
231 static void write_template_param (const tree);
232 static void write_template_template_param (const tree);
233 static void write_substitution (const int);
234 static int discriminator_for_local_entity (tree);
235 static int discriminator_for_string_literal (tree, tree);
236 static void write_discriminator (const int);
237 static void write_local_name (tree, const tree, const tree);
238 static void dump_substitution_candidates (void);
239 static tree mangle_decl_string (const tree);
240 static int local_class_index (tree);
241
242 /* Control functions.  */
243
244 static inline void start_mangling (const tree);
245 static tree mangle_special_for_type (const tree, const char *);
246
247 /* Foreign language functions.  */
248
249 static void write_java_integer_type_codes (const tree);
250
251 /* Append a single character to the end of the mangled
252    representation.  */
253 #define write_char(CHAR)                                                \
254   obstack_1grow (mangle_obstack, (CHAR))
255
256 /* Append a sized buffer to the end of the mangled representation.  */
257 #define write_chars(CHAR, LEN)                                          \
258   obstack_grow (mangle_obstack, (CHAR), (LEN))
259
260 /* Append a NUL-terminated string to the end of the mangled
261    representation.  */
262 #define write_string(STRING)                                            \
263   obstack_grow (mangle_obstack, (STRING), strlen (STRING))
264
265 /* Nonzero if NODE1 and NODE2 are both TREE_LIST nodes and have the
266    same purpose (context, which may be a type) and value (template
267    decl).  See write_template_prefix for more information on what this
268    is used for.  */
269 #define NESTED_TEMPLATE_MATCH(NODE1, NODE2)                             \
270   (TREE_CODE (NODE1) == TREE_LIST                                       \
271    && TREE_CODE (NODE2) == TREE_LIST                                    \
272    && ((TYPE_P (TREE_PURPOSE (NODE1))                                   \
273         && same_type_p (TREE_PURPOSE (NODE1), TREE_PURPOSE (NODE2)))    \
274        || TREE_PURPOSE (NODE1) == TREE_PURPOSE (NODE2))                 \
275    && TREE_VALUE (NODE1) == TREE_VALUE (NODE2))
276
277 /* Write out an unsigned quantity in base 10.  */
278 #define write_unsigned_number(NUMBER)                                   \
279   write_number ((NUMBER), /*unsigned_p=*/1, 10)
280
281 /* If DECL is a template instance, return nonzero and, if
282    TEMPLATE_INFO is non-NULL, set *TEMPLATE_INFO to its template info.
283    Otherwise return zero.  */
284
285 static int
286 decl_is_template_id (const tree decl, tree* const template_info)
287 {
288   if (TREE_CODE (decl) == TYPE_DECL)
289     {
290       /* TYPE_DECLs are handled specially.  Look at its type to decide
291          if this is a template instantiation.  */
292       const tree type = TREE_TYPE (decl);
293
294       if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_ID_P (type))
295         {
296           if (template_info != NULL)
297             /* For a templated TYPE_DECL, the template info is hanging
298                off the type.  */
299             *template_info = TYPE_TEMPLATE_INFO (type);
300           return 1;
301         }
302     }
303   else
304     {
305       /* Check if this is a primary template.  */
306       if (DECL_LANG_SPECIFIC (decl) != NULL
307           && DECL_USE_TEMPLATE (decl)
308           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
309           && TREE_CODE (decl) != TEMPLATE_DECL)
310         {
311           if (template_info != NULL)
312             /* For most templated decls, the template info is hanging
313                off the decl.  */
314             *template_info = DECL_TEMPLATE_INFO (decl);
315           return 1;
316         }
317     }
318
319   /* It's not a template id.  */
320   return 0;
321 }
322
323 /* Produce debugging output of current substitution candidates.  */
324
325 static void
326 dump_substitution_candidates (void)
327 {
328   unsigned i;
329   tree el;
330
331   fprintf (stderr, "  ++ substitutions  ");
332   FOR_EACH_VEC_ELT (*G.substitutions, i, el)
333     {
334       const char *name = "???";
335
336       if (i > 0)
337         fprintf (stderr, "                    ");
338       if (DECL_P (el))
339         name = IDENTIFIER_POINTER (DECL_NAME (el));
340       else if (TREE_CODE (el) == TREE_LIST)
341         name = IDENTIFIER_POINTER (DECL_NAME (TREE_VALUE (el)));
342       else if (TYPE_NAME (el))
343         name = TYPE_NAME_STRING (el);
344       fprintf (stderr, " S%d_ = ", i - 1);
345       if (TYPE_P (el) &&
346           (CP_TYPE_RESTRICT_P (el)
347            || CP_TYPE_VOLATILE_P (el)
348            || CP_TYPE_CONST_P (el)))
349         fprintf (stderr, "CV-");
350       fprintf (stderr, "%s (%s at %p)\n",
351                name, get_tree_code_name (TREE_CODE (el)), (void *) el);
352     }
353 }
354
355 /* Both decls and types can be substitution candidates, but sometimes
356    they refer to the same thing.  For instance, a TYPE_DECL and
357    RECORD_TYPE for the same class refer to the same thing, and should
358    be treated accordingly in substitutions.  This function returns a
359    canonicalized tree node representing NODE that is used when adding
360    and substitution candidates and finding matches.  */
361
362 static inline tree
363 canonicalize_for_substitution (tree node)
364 {
365   /* For a TYPE_DECL, use the type instead.  */
366   if (TREE_CODE (node) == TYPE_DECL)
367     node = TREE_TYPE (node);
368   if (TYPE_P (node)
369       && TYPE_CANONICAL (node) != node
370       && TYPE_MAIN_VARIANT (node) != node)
371     {
372       tree orig = node;
373       /* Here we want to strip the topmost typedef only.
374          We need to do that so is_std_substitution can do proper
375          name matching.  */
376       if (TREE_CODE (node) == FUNCTION_TYPE)
377         /* Use build_qualified_type and TYPE_QUALS here to preserve
378            the old buggy mangling of attribute noreturn with abi<5.  */
379         node = build_qualified_type (TYPE_MAIN_VARIANT (node),
380                                      TYPE_QUALS (node));
381       else
382         node = cp_build_qualified_type (TYPE_MAIN_VARIANT (node),
383                                         cp_type_quals (node));
384       if (TREE_CODE (node) == FUNCTION_TYPE
385           || TREE_CODE (node) == METHOD_TYPE)
386         node = build_ref_qualified_type (node, type_memfn_rqual (orig));
387     }
388   return node;
389 }
390
391 /* Add NODE as a substitution candidate.  NODE must not already be on
392    the list of candidates.  */
393
394 static void
395 add_substitution (tree node)
396 {
397   tree c;
398
399   if (DEBUG_MANGLE)
400     fprintf (stderr, "  ++ add_substitution (%s at %10p)\n",
401              get_tree_code_name (TREE_CODE (node)), (void *) node);
402
403   /* Get the canonicalized substitution candidate for NODE.  */
404   c = canonicalize_for_substitution (node);
405   if (DEBUG_MANGLE && c != node)
406     fprintf (stderr, "  ++ using candidate (%s at %10p)\n",
407              get_tree_code_name (TREE_CODE (node)), (void *) node);
408   node = c;
409
410 #if ENABLE_CHECKING
411   /* Make sure NODE isn't already a candidate.  */
412   {
413     int i;
414     tree candidate;
415
416     FOR_EACH_VEC_SAFE_ELT (G.substitutions, i, candidate)
417       {
418         gcc_assert (!(DECL_P (node) && node == candidate));
419         gcc_assert (!(TYPE_P (node) && TYPE_P (candidate)
420                       && same_type_p (node, candidate)));
421       }
422   }
423 #endif /* ENABLE_CHECKING */
424
425   /* Put the decl onto the varray of substitution candidates.  */
426   vec_safe_push (G.substitutions, node);
427
428   if (DEBUG_MANGLE)
429     dump_substitution_candidates ();
430 }
431
432 /* Helper function for find_substitution.  Returns nonzero if NODE,
433    which may be a decl or a CLASS_TYPE, is a template-id with template
434    name of substitution_index[INDEX] in the ::std namespace.  */
435
436 static inline int
437 is_std_substitution (const tree node,
438                      const substitution_identifier_index_t index)
439 {
440   tree type = NULL;
441   tree decl = NULL;
442
443   if (DECL_P (node))
444     {
445       type = TREE_TYPE (node);
446       decl = node;
447     }
448   else if (CLASS_TYPE_P (node))
449     {
450       type = node;
451       decl = TYPE_NAME (node);
452     }
453   else
454     /* These are not the droids you're looking for.  */
455     return 0;
456
457   return (DECL_NAMESPACE_STD_P (CP_DECL_CONTEXT (decl))
458           && TYPE_LANG_SPECIFIC (type)
459           && TYPE_TEMPLATE_INFO (type)
460           && (DECL_NAME (TYPE_TI_TEMPLATE (type))
461               == subst_identifiers[index]));
462 }
463
464 /* Helper function for find_substitution.  Returns nonzero if NODE,
465    which may be a decl or a CLASS_TYPE, is the template-id
466    ::std::identifier<char>, where identifier is
467    substitution_index[INDEX].  */
468
469 static inline int
470 is_std_substitution_char (const tree node,
471                           const substitution_identifier_index_t index)
472 {
473   tree args;
474   /* Check NODE's name is ::std::identifier.  */
475   if (!is_std_substitution (node, index))
476     return 0;
477   /* Figure out its template args.  */
478   if (DECL_P (node))
479     args = DECL_TI_ARGS (node);
480   else if (CLASS_TYPE_P (node))
481     args = CLASSTYPE_TI_ARGS (node);
482   else
483     /* Oops, not a template.  */
484     return 0;
485   /* NODE's template arg list should be <char>.  */
486   return
487     TREE_VEC_LENGTH (args) == 1
488     && TREE_VEC_ELT (args, 0) == char_type_node;
489 }
490
491 /* Check whether a substitution should be used to represent NODE in
492    the mangling.
493
494    First, check standard special-case substitutions.
495
496      <substitution> ::= St
497          # ::std
498
499                     ::= Sa
500          # ::std::allocator
501
502                     ::= Sb
503          # ::std::basic_string
504
505                     ::= Ss
506          # ::std::basic_string<char,
507                                ::std::char_traits<char>,
508                                ::std::allocator<char> >
509
510                     ::= Si
511          # ::std::basic_istream<char, ::std::char_traits<char> >
512
513                     ::= So
514          # ::std::basic_ostream<char, ::std::char_traits<char> >
515
516                     ::= Sd
517          # ::std::basic_iostream<char, ::std::char_traits<char> >
518
519    Then examine the stack of currently available substitution
520    candidates for entities appearing earlier in the same mangling
521
522    If a substitution is found, write its mangled representation and
523    return nonzero.  If none is found, just return zero.  */
524
525 static int
526 find_substitution (tree node)
527 {
528   int i;
529   const int size = vec_safe_length (G.substitutions);
530   tree decl;
531   tree type;
532   const char *abbr = NULL;
533
534   if (DEBUG_MANGLE)
535     fprintf (stderr, "  ++ find_substitution (%s at %p)\n",
536              get_tree_code_name (TREE_CODE (node)), (void *) node);
537
538   /* Obtain the canonicalized substitution representation for NODE.
539      This is what we'll compare against.  */
540   node = canonicalize_for_substitution (node);
541
542   /* Check for builtin substitutions.  */
543
544   decl = TYPE_P (node) ? TYPE_NAME (node) : node;
545   type = TYPE_P (node) ? node : TREE_TYPE (node);
546
547   /* Check for std::allocator.  */
548   if (decl
549       && is_std_substitution (decl, SUBID_ALLOCATOR)
550       && !CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
551     abbr = "Sa";
552
553   /* Check for std::basic_string.  */
554   else if (decl && is_std_substitution (decl, SUBID_BASIC_STRING))
555     {
556       if (TYPE_P (node))
557         {
558           /* If this is a type (i.e. a fully-qualified template-id),
559              check for
560                  std::basic_string <char,
561                                     std::char_traits<char>,
562                                     std::allocator<char> > .  */
563           if (cp_type_quals (type) == TYPE_UNQUALIFIED
564               && CLASSTYPE_USE_TEMPLATE (type))
565             {
566               tree args = CLASSTYPE_TI_ARGS (type);
567               if (TREE_VEC_LENGTH (args) == 3
568                   && same_type_p (TREE_VEC_ELT (args, 0), char_type_node)
569                   && is_std_substitution_char (TREE_VEC_ELT (args, 1),
570                                                SUBID_CHAR_TRAITS)
571                   && is_std_substitution_char (TREE_VEC_ELT (args, 2),
572                                                SUBID_ALLOCATOR))
573                 abbr = "Ss";
574             }
575         }
576       else
577         /* Substitute for the template name only if this isn't a type.  */
578         abbr = "Sb";
579     }
580
581   /* Check for basic_{i,o,io}stream.  */
582   else if (TYPE_P (node)
583            && cp_type_quals (type) == TYPE_UNQUALIFIED
584            && CLASS_TYPE_P (type)
585            && CLASSTYPE_USE_TEMPLATE (type)
586            && CLASSTYPE_TEMPLATE_INFO (type) != NULL)
587     {
588       /* First, check for the template
589          args <char, std::char_traits<char> > .  */
590       tree args = CLASSTYPE_TI_ARGS (type);
591       if (TREE_VEC_LENGTH (args) == 2
592           && TYPE_P (TREE_VEC_ELT (args, 0))
593           && same_type_p (TREE_VEC_ELT (args, 0), char_type_node)
594           && is_std_substitution_char (TREE_VEC_ELT (args, 1),
595                                        SUBID_CHAR_TRAITS))
596         {
597           /* Got them.  Is this basic_istream?  */
598           if (is_std_substitution (decl, SUBID_BASIC_ISTREAM))
599             abbr = "Si";
600           /* Or basic_ostream?  */
601           else if (is_std_substitution (decl, SUBID_BASIC_OSTREAM))
602             abbr = "So";
603           /* Or basic_iostream?  */
604           else if (is_std_substitution (decl, SUBID_BASIC_IOSTREAM))
605             abbr = "Sd";
606         }
607     }
608
609   /* Check for namespace std.  */
610   else if (decl && DECL_NAMESPACE_STD_P (decl))
611     {
612       write_string ("St");
613       return 1;
614     }
615
616   tree tags = NULL_TREE;
617   if (OVERLOAD_TYPE_P (node) || DECL_CLASS_TEMPLATE_P (node))
618     tags = lookup_attribute ("abi_tag", TYPE_ATTRIBUTES (type));
619   /* Now check the list of available substitutions for this mangling
620      operation.  */
621   if (!abbr || tags) for (i = 0; i < size; ++i)
622     {
623       tree candidate = (*G.substitutions)[i];
624       /* NODE is a matched to a candidate if it's the same decl node or
625          if it's the same type.  */
626       if (decl == candidate
627           || (TYPE_P (candidate) && type && TYPE_P (node)
628               && same_type_p (type, candidate))
629           || NESTED_TEMPLATE_MATCH (node, candidate))
630         {
631           write_substitution (i);
632           return 1;
633         }
634     }
635
636   if (!abbr)
637     /* No substitution found.  */
638     return 0;
639
640   write_string (abbr);
641   if (tags)
642     {
643       /* If there are ABI tags on the abbreviation, it becomes
644          a substitution candidate.  */
645       write_abi_tags (tags);
646       add_substitution (node);
647     }
648   return 1;
649 }
650
651
652 /* TOP_LEVEL is true, if this is being called at outermost level of
653   mangling. It should be false when mangling a decl appearing in an
654   expression within some other mangling.
655
656   <mangled-name>      ::= _Z <encoding>  */
657
658 static void
659 write_mangled_name (const tree decl, bool top_level)
660 {
661   MANGLE_TRACE_TREE ("mangled-name", decl);
662
663   if (/* The names of `extern "C"' functions are not mangled.  */
664       DECL_EXTERN_C_FUNCTION_P (decl)
665       /* But overloaded operator names *are* mangled.  */
666       && !DECL_OVERLOADED_OPERATOR_P (decl))
667     {
668     unmangled_name:;
669
670       if (top_level)
671         write_string (IDENTIFIER_POINTER (DECL_NAME (decl)));
672       else
673         {
674           /* The standard notes: "The <encoding> of an extern "C"
675              function is treated like global-scope data, i.e. as its
676              <source-name> without a type."  We cannot write
677              overloaded operators that way though, because it contains
678              characters invalid in assembler.  */
679           write_string ("_Z");
680           write_source_name (DECL_NAME (decl));
681         }
682     }
683   else if (VAR_P (decl)
684            /* Variable template instantiations are mangled.  */
685            && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
686            /* The names of non-static global variables aren't mangled.  */
687            && DECL_EXTERNAL_LINKAGE_P (decl)
688            && (CP_DECL_CONTEXT (decl) == global_namespace
689                /* And neither are `extern "C"' variables.  */
690                || DECL_EXTERN_C_P (decl)))
691     {
692       goto unmangled_name;
693     }
694   else
695     {
696       write_string ("_Z");
697       write_encoding (decl);
698     }
699 }
700
701 /*   <encoding>         ::= <function name> <bare-function-type>
702                         ::= <data name>  */
703
704 static void
705 write_encoding (const tree decl)
706 {
707   MANGLE_TRACE_TREE ("encoding", decl);
708
709   if (DECL_LANG_SPECIFIC (decl) && DECL_EXTERN_C_FUNCTION_P (decl))
710     {
711       /* For overloaded operators write just the mangled name
712          without arguments.  */
713       if (DECL_OVERLOADED_OPERATOR_P (decl))
714         write_name (decl, /*ignore_local_scope=*/0);
715       else
716         write_source_name (DECL_NAME (decl));
717       return;
718     }
719
720   write_name (decl, /*ignore_local_scope=*/0);
721   if (TREE_CODE (decl) == FUNCTION_DECL)
722     {
723       tree fn_type;
724       tree d;
725
726       if (decl_is_template_id (decl, NULL))
727         {
728           fn_type = get_mostly_instantiated_function_type (decl);
729           /* FN_TYPE will not have parameter types for in-charge or
730              VTT parameters.  Therefore, we pass NULL_TREE to
731              write_bare_function_type -- otherwise, it will get
732              confused about which artificial parameters to skip.  */
733           d = NULL_TREE;
734         }
735       else
736         {
737           fn_type = TREE_TYPE (decl);
738           d = decl;
739         }
740
741       write_bare_function_type (fn_type,
742                                 (!DECL_CONSTRUCTOR_P (decl)
743                                  && !DECL_DESTRUCTOR_P (decl)
744                                  && !DECL_CONV_FN_P (decl)
745                                  && decl_is_template_id (decl, NULL)),
746                                 d);
747     }
748 }
749
750 /* Lambdas can have a bit more context for mangling, specifically VAR_DECL
751    or PARM_DECL context, which doesn't belong in DECL_CONTEXT.  */
752
753 static tree
754 decl_mangling_context (tree decl)
755 {
756   tree tcontext = targetm.cxx.decl_mangling_context (decl);
757
758   if (tcontext != NULL_TREE)
759     return tcontext;
760
761   if (TREE_CODE (decl) == TEMPLATE_DECL
762       && DECL_TEMPLATE_RESULT (decl))
763     decl = DECL_TEMPLATE_RESULT (decl);
764
765   if (TREE_CODE (decl) == TYPE_DECL
766       && LAMBDA_TYPE_P (TREE_TYPE (decl)))
767     {
768       tree extra = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl));
769       if (extra)
770         return extra;
771     }
772   else if (template_type_parameter_p (decl))
773      /* template type parms have no mangling context.  */
774       return NULL_TREE;
775   return CP_DECL_CONTEXT (decl);
776 }
777
778 /* <name> ::= <unscoped-name>
779           ::= <unscoped-template-name> <template-args>
780           ::= <nested-name>
781           ::= <local-name>
782
783    If IGNORE_LOCAL_SCOPE is nonzero, this production of <name> is
784    called from <local-name>, which mangles the enclosing scope
785    elsewhere and then uses this function to mangle just the part
786    underneath the function scope.  So don't use the <local-name>
787    production, to avoid an infinite recursion.  */
788
789 static void
790 write_name (tree decl, const int ignore_local_scope)
791 {
792   tree context;
793
794   MANGLE_TRACE_TREE ("name", decl);
795
796   if (TREE_CODE (decl) == TYPE_DECL)
797     {
798       /* In case this is a typedef, fish out the corresponding
799          TYPE_DECL for the main variant.  */
800       decl = TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl)));
801     }
802
803   context = decl_mangling_context (decl);
804
805   gcc_assert (context != NULL_TREE);
806
807   if (abi_version_crosses (7)
808       && ignore_local_scope
809       && TREE_CODE (context) == PARM_DECL)
810     G.need_abi_warning = 1;
811
812   /* A decl in :: or ::std scope is treated specially.  The former is
813      mangled using <unscoped-name> or <unscoped-template-name>, the
814      latter with a special substitution.  Also, a name that is
815      directly in a local function scope is also mangled with
816      <unscoped-name> rather than a full <nested-name>.  */
817   if (context == global_namespace
818       || DECL_NAMESPACE_STD_P (context)
819       || (ignore_local_scope
820           && (TREE_CODE (context) == FUNCTION_DECL
821               || (abi_version_at_least (7)
822                   && TREE_CODE (context) == PARM_DECL))))
823     {
824       tree template_info;
825       /* Is this a template instance?  */
826       if (decl_is_template_id (decl, &template_info))
827         {
828           /* Yes: use <unscoped-template-name>.  */
829           write_unscoped_template_name (TI_TEMPLATE (template_info));
830           write_template_args (TI_ARGS (template_info));
831         }
832       else
833         /* Everything else gets an <unqualified-name>.  */
834         write_unscoped_name (decl);
835     }
836   else
837     {
838       /* Handle local names, unless we asked not to (that is, invoked
839          under <local-name>, to handle only the part of the name under
840          the local scope).  */
841       if (!ignore_local_scope)
842         {
843           /* Scan up the list of scope context, looking for a
844              function.  If we find one, this entity is in local
845              function scope.  local_entity tracks context one scope
846              level down, so it will contain the element that's
847              directly in that function's scope, either decl or one of
848              its enclosing scopes.  */
849           tree local_entity = decl;
850           while (context != global_namespace)
851             {
852               /* Make sure we're always dealing with decls.  */
853               if (TYPE_P (context))
854                 context = TYPE_NAME (context);
855               /* Is this a function?  */
856               if (TREE_CODE (context) == FUNCTION_DECL
857                   || TREE_CODE (context) == PARM_DECL)
858                 {
859                   /* Yes, we have local scope.  Use the <local-name>
860                      production for the innermost function scope.  */
861                   write_local_name (context, local_entity, decl);
862                   return;
863                 }
864               /* Up one scope level.  */
865               local_entity = context;
866               context = decl_mangling_context (context);
867             }
868
869           /* No local scope found?  Fall through to <nested-name>.  */
870         }
871
872       /* Other decls get a <nested-name> to encode their scope.  */
873       write_nested_name (decl);
874     }
875 }
876
877 /* <unscoped-name> ::= <unqualified-name>
878                    ::= St <unqualified-name>   # ::std::  */
879
880 static void
881 write_unscoped_name (const tree decl)
882 {
883   tree context = decl_mangling_context (decl);
884
885   MANGLE_TRACE_TREE ("unscoped-name", decl);
886
887   /* Is DECL in ::std?  */
888   if (DECL_NAMESPACE_STD_P (context))
889     {
890       write_string ("St");
891       write_unqualified_name (decl);
892     }
893   else
894     {
895       /* If not, it should be either in the global namespace, or directly
896          in a local function scope.  A lambda can also be mangled in the
897          scope of a default argument.  */
898       gcc_assert (context == global_namespace
899                   || TREE_CODE (context) == PARM_DECL
900                   || TREE_CODE (context) == FUNCTION_DECL);
901
902       write_unqualified_name (decl);
903     }
904 }
905
906 /* <unscoped-template-name> ::= <unscoped-name>
907                             ::= <substitution>  */
908
909 static void
910 write_unscoped_template_name (const tree decl)
911 {
912   MANGLE_TRACE_TREE ("unscoped-template-name", decl);
913
914   if (find_substitution (decl))
915     return;
916   write_unscoped_name (decl);
917   add_substitution (decl);
918 }
919
920 /* Write the nested name, including CV-qualifiers, of DECL.
921
922    <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
923                  ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
924
925    <ref-qualifier> ::= R # & ref-qualifier
926                    ::= O # && ref-qualifier
927    <CV-qualifiers> ::= [r] [V] [K]  */
928
929 static void
930 write_nested_name (const tree decl)
931 {
932   tree template_info;
933
934   MANGLE_TRACE_TREE ("nested-name", decl);
935
936   write_char ('N');
937
938   /* Write CV-qualifiers, if this is a member function.  */
939   if (TREE_CODE (decl) == FUNCTION_DECL
940       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
941     {
942       if (DECL_VOLATILE_MEMFUNC_P (decl))
943         write_char ('V');
944       if (DECL_CONST_MEMFUNC_P (decl))
945         write_char ('K');
946       if (FUNCTION_REF_QUALIFIED (TREE_TYPE (decl)))
947         {
948           if (FUNCTION_RVALUE_QUALIFIED (TREE_TYPE (decl)))
949             write_char ('O');
950           else
951             write_char ('R');
952         }
953     }
954
955   /* Is this a template instance?  */
956   if (decl_is_template_id (decl, &template_info))
957     {
958       /* Yes, use <template-prefix>.  */
959       write_template_prefix (decl);
960       write_template_args (TI_ARGS (template_info));
961     }
962   else if (TREE_CODE (TREE_TYPE (decl)) == TYPENAME_TYPE)
963     {
964       tree name = TYPENAME_TYPE_FULLNAME (TREE_TYPE (decl));
965       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
966         {
967           write_template_prefix (decl);
968           write_template_args (TREE_OPERAND (name, 1));
969         }
970       else
971         {
972           write_prefix (decl_mangling_context (decl));
973           write_unqualified_name (decl);
974         }
975     }
976   else
977     {
978       /* No, just use <prefix>  */
979       write_prefix (decl_mangling_context (decl));
980       write_unqualified_name (decl);
981     }
982   write_char ('E');
983 }
984
985 /* <prefix> ::= <prefix> <unqualified-name>
986             ::= <template-param>
987             ::= <template-prefix> <template-args>
988             ::= <decltype>
989             ::= # empty
990             ::= <substitution>  */
991
992 static void
993 write_prefix (const tree node)
994 {
995   tree decl;
996   /* Non-NULL if NODE represents a template-id.  */
997   tree template_info = NULL;
998
999   if (node == NULL
1000       || node == global_namespace)
1001     return;
1002
1003   MANGLE_TRACE_TREE ("prefix", node);
1004
1005   if (TREE_CODE (node) == DECLTYPE_TYPE)
1006     {
1007       write_type (node);
1008       return;
1009     }
1010
1011   if (find_substitution (node))
1012     return;
1013
1014   if (DECL_P (node))
1015     {
1016       /* If this is a function or parm decl, that means we've hit function
1017          scope, so this prefix must be for a local name.  In this
1018          case, we're under the <local-name> production, which encodes
1019          the enclosing function scope elsewhere.  So don't continue
1020          here.  */
1021       if (TREE_CODE (node) == FUNCTION_DECL
1022           || TREE_CODE (node) == PARM_DECL)
1023         return;
1024
1025       decl = node;
1026       decl_is_template_id (decl, &template_info);
1027     }
1028   else
1029     {
1030       /* Node is a type.  */
1031       decl = TYPE_NAME (node);
1032       if (CLASSTYPE_TEMPLATE_ID_P (node))
1033         template_info = TYPE_TEMPLATE_INFO (node);
1034     }
1035
1036   if (TREE_CODE (node) == TEMPLATE_TYPE_PARM)
1037     write_template_param (node);
1038   else if (template_info != NULL)
1039     /* Templated.  */
1040     {
1041       write_template_prefix (decl);
1042       write_template_args (TI_ARGS (template_info));
1043     }
1044   else if (TREE_CODE (TREE_TYPE (decl)) == TYPENAME_TYPE)
1045     {
1046       tree name = TYPENAME_TYPE_FULLNAME (TREE_TYPE (decl));
1047       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
1048         {
1049           write_template_prefix (decl);
1050           write_template_args (TREE_OPERAND (name, 1));
1051         }
1052       else
1053         {
1054           write_prefix (decl_mangling_context (decl));
1055           write_unqualified_name (decl);
1056         }
1057     }
1058   else
1059     /* Not templated.  */
1060     {
1061       write_prefix (decl_mangling_context (decl));
1062       write_unqualified_name (decl);
1063       if (VAR_P (decl)
1064           || TREE_CODE (decl) == FIELD_DECL)
1065         {
1066           /* <data-member-prefix> := <member source-name> M */
1067           write_char ('M');
1068           return;
1069         }
1070     }
1071
1072   add_substitution (node);
1073 }
1074
1075 /* <template-prefix> ::= <prefix> <template component>
1076                      ::= <template-param>
1077                      ::= <substitution>  */
1078
1079 static void
1080 write_template_prefix (const tree node)
1081 {
1082   tree decl = DECL_P (node) ? node : TYPE_NAME (node);
1083   tree type = DECL_P (node) ? TREE_TYPE (node) : node;
1084   tree context = decl_mangling_context (decl);
1085   tree template_info;
1086   tree templ;
1087   tree substitution;
1088
1089   MANGLE_TRACE_TREE ("template-prefix", node);
1090
1091   /* Find the template decl.  */
1092   if (decl_is_template_id (decl, &template_info))
1093     templ = TI_TEMPLATE (template_info);
1094   else if (TREE_CODE (type) == TYPENAME_TYPE)
1095     /* For a typename type, all we have is the name.  */
1096     templ = DECL_NAME (decl);
1097   else
1098     {
1099       gcc_assert (CLASSTYPE_TEMPLATE_ID_P (type));
1100
1101       templ = TYPE_TI_TEMPLATE (type);
1102     }
1103
1104   /* For a member template, though, the template name for the
1105      innermost name must have all the outer template levels
1106      instantiated.  For instance, consider
1107
1108        template<typename T> struct Outer {
1109          template<typename U> struct Inner {};
1110        };
1111
1112      The template name for `Inner' in `Outer<int>::Inner<float>' is
1113      `Outer<int>::Inner<U>'.  In g++, we don't instantiate the template
1114      levels separately, so there's no TEMPLATE_DECL available for this
1115      (there's only `Outer<T>::Inner<U>').
1116
1117      In order to get the substitutions right, we create a special
1118      TREE_LIST to represent the substitution candidate for a nested
1119      template.  The TREE_PURPOSE is the template's context, fully
1120      instantiated, and the TREE_VALUE is the TEMPLATE_DECL for the inner
1121      template.
1122
1123      So, for the example above, `Outer<int>::Inner' is represented as a
1124      substitution candidate by a TREE_LIST whose purpose is `Outer<int>'
1125      and whose value is `Outer<T>::Inner<U>'.  */
1126   if (TYPE_P (context))
1127     substitution = build_tree_list (context, templ);
1128   else
1129     substitution = templ;
1130
1131   if (find_substitution (substitution))
1132     return;
1133
1134   if (TREE_TYPE (templ)
1135       && TREE_CODE (TREE_TYPE (templ)) == TEMPLATE_TEMPLATE_PARM)
1136     write_template_param (TREE_TYPE (templ));
1137   else
1138     {
1139       write_prefix (context);
1140       write_unqualified_name (decl);
1141     }
1142
1143   add_substitution (substitution);
1144 }
1145
1146 /* We don't need to handle thunks, vtables, or VTTs here.  Those are
1147    mangled through special entry points.
1148
1149     <unqualified-name>  ::= <operator-name>
1150                         ::= <special-name>
1151                         ::= <source-name>
1152                         ::= <unnamed-type-name>
1153                         ::= <local-source-name> 
1154
1155     <local-source-name> ::= L <source-name> <discriminator> */
1156
1157 static void
1158 write_unqualified_id (tree identifier)
1159 {
1160   if (IDENTIFIER_TYPENAME_P (identifier))
1161     write_conversion_operator_name (TREE_TYPE (identifier));
1162   else if (IDENTIFIER_OPNAME_P (identifier))
1163     {
1164       int i;
1165       const char *mangled_name = NULL;
1166
1167       /* Unfortunately, there is no easy way to go from the
1168          name of the operator back to the corresponding tree
1169          code.  */
1170       for (i = 0; i < MAX_TREE_CODES; ++i)
1171         if (operator_name_info[i].identifier == identifier)
1172           {
1173             /* The ABI says that we prefer binary operator
1174                names to unary operator names.  */
1175             if (operator_name_info[i].arity == 2)
1176               {
1177                 mangled_name = operator_name_info[i].mangled_name;
1178                 break;
1179               }
1180             else if (!mangled_name)
1181               mangled_name = operator_name_info[i].mangled_name;
1182           }
1183         else if (assignment_operator_name_info[i].identifier
1184                  == identifier)
1185           {
1186             mangled_name
1187               = assignment_operator_name_info[i].mangled_name;
1188             break;
1189           }
1190       write_string (mangled_name);
1191     }
1192   else if (UDLIT_OPER_P (identifier))
1193     write_literal_operator_name (identifier);
1194   else
1195     write_source_name (identifier);
1196 }
1197
1198 static void
1199 write_unqualified_name (tree decl)
1200 {
1201   MANGLE_TRACE_TREE ("unqualified-name", decl);
1202
1203   if (identifier_p (decl))
1204     {
1205       write_unqualified_id (decl);
1206       return;
1207     }
1208
1209   bool found = false;
1210
1211   if (DECL_NAME (decl) == NULL_TREE)
1212     {
1213       found = true;
1214       gcc_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
1215       write_source_name (DECL_ASSEMBLER_NAME (decl));
1216     }
1217   else if (DECL_DECLARES_FUNCTION_P (decl))
1218     {
1219       found = true;
1220       if (DECL_CONSTRUCTOR_P (decl))
1221         write_special_name_constructor (decl);
1222       else if (DECL_DESTRUCTOR_P (decl))
1223         write_special_name_destructor (decl);
1224       else if (DECL_CONV_FN_P (decl))
1225         {
1226           /* Conversion operator. Handle it right here.
1227              <operator> ::= cv <type>  */
1228           tree type;
1229           if (decl_is_template_id (decl, NULL))
1230             {
1231               tree fn_type;
1232               fn_type = get_mostly_instantiated_function_type (decl);
1233               type = TREE_TYPE (fn_type);
1234             }
1235           else if (FNDECL_USED_AUTO (decl))
1236             type = (DECL_STRUCT_FUNCTION (decl)->language
1237                     ->x_auto_return_pattern);
1238           else
1239             type = DECL_CONV_FN_TYPE (decl);
1240           write_conversion_operator_name (type);
1241         }
1242       else if (DECL_OVERLOADED_OPERATOR_P (decl))
1243         {
1244           operator_name_info_t *oni;
1245           if (DECL_ASSIGNMENT_OPERATOR_P (decl))
1246             oni = assignment_operator_name_info;
1247           else
1248             oni = operator_name_info;
1249
1250           write_string (oni[DECL_OVERLOADED_OPERATOR_P (decl)].mangled_name);
1251         }
1252       else if (UDLIT_OPER_P (DECL_NAME (decl)))
1253         write_literal_operator_name (DECL_NAME (decl));
1254       else
1255         found = false;
1256     }
1257
1258   if (found)
1259     /* OK */;
1260   else if (VAR_OR_FUNCTION_DECL_P (decl) && ! TREE_PUBLIC (decl)
1261            && DECL_NAMESPACE_SCOPE_P (decl)
1262            && decl_linkage (decl) == lk_internal)
1263     {
1264       MANGLE_TRACE_TREE ("local-source-name", decl);
1265       write_char ('L');
1266       write_source_name (DECL_NAME (decl));
1267       /* The default discriminator is 1, and that's all we ever use,
1268          so there's no code to output one here.  */
1269     }
1270   else
1271     {
1272       tree type = TREE_TYPE (decl);
1273
1274       if (TREE_CODE (decl) == TYPE_DECL
1275           && TYPE_ANONYMOUS_P (type))
1276         write_unnamed_type_name (type);
1277       else if (TREE_CODE (decl) == TYPE_DECL
1278                && LAMBDA_TYPE_P (type))
1279         write_closure_type_name (type);
1280       else
1281         write_source_name (DECL_NAME (decl));
1282     }
1283
1284   /* We use the ABI tags from the primary template, ignoring tags on any
1285      specializations.  This is necessary because C++ doesn't require a
1286      specialization to be declared before it is used unless the use
1287      requires a complete type, but we need to get the tags right on
1288      incomplete types as well.  */
1289   if (tree tmpl = most_general_template (decl))
1290     decl = DECL_TEMPLATE_RESULT (tmpl);
1291   /* Don't crash on an unbound class template.  */
1292   if (decl)
1293     {
1294       tree attrs = (TREE_CODE (decl) == TYPE_DECL
1295                     ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
1296                     : DECL_ATTRIBUTES (decl));
1297       write_abi_tags (lookup_attribute ("abi_tag", attrs));
1298     }
1299 }
1300
1301 /* Write the unqualified-name for a conversion operator to TYPE.  */
1302
1303 static void
1304 write_conversion_operator_name (const tree type)
1305 {
1306   write_string ("cv");
1307   write_type (type);
1308 }
1309
1310 /* Non-terminal <source-name>.  IDENTIFIER is an IDENTIFIER_NODE.
1311
1312      <source-name> ::= </length/ number> <identifier>  */
1313
1314 static void
1315 write_source_name (tree identifier)
1316 {
1317   MANGLE_TRACE_TREE ("source-name", identifier);
1318
1319   /* Never write the whole template-id name including the template
1320      arguments; we only want the template name.  */
1321   if (IDENTIFIER_TEMPLATE (identifier))
1322     identifier = IDENTIFIER_TEMPLATE (identifier);
1323
1324   write_unsigned_number (IDENTIFIER_LENGTH (identifier));
1325   write_identifier (IDENTIFIER_POINTER (identifier));
1326 }
1327
1328 /* Compare two TREE_STRINGs like strcmp.  */
1329
1330 int
1331 tree_string_cmp (const void *p1, const void *p2)
1332 {
1333   if (p1 == p2)
1334     return 0;
1335   tree s1 = *(const tree*)p1;
1336   tree s2 = *(const tree*)p2;
1337   return strcmp (TREE_STRING_POINTER (s1),
1338                  TREE_STRING_POINTER (s2));
1339 }
1340
1341 /* ID is the name of a function or type with abi_tags attribute TAGS.
1342    Write out the name, suitably decorated.  */
1343
1344 static void
1345 write_abi_tags (tree tags)
1346 {
1347   if (tags == NULL_TREE)
1348     return;
1349
1350   tags = TREE_VALUE (tags);
1351
1352   vec<tree, va_gc> * vec = make_tree_vector();
1353
1354   for (tree t = tags; t; t = TREE_CHAIN (t))
1355     {
1356       if (ABI_TAG_IMPLICIT (t))
1357         continue;
1358       tree str = TREE_VALUE (t);
1359       vec_safe_push (vec, str);
1360     }
1361
1362   vec->qsort (tree_string_cmp);
1363
1364   unsigned i; tree str;
1365   FOR_EACH_VEC_ELT (*vec, i, str)
1366     {
1367       write_string ("B");
1368       write_unsigned_number (TREE_STRING_LENGTH (str) - 1);
1369       write_identifier (TREE_STRING_POINTER (str));
1370     }
1371
1372   release_tree_vector (vec);
1373 }
1374
1375 /* Write a user-defined literal operator.
1376           ::= li <source-name>    # "" <source-name>
1377    IDENTIFIER is an LITERAL_IDENTIFIER_NODE.  */
1378
1379 static void
1380 write_literal_operator_name (tree identifier)
1381 {
1382   const char* suffix = UDLIT_OP_SUFFIX (identifier);
1383   write_identifier (UDLIT_OP_MANGLED_PREFIX);
1384   write_unsigned_number (strlen (suffix));
1385   write_identifier (suffix);
1386 }
1387
1388 /* Encode 0 as _, and 1+ as n-1_.  */
1389
1390 static void
1391 write_compact_number (int num)
1392 {
1393   if (num > 0)
1394     write_unsigned_number (num - 1);
1395   write_char ('_');
1396 }
1397
1398 /* Return how many unnamed types precede TYPE in its enclosing class.  */
1399
1400 static int
1401 nested_anon_class_index (tree type)
1402 {
1403   int index = 0;
1404   tree member = TYPE_FIELDS (TYPE_CONTEXT (type));
1405   for (; member; member = DECL_CHAIN (member))
1406     if (DECL_IMPLICIT_TYPEDEF_P (member))
1407       {
1408         tree memtype = TREE_TYPE (member);
1409         if (memtype == type)
1410           return index;
1411         else if (TYPE_ANONYMOUS_P (memtype))
1412           ++index;
1413       }
1414
1415   gcc_unreachable ();
1416 }
1417
1418 /* <unnamed-type-name> ::= Ut [ <nonnegative number> ] _ */
1419
1420 static void
1421 write_unnamed_type_name (const tree type)
1422 {
1423   int discriminator;
1424   MANGLE_TRACE_TREE ("unnamed-type-name", type);
1425
1426   if (TYPE_FUNCTION_SCOPE_P (type))
1427     discriminator = local_class_index (type);
1428   else if (TYPE_CLASS_SCOPE_P (type))
1429     discriminator = nested_anon_class_index (type);
1430   else
1431     {
1432       gcc_assert (no_linkage_check (type, /*relaxed_p=*/true));
1433       /* Just use the old mangling at namespace scope.  */
1434       write_source_name (TYPE_IDENTIFIER (type));
1435       return;
1436     }
1437
1438   write_string ("Ut");
1439   write_compact_number (discriminator);
1440 }
1441
1442 /* <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1443    <lambda-sig> ::= <parameter type>+  # Parameter types or "v" if the lambda has no parameters */
1444
1445 static void
1446 write_closure_type_name (const tree type)
1447 {
1448   tree fn = lambda_function (type);
1449   tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
1450   tree parms = TYPE_ARG_TYPES (TREE_TYPE (fn));
1451
1452   MANGLE_TRACE_TREE ("closure-type-name", type);
1453
1454   write_string ("Ul");
1455   write_method_parms (parms, /*method_p=*/1, fn);
1456   write_char ('E');
1457   write_compact_number (LAMBDA_EXPR_DISCRIMINATOR (lambda));
1458 }
1459
1460 /* Convert NUMBER to ascii using base BASE and generating at least
1461    MIN_DIGITS characters. BUFFER points to the _end_ of the buffer
1462    into which to store the characters. Returns the number of
1463    characters generated (these will be laid out in advance of where
1464    BUFFER points).  */
1465
1466 static int
1467 hwint_to_ascii (unsigned HOST_WIDE_INT number, const unsigned int base,
1468                 char *buffer, const unsigned int min_digits)
1469 {
1470   static const char base_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1471   unsigned digits = 0;
1472
1473   while (number)
1474     {
1475       unsigned HOST_WIDE_INT d = number / base;
1476
1477       *--buffer = base_digits[number - d * base];
1478       digits++;
1479       number = d;
1480     }
1481   while (digits < min_digits)
1482     {
1483       *--buffer = base_digits[0];
1484       digits++;
1485     }
1486   return digits;
1487 }
1488
1489 /* Non-terminal <number>.
1490
1491      <number> ::= [n] </decimal integer/>  */
1492
1493 static void
1494 write_number (unsigned HOST_WIDE_INT number, const int unsigned_p,
1495               const unsigned int base)
1496 {
1497   char buffer[sizeof (HOST_WIDE_INT) * 8];
1498   unsigned count = 0;
1499
1500   if (!unsigned_p && (HOST_WIDE_INT) number < 0)
1501     {
1502       write_char ('n');
1503       number = -((HOST_WIDE_INT) number);
1504     }
1505   count = hwint_to_ascii (number, base, buffer + sizeof (buffer), 1);
1506   write_chars (buffer + sizeof (buffer) - count, count);
1507 }
1508
1509 /* Write out an integral CST in decimal. Most numbers are small, and
1510    representable in a HOST_WIDE_INT. Occasionally we'll have numbers
1511    bigger than that, which we must deal with.  */
1512
1513 static inline void
1514 write_integer_cst (const tree cst)
1515 {
1516   int sign = tree_int_cst_sgn (cst);
1517   widest_int abs_value = wi::abs (wi::to_widest (cst));
1518   if (!wi::fits_uhwi_p (abs_value))
1519     {
1520       /* A bignum. We do this in chunks, each of which fits in a
1521          HOST_WIDE_INT.  */
1522       char buffer[sizeof (HOST_WIDE_INT) * 8 * 2];
1523       unsigned HOST_WIDE_INT chunk;
1524       unsigned chunk_digits;
1525       char *ptr = buffer + sizeof (buffer);
1526       unsigned count = 0;
1527       tree n, base, type;
1528       int done;
1529
1530       /* HOST_WIDE_INT must be at least 32 bits, so 10^9 is
1531          representable.  */
1532       chunk = 1000000000;
1533       chunk_digits = 9;
1534
1535       if (sizeof (HOST_WIDE_INT) >= 8)
1536         {
1537           /* It is at least 64 bits, so 10^18 is representable.  */
1538           chunk_digits = 18;
1539           chunk *= chunk;
1540         }
1541
1542       type = c_common_signed_or_unsigned_type (1, TREE_TYPE (cst));
1543       base = build_int_cstu (type, chunk);
1544       n = wide_int_to_tree (type, cst);
1545
1546       if (sign < 0)
1547         {
1548           write_char ('n');
1549           n = fold_build1_loc (input_location, NEGATE_EXPR, type, n);
1550         }
1551       do
1552         {
1553           tree d = fold_build2_loc (input_location, FLOOR_DIV_EXPR, type, n, base);
1554           tree tmp = fold_build2_loc (input_location, MULT_EXPR, type, d, base);
1555           unsigned c;
1556
1557           done = integer_zerop (d);
1558           tmp = fold_build2_loc (input_location, MINUS_EXPR, type, n, tmp);
1559           c = hwint_to_ascii (TREE_INT_CST_LOW (tmp), 10, ptr,
1560                               done ? 1 : chunk_digits);
1561           ptr -= c;
1562           count += c;
1563           n = d;
1564         }
1565       while (!done);
1566       write_chars (ptr, count);
1567     }
1568   else
1569     {
1570       /* A small num.  */
1571       if (sign < 0)
1572         write_char ('n');
1573       write_unsigned_number (abs_value.to_uhwi ());
1574     }
1575 }
1576
1577 /* Write out a floating-point literal.
1578
1579     "Floating-point literals are encoded using the bit pattern of the
1580     target processor's internal representation of that number, as a
1581     fixed-length lowercase hexadecimal string, high-order bytes first
1582     (even if the target processor would store low-order bytes first).
1583     The "n" prefix is not used for floating-point literals; the sign
1584     bit is encoded with the rest of the number.
1585
1586     Here are some examples, assuming the IEEE standard representation
1587     for floating point numbers.  (Spaces are for readability, not
1588     part of the encoding.)
1589
1590         1.0f                    Lf 3f80 0000 E
1591        -1.0f                    Lf bf80 0000 E
1592         1.17549435e-38f         Lf 0080 0000 E
1593         1.40129846e-45f         Lf 0000 0001 E
1594         0.0f                    Lf 0000 0000 E"
1595
1596    Caller is responsible for the Lx and the E.  */
1597 static void
1598 write_real_cst (const tree value)
1599 {
1600   long target_real[4];  /* largest supported float */
1601   char buffer[9];       /* eight hex digits in a 32-bit number */
1602   int i, limit, dir;
1603
1604   tree type = TREE_TYPE (value);
1605   int words = GET_MODE_BITSIZE (TYPE_MODE (type)) / 32;
1606
1607   real_to_target (target_real, &TREE_REAL_CST (value),
1608                   TYPE_MODE (type));
1609
1610   /* The value in target_real is in the target word order,
1611      so we must write it out backward if that happens to be
1612      little-endian.  write_number cannot be used, it will
1613      produce uppercase.  */
1614   if (FLOAT_WORDS_BIG_ENDIAN)
1615     i = 0, limit = words, dir = 1;
1616   else
1617     i = words - 1, limit = -1, dir = -1;
1618
1619   for (; i != limit; i += dir)
1620     {
1621       sprintf (buffer, "%08lx", (unsigned long) target_real[i]);
1622       write_chars (buffer, 8);
1623     }
1624 }
1625
1626 /* Non-terminal <identifier>.
1627
1628      <identifier> ::= </unqualified source code identifier>  */
1629
1630 static void
1631 write_identifier (const char *identifier)
1632 {
1633   MANGLE_TRACE ("identifier", identifier);
1634   write_string (identifier);
1635 }
1636
1637 /* Handle constructor productions of non-terminal <special-name>.
1638    CTOR is a constructor FUNCTION_DECL.
1639
1640      <special-name> ::= C1   # complete object constructor
1641                     ::= C2   # base object constructor
1642                     ::= C3   # complete object allocating constructor
1643
1644    Currently, allocating constructors are never used.  */
1645
1646 static void
1647 write_special_name_constructor (const tree ctor)
1648 {
1649   if (DECL_BASE_CONSTRUCTOR_P (ctor))
1650     write_string ("C2");
1651   /* This is the old-style "[unified]" constructor.
1652      In some cases, we may emit this function and call
1653      it from the clones in order to share code and save space.  */
1654   else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (ctor))
1655     write_string ("C4");
1656   else
1657     {
1658       gcc_assert (DECL_COMPLETE_CONSTRUCTOR_P (ctor));
1659       write_string ("C1");
1660     }
1661 }
1662
1663 /* Handle destructor productions of non-terminal <special-name>.
1664    DTOR is a destructor FUNCTION_DECL.
1665
1666      <special-name> ::= D0 # deleting (in-charge) destructor
1667                     ::= D1 # complete object (in-charge) destructor
1668                     ::= D2 # base object (not-in-charge) destructor  */
1669
1670 static void
1671 write_special_name_destructor (const tree dtor)
1672 {
1673   if (DECL_DELETING_DESTRUCTOR_P (dtor))
1674     write_string ("D0");
1675   else if (DECL_BASE_DESTRUCTOR_P (dtor))
1676     write_string ("D2");
1677   else if (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (dtor))
1678     /* This is the old-style "[unified]" destructor.
1679        In some cases, we may emit this function and call
1680        it from the clones in order to share code and save space.  */
1681     write_string ("D4");
1682   else
1683     {
1684       gcc_assert (DECL_COMPLETE_DESTRUCTOR_P (dtor));
1685       write_string ("D1");
1686     }
1687 }
1688
1689 /* Scan the vector of local classes and return how many others with the
1690    same name (or same no name) and context precede ENTITY.  */
1691
1692 static int
1693 local_class_index (tree entity)
1694 {
1695   int ix, discriminator = 0;
1696   tree name = (TYPE_ANONYMOUS_P (entity) ? NULL_TREE
1697                : TYPE_IDENTIFIER (entity));
1698   tree ctx = TYPE_CONTEXT (entity);
1699   for (ix = 0; ; ix++)
1700     {
1701       tree type = (*local_classes)[ix];
1702       if (type == entity)
1703         return discriminator;
1704       if (TYPE_CONTEXT (type) == ctx
1705           && (name ? TYPE_IDENTIFIER (type) == name
1706               : TYPE_ANONYMOUS_P (type)))
1707         ++discriminator;
1708     }
1709   gcc_unreachable ();
1710 }
1711
1712 /* Return the discriminator for ENTITY appearing inside
1713    FUNCTION.  The discriminator is the lexical ordinal of VAR among
1714    entities with the same name in the same FUNCTION.  */
1715
1716 static int
1717 discriminator_for_local_entity (tree entity)
1718 {
1719   if (DECL_DISCRIMINATOR_P (entity))
1720     {
1721       if (DECL_DISCRIMINATOR_SET_P (entity))
1722         return DECL_DISCRIMINATOR (entity);
1723       else
1724         /* The first entity with a particular name doesn't get
1725            DECL_DISCRIMINATOR set up.  */
1726         return 0;
1727     }
1728   else if (TREE_CODE (entity) == TYPE_DECL)
1729     {
1730       /* Scan the list of local classes.  */
1731       entity = TREE_TYPE (entity);
1732
1733       /* Lambdas and unnamed types have their own discriminators.  */
1734       if (LAMBDA_TYPE_P (entity) || TYPE_ANONYMOUS_P (entity))
1735         return 0;
1736
1737       return local_class_index (entity);
1738     }
1739   else
1740     gcc_unreachable ();
1741 }
1742
1743 /* Return the discriminator for STRING, a string literal used inside
1744    FUNCTION.  The discriminator is the lexical ordinal of STRING among
1745    string literals used in FUNCTION.  */
1746
1747 static int
1748 discriminator_for_string_literal (tree /*function*/,
1749                                   tree /*string*/)
1750 {
1751   /* For now, we don't discriminate amongst string literals.  */
1752   return 0;
1753 }
1754
1755 /*   <discriminator> := _ <number>
1756
1757    The discriminator is used only for the second and later occurrences
1758    of the same name within a single function. In this case <number> is
1759    n - 2, if this is the nth occurrence, in lexical order.  */
1760
1761 static void
1762 write_discriminator (const int discriminator)
1763 {
1764   /* If discriminator is zero, don't write anything.  Otherwise...  */
1765   if (discriminator > 0)
1766     {
1767       write_char ('_');
1768       write_unsigned_number (discriminator - 1);
1769     }
1770 }
1771
1772 /* Mangle the name of a function-scope entity.  FUNCTION is the
1773    FUNCTION_DECL for the enclosing function, or a PARM_DECL for lambdas in
1774    default argument scope.  ENTITY is the decl for the entity itself.
1775    LOCAL_ENTITY is the entity that's directly scoped in FUNCTION_DECL,
1776    either ENTITY itself or an enclosing scope of ENTITY.
1777
1778      <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1779                   := Z <function encoding> E s [<discriminator>]
1780                   := Z <function encoding> Ed [ <parameter number> ] _ <entity name> */
1781
1782 static void
1783 write_local_name (tree function, const tree local_entity,
1784                   const tree entity)
1785 {
1786   tree parm = NULL_TREE;
1787
1788   MANGLE_TRACE_TREE ("local-name", entity);
1789
1790   if (TREE_CODE (function) == PARM_DECL)
1791     {
1792       parm = function;
1793       function = DECL_CONTEXT (parm);
1794     }
1795
1796   write_char ('Z');
1797   write_encoding (function);
1798   write_char ('E');
1799
1800   /* For this purpose, parameters are numbered from right-to-left.  */
1801   if (parm)
1802     {
1803       tree t;
1804       int i = 0;
1805       for (t = DECL_ARGUMENTS (function); t; t = DECL_CHAIN (t))
1806         {
1807           if (t == parm)
1808             i = 1;
1809           else if (i)
1810             ++i;
1811         }
1812       write_char ('d');
1813       write_compact_number (i - 1);
1814     }
1815
1816   if (TREE_CODE (entity) == STRING_CST)
1817     {
1818       write_char ('s');
1819       write_discriminator (discriminator_for_string_literal (function,
1820                                                              entity));
1821     }
1822   else
1823     {
1824       /* Now the <entity name>.  Let write_name know its being called
1825          from <local-name>, so it doesn't try to process the enclosing
1826          function scope again.  */
1827       write_name (entity, /*ignore_local_scope=*/1);
1828       write_discriminator (discriminator_for_local_entity (local_entity));
1829     }
1830 }
1831
1832 /* Non-terminals <type> and <CV-qualifier>.
1833
1834      <type> ::= <builtin-type>
1835             ::= <function-type>
1836             ::= <class-enum-type>
1837             ::= <array-type>
1838             ::= <pointer-to-member-type>
1839             ::= <template-param>
1840             ::= <substitution>
1841             ::= <CV-qualifier>
1842             ::= P <type>    # pointer-to
1843             ::= R <type>    # reference-to
1844             ::= C <type>    # complex pair (C 2000)
1845             ::= G <type>    # imaginary (C 2000)     [not supported]
1846             ::= U <source-name> <type>   # vendor extended type qualifier
1847
1848    C++0x extensions
1849
1850      <type> ::= RR <type>   # rvalue reference-to
1851      <type> ::= Dt <expression> # decltype of an id-expression or 
1852                                 # class member access
1853      <type> ::= DT <expression> # decltype of an expression
1854      <type> ::= Dn              # decltype of nullptr
1855
1856    TYPE is a type node.  */
1857
1858 static void
1859 write_type (tree type)
1860 {
1861   /* This gets set to nonzero if TYPE turns out to be a (possibly
1862      CV-qualified) builtin type.  */
1863   int is_builtin_type = 0;
1864
1865   MANGLE_TRACE_TREE ("type", type);
1866
1867   if (type == error_mark_node)
1868     return;
1869
1870   type = canonicalize_for_substitution (type);
1871   if (find_substitution (type))
1872     return;
1873
1874
1875   if (write_CV_qualifiers_for_type (type) > 0)
1876     /* If TYPE was CV-qualified, we just wrote the qualifiers; now
1877        mangle the unqualified type.  The recursive call is needed here
1878        since both the qualified and unqualified types are substitution
1879        candidates.  */
1880     {
1881       tree t = TYPE_MAIN_VARIANT (type);
1882       if (TREE_CODE (t) == FUNCTION_TYPE
1883           || TREE_CODE (t) == METHOD_TYPE)
1884         {
1885           t = build_ref_qualified_type (t, type_memfn_rqual (type));
1886           if (abi_version_at_least (8))
1887             /* Avoid adding the unqualified function type as a substitution.  */
1888             write_function_type (t);
1889           else
1890             write_type (t);
1891           if (abi_version_crosses (8))
1892             G.need_abi_warning = 1;
1893         }
1894       else
1895         write_type (t);
1896     }
1897   else if (TREE_CODE (type) == ARRAY_TYPE)
1898     /* It is important not to use the TYPE_MAIN_VARIANT of TYPE here
1899        so that the cv-qualification of the element type is available
1900        in write_array_type.  */
1901     write_array_type (type);
1902   else
1903     {
1904       tree type_orig = type;
1905
1906       /* See through any typedefs.  */
1907       type = TYPE_MAIN_VARIANT (type);
1908       if (TREE_CODE (type) == FUNCTION_TYPE
1909           || TREE_CODE (type) == METHOD_TYPE)
1910         type = build_ref_qualified_type (type, type_memfn_rqual (type_orig));
1911
1912       /* According to the C++ ABI, some library classes are passed the
1913          same as the scalar type of their single member and use the same
1914          mangling.  */
1915       if (TREE_CODE (type) == RECORD_TYPE && TYPE_TRANSPARENT_AGGR (type))
1916         type = TREE_TYPE (first_field (type));
1917
1918       if (TYPE_PTRDATAMEM_P (type))
1919         write_pointer_to_member_type (type);
1920       else
1921         {
1922           /* Handle any target-specific fundamental types.  */
1923           const char *target_mangling
1924             = targetm.mangle_type (type_orig);
1925
1926           if (target_mangling)
1927             {
1928               write_string (target_mangling);
1929               /* Add substitutions for types other than fundamental
1930                  types.  */
1931               if (!VOID_TYPE_P (type)
1932                   && TREE_CODE (type) != INTEGER_TYPE
1933                   && TREE_CODE (type) != REAL_TYPE
1934                   && TREE_CODE (type) != BOOLEAN_TYPE)
1935                 add_substitution (type);
1936               return;
1937             }
1938
1939           switch (TREE_CODE (type))
1940             {
1941             case VOID_TYPE:
1942             case BOOLEAN_TYPE:
1943             case INTEGER_TYPE:  /* Includes wchar_t.  */
1944             case REAL_TYPE:
1945             case FIXED_POINT_TYPE:
1946               {
1947                 /* If this is a typedef, TYPE may not be one of
1948                    the standard builtin type nodes, but an alias of one.  Use
1949                    TYPE_MAIN_VARIANT to get to the underlying builtin type.  */
1950                 write_builtin_type (TYPE_MAIN_VARIANT (type));
1951                 ++is_builtin_type;
1952               }
1953               break;
1954
1955             case COMPLEX_TYPE:
1956               write_char ('C');
1957               write_type (TREE_TYPE (type));
1958               break;
1959
1960             case FUNCTION_TYPE:
1961             case METHOD_TYPE:
1962               write_function_type (type);
1963               break;
1964
1965             case UNION_TYPE:
1966             case RECORD_TYPE:
1967             case ENUMERAL_TYPE:
1968               /* A pointer-to-member function is represented as a special
1969                  RECORD_TYPE, so check for this first.  */
1970               if (TYPE_PTRMEMFUNC_P (type))
1971                 write_pointer_to_member_type (type);
1972               else
1973                 write_class_enum_type (type);
1974               break;
1975
1976             case TYPENAME_TYPE:
1977             case UNBOUND_CLASS_TEMPLATE:
1978               /* We handle TYPENAME_TYPEs and UNBOUND_CLASS_TEMPLATEs like
1979                  ordinary nested names.  */
1980               write_nested_name (TYPE_STUB_DECL (type));
1981               break;
1982
1983             case POINTER_TYPE:
1984             case REFERENCE_TYPE:
1985               if (TYPE_PTR_P (type))
1986                 write_char ('P');
1987               else if (TYPE_REF_IS_RVALUE (type))
1988                 write_char ('O');
1989               else
1990                 write_char ('R');
1991               {
1992                 tree target = TREE_TYPE (type);
1993                 /* Attribute const/noreturn are not reflected in mangling.
1994                    We strip them here rather than at a lower level because
1995                    a typedef or template argument can have function type
1996                    with function-cv-quals (that use the same representation),
1997                    but you can't have a pointer/reference to such a type.  */
1998                 if (TREE_CODE (target) == FUNCTION_TYPE)
1999                   {
2000                     if (abi_version_crosses (5)
2001                         && TYPE_QUALS (target) != TYPE_UNQUALIFIED)
2002                       G.need_abi_warning = 1;
2003                     if (abi_version_at_least (5))
2004                       target = build_qualified_type (target, TYPE_UNQUALIFIED);
2005                   }
2006                 write_type (target);
2007               }
2008               break;
2009
2010             case TEMPLATE_TYPE_PARM:
2011               if (is_auto (type))
2012                 {
2013                   if (AUTO_IS_DECLTYPE (type))
2014                     write_identifier ("Dc");
2015                   else
2016                     write_identifier ("Da");
2017                   ++is_builtin_type;
2018                   break;
2019                 }
2020               /* else fall through.  */
2021             case TEMPLATE_PARM_INDEX:
2022               write_template_param (type);
2023               break;
2024
2025             case TEMPLATE_TEMPLATE_PARM:
2026               write_template_template_param (type);
2027               break;
2028
2029             case BOUND_TEMPLATE_TEMPLATE_PARM:
2030               write_template_template_param (type);
2031               write_template_args
2032                 (TI_ARGS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (type)));
2033               break;
2034
2035             case VECTOR_TYPE:
2036               if (abi_version_at_least (4))
2037                 {
2038                   write_string ("Dv");
2039                   /* Non-constant vector size would be encoded with
2040                      _ expression, but we don't support that yet.  */
2041                   write_unsigned_number (TYPE_VECTOR_SUBPARTS (type));
2042                   write_char ('_');
2043                 }
2044               else
2045                 write_string ("U8__vector");
2046               if (abi_version_crosses (4))
2047                 G.need_abi_warning = 1;
2048               write_type (TREE_TYPE (type));
2049               break;
2050
2051             case TYPE_PACK_EXPANSION:
2052               write_string ("Dp");
2053               write_type (PACK_EXPANSION_PATTERN (type));
2054               break;
2055
2056             case DECLTYPE_TYPE:
2057               /* These shouldn't make it into mangling.  */
2058               gcc_assert (!DECLTYPE_FOR_LAMBDA_CAPTURE (type)
2059                           && !DECLTYPE_FOR_LAMBDA_PROXY (type));
2060
2061               /* In ABI <5, we stripped decltype of a plain decl.  */
2062               if (DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (type))
2063                 {
2064                   tree expr = DECLTYPE_TYPE_EXPR (type);
2065                   tree etype = NULL_TREE;
2066                   switch (TREE_CODE (expr))
2067                     {
2068                     case VAR_DECL:
2069                     case PARM_DECL:
2070                     case RESULT_DECL:
2071                     case FUNCTION_DECL:
2072                     case CONST_DECL:
2073                     case TEMPLATE_PARM_INDEX:
2074                       etype = TREE_TYPE (expr);
2075                       break;
2076
2077                     default:
2078                       break;
2079                     }
2080
2081                   if (etype && !type_uses_auto (etype))
2082                     {
2083                       if (abi_version_crosses (5))
2084                         G.need_abi_warning = 1;
2085                       if (!abi_version_at_least (5))
2086                         {
2087                           write_type (etype);
2088                           return;
2089                         }
2090                     }
2091                 }
2092
2093               write_char ('D');
2094               if (DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (type))
2095                 write_char ('t');
2096               else
2097                 write_char ('T');
2098               ++cp_unevaluated_operand;
2099               write_expression (DECLTYPE_TYPE_EXPR (type));
2100               --cp_unevaluated_operand;
2101               write_char ('E');
2102               break;
2103
2104             case NULLPTR_TYPE:
2105               write_string ("Dn");
2106               if (abi_version_at_least (7))
2107                 ++is_builtin_type;
2108               if (abi_version_crosses (7))
2109                 G.need_abi_warning = 1;
2110               break;
2111
2112             case TYPEOF_TYPE:
2113               sorry ("mangling typeof, use decltype instead");
2114               break;
2115
2116             case UNDERLYING_TYPE:
2117               sorry ("mangling __underlying_type");
2118               break;
2119
2120             case LANG_TYPE:
2121               /* fall through.  */
2122
2123             default:
2124               gcc_unreachable ();
2125             }
2126         }
2127     }
2128
2129   /* Types other than builtin types are substitution candidates.  */
2130   if (!is_builtin_type)
2131     add_substitution (type);
2132 }
2133
2134 /* Non-terminal <CV-qualifiers> for type nodes.  Returns the number of
2135    CV-qualifiers written for TYPE.
2136
2137      <CV-qualifiers> ::= [r] [V] [K]  */
2138
2139 static int
2140 write_CV_qualifiers_for_type (const tree type)
2141 {
2142   int num_qualifiers = 0;
2143
2144   /* The order is specified by:
2145
2146        "In cases where multiple order-insensitive qualifiers are
2147        present, they should be ordered 'K' (closest to the base type),
2148        'V', 'r', and 'U' (farthest from the base type) ..."
2149
2150      Note that we do not use cp_type_quals below; given "const
2151      int[3]", the "const" is emitted with the "int", not with the
2152      array.  */
2153   cp_cv_quals quals = TYPE_QUALS (type);
2154
2155   if (quals & TYPE_QUAL_RESTRICT)
2156     {
2157       write_char ('r');
2158       ++num_qualifiers;
2159     }
2160   if (quals & TYPE_QUAL_VOLATILE)
2161     {
2162       write_char ('V');
2163       ++num_qualifiers;
2164     }
2165   if (quals & TYPE_QUAL_CONST)
2166     {
2167       write_char ('K');
2168       ++num_qualifiers;
2169     }
2170
2171   return num_qualifiers;
2172 }
2173
2174 /* Non-terminal <builtin-type>.
2175
2176      <builtin-type> ::= v   # void
2177                     ::= b   # bool
2178                     ::= w   # wchar_t
2179                     ::= c   # char
2180                     ::= a   # signed char
2181                     ::= h   # unsigned char
2182                     ::= s   # short
2183                     ::= t   # unsigned short
2184                     ::= i   # int
2185                     ::= j   # unsigned int
2186                     ::= l   # long
2187                     ::= m   # unsigned long
2188                     ::= x   # long long, __int64
2189                     ::= y   # unsigned long long, __int64
2190                     ::= n   # __int128
2191                     ::= o   # unsigned __int128
2192                     ::= f   # float
2193                     ::= d   # double
2194                     ::= e   # long double, __float80
2195                     ::= g   # __float128          [not supported]
2196                     ::= u <source-name>  # vendor extended type */
2197
2198 static void
2199 write_builtin_type (tree type)
2200 {
2201   if (TYPE_CANONICAL (type))
2202     type = TYPE_CANONICAL (type);
2203
2204   switch (TREE_CODE (type))
2205     {
2206     case VOID_TYPE:
2207       write_char ('v');
2208       break;
2209
2210     case BOOLEAN_TYPE:
2211       write_char ('b');
2212       break;
2213
2214     case INTEGER_TYPE:
2215       /* TYPE may still be wchar_t, char16_t, or char32_t, since that
2216          isn't in integer_type_nodes.  */
2217       if (type == wchar_type_node)
2218         write_char ('w');
2219       else if (type == char16_type_node)
2220         write_string ("Ds");
2221       else if (type == char32_type_node)
2222         write_string ("Di");
2223       else if (TYPE_FOR_JAVA (type))
2224         write_java_integer_type_codes (type);
2225       else
2226         {
2227           size_t itk;
2228           /* Assume TYPE is one of the shared integer type nodes.  Find
2229              it in the array of these nodes.  */
2230         iagain:
2231           for (itk = 0; itk < itk_none; ++itk)
2232             if (integer_types[itk] != NULL_TREE
2233                 && integer_type_codes[itk] != '\0'
2234                 && type == integer_types[itk])
2235               {
2236                 /* Print the corresponding single-letter code.  */
2237                 write_char (integer_type_codes[itk]);
2238                 break;
2239               }
2240
2241           if (itk == itk_none)
2242             {
2243               tree t = c_common_type_for_mode (TYPE_MODE (type),
2244                                                TYPE_UNSIGNED (type));
2245               if (type != t)
2246                 {
2247                   type = t;
2248                   goto iagain;
2249                 }
2250
2251               if (TYPE_PRECISION (type) == 128)
2252                 write_char (TYPE_UNSIGNED (type) ? 'o' : 'n');
2253               else
2254                 {
2255                   /* Allow for cases where TYPE is not one of the shared
2256                      integer type nodes and write a "vendor extended builtin
2257                      type" with a name the form intN or uintN, respectively.
2258                      Situations like this can happen if you have an
2259                      __attribute__((__mode__(__SI__))) type and use exotic
2260                      switches like '-mint8' on AVR.  Of course, this is
2261                      undefined by the C++ ABI (and '-mint8' is not even
2262                      Standard C conforming), but when using such special
2263                      options you're pretty much in nowhere land anyway.  */
2264                   const char *prefix;
2265                   char prec[11];        /* up to ten digits for an unsigned */
2266
2267                   prefix = TYPE_UNSIGNED (type) ? "uint" : "int";
2268                   sprintf (prec, "%u", (unsigned) TYPE_PRECISION (type));
2269                   write_char ('u');     /* "vendor extended builtin type" */
2270                   write_unsigned_number (strlen (prefix) + strlen (prec));
2271                   write_string (prefix);
2272                   write_string (prec);
2273                 }
2274             }
2275         }
2276       break;
2277
2278     case REAL_TYPE:
2279       if (type == float_type_node
2280           || type == java_float_type_node)
2281         write_char ('f');
2282       else if (type == double_type_node
2283                || type == java_double_type_node)
2284         write_char ('d');
2285       else if (type == long_double_type_node)
2286         write_char ('e');
2287       else if (type == dfloat32_type_node)
2288         write_string ("Df");
2289       else if (type == dfloat64_type_node)
2290         write_string ("Dd");
2291       else if (type == dfloat128_type_node)
2292         write_string ("De");
2293       else
2294         gcc_unreachable ();
2295       break;
2296
2297     case FIXED_POINT_TYPE:
2298       write_string ("DF");
2299       if (GET_MODE_IBIT (TYPE_MODE (type)) > 0)
2300         write_unsigned_number (GET_MODE_IBIT (TYPE_MODE (type)));
2301       if (type == fract_type_node
2302           || type == sat_fract_type_node
2303           || type == accum_type_node
2304           || type == sat_accum_type_node)
2305         write_char ('i');
2306       else if (type == unsigned_fract_type_node
2307                || type == sat_unsigned_fract_type_node
2308                || type == unsigned_accum_type_node
2309                || type == sat_unsigned_accum_type_node)
2310         write_char ('j');
2311       else if (type == short_fract_type_node
2312                || type == sat_short_fract_type_node
2313                || type == short_accum_type_node
2314                || type == sat_short_accum_type_node)
2315         write_char ('s');
2316       else if (type == unsigned_short_fract_type_node
2317                || type == sat_unsigned_short_fract_type_node
2318                || type == unsigned_short_accum_type_node
2319                || type == sat_unsigned_short_accum_type_node)
2320         write_char ('t');
2321       else if (type == long_fract_type_node
2322                || type == sat_long_fract_type_node
2323                || type == long_accum_type_node
2324                || type == sat_long_accum_type_node)
2325         write_char ('l');
2326       else if (type == unsigned_long_fract_type_node
2327                || type == sat_unsigned_long_fract_type_node
2328                || type == unsigned_long_accum_type_node
2329                || type == sat_unsigned_long_accum_type_node)
2330         write_char ('m');
2331       else if (type == long_long_fract_type_node
2332                || type == sat_long_long_fract_type_node
2333                || type == long_long_accum_type_node
2334                || type == sat_long_long_accum_type_node)
2335         write_char ('x');
2336       else if (type == unsigned_long_long_fract_type_node
2337                || type == sat_unsigned_long_long_fract_type_node
2338                || type == unsigned_long_long_accum_type_node
2339                || type == sat_unsigned_long_long_accum_type_node)
2340         write_char ('y');
2341       else
2342         sorry ("mangling unknown fixed point type");
2343       write_unsigned_number (GET_MODE_FBIT (TYPE_MODE (type)));
2344       if (TYPE_SATURATING (type))
2345         write_char ('s');
2346       else
2347         write_char ('n');
2348       break;
2349
2350     default:
2351       gcc_unreachable ();
2352     }
2353 }
2354
2355 /* Non-terminal <function-type>.  NODE is a FUNCTION_TYPE or
2356    METHOD_TYPE.  The return type is mangled before the parameter
2357    types.
2358
2359      <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] E   */
2360
2361 static void
2362 write_function_type (const tree type)
2363 {
2364   MANGLE_TRACE_TREE ("function-type", type);
2365
2366   /* For a pointer to member function, the function type may have
2367      cv-qualifiers, indicating the quals for the artificial 'this'
2368      parameter.  */
2369   if (TREE_CODE (type) == METHOD_TYPE)
2370     {
2371       /* The first parameter must be a POINTER_TYPE pointing to the
2372          `this' parameter.  */
2373       tree this_type = class_of_this_parm (type);
2374       write_CV_qualifiers_for_type (this_type);
2375     }
2376
2377   write_char ('F');
2378   /* We don't track whether or not a type is `extern "C"'.  Note that
2379      you can have an `extern "C"' function that does not have
2380      `extern "C"' type, and vice versa:
2381
2382        extern "C" typedef void function_t();
2383        function_t f; // f has C++ linkage, but its type is
2384                      // `extern "C"'
2385
2386        typedef void function_t();
2387        extern "C" function_t f; // Vice versa.
2388
2389      See [dcl.link].  */
2390   write_bare_function_type (type, /*include_return_type_p=*/1,
2391                             /*decl=*/NULL);
2392   if (FUNCTION_REF_QUALIFIED (type))
2393     {
2394       if (FUNCTION_RVALUE_QUALIFIED (type))
2395         write_char ('O');
2396       else
2397         write_char ('R');
2398     }
2399   write_char ('E');
2400 }
2401
2402 /* Non-terminal <bare-function-type>.  TYPE is a FUNCTION_TYPE or
2403    METHOD_TYPE.  If INCLUDE_RETURN_TYPE is nonzero, the return value
2404    is mangled before the parameter types.  If non-NULL, DECL is
2405    FUNCTION_DECL for the function whose type is being emitted.
2406
2407    If DECL is a member of a Java type, then a literal 'J'
2408    is output and the return type is mangled as if INCLUDE_RETURN_TYPE
2409    were nonzero.
2410
2411      <bare-function-type> ::= [J]</signature/ type>+  */
2412
2413 static void
2414 write_bare_function_type (const tree type, const int include_return_type_p,
2415                           const tree decl)
2416 {
2417   int java_method_p;
2418
2419   MANGLE_TRACE_TREE ("bare-function-type", type);
2420
2421   /* Detect Java methods and emit special encoding.  */
2422   if (decl != NULL
2423       && DECL_FUNCTION_MEMBER_P (decl)
2424       && TYPE_FOR_JAVA (DECL_CONTEXT (decl))
2425       && !DECL_CONSTRUCTOR_P (decl)
2426       && !DECL_DESTRUCTOR_P (decl)
2427       && !DECL_CONV_FN_P (decl))
2428     {
2429       java_method_p = 1;
2430       write_char ('J');
2431     }
2432   else
2433     {
2434       java_method_p = 0;
2435     }
2436
2437   /* Mangle the return type, if requested.  */
2438   if (include_return_type_p || java_method_p)
2439     write_type (TREE_TYPE (type));
2440
2441   /* Now mangle the types of the arguments.  */
2442   ++G.parm_depth;
2443   write_method_parms (TYPE_ARG_TYPES (type),
2444                       TREE_CODE (type) == METHOD_TYPE,
2445                       decl);
2446   --G.parm_depth;
2447 }
2448
2449 /* Write the mangled representation of a method parameter list of
2450    types given in PARM_TYPES.  If METHOD_P is nonzero, the function is
2451    considered a non-static method, and the this parameter is omitted.
2452    If non-NULL, DECL is the FUNCTION_DECL for the function whose
2453    parameters are being emitted.  */
2454
2455 static void
2456 write_method_parms (tree parm_types, const int method_p, const tree decl)
2457 {
2458   tree first_parm_type;
2459   tree parm_decl = decl ? DECL_ARGUMENTS (decl) : NULL_TREE;
2460
2461   /* Assume this parameter type list is variable-length.  If it ends
2462      with a void type, then it's not.  */
2463   int varargs_p = 1;
2464
2465   /* If this is a member function, skip the first arg, which is the
2466      this pointer.
2467        "Member functions do not encode the type of their implicit this
2468        parameter."
2469
2470      Similarly, there's no need to mangle artificial parameters, like
2471      the VTT parameters for constructors and destructors.  */
2472   if (method_p)
2473     {
2474       parm_types = TREE_CHAIN (parm_types);
2475       parm_decl = parm_decl ? DECL_CHAIN (parm_decl) : NULL_TREE;
2476
2477       while (parm_decl && DECL_ARTIFICIAL (parm_decl))
2478         {
2479           parm_types = TREE_CHAIN (parm_types);
2480           parm_decl = DECL_CHAIN (parm_decl);
2481         }
2482     }
2483
2484   for (first_parm_type = parm_types;
2485        parm_types;
2486        parm_types = TREE_CHAIN (parm_types))
2487     {
2488       tree parm = TREE_VALUE (parm_types);
2489       if (parm == void_type_node)
2490         {
2491           /* "Empty parameter lists, whether declared as () or
2492              conventionally as (void), are encoded with a void parameter
2493              (v)."  */
2494           if (parm_types == first_parm_type)
2495             write_type (parm);
2496           /* If the parm list is terminated with a void type, it's
2497              fixed-length.  */
2498           varargs_p = 0;
2499           /* A void type better be the last one.  */
2500           gcc_assert (TREE_CHAIN (parm_types) == NULL);
2501         }
2502       else
2503         write_type (parm);
2504     }
2505
2506   if (varargs_p)
2507     /* <builtin-type> ::= z  # ellipsis  */
2508     write_char ('z');
2509 }
2510
2511 /* <class-enum-type> ::= <name>  */
2512
2513 static void
2514 write_class_enum_type (const tree type)
2515 {
2516   write_name (TYPE_NAME (type), /*ignore_local_scope=*/0);
2517 }
2518
2519 /* Non-terminal <template-args>.  ARGS is a TREE_VEC of template
2520    arguments.
2521
2522      <template-args> ::= I <template-arg>* E  */
2523
2524 static void
2525 write_template_args (tree args)
2526 {
2527   int i;
2528   int length = 0;
2529
2530   MANGLE_TRACE_TREE ("template-args", args);
2531
2532   write_char ('I');
2533
2534   if (args)
2535     length = TREE_VEC_LENGTH (args);
2536
2537   if (args && TREE_CODE (TREE_VEC_ELT (args, 0)) == TREE_VEC)
2538     {
2539       /* We have nested template args.  We want the innermost template
2540          argument list.  */
2541       args = TREE_VEC_ELT (args, length - 1);
2542       length = TREE_VEC_LENGTH (args);
2543     }
2544   for (i = 0; i < length; ++i)
2545     write_template_arg (TREE_VEC_ELT (args, i));
2546
2547   write_char ('E');
2548 }
2549
2550 /* Write out the
2551    <unqualified-name>
2552    <unqualified-name> <template-args>
2553    part of SCOPE_REF or COMPONENT_REF mangling.  */
2554
2555 static void
2556 write_member_name (tree member)
2557 {
2558   if (identifier_p (member))
2559     write_unqualified_id (member);
2560   else if (DECL_P (member))
2561     write_unqualified_name (member);
2562   else if (TREE_CODE (member) == TEMPLATE_ID_EXPR)
2563     {
2564       tree name = TREE_OPERAND (member, 0);
2565       if (TREE_CODE (name) == OVERLOAD)
2566         name = OVL_FUNCTION (name);
2567       write_member_name (name);
2568       write_template_args (TREE_OPERAND (member, 1));
2569     }
2570   else
2571     write_expression (member);
2572 }
2573
2574 /* <expression> ::= <unary operator-name> <expression>
2575                 ::= <binary operator-name> <expression> <expression>
2576                 ::= <expr-primary>
2577
2578    <expr-primary> ::= <template-param>
2579                   ::= L <type> <value number> E         # literal
2580                   ::= L <mangled-name> E                # external name
2581                   ::= st <type>                         # sizeof
2582                   ::= sr <type> <unqualified-name>      # dependent name
2583                   ::= sr <type> <unqualified-name> <template-args> */
2584
2585 static void
2586 write_expression (tree expr)
2587 {
2588   enum tree_code code = TREE_CODE (expr);
2589
2590   /* Skip NOP_EXPRs.  They can occur when (say) a pointer argument
2591      is converted (via qualification conversions) to another
2592      type.  */
2593   while (TREE_CODE (expr) == NOP_EXPR
2594          /* Parentheses aren't mangled.  */
2595          || code == PAREN_EXPR
2596          || TREE_CODE (expr) == NON_LVALUE_EXPR)
2597     {
2598       expr = TREE_OPERAND (expr, 0);
2599       code = TREE_CODE (expr);
2600     }
2601
2602   if (code == BASELINK
2603       && (!type_unknown_p (expr)
2604           || !BASELINK_QUALIFIED_P (expr)))
2605     {
2606       expr = BASELINK_FUNCTIONS (expr);
2607       code = TREE_CODE (expr);
2608     }
2609
2610   /* Handle pointers-to-members by making them look like expression
2611      nodes.  */
2612   if (code == PTRMEM_CST)
2613     {
2614       expr = build_nt (ADDR_EXPR,
2615                        build_qualified_name (/*type=*/NULL_TREE,
2616                                              PTRMEM_CST_CLASS (expr),
2617                                              PTRMEM_CST_MEMBER (expr),
2618                                              /*template_p=*/false));
2619       code = TREE_CODE (expr);
2620     }
2621
2622   /* Handle template parameters.  */
2623   if (code == TEMPLATE_TYPE_PARM
2624       || code == TEMPLATE_TEMPLATE_PARM
2625       || code == BOUND_TEMPLATE_TEMPLATE_PARM
2626       || code == TEMPLATE_PARM_INDEX)
2627     write_template_param (expr);
2628   /* Handle literals.  */
2629   else if (TREE_CODE_CLASS (code) == tcc_constant
2630            || code == CONST_DECL)
2631     write_template_arg_literal (expr);
2632   else if (code == PARM_DECL && DECL_ARTIFICIAL (expr))
2633     {
2634       gcc_assert (!strcmp ("this", IDENTIFIER_POINTER (DECL_NAME (expr))));
2635       write_string ("fpT");
2636     }
2637   else if (code == PARM_DECL)
2638     {
2639       /* A function parameter used in a late-specified return type.  */
2640       int index = DECL_PARM_INDEX (expr);
2641       int level = DECL_PARM_LEVEL (expr);
2642       int delta = G.parm_depth - level + 1;
2643       gcc_assert (index >= 1);
2644       write_char ('f');
2645       if (delta != 0)
2646         {
2647           if (abi_version_at_least (5))
2648             {
2649               /* Let L be the number of function prototype scopes from the
2650                  innermost one (in which the parameter reference occurs) up
2651                  to (and including) the one containing the declaration of
2652                  the referenced parameter.  If the parameter declaration
2653                  clause of the innermost function prototype scope has been
2654                  completely seen, it is not counted (in that case -- which
2655                  is perhaps the most common -- L can be zero).  */
2656               write_char ('L');
2657               write_unsigned_number (delta - 1);
2658             }
2659           if (abi_version_crosses (5))
2660             G.need_abi_warning = true;
2661         }
2662       write_char ('p');
2663       write_compact_number (index - 1);
2664     }
2665   else if (DECL_P (expr))
2666     {
2667       write_char ('L');
2668       write_mangled_name (expr, false);
2669       write_char ('E');
2670     }
2671   else if (TREE_CODE (expr) == SIZEOF_EXPR
2672            && SIZEOF_EXPR_TYPE_P (expr))
2673     {
2674       write_string ("st");
2675       write_type (TREE_TYPE (TREE_OPERAND (expr, 0)));
2676     }
2677   else if (TREE_CODE (expr) == SIZEOF_EXPR
2678            && TYPE_P (TREE_OPERAND (expr, 0)))
2679     {
2680       write_string ("st");
2681       write_type (TREE_OPERAND (expr, 0));
2682     }
2683   else if (TREE_CODE (expr) == ALIGNOF_EXPR
2684            && TYPE_P (TREE_OPERAND (expr, 0)))
2685     {
2686       write_string ("at");
2687       write_type (TREE_OPERAND (expr, 0));
2688     }
2689   else if (code == SCOPE_REF
2690            || code == BASELINK)
2691     {
2692       tree scope, member;
2693       if (code == SCOPE_REF)
2694         {
2695           scope = TREE_OPERAND (expr, 0);
2696           member = TREE_OPERAND (expr, 1);
2697         }
2698       else
2699         {
2700           scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (expr));
2701           member = BASELINK_FUNCTIONS (expr);
2702         }
2703
2704       /* If the MEMBER is a real declaration, then the qualifying
2705          scope was not dependent.  Ideally, we would not have a
2706          SCOPE_REF in those cases, but sometimes we do.  If the second
2707          argument is a DECL, then the name must not have been
2708          dependent.  */
2709       if (DECL_P (member))
2710         write_expression (member);
2711       else
2712         {
2713           write_string ("sr");
2714           write_type (scope);
2715           write_member_name (member);
2716         }
2717     }
2718   else if (INDIRECT_REF_P (expr)
2719            && TREE_TYPE (TREE_OPERAND (expr, 0))
2720            && TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == REFERENCE_TYPE)
2721     {
2722       write_expression (TREE_OPERAND (expr, 0));
2723     }
2724   else if (identifier_p (expr))
2725     {
2726       /* An operator name appearing as a dependent name needs to be
2727          specially marked to disambiguate between a use of the operator
2728          name and a use of the operator in an expression.  */
2729       if (IDENTIFIER_OPNAME_P (expr))
2730         write_string ("on");
2731       write_unqualified_id (expr);
2732     }
2733   else if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
2734     {
2735       tree fn = TREE_OPERAND (expr, 0);
2736       if (is_overloaded_fn (fn))
2737         fn = DECL_NAME (get_first_fn (fn));
2738       if (IDENTIFIER_OPNAME_P (fn))
2739         write_string ("on");
2740       write_unqualified_id (fn);
2741       write_template_args (TREE_OPERAND (expr, 1));
2742     }
2743   else if (TREE_CODE (expr) == MODOP_EXPR)
2744     {
2745       enum tree_code subop = TREE_CODE (TREE_OPERAND (expr, 1));
2746       const char *name = (assignment_operator_name_info[(int) subop]
2747                           .mangled_name);
2748       write_string (name);
2749       write_expression (TREE_OPERAND (expr, 0));
2750       write_expression (TREE_OPERAND (expr, 2));
2751     }
2752   else if (code == NEW_EXPR || code == VEC_NEW_EXPR)
2753     {
2754       /* ::= [gs] nw <expression>* _ <type> E
2755          ::= [gs] nw <expression>* _ <type> <initializer>
2756          ::= [gs] na <expression>* _ <type> E
2757          ::= [gs] na <expression>* _ <type> <initializer>
2758          <initializer> ::= pi <expression>* E  */
2759       tree placement = TREE_OPERAND (expr, 0);
2760       tree type = TREE_OPERAND (expr, 1);
2761       tree nelts = TREE_OPERAND (expr, 2);
2762       tree init = TREE_OPERAND (expr, 3);
2763       tree t;
2764
2765       gcc_assert (code == NEW_EXPR);
2766       if (TREE_OPERAND (expr, 2))
2767         code = VEC_NEW_EXPR;
2768
2769       if (NEW_EXPR_USE_GLOBAL (expr))
2770         write_string ("gs");
2771
2772       write_string (operator_name_info[(int) code].mangled_name);
2773
2774       for (t = placement; t; t = TREE_CHAIN (t))
2775         write_expression (TREE_VALUE (t));
2776
2777       write_char ('_');
2778
2779       if (nelts)
2780         {
2781           tree domain;
2782           ++processing_template_decl;
2783           domain = compute_array_index_type (NULL_TREE, nelts,
2784                                              tf_warning_or_error);
2785           type = build_cplus_array_type (type, domain);
2786           --processing_template_decl;
2787         }
2788       write_type (type);
2789
2790       if (init && TREE_CODE (init) == TREE_LIST
2791           && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
2792         write_expression (TREE_VALUE (init));
2793       else
2794         {
2795           if (init)
2796             write_string ("pi");
2797           if (init && init != void_node)
2798             for (t = init; t; t = TREE_CHAIN (t))
2799               write_expression (TREE_VALUE (t));
2800           write_char ('E');
2801         }
2802     }
2803   else if (code == DELETE_EXPR || code == VEC_DELETE_EXPR)
2804     {
2805       gcc_assert (code == DELETE_EXPR);
2806       if (DELETE_EXPR_USE_VEC (expr))
2807         code = VEC_DELETE_EXPR;
2808
2809       if (DELETE_EXPR_USE_GLOBAL (expr))
2810         write_string ("gs");
2811
2812       write_string (operator_name_info[(int) code].mangled_name);
2813
2814       write_expression (TREE_OPERAND (expr, 0));
2815     }
2816   else if (code == THROW_EXPR)
2817     {
2818       tree op = TREE_OPERAND (expr, 0);
2819       if (op)
2820         {
2821           write_string ("tw");
2822           write_expression (op);
2823         }
2824       else
2825         write_string ("tr");
2826     }
2827   else if (code == CONSTRUCTOR)
2828     {
2829       vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (expr);
2830       unsigned i; tree val;
2831
2832       if (BRACE_ENCLOSED_INITIALIZER_P (expr))
2833         write_string ("il");
2834       else
2835         {
2836           write_string ("tl");
2837           write_type (TREE_TYPE (expr));
2838         }
2839       FOR_EACH_CONSTRUCTOR_VALUE (elts, i, val)
2840         write_expression (val);
2841       write_char ('E');
2842     }
2843   else if (dependent_name (expr))
2844     {
2845       write_unqualified_id (dependent_name (expr));
2846     }
2847   else
2848     {
2849       int i, len;
2850       const char *name;
2851
2852       /* When we bind a variable or function to a non-type template
2853          argument with reference type, we create an ADDR_EXPR to show
2854          the fact that the entity's address has been taken.  But, we
2855          don't actually want to output a mangling code for the `&'.  */
2856       if (TREE_CODE (expr) == ADDR_EXPR
2857           && TREE_TYPE (expr)
2858           && TREE_CODE (TREE_TYPE (expr)) == REFERENCE_TYPE)
2859         {
2860           expr = TREE_OPERAND (expr, 0);
2861           if (DECL_P (expr))
2862             {
2863               write_expression (expr);
2864               return;
2865             }
2866
2867           code = TREE_CODE (expr);
2868         }
2869
2870       if (code == COMPONENT_REF)
2871         {
2872           tree ob = TREE_OPERAND (expr, 0);
2873
2874           if (TREE_CODE (ob) == ARROW_EXPR)
2875             {
2876               write_string (operator_name_info[(int)code].mangled_name);
2877               ob = TREE_OPERAND (ob, 0);
2878               write_expression (ob);
2879             }
2880           else if (!is_dummy_object (ob))
2881             {
2882               write_string ("dt");
2883               write_expression (ob);
2884             }
2885           /* else, for a non-static data member with no associated object (in
2886              unevaluated context), use the unresolved-name mangling.  */
2887
2888           write_member_name (TREE_OPERAND (expr, 1));
2889           return;
2890         }
2891
2892       /* If it wasn't any of those, recursively expand the expression.  */
2893       name = operator_name_info[(int) code].mangled_name;
2894
2895       /* We used to mangle const_cast and static_cast like a C cast.  */
2896       if (code == CONST_CAST_EXPR
2897           || code == STATIC_CAST_EXPR)
2898         {
2899           if (abi_version_crosses (6))
2900             G.need_abi_warning = 1;
2901           if (!abi_version_at_least (6))
2902             name = operator_name_info[CAST_EXPR].mangled_name;
2903         }
2904
2905       if (name == NULL)
2906         {
2907           switch (code)
2908             {
2909             case TRAIT_EXPR:
2910               error ("use of built-in trait %qE in function signature; "
2911                      "use library traits instead", expr);
2912               break;
2913
2914             default:
2915               sorry ("mangling %C", code);
2916               break;
2917             }
2918           return;
2919         }
2920       else
2921         write_string (name);    
2922
2923       switch (code)
2924         {
2925         case CALL_EXPR:
2926           {
2927             tree fn = CALL_EXPR_FN (expr);
2928
2929             if (TREE_CODE (fn) == ADDR_EXPR)
2930               fn = TREE_OPERAND (fn, 0);
2931
2932             /* Mangle a dependent name as the name, not whatever happens to
2933                be the first function in the overload set.  */
2934             if ((TREE_CODE (fn) == FUNCTION_DECL
2935                  || TREE_CODE (fn) == OVERLOAD)
2936                 && type_dependent_expression_p_push (expr))
2937               fn = DECL_NAME (get_first_fn (fn));
2938
2939             write_expression (fn);
2940           }
2941
2942           for (i = 0; i < call_expr_nargs (expr); ++i)
2943             write_expression (CALL_EXPR_ARG (expr, i));
2944           write_char ('E');
2945           break;
2946
2947         case CAST_EXPR:
2948           write_type (TREE_TYPE (expr));
2949           if (list_length (TREE_OPERAND (expr, 0)) == 1)          
2950             write_expression (TREE_VALUE (TREE_OPERAND (expr, 0)));
2951           else
2952             {
2953               tree args = TREE_OPERAND (expr, 0);
2954               write_char ('_');
2955               for (; args; args = TREE_CHAIN (args))
2956                 write_expression (TREE_VALUE (args));
2957               write_char ('E');
2958             }
2959           break;
2960
2961         case DYNAMIC_CAST_EXPR:
2962         case REINTERPRET_CAST_EXPR:
2963         case STATIC_CAST_EXPR:
2964         case CONST_CAST_EXPR:
2965           write_type (TREE_TYPE (expr));
2966           write_expression (TREE_OPERAND (expr, 0));
2967           break;
2968
2969         case PREINCREMENT_EXPR:
2970         case PREDECREMENT_EXPR:
2971           if (abi_version_at_least (6))
2972             write_char ('_');
2973           if (abi_version_crosses (6))
2974             G.need_abi_warning = 1;
2975           /* Fall through.  */
2976
2977         default:
2978           /* In the middle-end, some expressions have more operands than
2979              they do in templates (and mangling).  */
2980           len = cp_tree_operand_length (expr);
2981
2982           for (i = 0; i < len; ++i)
2983             {
2984               tree operand = TREE_OPERAND (expr, i);
2985               /* As a GNU extension, the middle operand of a
2986                  conditional may be omitted.  Since expression
2987                  manglings are supposed to represent the input token
2988                  stream, there's no good way to mangle such an
2989                  expression without extending the C++ ABI.  */
2990               if (code == COND_EXPR && i == 1 && !operand)
2991                 {
2992                   error ("omitted middle operand to %<?:%> operand "
2993                          "cannot be mangled");
2994                   continue;
2995                 }
2996               write_expression (operand);
2997             }
2998         }
2999     }
3000 }
3001
3002 /* Literal subcase of non-terminal <template-arg>.
3003
3004      "Literal arguments, e.g. "A<42L>", are encoded with their type
3005      and value. Negative integer values are preceded with "n"; for
3006      example, "A<-42L>" becomes "1AILln42EE". The bool value false is
3007      encoded as 0, true as 1."  */
3008
3009 static void
3010 write_template_arg_literal (const tree value)
3011 {
3012   write_char ('L');
3013   write_type (TREE_TYPE (value));
3014
3015   /* Write a null member pointer value as (type)0, regardless of its
3016      real representation.  */
3017   if (null_member_pointer_value_p (value))
3018     write_integer_cst (integer_zero_node);
3019   else
3020     switch (TREE_CODE (value))
3021       {
3022       case CONST_DECL:
3023         write_integer_cst (DECL_INITIAL (value));
3024         break;
3025
3026       case INTEGER_CST:
3027         gcc_assert (!same_type_p (TREE_TYPE (value), boolean_type_node)
3028                     || integer_zerop (value) || integer_onep (value));
3029         write_integer_cst (value);
3030         break;
3031
3032       case REAL_CST:
3033         write_real_cst (value);
3034         break;
3035
3036       case COMPLEX_CST:
3037         if (TREE_CODE (TREE_REALPART (value)) == INTEGER_CST
3038             && TREE_CODE (TREE_IMAGPART (value)) == INTEGER_CST)
3039           {
3040             write_integer_cst (TREE_REALPART (value));
3041             write_char ('_');
3042             write_integer_cst (TREE_IMAGPART (value));
3043           }
3044         else if (TREE_CODE (TREE_REALPART (value)) == REAL_CST
3045                  && TREE_CODE (TREE_IMAGPART (value)) == REAL_CST)
3046           {
3047             write_real_cst (TREE_REALPART (value));
3048             write_char ('_');
3049             write_real_cst (TREE_IMAGPART (value));
3050           }
3051         else
3052           gcc_unreachable ();
3053         break;
3054
3055       case STRING_CST:
3056         sorry ("string literal in function template signature");
3057         break;
3058
3059       default:
3060         gcc_unreachable ();
3061       }
3062
3063   write_char ('E');
3064 }
3065
3066 /* Non-terminal <template-arg>.
3067
3068      <template-arg> ::= <type>                          # type
3069                     ::= L <type> </value/ number> E     # literal
3070                     ::= LZ <name> E                     # external name
3071                     ::= X <expression> E                # expression  */
3072
3073 static void
3074 write_template_arg (tree node)
3075 {
3076   enum tree_code code = TREE_CODE (node);
3077
3078   MANGLE_TRACE_TREE ("template-arg", node);
3079
3080   /* A template template parameter's argument list contains TREE_LIST
3081      nodes of which the value field is the actual argument.  */
3082   if (code == TREE_LIST)
3083     {
3084       node = TREE_VALUE (node);
3085       /* If it's a decl, deal with its type instead.  */
3086       if (DECL_P (node))
3087         {
3088           node = TREE_TYPE (node);
3089           code = TREE_CODE (node);
3090         }
3091     }
3092
3093   if (REFERENCE_REF_P (node))
3094     node = TREE_OPERAND (node, 0);
3095   if (TREE_CODE (node) == NOP_EXPR
3096       && TREE_CODE (TREE_TYPE (node)) == REFERENCE_TYPE)
3097     {
3098       /* Template parameters can be of reference type. To maintain
3099          internal consistency, such arguments use a conversion from
3100          address of object to reference type.  */
3101       gcc_assert (TREE_CODE (TREE_OPERAND (node, 0)) == ADDR_EXPR);
3102       node = TREE_OPERAND (TREE_OPERAND (node, 0), 0);
3103     }
3104
3105   if (TREE_CODE (node) == BASELINK
3106       && !type_unknown_p (node))
3107     {
3108       if (abi_version_at_least (6))
3109         node = BASELINK_FUNCTIONS (node);
3110       if (abi_version_crosses (6))
3111         /* We wrongly wrapped a class-scope function in X/E.  */
3112         G.need_abi_warning = 1;
3113     }
3114
3115   if (ARGUMENT_PACK_P (node))
3116     {
3117       /* Expand the template argument pack. */
3118       tree args = ARGUMENT_PACK_ARGS (node);
3119       int i, length = TREE_VEC_LENGTH (args);
3120       if (abi_version_at_least (6))
3121         write_char ('J');
3122       else
3123         write_char ('I');
3124       if (abi_version_crosses (6))
3125         G.need_abi_warning = 1;
3126       for (i = 0; i < length; ++i)
3127         write_template_arg (TREE_VEC_ELT (args, i));
3128       write_char ('E');
3129     }
3130   else if (TYPE_P (node))
3131     write_type (node);
3132   else if (code == TEMPLATE_DECL)
3133     /* A template appearing as a template arg is a template template arg.  */
3134     write_template_template_arg (node);
3135   else if ((TREE_CODE_CLASS (code) == tcc_constant && code != PTRMEM_CST)
3136            || code == CONST_DECL
3137            || null_member_pointer_value_p (node))
3138     write_template_arg_literal (node);
3139   else if (DECL_P (node))
3140     {
3141       write_char ('L');
3142       /* Until ABI version 3, the underscore before the mangled name
3143          was incorrectly omitted.  */
3144       if (!abi_version_at_least (3))
3145         write_char ('Z');
3146       else
3147         write_string ("_Z");
3148       if (abi_version_crosses (3))
3149         G.need_abi_warning = 1;
3150       write_encoding (node);
3151       write_char ('E');
3152     }
3153   else
3154     {
3155       /* Template arguments may be expressions.  */
3156       write_char ('X');
3157       write_expression (node);
3158       write_char ('E');
3159     }
3160 }
3161
3162 /*  <template-template-arg>
3163                         ::= <name>
3164                         ::= <substitution>  */
3165
3166 static void
3167 write_template_template_arg (const tree decl)
3168 {
3169   MANGLE_TRACE_TREE ("template-template-arg", decl);
3170
3171   if (find_substitution (decl))
3172     return;
3173   write_name (decl, /*ignore_local_scope=*/0);
3174   add_substitution (decl);
3175 }
3176
3177
3178 /* Non-terminal <array-type>.  TYPE is an ARRAY_TYPE.
3179
3180      <array-type> ::= A [</dimension/ number>] _ </element/ type>
3181                   ::= A <expression> _ </element/ type>
3182
3183      "Array types encode the dimension (number of elements) and the
3184      element type. For variable length arrays, the dimension (but not
3185      the '_' separator) is omitted."  */
3186
3187 static void
3188 write_array_type (const tree type)
3189 {
3190   write_char ('A');
3191   if (TYPE_DOMAIN (type))
3192     {
3193       tree index_type;
3194       tree max;
3195
3196       index_type = TYPE_DOMAIN (type);
3197       /* The INDEX_TYPE gives the upper and lower bounds of the
3198          array.  */
3199       max = TYPE_MAX_VALUE (index_type);
3200       if (TREE_CODE (max) == INTEGER_CST)
3201         {
3202           /* The ABI specifies that we should mangle the number of
3203              elements in the array, not the largest allowed index.  */
3204           offset_int wmax = wi::to_offset (max) + 1;
3205           /* Truncate the result - this will mangle [0, SIZE_INT_MAX]
3206              number of elements as zero.  */
3207           wmax = wi::zext (wmax, TYPE_PRECISION (TREE_TYPE (max)));
3208           gcc_assert (wi::fits_uhwi_p (wmax));
3209           write_unsigned_number (wmax.to_uhwi ());
3210         }
3211       else
3212         {
3213           max = TREE_OPERAND (max, 0);
3214           write_expression (max);
3215         }
3216
3217     }
3218   write_char ('_');
3219   write_type (TREE_TYPE (type));
3220 }
3221
3222 /* Non-terminal <pointer-to-member-type> for pointer-to-member
3223    variables.  TYPE is a pointer-to-member POINTER_TYPE.
3224
3225      <pointer-to-member-type> ::= M </class/ type> </member/ type>  */
3226
3227 static void
3228 write_pointer_to_member_type (const tree type)
3229 {
3230   write_char ('M');
3231   write_type (TYPE_PTRMEM_CLASS_TYPE (type));
3232   write_type (TYPE_PTRMEM_POINTED_TO_TYPE (type));
3233 }
3234
3235 /* Non-terminal <template-param>.  PARM is a TEMPLATE_TYPE_PARM,
3236    TEMPLATE_TEMPLATE_PARM, BOUND_TEMPLATE_TEMPLATE_PARM or a
3237    TEMPLATE_PARM_INDEX.
3238
3239      <template-param> ::= T </parameter/ number> _  */
3240
3241 static void
3242 write_template_param (const tree parm)
3243 {
3244   int parm_index;
3245
3246   MANGLE_TRACE_TREE ("template-parm", parm);
3247
3248   switch (TREE_CODE (parm))
3249     {
3250     case TEMPLATE_TYPE_PARM:
3251     case TEMPLATE_TEMPLATE_PARM:
3252     case BOUND_TEMPLATE_TEMPLATE_PARM:
3253       parm_index = TEMPLATE_TYPE_IDX (parm);
3254       break;
3255
3256     case TEMPLATE_PARM_INDEX:
3257       parm_index = TEMPLATE_PARM_IDX (parm);
3258       break;
3259
3260     default:
3261       gcc_unreachable ();
3262     }
3263
3264   write_char ('T');
3265   /* NUMBER as it appears in the mangling is (-1)-indexed, with the
3266      earliest template param denoted by `_'.  */
3267   write_compact_number (parm_index);
3268 }
3269
3270 /*  <template-template-param>
3271                         ::= <template-param>
3272                         ::= <substitution>  */
3273
3274 static void
3275 write_template_template_param (const tree parm)
3276 {
3277   tree templ = NULL_TREE;
3278
3279   /* PARM, a TEMPLATE_TEMPLATE_PARM, is an instantiation of the
3280      template template parameter.  The substitution candidate here is
3281      only the template.  */
3282   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
3283     {
3284       templ
3285         = TI_TEMPLATE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm));
3286       if (find_substitution (templ))
3287         return;
3288     }
3289
3290   /* <template-param> encodes only the template parameter position,
3291      not its template arguments, which is fine here.  */
3292   write_template_param (parm);
3293   if (templ)
3294     add_substitution (templ);
3295 }
3296
3297 /* Non-terminal <substitution>.
3298
3299       <substitution> ::= S <seq-id> _
3300                      ::= S_  */
3301
3302 static void
3303 write_substitution (const int seq_id)
3304 {
3305   MANGLE_TRACE ("substitution", "");
3306
3307   write_char ('S');
3308   if (seq_id > 0)
3309     write_number (seq_id - 1, /*unsigned=*/1, 36);
3310   write_char ('_');
3311 }
3312
3313 /* Start mangling ENTITY.  */
3314
3315 static inline void
3316 start_mangling (const tree entity)
3317 {
3318   G.entity = entity;
3319   G.need_abi_warning = false;
3320   obstack_free (&name_obstack, name_base);
3321   mangle_obstack = &name_obstack;
3322   name_base = obstack_alloc (&name_obstack, 0);
3323 }
3324
3325 /* Done with mangling. If WARN is true, and the name of G.entity will
3326    be mangled differently in a future version of the ABI, issue a
3327    warning.  */
3328
3329 static void
3330 finish_mangling_internal (void)
3331 {
3332   /* Clear all the substitutions.  */
3333   vec_safe_truncate (G.substitutions, 0);
3334
3335   /* Null-terminate the string.  */
3336   write_char ('\0');
3337 }
3338
3339
3340 /* Like finish_mangling_internal, but return the mangled string.  */
3341
3342 static inline const char *
3343 finish_mangling (void)
3344 {
3345   finish_mangling_internal ();
3346   return (const char *) obstack_finish (mangle_obstack);
3347 }
3348
3349 /* Like finish_mangling_internal, but return an identifier.  */
3350
3351 static tree
3352 finish_mangling_get_identifier (void)
3353 {
3354   finish_mangling_internal ();
3355   /* Don't obstack_finish here, and the next start_mangling will
3356      remove the identifier.  */
3357   return get_identifier ((const char *) obstack_base (mangle_obstack));
3358 }
3359
3360 /* Initialize data structures for mangling.  */
3361
3362 void
3363 init_mangle (void)
3364 {
3365   gcc_obstack_init (&name_obstack);
3366   name_base = obstack_alloc (&name_obstack, 0);
3367   vec_alloc (G.substitutions, 0);
3368
3369   /* Cache these identifiers for quick comparison when checking for
3370      standard substitutions.  */
3371   subst_identifiers[SUBID_ALLOCATOR] = get_identifier ("allocator");
3372   subst_identifiers[SUBID_BASIC_STRING] = get_identifier ("basic_string");
3373   subst_identifiers[SUBID_CHAR_TRAITS] = get_identifier ("char_traits");
3374   subst_identifiers[SUBID_BASIC_ISTREAM] = get_identifier ("basic_istream");
3375   subst_identifiers[SUBID_BASIC_OSTREAM] = get_identifier ("basic_ostream");
3376   subst_identifiers[SUBID_BASIC_IOSTREAM] = get_identifier ("basic_iostream");
3377 }
3378
3379 /* Generate the mangled name of DECL.  */
3380
3381 static tree
3382 mangle_decl_string (const tree decl)
3383 {
3384   tree result;
3385   location_t saved_loc = input_location;
3386   tree saved_fn = NULL_TREE;
3387   bool template_p = false;
3388
3389   /* We shouldn't be trying to mangle an uninstantiated template.  */
3390   gcc_assert (!type_dependent_expression_p (decl));
3391
3392   if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
3393     {
3394       struct tinst_level *tl = current_instantiation ();
3395       if ((!tl || tl->decl != decl)
3396           && push_tinst_level (decl))
3397         {
3398           template_p = true;
3399           saved_fn = current_function_decl;
3400           current_function_decl = NULL_TREE;
3401         }
3402     }
3403   input_location = DECL_SOURCE_LOCATION (decl);
3404
3405   start_mangling (decl);
3406
3407   if (TREE_CODE (decl) == TYPE_DECL)
3408     write_type (TREE_TYPE (decl));
3409   else
3410     write_mangled_name (decl, true);
3411
3412   result = finish_mangling_get_identifier ();
3413   if (DEBUG_MANGLE)
3414     fprintf (stderr, "mangle_decl_string = '%s'\n\n",
3415              IDENTIFIER_POINTER (result));
3416
3417   if (template_p)
3418     {
3419       pop_tinst_level ();
3420       current_function_decl = saved_fn;
3421     }
3422   input_location = saved_loc;
3423
3424   return result;
3425 }
3426
3427 /* Return an identifier for the external mangled name of DECL.  */
3428
3429 static tree
3430 get_mangled_id (tree decl)
3431 {
3432   tree id = mangle_decl_string (decl);
3433   return targetm.mangle_decl_assembler_name (decl, id);
3434 }
3435
3436 /* If DECL is a mangling alias, remove it from the symbol table and return
3437    true; otherwise return false.  */
3438
3439 bool
3440 maybe_remove_implicit_alias (tree decl)
3441 {
3442   if (DECL_P (decl) && DECL_ARTIFICIAL (decl)
3443       && DECL_IGNORED_P (decl)
3444       && (TREE_CODE (decl) == FUNCTION_DECL
3445           || (TREE_CODE (decl) == VAR_DECL
3446               && TREE_STATIC (decl))))
3447     {
3448       symtab_node *n = symtab_node::get (decl);
3449       if (n && n->cpp_implicit_alias)
3450         {
3451           n->remove();
3452           return true;
3453         }
3454     }
3455   return false;
3456 }
3457
3458 /* Create an identifier for the external mangled name of DECL.  */
3459
3460 void
3461 mangle_decl (const tree decl)
3462 {
3463   tree id;
3464   bool dep;
3465
3466   /* Don't bother mangling uninstantiated templates.  */
3467   ++processing_template_decl;
3468   if (TREE_CODE (decl) == TYPE_DECL)
3469     dep = dependent_type_p (TREE_TYPE (decl));
3470   else
3471     dep = (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
3472            && any_dependent_template_arguments_p (DECL_TI_ARGS (decl)));
3473   --processing_template_decl;
3474   if (dep)
3475     return;
3476
3477   id = get_mangled_id (decl);
3478   SET_DECL_ASSEMBLER_NAME (decl, id);
3479
3480   if (G.need_abi_warning
3481       /* Don't do this for a fake symbol we aren't going to emit anyway.  */
3482       && TREE_CODE (decl) != TYPE_DECL
3483       && !DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
3484       && !DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl))
3485     {
3486       /* If the mangling will change in the future, emit an alias with the
3487          future mangled name for forward-compatibility.  */
3488       int save_ver;
3489       tree id2;
3490
3491       SET_IDENTIFIER_GLOBAL_VALUE (id, decl);
3492       if (IDENTIFIER_GLOBAL_VALUE (id) != decl)
3493         inform (DECL_SOURCE_LOCATION (decl), "a later -fabi-version= (or =0) "
3494                 "avoids this error with a change in mangling");
3495
3496       save_ver = flag_abi_version;
3497       flag_abi_version = flag_abi_compat_version;
3498       id2 = mangle_decl_string (decl);
3499       id2 = targetm.mangle_decl_assembler_name (decl, id2);
3500       flag_abi_version = save_ver;
3501
3502       if (id2 == id)
3503         return;
3504
3505       if (warn_abi)
3506         {
3507           if (flag_abi_compat_version != 0
3508               && abi_version_at_least (flag_abi_compat_version))
3509             warning (OPT_Wabi, "the mangled name of %q+D changed between "
3510                      "-fabi-version=%d (%D) and -fabi-version=%d (%D)",
3511                      G.entity, flag_abi_compat_version, id2,
3512                      flag_abi_version, id);
3513           else
3514             warning (OPT_Wabi, "the mangled name of %q+D changes between "
3515                      "-fabi-version=%d (%D) and -fabi-version=%d (%D)",
3516                      G.entity, flag_abi_version, id,
3517                      flag_abi_compat_version, id2);
3518         }
3519
3520 #ifdef ASM_OUTPUT_DEF
3521       /* If there's a declaration already using this mangled name,
3522          don't create a compatibility alias that conflicts.  */
3523       if (IDENTIFIER_GLOBAL_VALUE (id2))
3524         return;
3525
3526       struct cgraph_node *n = NULL;
3527       if (TREE_CODE (decl) == FUNCTION_DECL
3528           && !(n = cgraph_node::get (decl)))
3529         /* Don't create an alias to an unreferenced function.  */
3530         return;
3531
3532       tree alias = make_alias_for (decl, id2);
3533       SET_IDENTIFIER_GLOBAL_VALUE (id2, alias);
3534       DECL_IGNORED_P (alias) = 1;
3535       TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
3536       DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
3537       if (vague_linkage_p (decl))
3538         DECL_WEAK (alias) = 1;
3539       if (TREE_CODE (decl) == FUNCTION_DECL)
3540         n->create_same_body_alias (alias, decl);
3541       else
3542         varpool_node::create_extra_name_alias (alias, decl);
3543 #endif
3544     }
3545 }
3546
3547 /* Generate the mangled representation of TYPE.  */
3548
3549 const char *
3550 mangle_type_string (const tree type)
3551 {
3552   const char *result;
3553
3554   start_mangling (type);
3555   write_type (type);
3556   result = finish_mangling ();
3557   if (DEBUG_MANGLE)
3558     fprintf (stderr, "mangle_type_string = '%s'\n\n", result);
3559   return result;
3560 }
3561
3562 /* Create an identifier for the mangled name of a special component
3563    for belonging to TYPE.  CODE is the ABI-specified code for this
3564    component.  */
3565
3566 static tree
3567 mangle_special_for_type (const tree type, const char *code)
3568 {
3569   tree result;
3570
3571   /* We don't have an actual decl here for the special component, so
3572      we can't just process the <encoded-name>.  Instead, fake it.  */
3573   start_mangling (type);
3574
3575   /* Start the mangling.  */
3576   write_string ("_Z");
3577   write_string (code);
3578
3579   /* Add the type.  */
3580   write_type (type);
3581   result = finish_mangling_get_identifier ();
3582
3583   if (DEBUG_MANGLE)
3584     fprintf (stderr, "mangle_special_for_type = %s\n\n",
3585              IDENTIFIER_POINTER (result));
3586
3587   return result;
3588 }
3589
3590 /* Create an identifier for the mangled representation of the typeinfo
3591    structure for TYPE.  */
3592
3593 tree
3594 mangle_typeinfo_for_type (const tree type)
3595 {
3596   return mangle_special_for_type (type, "TI");
3597 }
3598
3599 /* Create an identifier for the mangled name of the NTBS containing
3600    the mangled name of TYPE.  */
3601
3602 tree
3603 mangle_typeinfo_string_for_type (const tree type)
3604 {
3605   return mangle_special_for_type (type, "TS");
3606 }
3607
3608 /* Create an identifier for the mangled name of the vtable for TYPE.  */
3609
3610 tree
3611 mangle_vtbl_for_type (const tree type)
3612 {
3613   return mangle_special_for_type (type, "TV");
3614 }
3615
3616 /* Returns an identifier for the mangled name of the VTT for TYPE.  */
3617
3618 tree
3619 mangle_vtt_for_type (const tree type)
3620 {
3621   return mangle_special_for_type (type, "TT");
3622 }
3623
3624 /* Return an identifier for a construction vtable group.  TYPE is
3625    the most derived class in the hierarchy; BINFO is the base
3626    subobject for which this construction vtable group will be used.
3627
3628    This mangling isn't part of the ABI specification; in the ABI
3629    specification, the vtable group is dumped in the same COMDAT as the
3630    main vtable, and is referenced only from that vtable, so it doesn't
3631    need an external name.  For binary formats without COMDAT sections,
3632    though, we need external names for the vtable groups.
3633
3634    We use the production
3635
3636     <special-name> ::= CT <type> <offset number> _ <base type>  */
3637
3638 tree
3639 mangle_ctor_vtbl_for_type (const tree type, const tree binfo)
3640 {
3641   tree result;
3642
3643   start_mangling (type);
3644
3645   write_string ("_Z");
3646   write_string ("TC");
3647   write_type (type);
3648   write_integer_cst (BINFO_OFFSET (binfo));
3649   write_char ('_');
3650   write_type (BINFO_TYPE (binfo));
3651
3652   result = finish_mangling_get_identifier ();
3653   if (DEBUG_MANGLE)
3654     fprintf (stderr, "mangle_ctor_vtbl_for_type = %s\n\n",
3655              IDENTIFIER_POINTER (result));
3656   return result;
3657 }
3658
3659 /* Mangle a this pointer or result pointer adjustment.
3660
3661    <call-offset> ::= h <fixed offset number> _
3662                  ::= v <fixed offset number> _ <virtual offset number> _ */
3663
3664 static void
3665 mangle_call_offset (const tree fixed_offset, const tree virtual_offset)
3666 {
3667   write_char (virtual_offset ? 'v' : 'h');
3668
3669   /* For either flavor, write the fixed offset.  */
3670   write_integer_cst (fixed_offset);
3671   write_char ('_');
3672
3673   /* For a virtual thunk, add the virtual offset.  */
3674   if (virtual_offset)
3675     {
3676       write_integer_cst (virtual_offset);
3677       write_char ('_');
3678     }
3679 }
3680
3681 /* Return an identifier for the mangled name of a this-adjusting or
3682    covariant thunk to FN_DECL.  FIXED_OFFSET is the initial adjustment
3683    to this used to find the vptr.  If VIRTUAL_OFFSET is non-NULL, this
3684    is a virtual thunk, and it is the vtbl offset in
3685    bytes. THIS_ADJUSTING is nonzero for a this adjusting thunk and
3686    zero for a covariant thunk. Note, that FN_DECL might be a covariant
3687    thunk itself. A covariant thunk name always includes the adjustment
3688    for the this pointer, even if there is none.
3689
3690    <special-name> ::= T <call-offset> <base encoding>
3691                   ::= Tc <this_adjust call-offset> <result_adjust call-offset>
3692                                         <base encoding>  */
3693
3694 tree
3695 mangle_thunk (tree fn_decl, const int this_adjusting, tree fixed_offset,
3696               tree virtual_offset)
3697 {
3698   tree result;
3699
3700   start_mangling (fn_decl);
3701
3702   write_string ("_Z");
3703   write_char ('T');
3704
3705   if (!this_adjusting)
3706     {
3707       /* Covariant thunk with no this adjustment */
3708       write_char ('c');
3709       mangle_call_offset (integer_zero_node, NULL_TREE);
3710       mangle_call_offset (fixed_offset, virtual_offset);
3711     }
3712   else if (!DECL_THUNK_P (fn_decl))
3713     /* Plain this adjusting thunk.  */
3714     mangle_call_offset (fixed_offset, virtual_offset);
3715   else
3716     {
3717       /* This adjusting thunk to covariant thunk.  */
3718       write_char ('c');
3719       mangle_call_offset (fixed_offset, virtual_offset);
3720       fixed_offset = ssize_int (THUNK_FIXED_OFFSET (fn_decl));
3721       virtual_offset = THUNK_VIRTUAL_OFFSET (fn_decl);
3722       if (virtual_offset)
3723         virtual_offset = BINFO_VPTR_FIELD (virtual_offset);
3724       mangle_call_offset (fixed_offset, virtual_offset);
3725       fn_decl = THUNK_TARGET (fn_decl);
3726     }
3727
3728   /* Scoped name.  */
3729   write_encoding (fn_decl);
3730
3731   result = finish_mangling_get_identifier ();
3732   if (DEBUG_MANGLE)
3733     fprintf (stderr, "mangle_thunk = %s\n\n", IDENTIFIER_POINTER (result));
3734   return result;
3735 }
3736
3737 struct conv_type_hasher : ggc_hasher<tree>
3738 {
3739   static hashval_t hash (tree);
3740   static bool equal (tree, tree);
3741 };
3742
3743 /* This hash table maps TYPEs to the IDENTIFIER for a conversion
3744    operator to TYPE.  The nodes are IDENTIFIERs whose TREE_TYPE is the
3745    TYPE.  */
3746
3747 static GTY (()) hash_table<conv_type_hasher> *conv_type_names;
3748
3749 /* Hash a node (VAL1) in the table.  */
3750
3751 hashval_t
3752 conv_type_hasher::hash (tree val)
3753 {
3754   return (hashval_t) TYPE_UID (TREE_TYPE (val));
3755 }
3756
3757 /* Compare VAL1 (a node in the table) with VAL2 (a TYPE).  */
3758
3759 bool
3760 conv_type_hasher::equal (tree val1, tree val2)
3761 {
3762   return TREE_TYPE (val1) == val2;
3763 }
3764
3765 /* Return an identifier for the mangled unqualified name for a
3766    conversion operator to TYPE.  This mangling is not specified by the
3767    ABI spec; it is only used internally.  */
3768
3769 tree
3770 mangle_conv_op_name_for_type (const tree type)
3771 {
3772   tree *slot;
3773   tree identifier;
3774
3775   if (type == error_mark_node)
3776     return error_mark_node;
3777
3778   if (conv_type_names == NULL)
3779     conv_type_names = hash_table<conv_type_hasher>::create_ggc (31);
3780
3781   slot = conv_type_names->find_slot_with_hash (type,
3782                                                (hashval_t) TYPE_UID (type),
3783                                                INSERT);
3784   identifier = *slot;
3785   if (!identifier)
3786     {
3787       char buffer[64];
3788
3789        /* Create a unique name corresponding to TYPE.  */
3790       sprintf (buffer, "operator %lu",
3791                (unsigned long) conv_type_names->elements ());
3792       identifier = get_identifier (buffer);
3793       *slot = identifier;
3794
3795       /* Hang TYPE off the identifier so it can be found easily later
3796          when performing conversions.  */
3797       TREE_TYPE (identifier) = type;
3798
3799       /* Set bits on the identifier so we know later it's a conversion.  */
3800       IDENTIFIER_OPNAME_P (identifier) = 1;
3801       IDENTIFIER_TYPENAME_P (identifier) = 1;
3802     }
3803
3804   return identifier;
3805 }
3806
3807 /* Write out the appropriate string for this variable when generating
3808    another mangled name based on this one.  */
3809
3810 static void
3811 write_guarded_var_name (const tree variable)
3812 {
3813   if (DECL_NAME (variable)
3814       && strncmp (IDENTIFIER_POINTER (DECL_NAME (variable)), "_ZGR", 4) == 0)
3815     /* The name of a guard variable for a reference temporary should refer
3816        to the reference, not the temporary.  */
3817     write_string (IDENTIFIER_POINTER (DECL_NAME (variable)) + 4);
3818   else
3819     write_name (variable, /*ignore_local_scope=*/0);
3820 }
3821
3822 /* Return an identifier for the name of an initialization guard
3823    variable for indicated VARIABLE.  */
3824
3825 tree
3826 mangle_guard_variable (const tree variable)
3827 {
3828   start_mangling (variable);
3829   write_string ("_ZGV");
3830   write_guarded_var_name (variable);
3831   return finish_mangling_get_identifier ();
3832 }
3833
3834 /* Return an identifier for the name of a thread_local initialization
3835    function for VARIABLE.  */
3836
3837 tree
3838 mangle_tls_init_fn (const tree variable)
3839 {
3840   start_mangling (variable);
3841   write_string ("_ZTH");
3842   write_guarded_var_name (variable);
3843   return finish_mangling_get_identifier ();
3844 }
3845
3846 /* Return an identifier for the name of a thread_local wrapper
3847    function for VARIABLE.  */
3848
3849 #define TLS_WRAPPER_PREFIX "_ZTW"
3850
3851 tree
3852 mangle_tls_wrapper_fn (const tree variable)
3853 {
3854   start_mangling (variable);
3855   write_string (TLS_WRAPPER_PREFIX);
3856   write_guarded_var_name (variable);
3857   return finish_mangling_get_identifier ();
3858 }
3859
3860 /* Return true iff FN is a thread_local wrapper function.  */
3861
3862 bool
3863 decl_tls_wrapper_p (const tree fn)
3864 {
3865   if (TREE_CODE (fn) != FUNCTION_DECL)
3866     return false;
3867   tree name = DECL_NAME (fn);
3868   return strncmp (IDENTIFIER_POINTER (name), TLS_WRAPPER_PREFIX,
3869                   strlen (TLS_WRAPPER_PREFIX)) == 0;
3870 }
3871
3872 /* Return an identifier for the name of a temporary variable used to
3873    initialize a static reference.  This isn't part of the ABI, but we might
3874    as well call them something readable.  */
3875
3876 static GTY(()) int temp_count;
3877
3878 tree
3879 mangle_ref_init_variable (const tree variable)
3880 {
3881   start_mangling (variable);
3882   write_string ("_ZGR");
3883   write_name (variable, /*ignore_local_scope=*/0);
3884   /* Avoid name clashes with aggregate initialization of multiple
3885      references at once.  */
3886   write_unsigned_number (temp_count++);
3887   return finish_mangling_get_identifier ();
3888 }
3889 \f
3890
3891 /* Foreign language type mangling section.  */
3892
3893 /* How to write the type codes for the integer Java type.  */
3894
3895 static void
3896 write_java_integer_type_codes (const tree type)
3897 {
3898   if (type == java_int_type_node)
3899     write_char ('i');
3900   else if (type == java_short_type_node)
3901     write_char ('s');
3902   else if (type == java_byte_type_node)
3903     write_char ('c');
3904   else if (type == java_char_type_node)
3905     write_char ('w');
3906   else if (type == java_long_type_node)
3907     write_char ('x');
3908   else if (type == java_boolean_type_node)
3909     write_char ('b');
3910   else
3911     gcc_unreachable ();
3912 }
3913
3914 /* Given a CLASS_TYPE, such as a record for std::bad_exception this
3915    function generates a mangled name for the vtable map variable of
3916    the class type.  For example, if the class type is
3917    "std::bad_exception", the mangled name for the class is
3918    "St13bad_exception".  This function would generate the name
3919    "_ZN4_VTVISt13bad_exceptionE12__vtable_mapE", which unmangles as:
3920    "_VTV<std::bad_exception>::__vtable_map".  */
3921
3922
3923 char *
3924 get_mangled_vtable_map_var_name (tree class_type)
3925 {
3926   char *var_name = NULL;
3927   const char *prefix = "_ZN4_VTVI";
3928   const char *postfix = "E12__vtable_mapE";
3929
3930   gcc_assert (TREE_CODE (class_type) == RECORD_TYPE);
3931
3932   tree class_id = DECL_ASSEMBLER_NAME (TYPE_NAME (class_type));
3933   unsigned int len = strlen (IDENTIFIER_POINTER (class_id)) +
3934                      strlen (prefix) +
3935                      strlen (postfix) + 1;
3936
3937   var_name = (char *) xmalloc (len);
3938
3939   sprintf (var_name, "%s%s%s", prefix, IDENTIFIER_POINTER (class_id), postfix);
3940
3941   return var_name;
3942 }
3943
3944 #include "gt-cp-mangle.h"