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