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