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