1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2014
3    Free Software Foundation, Inc.
4    Written by Ian Lance Taylor <ian@wasabisystems.com>.
5 
6    This file is part of the libiberty library, which is part of GCC.
7 
8    This file is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12 
13    In addition to the permissions in the GNU General Public License, the
14    Free Software Foundation gives you unlimited permission to link the
15    compiled version of this file into combinations with other programs,
16    and to distribute those combinations without any restriction coming
17    from the use of this file.  (The General Public License restrictions
18    do apply in other respects; for example, they cover modification of
19    the file, and distribution when not linked into a combined
20    executable.)
21 
22    This program is distributed in the hope that it will be useful,
23    but WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25    GNU General Public License for more details.
26 
27    You should have received a copy of the GNU General Public License
28    along with this program; if not, write to the Free Software
29    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
30 */
31 
32 /* This code implements a demangler for the g++ V3 ABI.  The ABI is
33    described on this web page:
34        http://www.codesourcery.com/cxx-abi/abi.html#mangling
35 
36    This code was written while looking at the demangler written by
37    Alex Samuel <samuel@codesourcery.com>.
38 
39    This code first pulls the mangled name apart into a list of
40    components, and then walks the list generating the demangled
41    name.
42 
43    This file will normally define the following functions, q.v.:
44       char *cplus_demangle_v3(const char *mangled, int options)
45       char *java_demangle_v3(const char *mangled)
46       int cplus_demangle_v3_callback(const char *mangled, int options,
47                                      demangle_callbackref callback)
48       int java_demangle_v3_callback(const char *mangled,
49                                     demangle_callbackref callback)
50       enum gnu_v3_ctor_kinds is_gnu_v3_mangled_ctor (const char *name)
51       enum gnu_v3_dtor_kinds is_gnu_v3_mangled_dtor (const char *name)
52 
53    Also, the interface to the component list is public, and defined in
54    demangle.h.  The interface consists of these types, which are
55    defined in demangle.h:
56       enum demangle_component_type
57       struct demangle_component
58       demangle_callbackref
59    and these functions defined in this file:
60       cplus_demangle_fill_name
61       cplus_demangle_fill_extended_operator
62       cplus_demangle_fill_ctor
63       cplus_demangle_fill_dtor
64       cplus_demangle_print
65       cplus_demangle_print_callback
66    and other functions defined in the file cp-demint.c.
67 
68    This file also defines some other functions and variables which are
69    only to be used by the file cp-demint.c.
70 
71    Preprocessor macros you can define while compiling this file:
72 
73    IN_LIBGCC2
74       If defined, this file defines the following functions, q.v.:
75          char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
76                                int *status)
77          int __gcclibcxx_demangle_callback (const char *,
78                                             void (*)
79                                               (const char *, size_t, void *),
80                                             void *)
81       instead of cplus_demangle_v3[_callback]() and
82       java_demangle_v3[_callback]().
83 
84    IN_GLIBCPP_V3
85       If defined, this file defines only __cxa_demangle() and
86       __gcclibcxx_demangle_callback(), and no other publically visible
87       functions or variables.
88 
89    STANDALONE_DEMANGLER
90       If defined, this file defines a main() function which demangles
91       any arguments, or, if none, demangles stdin.
92 
93    CP_DEMANGLE_DEBUG
94       If defined, turns on debugging mode, which prints information on
95       stdout about the mangled string.  This is not generally useful.
96 
97    CHECK_DEMANGLER
98       If defined, additional sanity checks will be performed.  It will
99       cause some slowdown, but will allow to catch out-of-bound access
100       errors earlier.  This macro is intended for testing and debugging.  */
101 
102 #if defined (_AIX) && !defined (__GNUC__)
103  #pragma alloca
104 #endif
105 
106 #ifdef HAVE_CONFIG_H
107 #include "config.h"
108 #endif
109 
110 #include <stdio.h>
111 
112 #ifdef HAVE_STDLIB_H
113 #include <stdlib.h>
114 #endif
115 #ifdef HAVE_STRING_H
116 #include <string.h>
117 #endif
118 
119 #ifdef HAVE_ALLOCA_H
120 # include <alloca.h>
121 #else
122 # ifndef alloca
123 #  ifdef __GNUC__
124 #   define alloca __builtin_alloca
125 #  else
126 extern char *alloca ();
127 #  endif /* __GNUC__ */
128 # endif /* alloca */
129 #endif /* HAVE_ALLOCA_H */
130 
131 #include "ansidecl.h"
132 #include "libiberty.h"
133 #include "demangle.h"
134 #include "cp-demangle.h"
135 
136 /* If IN_GLIBCPP_V3 is defined, some functions are made static.  We
137    also rename them via #define to avoid compiler errors when the
138    static definition conflicts with the extern declaration in a header
139    file.  */
140 #ifdef IN_GLIBCPP_V3
141 
142 #define CP_STATIC_IF_GLIBCPP_V3 static
143 
144 #define cplus_demangle_fill_name d_fill_name
145 static int d_fill_name (struct demangle_component *, const char *, int);
146 
147 #define cplus_demangle_fill_extended_operator d_fill_extended_operator
148 static int
149 d_fill_extended_operator (struct demangle_component *, int,
150                           struct demangle_component *);
151 
152 #define cplus_demangle_fill_ctor d_fill_ctor
153 static int
154 d_fill_ctor (struct demangle_component *, enum gnu_v3_ctor_kinds,
155              struct demangle_component *);
156 
157 #define cplus_demangle_fill_dtor d_fill_dtor
158 static int
159 d_fill_dtor (struct demangle_component *, enum gnu_v3_dtor_kinds,
160              struct demangle_component *);
161 
162 #define cplus_demangle_mangled_name d_mangled_name
163 static struct demangle_component *d_mangled_name (struct d_info *, int);
164 
165 #define cplus_demangle_type d_type
166 static struct demangle_component *d_type (struct d_info *);
167 
168 #define cplus_demangle_print d_print
169 static char *d_print (int, const struct demangle_component *, int, size_t *);
170 
171 #define cplus_demangle_print_callback d_print_callback
172 static int d_print_callback (int, const struct demangle_component *,
173                              demangle_callbackref, void *);
174 
175 #define cplus_demangle_init_info d_init_info
176 static void d_init_info (const char *, int, size_t, struct d_info *);
177 
178 #else /* ! defined(IN_GLIBCPP_V3) */
179 #define CP_STATIC_IF_GLIBCPP_V3
180 #endif /* ! defined(IN_GLIBCPP_V3) */
181 
182 /* See if the compiler supports dynamic arrays.  */
183 
184 #ifdef __GNUC__
185 #define CP_DYNAMIC_ARRAYS
186 #else
187 #ifdef __STDC__
188 #ifdef __STDC_VERSION__
189 #if __STDC_VERSION__ >= 199901L
190 #define CP_DYNAMIC_ARRAYS
191 #endif /* __STDC__VERSION >= 199901L */
192 #endif /* defined (__STDC_VERSION__) */
193 #endif /* defined (__STDC__) */
194 #endif /* ! defined (__GNUC__) */
195 
196 /* We avoid pulling in the ctype tables, to prevent pulling in
197    additional unresolved symbols when this code is used in a library.
198    FIXME: Is this really a valid reason?  This comes from the original
199    V3 demangler code.
200 
201    As of this writing this file has the following undefined references
202    when compiled with -DIN_GLIBCPP_V3: realloc, free, memcpy, strcpy,
203    strcat, strlen.  */
204 
205 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
206 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
207 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
208 
209 /* The prefix prepended by GCC to an identifier represnting the
210    anonymous namespace.  */
211 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
212 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
213   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
214 
215 /* Information we keep for the standard substitutions.  */
216 
217 struct d_standard_sub_info
218 {
219   /* The code for this substitution.  */
220   char code;
221   /* The simple string it expands to.  */
222   const char *simple_expansion;
223   /* The length of the simple expansion.  */
224   int simple_len;
225   /* The results of a full, verbose, expansion.  This is used when
226      qualifying a constructor/destructor, or when in verbose mode.  */
227   const char *full_expansion;
228   /* The length of the full expansion.  */
229   int full_len;
230   /* What to set the last_name field of d_info to; NULL if we should
231      not set it.  This is only relevant when qualifying a
232      constructor/destructor.  */
233   const char *set_last_name;
234   /* The length of set_last_name.  */
235   int set_last_name_len;
236 };
237 
238 /* Accessors for subtrees of struct demangle_component.  */
239 
240 #define d_left(dc) ((dc)->u.s_binary.left)
241 #define d_right(dc) ((dc)->u.s_binary.right)
242 
243 /* A list of templates.  This is used while printing.  */
244 
245 struct d_print_template
246 {
247   /* Next template on the list.  */
248   struct d_print_template *next;
249   /* This template.  */
250   const struct demangle_component *template_decl;
251 };
252 
253 /* A list of type modifiers.  This is used while printing.  */
254 
255 struct d_print_mod
256 {
257   /* Next modifier on the list.  These are in the reverse of the order
258      in which they appeared in the mangled string.  */
259   struct d_print_mod *next;
260   /* The modifier.  */
261   const struct demangle_component *mod;
262   /* Whether this modifier was printed.  */
263   int printed;
264   /* The list of templates which applies to this modifier.  */
265   struct d_print_template *templates;
266 };
267 
268 /* We use these structures to hold information during printing.  */
269 
270 struct d_growable_string
271 {
272   /* Buffer holding the result.  */
273   char *buf;
274   /* Current length of data in buffer.  */
275   size_t len;
276   /* Allocated size of buffer.  */
277   size_t alc;
278   /* Set to 1 if we had a memory allocation failure.  */
279   int allocation_failure;
280 };
281 
282 /* Stack of components, innermost first, used to avoid loops.  */
283 
284 struct d_component_stack
285 {
286   /* This component.  */
287   const struct demangle_component *dc;
288   /* This component's parent.  */
289   const struct d_component_stack *parent;
290 };
291 
292 /* A demangle component and some scope captured when it was first
293    traversed.  */
294 
295 struct d_saved_scope
296 {
297   /* The component whose scope this is.  */
298   const struct demangle_component *container;
299   /* The list of templates, if any, that was current when this
300      scope was captured.  */
301   struct d_print_template *templates;
302 };
303 
304 /* Checkpoint structure to allow backtracking.  This holds copies
305    of the fields of struct d_info that need to be restored
306    if a trial parse needs to be backtracked over.  */
307 
308 struct d_info_checkpoint
309 {
310   const char *n;
311   int next_comp;
312   int next_sub;
313   int did_subs;
314   int expansion;
315 };
316 
317 enum { D_PRINT_BUFFER_LENGTH = 256 };
318 struct d_print_info
319 {
320   /* Fixed-length allocated buffer for demangled data, flushed to the
321      callback with a NUL termination once full.  */
322   char buf[D_PRINT_BUFFER_LENGTH];
323   /* Current length of data in buffer.  */
324   size_t len;
325   /* The last character printed, saved individually so that it survives
326      any buffer flush.  */
327   char last_char;
328   /* Callback function to handle demangled buffer flush.  */
329   demangle_callbackref callback;
330   /* Opaque callback argument.  */
331   void *opaque;
332   /* The current list of templates, if any.  */
333   struct d_print_template *templates;
334   /* The current list of modifiers (e.g., pointer, reference, etc.),
335      if any.  */
336   struct d_print_mod *modifiers;
337   /* Set to 1 if we saw a demangling error.  */
338   int demangle_failure;
339   /* The current index into any template argument packs we are using
340      for printing.  */
341   int pack_index;
342   /* Number of d_print_flush calls so far.  */
343   unsigned long int flush_count;
344   /* Stack of components, innermost first, used to avoid loops.  */
345   const struct d_component_stack *component_stack;
346   /* Array of saved scopes for evaluating substitutions.  */
347   struct d_saved_scope *saved_scopes;
348   /* Index of the next unused saved scope in the above array.  */
349   int next_saved_scope;
350   /* Number of saved scopes in the above array.  */
351   int num_saved_scopes;
352   /* Array of templates for saving into scopes.  */
353   struct d_print_template *copy_templates;
354   /* Index of the next unused copy template in the above array.  */
355   int next_copy_template;
356   /* Number of copy templates in the above array.  */
357   int num_copy_templates;
358   /* The nearest enclosing template, if any.  */
359   const struct demangle_component *current_template;
360 };
361 
362 #ifdef CP_DEMANGLE_DEBUG
363 static void d_dump (struct demangle_component *, int);
364 #endif
365 
366 static struct demangle_component *
367 d_make_empty (struct d_info *);
368 
369 static struct demangle_component *
370 d_make_comp (struct d_info *, enum demangle_component_type,
371              struct demangle_component *,
372              struct demangle_component *);
373 
374 static struct demangle_component *
375 d_make_name (struct d_info *, const char *, int);
376 
377 static struct demangle_component *
378 d_make_demangle_mangled_name (struct d_info *, const char *);
379 
380 static struct demangle_component *
381 d_make_builtin_type (struct d_info *,
382                      const struct demangle_builtin_type_info *);
383 
384 static struct demangle_component *
385 d_make_operator (struct d_info *,
386                  const struct demangle_operator_info *);
387 
388 static struct demangle_component *
389 d_make_extended_operator (struct d_info *, int,
390                           struct demangle_component *);
391 
392 static struct demangle_component *
393 d_make_ctor (struct d_info *, enum gnu_v3_ctor_kinds,
394              struct demangle_component *);
395 
396 static struct demangle_component *
397 d_make_dtor (struct d_info *, enum gnu_v3_dtor_kinds,
398              struct demangle_component *);
399 
400 static struct demangle_component *
401 d_make_template_param (struct d_info *, long);
402 
403 static struct demangle_component *
404 d_make_sub (struct d_info *, const char *, int);
405 
406 static int
407 has_return_type (struct demangle_component *);
408 
409 static int
410 is_ctor_dtor_or_conversion (struct demangle_component *);
411 
412 static struct demangle_component *d_encoding (struct d_info *, int);
413 
414 static struct demangle_component *d_name (struct d_info *);
415 
416 static struct demangle_component *d_nested_name (struct d_info *);
417 
418 static struct demangle_component *d_prefix (struct d_info *);
419 
420 static struct demangle_component *d_unqualified_name (struct d_info *);
421 
422 static struct demangle_component *d_source_name (struct d_info *);
423 
424 static long d_number (struct d_info *);
425 
426 static struct demangle_component *d_identifier (struct d_info *, long);
427 
428 static struct demangle_component *d_operator_name (struct d_info *);
429 
430 static struct demangle_component *d_special_name (struct d_info *);
431 
432 static int d_call_offset (struct d_info *, int);
433 
434 static struct demangle_component *d_ctor_dtor_name (struct d_info *);
435 
436 static struct demangle_component **
437 d_cv_qualifiers (struct d_info *, struct demangle_component **, int);
438 
439 static struct demangle_component *
440 d_ref_qualifier (struct d_info *, struct demangle_component *);
441 
442 static struct demangle_component *
443 d_function_type (struct d_info *);
444 
445 static struct demangle_component *
446 d_bare_function_type (struct d_info *, int);
447 
448 static struct demangle_component *
449 d_class_enum_type (struct d_info *);
450 
451 static struct demangle_component *d_array_type (struct d_info *);
452 
453 static struct demangle_component *d_vector_type (struct d_info *);
454 
455 static struct demangle_component *
456 d_pointer_to_member_type (struct d_info *);
457 
458 static struct demangle_component *
459 d_template_param (struct d_info *);
460 
461 static struct demangle_component *d_template_args (struct d_info *);
462 
463 static struct demangle_component *
464 d_template_arg (struct d_info *);
465 
466 static struct demangle_component *d_expression (struct d_info *);
467 
468 static struct demangle_component *d_expr_primary (struct d_info *);
469 
470 static struct demangle_component *d_local_name (struct d_info *);
471 
472 static int d_discriminator (struct d_info *);
473 
474 static struct demangle_component *d_lambda (struct d_info *);
475 
476 static struct demangle_component *d_unnamed_type (struct d_info *);
477 
478 static struct demangle_component *
479 d_clone_suffix (struct d_info *, struct demangle_component *);
480 
481 static int
482 d_add_substitution (struct d_info *, struct demangle_component *);
483 
484 static struct demangle_component *d_substitution (struct d_info *, int);
485 
486 static void d_checkpoint (struct d_info *, struct d_info_checkpoint *);
487 
488 static void d_backtrack (struct d_info *, struct d_info_checkpoint *);
489 
490 static void d_growable_string_init (struct d_growable_string *, size_t);
491 
492 static inline void
493 d_growable_string_resize (struct d_growable_string *, size_t);
494 
495 static inline void
496 d_growable_string_append_buffer (struct d_growable_string *,
497                                  const char *, size_t);
498 static void
499 d_growable_string_callback_adapter (const char *, size_t, void *);
500 
501 static void
502 d_print_init (struct d_print_info *, demangle_callbackref, void *,
503 	      const struct demangle_component *);
504 
505 static inline void d_print_error (struct d_print_info *);
506 
507 static inline int d_print_saw_error (struct d_print_info *);
508 
509 static inline void d_print_flush (struct d_print_info *);
510 
511 static inline void d_append_char (struct d_print_info *, char);
512 
513 static inline void d_append_buffer (struct d_print_info *,
514                                     const char *, size_t);
515 
516 static inline void d_append_string (struct d_print_info *, const char *);
517 
518 static inline char d_last_char (struct d_print_info *);
519 
520 static void
521 d_print_comp (struct d_print_info *, int, const struct demangle_component *);
522 
523 static void
524 d_print_java_identifier (struct d_print_info *, const char *, int);
525 
526 static void
527 d_print_mod_list (struct d_print_info *, int, struct d_print_mod *, int);
528 
529 static void
530 d_print_mod (struct d_print_info *, int, const struct demangle_component *);
531 
532 static void
533 d_print_function_type (struct d_print_info *, int,
534                        const struct demangle_component *,
535                        struct d_print_mod *);
536 
537 static void
538 d_print_array_type (struct d_print_info *, int,
539                     const struct demangle_component *,
540                     struct d_print_mod *);
541 
542 static void
543 d_print_expr_op (struct d_print_info *, int, const struct demangle_component *);
544 
545 static void d_print_cast (struct d_print_info *, int,
546 			  const struct demangle_component *);
547 static void d_print_conversion (struct d_print_info *, int,
548 				const struct demangle_component *);
549 
550 static int d_demangle_callback (const char *, int,
551                                 demangle_callbackref, void *);
552 static char *d_demangle (const char *, int, size_t *);
553 
554 #ifdef CP_DEMANGLE_DEBUG
555 
556 static void
557 d_dump (struct demangle_component *dc, int indent)
558 {
559   int i;
560 
561   if (dc == NULL)
562     {
563       if (indent == 0)
564         printf ("failed demangling\n");
565       return;
566     }
567 
568   for (i = 0; i < indent; ++i)
569     putchar (' ');
570 
571   switch (dc->type)
572     {
573     case DEMANGLE_COMPONENT_NAME:
574       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
575       return;
576     case DEMANGLE_COMPONENT_TAGGED_NAME:
577       printf ("tagged name\n");
578       d_dump (dc->u.s_binary.left, indent + 2);
579       d_dump (dc->u.s_binary.right, indent + 2);
580       return;
581     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
582       printf ("template parameter %ld\n", dc->u.s_number.number);
583       return;
584     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
585       printf ("function parameter %ld\n", dc->u.s_number.number);
586       return;
587     case DEMANGLE_COMPONENT_CTOR:
588       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
589       d_dump (dc->u.s_ctor.name, indent + 2);
590       return;
591     case DEMANGLE_COMPONENT_DTOR:
592       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
593       d_dump (dc->u.s_dtor.name, indent + 2);
594       return;
595     case DEMANGLE_COMPONENT_SUB_STD:
596       printf ("standard substitution %s\n", dc->u.s_string.string);
597       return;
598     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
599       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
600       return;
601     case DEMANGLE_COMPONENT_OPERATOR:
602       printf ("operator %s\n", dc->u.s_operator.op->name);
603       return;
604     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
605       printf ("extended operator with %d args\n",
606 	      dc->u.s_extended_operator.args);
607       d_dump (dc->u.s_extended_operator.name, indent + 2);
608       return;
609 
610     case DEMANGLE_COMPONENT_QUAL_NAME:
611       printf ("qualified name\n");
612       break;
613     case DEMANGLE_COMPONENT_LOCAL_NAME:
614       printf ("local name\n");
615       break;
616     case DEMANGLE_COMPONENT_TYPED_NAME:
617       printf ("typed name\n");
618       break;
619     case DEMANGLE_COMPONENT_TEMPLATE:
620       printf ("template\n");
621       break;
622     case DEMANGLE_COMPONENT_VTABLE:
623       printf ("vtable\n");
624       break;
625     case DEMANGLE_COMPONENT_VTT:
626       printf ("VTT\n");
627       break;
628     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
629       printf ("construction vtable\n");
630       break;
631     case DEMANGLE_COMPONENT_TYPEINFO:
632       printf ("typeinfo\n");
633       break;
634     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
635       printf ("typeinfo name\n");
636       break;
637     case DEMANGLE_COMPONENT_TYPEINFO_FN:
638       printf ("typeinfo function\n");
639       break;
640     case DEMANGLE_COMPONENT_THUNK:
641       printf ("thunk\n");
642       break;
643     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
644       printf ("virtual thunk\n");
645       break;
646     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
647       printf ("covariant thunk\n");
648       break;
649     case DEMANGLE_COMPONENT_JAVA_CLASS:
650       printf ("java class\n");
651       break;
652     case DEMANGLE_COMPONENT_GUARD:
653       printf ("guard\n");
654       break;
655     case DEMANGLE_COMPONENT_REFTEMP:
656       printf ("reference temporary\n");
657       break;
658     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
659       printf ("hidden alias\n");
660       break;
661     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
662       printf ("transaction clone\n");
663       break;
664     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
665       printf ("non-transaction clone\n");
666       break;
667     case DEMANGLE_COMPONENT_RESTRICT:
668       printf ("restrict\n");
669       break;
670     case DEMANGLE_COMPONENT_VOLATILE:
671       printf ("volatile\n");
672       break;
673     case DEMANGLE_COMPONENT_CONST:
674       printf ("const\n");
675       break;
676     case DEMANGLE_COMPONENT_RESTRICT_THIS:
677       printf ("restrict this\n");
678       break;
679     case DEMANGLE_COMPONENT_VOLATILE_THIS:
680       printf ("volatile this\n");
681       break;
682     case DEMANGLE_COMPONENT_CONST_THIS:
683       printf ("const this\n");
684       break;
685     case DEMANGLE_COMPONENT_REFERENCE_THIS:
686       printf ("reference this\n");
687       break;
688     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
689       printf ("rvalue reference this\n");
690       break;
691     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
692       printf ("transaction_safe this\n");
693       break;
694     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
695       printf ("vendor type qualifier\n");
696       break;
697     case DEMANGLE_COMPONENT_POINTER:
698       printf ("pointer\n");
699       break;
700     case DEMANGLE_COMPONENT_REFERENCE:
701       printf ("reference\n");
702       break;
703     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
704       printf ("rvalue reference\n");
705       break;
706     case DEMANGLE_COMPONENT_COMPLEX:
707       printf ("complex\n");
708       break;
709     case DEMANGLE_COMPONENT_IMAGINARY:
710       printf ("imaginary\n");
711       break;
712     case DEMANGLE_COMPONENT_VENDOR_TYPE:
713       printf ("vendor type\n");
714       break;
715     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
716       printf ("function type\n");
717       break;
718     case DEMANGLE_COMPONENT_ARRAY_TYPE:
719       printf ("array type\n");
720       break;
721     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
722       printf ("pointer to member type\n");
723       break;
724     case DEMANGLE_COMPONENT_FIXED_TYPE:
725       printf ("fixed-point type, accum? %d, sat? %d\n",
726               dc->u.s_fixed.accum, dc->u.s_fixed.sat);
727       d_dump (dc->u.s_fixed.length, indent + 2);
728       break;
729     case DEMANGLE_COMPONENT_ARGLIST:
730       printf ("argument list\n");
731       break;
732     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
733       printf ("template argument list\n");
734       break;
735     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
736       printf ("initializer list\n");
737       break;
738     case DEMANGLE_COMPONENT_CAST:
739       printf ("cast\n");
740       break;
741     case DEMANGLE_COMPONENT_CONVERSION:
742       printf ("conversion operator\n");
743       break;
744     case DEMANGLE_COMPONENT_NULLARY:
745       printf ("nullary operator\n");
746       break;
747     case DEMANGLE_COMPONENT_UNARY:
748       printf ("unary operator\n");
749       break;
750     case DEMANGLE_COMPONENT_BINARY:
751       printf ("binary operator\n");
752       break;
753     case DEMANGLE_COMPONENT_BINARY_ARGS:
754       printf ("binary operator arguments\n");
755       break;
756     case DEMANGLE_COMPONENT_TRINARY:
757       printf ("trinary operator\n");
758       break;
759     case DEMANGLE_COMPONENT_TRINARY_ARG1:
760       printf ("trinary operator arguments 1\n");
761       break;
762     case DEMANGLE_COMPONENT_TRINARY_ARG2:
763       printf ("trinary operator arguments 1\n");
764       break;
765     case DEMANGLE_COMPONENT_LITERAL:
766       printf ("literal\n");
767       break;
768     case DEMANGLE_COMPONENT_LITERAL_NEG:
769       printf ("negative literal\n");
770       break;
771     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
772       printf ("java resource\n");
773       break;
774     case DEMANGLE_COMPONENT_COMPOUND_NAME:
775       printf ("compound name\n");
776       break;
777     case DEMANGLE_COMPONENT_CHARACTER:
778       printf ("character '%c'\n",  dc->u.s_character.character);
779       return;
780     case DEMANGLE_COMPONENT_NUMBER:
781       printf ("number %ld\n", dc->u.s_number.number);
782       return;
783     case DEMANGLE_COMPONENT_DECLTYPE:
784       printf ("decltype\n");
785       break;
786     case DEMANGLE_COMPONENT_PACK_EXPANSION:
787       printf ("pack expansion\n");
788       break;
789     case DEMANGLE_COMPONENT_TLS_INIT:
790       printf ("tls init function\n");
791       break;
792     case DEMANGLE_COMPONENT_TLS_WRAPPER:
793       printf ("tls wrapper function\n");
794       break;
795     case DEMANGLE_COMPONENT_DEFAULT_ARG:
796       printf ("default argument %d\n", dc->u.s_unary_num.num);
797       d_dump (dc->u.s_unary_num.sub, indent+2);
798       return;
799     case DEMANGLE_COMPONENT_LAMBDA:
800       printf ("lambda %d\n", dc->u.s_unary_num.num);
801       d_dump (dc->u.s_unary_num.sub, indent+2);
802       return;
803     }
804 
805   d_dump (d_left (dc), indent + 2);
806   d_dump (d_right (dc), indent + 2);
807 }
808 
809 #endif /* CP_DEMANGLE_DEBUG */
810 
811 /* Fill in a DEMANGLE_COMPONENT_NAME.  */
812 
813 CP_STATIC_IF_GLIBCPP_V3
814 int
815 cplus_demangle_fill_name (struct demangle_component *p, const char *s, int len)
816 {
817   if (p == NULL || s == NULL || len == 0)
818     return 0;
819   p->type = DEMANGLE_COMPONENT_NAME;
820   p->u.s_name.s = s;
821   p->u.s_name.len = len;
822   return 1;
823 }
824 
825 /* Fill in a DEMANGLE_COMPONENT_EXTENDED_OPERATOR.  */
826 
827 CP_STATIC_IF_GLIBCPP_V3
828 int
829 cplus_demangle_fill_extended_operator (struct demangle_component *p, int args,
830                                        struct demangle_component *name)
831 {
832   if (p == NULL || args < 0 || name == NULL)
833     return 0;
834   p->type = DEMANGLE_COMPONENT_EXTENDED_OPERATOR;
835   p->u.s_extended_operator.args = args;
836   p->u.s_extended_operator.name = name;
837   return 1;
838 }
839 
840 /* Fill in a DEMANGLE_COMPONENT_CTOR.  */
841 
842 CP_STATIC_IF_GLIBCPP_V3
843 int
844 cplus_demangle_fill_ctor (struct demangle_component *p,
845                           enum gnu_v3_ctor_kinds kind,
846                           struct demangle_component *name)
847 {
848   if (p == NULL
849       || name == NULL
850       || (int) kind < gnu_v3_complete_object_ctor
851       || (int) kind > gnu_v3_object_ctor_group)
852     return 0;
853   p->type = DEMANGLE_COMPONENT_CTOR;
854   p->u.s_ctor.kind = kind;
855   p->u.s_ctor.name = name;
856   return 1;
857 }
858 
859 /* Fill in a DEMANGLE_COMPONENT_DTOR.  */
860 
861 CP_STATIC_IF_GLIBCPP_V3
862 int
863 cplus_demangle_fill_dtor (struct demangle_component *p,
864                           enum gnu_v3_dtor_kinds kind,
865                           struct demangle_component *name)
866 {
867   if (p == NULL
868       || name == NULL
869       || (int) kind < gnu_v3_deleting_dtor
870       || (int) kind > gnu_v3_object_dtor_group)
871     return 0;
872   p->type = DEMANGLE_COMPONENT_DTOR;
873   p->u.s_dtor.kind = kind;
874   p->u.s_dtor.name = name;
875   return 1;
876 }
877 
878 /* Add a new component.  */
879 
880 static struct demangle_component *
881 d_make_empty (struct d_info *di)
882 {
883   struct demangle_component *p;
884 
885   if (di->next_comp >= di->num_comps)
886     return NULL;
887   p = &di->comps[di->next_comp];
888   ++di->next_comp;
889   return p;
890 }
891 
892 /* Add a new generic component.  */
893 
894 static struct demangle_component *
895 d_make_comp (struct d_info *di, enum demangle_component_type type,
896              struct demangle_component *left,
897              struct demangle_component *right)
898 {
899   struct demangle_component *p;
900 
901   /* We check for errors here.  A typical error would be a NULL return
902      from a subroutine.  We catch those here, and return NULL
903      upward.  */
904   switch (type)
905     {
906       /* These types require two parameters.  */
907     case DEMANGLE_COMPONENT_QUAL_NAME:
908     case DEMANGLE_COMPONENT_LOCAL_NAME:
909     case DEMANGLE_COMPONENT_TYPED_NAME:
910     case DEMANGLE_COMPONENT_TAGGED_NAME:
911     case DEMANGLE_COMPONENT_TEMPLATE:
912     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
913     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
914     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
915     case DEMANGLE_COMPONENT_UNARY:
916     case DEMANGLE_COMPONENT_BINARY:
917     case DEMANGLE_COMPONENT_BINARY_ARGS:
918     case DEMANGLE_COMPONENT_TRINARY:
919     case DEMANGLE_COMPONENT_TRINARY_ARG1:
920     case DEMANGLE_COMPONENT_LITERAL:
921     case DEMANGLE_COMPONENT_LITERAL_NEG:
922     case DEMANGLE_COMPONENT_COMPOUND_NAME:
923     case DEMANGLE_COMPONENT_VECTOR_TYPE:
924     case DEMANGLE_COMPONENT_CLONE:
925       if (left == NULL || right == NULL)
926 	return NULL;
927       break;
928 
929       /* These types only require one parameter.  */
930     case DEMANGLE_COMPONENT_VTABLE:
931     case DEMANGLE_COMPONENT_VTT:
932     case DEMANGLE_COMPONENT_TYPEINFO:
933     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
934     case DEMANGLE_COMPONENT_TYPEINFO_FN:
935     case DEMANGLE_COMPONENT_THUNK:
936     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
937     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
938     case DEMANGLE_COMPONENT_JAVA_CLASS:
939     case DEMANGLE_COMPONENT_GUARD:
940     case DEMANGLE_COMPONENT_TLS_INIT:
941     case DEMANGLE_COMPONENT_TLS_WRAPPER:
942     case DEMANGLE_COMPONENT_REFTEMP:
943     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
944     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
945     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
946     case DEMANGLE_COMPONENT_POINTER:
947     case DEMANGLE_COMPONENT_REFERENCE:
948     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
949     case DEMANGLE_COMPONENT_COMPLEX:
950     case DEMANGLE_COMPONENT_IMAGINARY:
951     case DEMANGLE_COMPONENT_VENDOR_TYPE:
952     case DEMANGLE_COMPONENT_CAST:
953     case DEMANGLE_COMPONENT_CONVERSION:
954     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
955     case DEMANGLE_COMPONENT_DECLTYPE:
956     case DEMANGLE_COMPONENT_PACK_EXPANSION:
957     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
958     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
959     case DEMANGLE_COMPONENT_NULLARY:
960     case DEMANGLE_COMPONENT_TRINARY_ARG2:
961       if (left == NULL)
962 	return NULL;
963       break;
964 
965       /* This needs a right parameter, but the left parameter can be
966 	 empty.  */
967     case DEMANGLE_COMPONENT_ARRAY_TYPE:
968     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
969       if (right == NULL)
970 	return NULL;
971       break;
972 
973       /* These are allowed to have no parameters--in some cases they
974 	 will be filled in later.  */
975     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
976     case DEMANGLE_COMPONENT_RESTRICT:
977     case DEMANGLE_COMPONENT_VOLATILE:
978     case DEMANGLE_COMPONENT_CONST:
979     case DEMANGLE_COMPONENT_RESTRICT_THIS:
980     case DEMANGLE_COMPONENT_VOLATILE_THIS:
981     case DEMANGLE_COMPONENT_CONST_THIS:
982     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
983     case DEMANGLE_COMPONENT_REFERENCE_THIS:
984     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
985     case DEMANGLE_COMPONENT_ARGLIST:
986     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
987       break;
988 
989       /* Other types should not be seen here.  */
990     default:
991       return NULL;
992     }
993 
994   p = d_make_empty (di);
995   if (p != NULL)
996     {
997       p->type = type;
998       p->u.s_binary.left = left;
999       p->u.s_binary.right = right;
1000     }
1001   return p;
1002 }
1003 
1004 /* Add a new demangle mangled name component.  */
1005 
1006 static struct demangle_component *
1007 d_make_demangle_mangled_name (struct d_info *di, const char *s)
1008 {
1009   if (d_peek_char (di) != '_' || d_peek_next_char (di) != 'Z')
1010     return d_make_name (di, s, strlen (s));
1011   d_advance (di, 2);
1012   return d_encoding (di, 0);
1013 }
1014 
1015 /* Add a new name component.  */
1016 
1017 static struct demangle_component *
1018 d_make_name (struct d_info *di, const char *s, int len)
1019 {
1020   struct demangle_component *p;
1021 
1022   p = d_make_empty (di);
1023   if (! cplus_demangle_fill_name (p, s, len))
1024     return NULL;
1025   return p;
1026 }
1027 
1028 /* Add a new builtin type component.  */
1029 
1030 static struct demangle_component *
1031 d_make_builtin_type (struct d_info *di,
1032                      const struct demangle_builtin_type_info *type)
1033 {
1034   struct demangle_component *p;
1035 
1036   if (type == NULL)
1037     return NULL;
1038   p = d_make_empty (di);
1039   if (p != NULL)
1040     {
1041       p->type = DEMANGLE_COMPONENT_BUILTIN_TYPE;
1042       p->u.s_builtin.type = type;
1043     }
1044   return p;
1045 }
1046 
1047 /* Add a new operator component.  */
1048 
1049 static struct demangle_component *
1050 d_make_operator (struct d_info *di, const struct demangle_operator_info *op)
1051 {
1052   struct demangle_component *p;
1053 
1054   p = d_make_empty (di);
1055   if (p != NULL)
1056     {
1057       p->type = DEMANGLE_COMPONENT_OPERATOR;
1058       p->u.s_operator.op = op;
1059     }
1060   return p;
1061 }
1062 
1063 /* Add a new extended operator component.  */
1064 
1065 static struct demangle_component *
1066 d_make_extended_operator (struct d_info *di, int args,
1067                           struct demangle_component *name)
1068 {
1069   struct demangle_component *p;
1070 
1071   p = d_make_empty (di);
1072   if (! cplus_demangle_fill_extended_operator (p, args, name))
1073     return NULL;
1074   return p;
1075 }
1076 
1077 static struct demangle_component *
1078 d_make_default_arg (struct d_info *di, int num,
1079 		    struct demangle_component *sub)
1080 {
1081   struct demangle_component *p = d_make_empty (di);
1082   if (p)
1083     {
1084       p->type = DEMANGLE_COMPONENT_DEFAULT_ARG;
1085       p->u.s_unary_num.num = num;
1086       p->u.s_unary_num.sub = sub;
1087     }
1088   return p;
1089 }
1090 
1091 /* Add a new constructor component.  */
1092 
1093 static struct demangle_component *
1094 d_make_ctor (struct d_info *di, enum gnu_v3_ctor_kinds kind,
1095              struct demangle_component *name)
1096 {
1097   struct demangle_component *p;
1098 
1099   p = d_make_empty (di);
1100   if (! cplus_demangle_fill_ctor (p, kind, name))
1101     return NULL;
1102   return p;
1103 }
1104 
1105 /* Add a new destructor component.  */
1106 
1107 static struct demangle_component *
1108 d_make_dtor (struct d_info *di, enum gnu_v3_dtor_kinds kind,
1109              struct demangle_component *name)
1110 {
1111   struct demangle_component *p;
1112 
1113   p = d_make_empty (di);
1114   if (! cplus_demangle_fill_dtor (p, kind, name))
1115     return NULL;
1116   return p;
1117 }
1118 
1119 /* Add a new template parameter.  */
1120 
1121 static struct demangle_component *
1122 d_make_template_param (struct d_info *di, long i)
1123 {
1124   struct demangle_component *p;
1125 
1126   p = d_make_empty (di);
1127   if (p != NULL)
1128     {
1129       p->type = DEMANGLE_COMPONENT_TEMPLATE_PARAM;
1130       p->u.s_number.number = i;
1131     }
1132   return p;
1133 }
1134 
1135 /* Add a new function parameter.  */
1136 
1137 static struct demangle_component *
1138 d_make_function_param (struct d_info *di, long i)
1139 {
1140   struct demangle_component *p;
1141 
1142   p = d_make_empty (di);
1143   if (p != NULL)
1144     {
1145       p->type = DEMANGLE_COMPONENT_FUNCTION_PARAM;
1146       p->u.s_number.number = i;
1147     }
1148   return p;
1149 }
1150 
1151 /* Add a new standard substitution component.  */
1152 
1153 static struct demangle_component *
1154 d_make_sub (struct d_info *di, const char *name, int len)
1155 {
1156   struct demangle_component *p;
1157 
1158   p = d_make_empty (di);
1159   if (p != NULL)
1160     {
1161       p->type = DEMANGLE_COMPONENT_SUB_STD;
1162       p->u.s_string.string = name;
1163       p->u.s_string.len = len;
1164     }
1165   return p;
1166 }
1167 
1168 /* <mangled-name> ::= _Z <encoding> [<clone-suffix>]*
1169 
1170    TOP_LEVEL is non-zero when called at the top level.  */
1171 
1172 CP_STATIC_IF_GLIBCPP_V3
1173 struct demangle_component *
1174 cplus_demangle_mangled_name (struct d_info *di, int top_level)
1175 {
1176   struct demangle_component *p;
1177 
1178   if (! d_check_char (di, '_')
1179       /* Allow missing _ if not at toplevel to work around a
1180 	 bug in G++ abi-version=2 mangling; see the comment in
1181 	 write_template_arg.  */
1182       && top_level)
1183     return NULL;
1184   if (! d_check_char (di, 'Z'))
1185     return NULL;
1186   p = d_encoding (di, top_level);
1187 
1188   /* If at top level and parsing parameters, check for a clone
1189      suffix.  */
1190   if (top_level && (di->options & DMGL_PARAMS) != 0)
1191     while (d_peek_char (di) == '.'
1192 	   && (IS_LOWER (d_peek_next_char (di))
1193 	       || d_peek_next_char (di) == '_'
1194 	       || IS_DIGIT (d_peek_next_char (di))))
1195       p = d_clone_suffix (di, p);
1196 
1197   return p;
1198 }
1199 
1200 /* Return whether a function should have a return type.  The argument
1201    is the function name, which may be qualified in various ways.  The
1202    rules are that template functions have return types with some
1203    exceptions, function types which are not part of a function name
1204    mangling have return types with some exceptions, and non-template
1205    function names do not have return types.  The exceptions are that
1206    constructors, destructors, and conversion operators do not have
1207    return types.  */
1208 
1209 static int
1210 has_return_type (struct demangle_component *dc)
1211 {
1212   if (dc == NULL)
1213     return 0;
1214   switch (dc->type)
1215     {
1216     default:
1217       return 0;
1218     case DEMANGLE_COMPONENT_TEMPLATE:
1219       return ! is_ctor_dtor_or_conversion (d_left (dc));
1220     case DEMANGLE_COMPONENT_RESTRICT_THIS:
1221     case DEMANGLE_COMPONENT_VOLATILE_THIS:
1222     case DEMANGLE_COMPONENT_CONST_THIS:
1223     case DEMANGLE_COMPONENT_REFERENCE_THIS:
1224     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
1225     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
1226       return has_return_type (d_left (dc));
1227     }
1228 }
1229 
1230 /* Return whether a name is a constructor, a destructor, or a
1231    conversion operator.  */
1232 
1233 static int
1234 is_ctor_dtor_or_conversion (struct demangle_component *dc)
1235 {
1236   if (dc == NULL)
1237     return 0;
1238   switch (dc->type)
1239     {
1240     default:
1241       return 0;
1242     case DEMANGLE_COMPONENT_QUAL_NAME:
1243     case DEMANGLE_COMPONENT_LOCAL_NAME:
1244       return is_ctor_dtor_or_conversion (d_right (dc));
1245     case DEMANGLE_COMPONENT_CTOR:
1246     case DEMANGLE_COMPONENT_DTOR:
1247     case DEMANGLE_COMPONENT_CONVERSION:
1248       return 1;
1249     }
1250 }
1251 
1252 /* <encoding> ::= <(function) name> <bare-function-type>
1253               ::= <(data) name>
1254               ::= <special-name>
1255 
1256    TOP_LEVEL is non-zero when called at the top level, in which case
1257    if DMGL_PARAMS is not set we do not demangle the function
1258    parameters.  We only set this at the top level, because otherwise
1259    we would not correctly demangle names in local scopes.  */
1260 
1261 static struct demangle_component *
1262 d_encoding (struct d_info *di, int top_level)
1263 {
1264   char peek = d_peek_char (di);
1265 
1266   if (peek == 'G' || peek == 'T')
1267     return d_special_name (di);
1268   else
1269     {
1270       struct demangle_component *dc;
1271 
1272       dc = d_name (di);
1273 
1274       if (dc != NULL && top_level && (di->options & DMGL_PARAMS) == 0)
1275 	{
1276 	  /* Strip off any initial CV-qualifiers, as they really apply
1277 	     to the `this' parameter, and they were not output by the
1278 	     v2 demangler without DMGL_PARAMS.  */
1279 	  while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1280 		 || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1281 		 || dc->type == DEMANGLE_COMPONENT_CONST_THIS
1282 		 || dc->type == DEMANGLE_COMPONENT_TRANSACTION_SAFE
1283 		 || dc->type == DEMANGLE_COMPONENT_REFERENCE_THIS
1284 		 || dc->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
1285 	    dc = d_left (dc);
1286 
1287 	  /* If the top level is a DEMANGLE_COMPONENT_LOCAL_NAME, then
1288 	     there may be CV-qualifiers on its right argument which
1289 	     really apply here; this happens when parsing a class
1290 	     which is local to a function.  */
1291 	  if (dc->type == DEMANGLE_COMPONENT_LOCAL_NAME)
1292 	    {
1293 	      struct demangle_component *dcr;
1294 
1295 	      dcr = d_right (dc);
1296 	      while (dcr->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1297 		     || dcr->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1298 		     || dcr->type == DEMANGLE_COMPONENT_CONST_THIS
1299 		     || dcr->type == DEMANGLE_COMPONENT_TRANSACTION_SAFE
1300 		     || dcr->type == DEMANGLE_COMPONENT_REFERENCE_THIS
1301 		     || dcr->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
1302 		dcr = d_left (dcr);
1303 	      dc->u.s_binary.right = dcr;
1304 	    }
1305 
1306 	  return dc;
1307 	}
1308 
1309       peek = d_peek_char (di);
1310       if (dc == NULL || peek == '\0' || peek == 'E')
1311 	return dc;
1312       return d_make_comp (di, DEMANGLE_COMPONENT_TYPED_NAME, dc,
1313 			  d_bare_function_type (di, has_return_type (dc)));
1314     }
1315 }
1316 
1317 /* <tagged-name> ::= <name> B <source-name> */
1318 
1319 static struct demangle_component *
1320 d_abi_tags (struct d_info *di, struct demangle_component *dc)
1321 {
1322   struct demangle_component *hold_last_name;
1323   char peek;
1324 
1325   /* Preserve the last name, so the ABI tag doesn't clobber it.  */
1326   hold_last_name = di->last_name;
1327 
1328   while (peek = d_peek_char (di),
1329 	 peek == 'B')
1330     {
1331       struct demangle_component *tag;
1332       d_advance (di, 1);
1333       tag = d_source_name (di);
1334       dc = d_make_comp (di, DEMANGLE_COMPONENT_TAGGED_NAME, dc, tag);
1335     }
1336 
1337   di->last_name = hold_last_name;
1338 
1339   return dc;
1340 }
1341 
1342 /* <name> ::= <nested-name>
1343           ::= <unscoped-name>
1344           ::= <unscoped-template-name> <template-args>
1345           ::= <local-name>
1346 
1347    <unscoped-name> ::= <unqualified-name>
1348                    ::= St <unqualified-name>
1349 
1350    <unscoped-template-name> ::= <unscoped-name>
1351                             ::= <substitution>
1352 */
1353 
1354 static struct demangle_component *
1355 d_name (struct d_info *di)
1356 {
1357   char peek = d_peek_char (di);
1358   struct demangle_component *dc;
1359 
1360   switch (peek)
1361     {
1362     case 'N':
1363       return d_nested_name (di);
1364 
1365     case 'Z':
1366       return d_local_name (di);
1367 
1368     case 'U':
1369       return d_unqualified_name (di);
1370 
1371     case 'S':
1372       {
1373 	int subst;
1374 
1375 	if (d_peek_next_char (di) != 't')
1376 	  {
1377 	    dc = d_substitution (di, 0);
1378 	    subst = 1;
1379 	  }
1380 	else
1381 	  {
1382 	    d_advance (di, 2);
1383 	    dc = d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME,
1384 			      d_make_name (di, "std", 3),
1385 			      d_unqualified_name (di));
1386 	    di->expansion += 3;
1387 	    subst = 0;
1388 	  }
1389 
1390 	if (d_peek_char (di) != 'I')
1391 	  {
1392 	    /* The grammar does not permit this case to occur if we
1393 	       called d_substitution() above (i.e., subst == 1).  We
1394 	       don't bother to check.  */
1395 	  }
1396 	else
1397 	  {
1398 	    /* This is <template-args>, which means that we just saw
1399 	       <unscoped-template-name>, which is a substitution
1400 	       candidate if we didn't just get it from a
1401 	       substitution.  */
1402 	    if (! subst)
1403 	      {
1404 		if (! d_add_substitution (di, dc))
1405 		  return NULL;
1406 	      }
1407 	    dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1408 			      d_template_args (di));
1409 	  }
1410 
1411 	return dc;
1412       }
1413 
1414     case 'L':
1415     default:
1416       dc = d_unqualified_name (di);
1417       if (d_peek_char (di) == 'I')
1418 	{
1419 	  /* This is <template-args>, which means that we just saw
1420 	     <unscoped-template-name>, which is a substitution
1421 	     candidate.  */
1422 	  if (! d_add_substitution (di, dc))
1423 	    return NULL;
1424 	  dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1425 			    d_template_args (di));
1426 	}
1427       return dc;
1428     }
1429 }
1430 
1431 /* <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1432                  ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
1433 */
1434 
1435 static struct demangle_component *
1436 d_nested_name (struct d_info *di)
1437 {
1438   struct demangle_component *ret;
1439   struct demangle_component **pret;
1440   struct demangle_component *rqual;
1441 
1442   if (! d_check_char (di, 'N'))
1443     return NULL;
1444 
1445   pret = d_cv_qualifiers (di, &ret, 1);
1446   if (pret == NULL)
1447     return NULL;
1448 
1449   /* Parse the ref-qualifier now and then attach it
1450      once we have something to attach it to.  */
1451   rqual = d_ref_qualifier (di, NULL);
1452 
1453   *pret = d_prefix (di);
1454   if (*pret == NULL)
1455     return NULL;
1456 
1457   if (rqual)
1458     {
1459       d_left (rqual) = ret;
1460       ret = rqual;
1461     }
1462 
1463   if (! d_check_char (di, 'E'))
1464     return NULL;
1465 
1466   return ret;
1467 }
1468 
1469 /* <prefix> ::= <prefix> <unqualified-name>
1470             ::= <template-prefix> <template-args>
1471             ::= <template-param>
1472             ::= <decltype>
1473             ::=
1474             ::= <substitution>
1475 
1476    <template-prefix> ::= <prefix> <(template) unqualified-name>
1477                      ::= <template-param>
1478                      ::= <substitution>
1479 */
1480 
1481 static struct demangle_component *
1482 d_prefix (struct d_info *di)
1483 {
1484   struct demangle_component *ret = NULL;
1485 
1486   while (1)
1487     {
1488       char peek;
1489       enum demangle_component_type comb_type;
1490       struct demangle_component *dc;
1491 
1492       peek = d_peek_char (di);
1493       if (peek == '\0')
1494 	return NULL;
1495 
1496       /* The older code accepts a <local-name> here, but I don't see
1497 	 that in the grammar.  The older code does not accept a
1498 	 <template-param> here.  */
1499 
1500       comb_type = DEMANGLE_COMPONENT_QUAL_NAME;
1501       if (peek == 'D')
1502 	{
1503 	  char peek2 = d_peek_next_char (di);
1504 	  if (peek2 == 'T' || peek2 == 't')
1505 	    /* Decltype.  */
1506 	    dc = cplus_demangle_type (di);
1507 	  else
1508 	    /* Destructor name.  */
1509 	    dc = d_unqualified_name (di);
1510 	}
1511       else if (IS_DIGIT (peek)
1512 	  || IS_LOWER (peek)
1513 	  || peek == 'C'
1514 	  || peek == 'U'
1515 	  || peek == 'L')
1516 	dc = d_unqualified_name (di);
1517       else if (peek == 'S')
1518 	dc = d_substitution (di, 1);
1519       else if (peek == 'I')
1520 	{
1521 	  if (ret == NULL)
1522 	    return NULL;
1523 	  comb_type = DEMANGLE_COMPONENT_TEMPLATE;
1524 	  dc = d_template_args (di);
1525 	}
1526       else if (peek == 'T')
1527 	dc = d_template_param (di);
1528       else if (peek == 'E')
1529 	return ret;
1530       else if (peek == 'M')
1531 	{
1532 	  /* Initializer scope for a lambda.  We don't need to represent
1533 	     this; the normal code will just treat the variable as a type
1534 	     scope, which gives appropriate output.  */
1535 	  if (ret == NULL)
1536 	    return NULL;
1537 	  d_advance (di, 1);
1538 	  continue;
1539 	}
1540       else
1541 	return NULL;
1542 
1543       if (ret == NULL)
1544 	ret = dc;
1545       else
1546 	ret = d_make_comp (di, comb_type, ret, dc);
1547 
1548       if (peek != 'S' && d_peek_char (di) != 'E')
1549 	{
1550 	  if (! d_add_substitution (di, ret))
1551 	    return NULL;
1552 	}
1553     }
1554 }
1555 
1556 /* <unqualified-name> ::= <operator-name>
1557                       ::= <ctor-dtor-name>
1558                       ::= <source-name>
1559 		      ::= <local-source-name>
1560 
1561     <local-source-name>	::= L <source-name> <discriminator>
1562 */
1563 
1564 static struct demangle_component *
1565 d_unqualified_name (struct d_info *di)
1566 {
1567   struct demangle_component *ret;
1568   char peek;
1569 
1570   peek = d_peek_char (di);
1571   if (IS_DIGIT (peek))
1572     ret = d_source_name (di);
1573   else if (IS_LOWER (peek))
1574     {
1575       ret = d_operator_name (di);
1576       if (ret != NULL && ret->type == DEMANGLE_COMPONENT_OPERATOR)
1577 	{
1578 	  di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1579 	  if (!strcmp (ret->u.s_operator.op->code, "li"))
1580 	    ret = d_make_comp (di, DEMANGLE_COMPONENT_UNARY, ret,
1581 			       d_source_name (di));
1582 	}
1583     }
1584   else if (peek == 'C' || peek == 'D')
1585     ret = d_ctor_dtor_name (di);
1586   else if (peek == 'L')
1587     {
1588       d_advance (di, 1);
1589 
1590       ret = d_source_name (di);
1591       if (ret == NULL)
1592 	return NULL;
1593       if (! d_discriminator (di))
1594 	return NULL;
1595     }
1596   else if (peek == 'U')
1597     {
1598       switch (d_peek_next_char (di))
1599 	{
1600 	case 'l':
1601 	  ret = d_lambda (di);
1602 	  break;
1603 	case 't':
1604 	  ret = d_unnamed_type (di);
1605 	  break;
1606 	default:
1607 	  return NULL;
1608 	}
1609     }
1610   else
1611     return NULL;
1612 
1613   if (d_peek_char (di) == 'B')
1614     ret = d_abi_tags (di, ret);
1615   return ret;
1616 }
1617 
1618 /* <source-name> ::= <(positive length) number> <identifier>  */
1619 
1620 static struct demangle_component *
1621 d_source_name (struct d_info *di)
1622 {
1623   long len;
1624   struct demangle_component *ret;
1625 
1626   len = d_number (di);
1627   if (len <= 0)
1628     return NULL;
1629   ret = d_identifier (di, len);
1630   di->last_name = ret;
1631   return ret;
1632 }
1633 
1634 /* number ::= [n] <(non-negative decimal integer)>  */
1635 
1636 static long
1637 d_number (struct d_info *di)
1638 {
1639   int negative;
1640   char peek;
1641   long ret;
1642 
1643   negative = 0;
1644   peek = d_peek_char (di);
1645   if (peek == 'n')
1646     {
1647       negative = 1;
1648       d_advance (di, 1);
1649       peek = d_peek_char (di);
1650     }
1651 
1652   ret = 0;
1653   while (1)
1654     {
1655       if (! IS_DIGIT (peek))
1656 	{
1657 	  if (negative)
1658 	    ret = - ret;
1659 	  return ret;
1660 	}
1661       ret = ret * 10 + peek - '0';
1662       d_advance (di, 1);
1663       peek = d_peek_char (di);
1664     }
1665 }
1666 
1667 /* Like d_number, but returns a demangle_component.  */
1668 
1669 static struct demangle_component *
1670 d_number_component (struct d_info *di)
1671 {
1672   struct demangle_component *ret = d_make_empty (di);
1673   if (ret)
1674     {
1675       ret->type = DEMANGLE_COMPONENT_NUMBER;
1676       ret->u.s_number.number = d_number (di);
1677     }
1678   return ret;
1679 }
1680 
1681 /* identifier ::= <(unqualified source code identifier)>  */
1682 
1683 static struct demangle_component *
1684 d_identifier (struct d_info *di, long len)
1685 {
1686   const char *name;
1687 
1688   name = d_str (di);
1689 
1690   if (di->send - name < len)
1691     return NULL;
1692 
1693   d_advance (di, len);
1694 
1695   /* A Java mangled name may have a trailing '$' if it is a C++
1696      keyword.  This '$' is not included in the length count.  We just
1697      ignore the '$'.  */
1698   if ((di->options & DMGL_JAVA) != 0
1699       && d_peek_char (di) == '$')
1700     d_advance (di, 1);
1701 
1702   /* Look for something which looks like a gcc encoding of an
1703      anonymous namespace, and replace it with a more user friendly
1704      name.  */
1705   if (len >= (long) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1706       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1707 		 ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1708     {
1709       const char *s;
1710 
1711       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1712       if ((*s == '.' || *s == '_' || *s == '$')
1713 	  && s[1] == 'N')
1714 	{
1715 	  di->expansion -= len - sizeof "(anonymous namespace)";
1716 	  return d_make_name (di, "(anonymous namespace)",
1717 			      sizeof "(anonymous namespace)" - 1);
1718 	}
1719     }
1720 
1721   return d_make_name (di, name, len);
1722 }
1723 
1724 /* operator_name ::= many different two character encodings.
1725                  ::= cv <type>
1726                  ::= v <digit> <source-name>
1727 
1728    This list is sorted for binary search.  */
1729 
1730 #define NL(s) s, (sizeof s) - 1
1731 
1732 CP_STATIC_IF_GLIBCPP_V3
1733 const struct demangle_operator_info cplus_demangle_operators[] =
1734 {
1735   { "aN", NL ("&="),        2 },
1736   { "aS", NL ("="),         2 },
1737   { "aa", NL ("&&"),        2 },
1738   { "ad", NL ("&"),         1 },
1739   { "an", NL ("&"),         2 },
1740   { "at", NL ("alignof "),   1 },
1741   { "az", NL ("alignof "),   1 },
1742   { "cc", NL ("const_cast"), 2 },
1743   { "cl", NL ("()"),        2 },
1744   { "cm", NL (","),         2 },
1745   { "co", NL ("~"),         1 },
1746   { "dV", NL ("/="),        2 },
1747   { "da", NL ("delete[] "), 1 },
1748   { "dc", NL ("dynamic_cast"), 2 },
1749   { "de", NL ("*"),         1 },
1750   { "dl", NL ("delete "),   1 },
1751   { "ds", NL (".*"),        2 },
1752   { "dt", NL ("."),         2 },
1753   { "dv", NL ("/"),         2 },
1754   { "eO", NL ("^="),        2 },
1755   { "eo", NL ("^"),         2 },
1756   { "eq", NL ("=="),        2 },
1757   { "ge", NL (">="),        2 },
1758   { "gs", NL ("::"),	    1 },
1759   { "gt", NL (">"),         2 },
1760   { "ix", NL ("[]"),        2 },
1761   { "lS", NL ("<<="),       2 },
1762   { "le", NL ("<="),        2 },
1763   { "li", NL ("operator\"\" "), 1 },
1764   { "ls", NL ("<<"),        2 },
1765   { "lt", NL ("<"),         2 },
1766   { "mI", NL ("-="),        2 },
1767   { "mL", NL ("*="),        2 },
1768   { "mi", NL ("-"),         2 },
1769   { "ml", NL ("*"),         2 },
1770   { "mm", NL ("--"),        1 },
1771   { "na", NL ("new[]"),     3 },
1772   { "ne", NL ("!="),        2 },
1773   { "ng", NL ("-"),         1 },
1774   { "nt", NL ("!"),         1 },
1775   { "nw", NL ("new"),       3 },
1776   { "oR", NL ("|="),        2 },
1777   { "oo", NL ("||"),        2 },
1778   { "or", NL ("|"),         2 },
1779   { "pL", NL ("+="),        2 },
1780   { "pl", NL ("+"),         2 },
1781   { "pm", NL ("->*"),       2 },
1782   { "pp", NL ("++"),        1 },
1783   { "ps", NL ("+"),         1 },
1784   { "pt", NL ("->"),        2 },
1785   { "qu", NL ("?"),         3 },
1786   { "rM", NL ("%="),        2 },
1787   { "rS", NL (">>="),       2 },
1788   { "rc", NL ("reinterpret_cast"), 2 },
1789   { "rm", NL ("%"),         2 },
1790   { "rs", NL (">>"),        2 },
1791   { "sc", NL ("static_cast"), 2 },
1792   { "st", NL ("sizeof "),   1 },
1793   { "sz", NL ("sizeof "),   1 },
1794   { "tr", NL ("throw"),     0 },
1795   { "tw", NL ("throw "),    1 },
1796   { NULL, NULL, 0,          0 }
1797 };
1798 
1799 static struct demangle_component *
1800 d_operator_name (struct d_info *di)
1801 {
1802   char c1;
1803   char c2;
1804 
1805   c1 = d_next_char (di);
1806   c2 = d_next_char (di);
1807   if (c1 == 'v' && IS_DIGIT (c2))
1808     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1809   else if (c1 == 'c' && c2 == 'v')
1810     {
1811       struct demangle_component *type;
1812       int was_conversion = di->is_conversion;
1813       struct demangle_component *res;
1814 
1815       di->is_conversion = ! di->is_expression;
1816       type = cplus_demangle_type (di);
1817       if (di->is_conversion)
1818 	res = d_make_comp (di, DEMANGLE_COMPONENT_CONVERSION, type, NULL);
1819       else
1820 	res = d_make_comp (di, DEMANGLE_COMPONENT_CAST, type, NULL);
1821       di->is_conversion = was_conversion;
1822       return res;
1823     }
1824   else
1825     {
1826       /* LOW is the inclusive lower bound.  */
1827       int low = 0;
1828       /* HIGH is the exclusive upper bound.  We subtract one to ignore
1829 	 the sentinel at the end of the array.  */
1830       int high = ((sizeof (cplus_demangle_operators)
1831 		   / sizeof (cplus_demangle_operators[0]))
1832 		  - 1);
1833 
1834       while (1)
1835 	{
1836 	  int i;
1837 	  const struct demangle_operator_info *p;
1838 
1839 	  i = low + (high - low) / 2;
1840 	  p = cplus_demangle_operators + i;
1841 
1842 	  if (c1 == p->code[0] && c2 == p->code[1])
1843 	    return d_make_operator (di, p);
1844 
1845 	  if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1846 	    high = i;
1847 	  else
1848 	    low = i + 1;
1849 	  if (low == high)
1850 	    return NULL;
1851 	}
1852     }
1853 }
1854 
1855 static struct demangle_component *
1856 d_make_character (struct d_info *di, int c)
1857 {
1858   struct demangle_component *p;
1859   p = d_make_empty (di);
1860   if (p != NULL)
1861     {
1862       p->type = DEMANGLE_COMPONENT_CHARACTER;
1863       p->u.s_character.character = c;
1864     }
1865   return p;
1866 }
1867 
1868 static struct demangle_component *
1869 d_java_resource (struct d_info *di)
1870 {
1871   struct demangle_component *p = NULL;
1872   struct demangle_component *next = NULL;
1873   long len, i;
1874   char c;
1875   const char *str;
1876 
1877   len = d_number (di);
1878   if (len <= 1)
1879     return NULL;
1880 
1881   /* Eat the leading '_'.  */
1882   if (d_next_char (di) != '_')
1883     return NULL;
1884   len--;
1885 
1886   str = d_str (di);
1887   i = 0;
1888 
1889   while (len > 0)
1890     {
1891       c = str[i];
1892       if (!c)
1893 	return NULL;
1894 
1895       /* Each chunk is either a '$' escape...  */
1896       if (c == '$')
1897 	{
1898 	  i++;
1899 	  switch (str[i++])
1900 	    {
1901 	    case 'S':
1902 	      c = '/';
1903 	      break;
1904 	    case '_':
1905 	      c = '.';
1906 	      break;
1907 	    case '$':
1908 	      c = '$';
1909 	      break;
1910 	    default:
1911 	      return NULL;
1912 	    }
1913 	  next = d_make_character (di, c);
1914 	  d_advance (di, i);
1915 	  str = d_str (di);
1916 	  len -= i;
1917 	  i = 0;
1918 	  if (next == NULL)
1919 	    return NULL;
1920 	}
1921       /* ... or a sequence of characters.  */
1922       else
1923 	{
1924 	  while (i < len && str[i] && str[i] != '$')
1925 	    i++;
1926 
1927 	  next = d_make_name (di, str, i);
1928 	  d_advance (di, i);
1929 	  str = d_str (di);
1930 	  len -= i;
1931 	  i = 0;
1932 	  if (next == NULL)
1933 	    return NULL;
1934 	}
1935 
1936       if (p == NULL)
1937 	p = next;
1938       else
1939 	{
1940 	  p = d_make_comp (di, DEMANGLE_COMPONENT_COMPOUND_NAME, p, next);
1941 	  if (p == NULL)
1942 	    return NULL;
1943 	}
1944     }
1945 
1946   p = d_make_comp (di, DEMANGLE_COMPONENT_JAVA_RESOURCE, p, NULL);
1947 
1948   return p;
1949 }
1950 
1951 /* <special-name> ::= TV <type>
1952                   ::= TT <type>
1953                   ::= TI <type>
1954                   ::= TS <type>
1955                   ::= GV <(object) name>
1956                   ::= T <call-offset> <(base) encoding>
1957                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1958    Also g++ extensions:
1959                   ::= TC <type> <(offset) number> _ <(base) type>
1960                   ::= TF <type>
1961                   ::= TJ <type>
1962                   ::= GR <name>
1963 		  ::= GA <encoding>
1964 		  ::= Gr <resource name>
1965 		  ::= GTt <encoding>
1966 		  ::= GTn <encoding>
1967 */
1968 
1969 static struct demangle_component *
1970 d_special_name (struct d_info *di)
1971 {
1972   di->expansion += 20;
1973   if (d_check_char (di, 'T'))
1974     {
1975       switch (d_next_char (di))
1976 	{
1977 	case 'V':
1978 	  di->expansion -= 5;
1979 	  return d_make_comp (di, DEMANGLE_COMPONENT_VTABLE,
1980 			      cplus_demangle_type (di), NULL);
1981 	case 'T':
1982 	  di->expansion -= 10;
1983 	  return d_make_comp (di, DEMANGLE_COMPONENT_VTT,
1984 			      cplus_demangle_type (di), NULL);
1985 	case 'I':
1986 	  return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO,
1987 			      cplus_demangle_type (di), NULL);
1988 	case 'S':
1989 	  return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_NAME,
1990 			      cplus_demangle_type (di), NULL);
1991 
1992 	case 'h':
1993 	  if (! d_call_offset (di, 'h'))
1994 	    return NULL;
1995 	  return d_make_comp (di, DEMANGLE_COMPONENT_THUNK,
1996 			      d_encoding (di, 0), NULL);
1997 
1998 	case 'v':
1999 	  if (! d_call_offset (di, 'v'))
2000 	    return NULL;
2001 	  return d_make_comp (di, DEMANGLE_COMPONENT_VIRTUAL_THUNK,
2002 			      d_encoding (di, 0), NULL);
2003 
2004 	case 'c':
2005 	  if (! d_call_offset (di, '\0'))
2006 	    return NULL;
2007 	  if (! d_call_offset (di, '\0'))
2008 	    return NULL;
2009 	  return d_make_comp (di, DEMANGLE_COMPONENT_COVARIANT_THUNK,
2010 			      d_encoding (di, 0), NULL);
2011 
2012 	case 'C':
2013 	  {
2014 	    struct demangle_component *derived_type;
2015 	    long offset;
2016 	    struct demangle_component *base_type;
2017 
2018 	    derived_type = cplus_demangle_type (di);
2019 	    offset = d_number (di);
2020 	    if (offset < 0)
2021 	      return NULL;
2022 	    if (! d_check_char (di, '_'))
2023 	      return NULL;
2024 	    base_type = cplus_demangle_type (di);
2025 	    /* We don't display the offset.  FIXME: We should display
2026 	       it in verbose mode.  */
2027 	    di->expansion += 5;
2028 	    return d_make_comp (di, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE,
2029 				base_type, derived_type);
2030 	  }
2031 
2032 	case 'F':
2033 	  return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_FN,
2034 			      cplus_demangle_type (di), NULL);
2035 	case 'J':
2036 	  return d_make_comp (di, DEMANGLE_COMPONENT_JAVA_CLASS,
2037 			      cplus_demangle_type (di), NULL);
2038 
2039 	case 'H':
2040 	  return d_make_comp (di, DEMANGLE_COMPONENT_TLS_INIT,
2041 			      d_name (di), NULL);
2042 
2043 	case 'W':
2044 	  return d_make_comp (di, DEMANGLE_COMPONENT_TLS_WRAPPER,
2045 			      d_name (di), NULL);
2046 
2047 	default:
2048 	  return NULL;
2049 	}
2050     }
2051   else if (d_check_char (di, 'G'))
2052     {
2053       switch (d_next_char (di))
2054 	{
2055 	case 'V':
2056 	  return d_make_comp (di, DEMANGLE_COMPONENT_GUARD, d_name (di), NULL);
2057 
2058 	case 'R':
2059 	  {
2060 	    struct demangle_component *name = d_name (di);
2061 	    return d_make_comp (di, DEMANGLE_COMPONENT_REFTEMP, name,
2062 				d_number_component (di));
2063 	  }
2064 
2065 	case 'A':
2066 	  return d_make_comp (di, DEMANGLE_COMPONENT_HIDDEN_ALIAS,
2067 			      d_encoding (di, 0), NULL);
2068 
2069 	case 'T':
2070 	  switch (d_next_char (di))
2071 	    {
2072 	    case 'n':
2073 	      return d_make_comp (di, DEMANGLE_COMPONENT_NONTRANSACTION_CLONE,
2074 				  d_encoding (di, 0), NULL);
2075 	    default:
2076 	      /* ??? The proposal is that other letters (such as 'h') stand
2077 		 for different variants of transaction cloning, such as
2078 		 compiling directly for hardware transaction support.  But
2079 		 they still should all be transactional clones of some sort
2080 		 so go ahead and call them that.  */
2081 	    case 't':
2082 	      return d_make_comp (di, DEMANGLE_COMPONENT_TRANSACTION_CLONE,
2083 				  d_encoding (di, 0), NULL);
2084 	    }
2085 
2086 	case 'r':
2087 	  return d_java_resource (di);
2088 
2089 	default:
2090 	  return NULL;
2091 	}
2092     }
2093   else
2094     return NULL;
2095 }
2096 
2097 /* <call-offset> ::= h <nv-offset> _
2098                  ::= v <v-offset> _
2099 
2100    <nv-offset> ::= <(offset) number>
2101 
2102    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
2103 
2104    The C parameter, if not '\0', is a character we just read which is
2105    the start of the <call-offset>.
2106 
2107    We don't display the offset information anywhere.  FIXME: We should
2108    display it in verbose mode.  */
2109 
2110 static int
2111 d_call_offset (struct d_info *di, int c)
2112 {
2113   if (c == '\0')
2114     c = d_next_char (di);
2115 
2116   if (c == 'h')
2117     d_number (di);
2118   else if (c == 'v')
2119     {
2120       d_number (di);
2121       if (! d_check_char (di, '_'))
2122 	return 0;
2123       d_number (di);
2124     }
2125   else
2126     return 0;
2127 
2128   if (! d_check_char (di, '_'))
2129     return 0;
2130 
2131   return 1;
2132 }
2133 
2134 /* <ctor-dtor-name> ::= C1
2135                     ::= C2
2136                     ::= C3
2137                     ::= D0
2138                     ::= D1
2139                     ::= D2
2140 */
2141 
2142 static struct demangle_component *
2143 d_ctor_dtor_name (struct d_info *di)
2144 {
2145   if (di->last_name != NULL)
2146     {
2147       if (di->last_name->type == DEMANGLE_COMPONENT_NAME)
2148 	di->expansion += di->last_name->u.s_name.len;
2149       else if (di->last_name->type == DEMANGLE_COMPONENT_SUB_STD)
2150 	di->expansion += di->last_name->u.s_string.len;
2151     }
2152   switch (d_peek_char (di))
2153     {
2154     case 'C':
2155       {
2156 	enum gnu_v3_ctor_kinds kind;
2157 
2158 	switch (d_peek_next_char (di))
2159 	  {
2160 	  case '1':
2161 	    kind = gnu_v3_complete_object_ctor;
2162 	    break;
2163 	  case '2':
2164 	    kind = gnu_v3_base_object_ctor;
2165 	    break;
2166 	  case '3':
2167 	    kind = gnu_v3_complete_object_allocating_ctor;
2168 	    break;
2169           case '4':
2170 	    kind = gnu_v3_unified_ctor;
2171 	    break;
2172 	  case '5':
2173 	    kind = gnu_v3_object_ctor_group;
2174 	    break;
2175 	  default:
2176 	    return NULL;
2177 	  }
2178 	d_advance (di, 2);
2179 	return d_make_ctor (di, kind, di->last_name);
2180       }
2181 
2182     case 'D':
2183       {
2184 	enum gnu_v3_dtor_kinds kind;
2185 
2186 	switch (d_peek_next_char (di))
2187 	  {
2188 	  case '0':
2189 	    kind = gnu_v3_deleting_dtor;
2190 	    break;
2191 	  case '1':
2192 	    kind = gnu_v3_complete_object_dtor;
2193 	    break;
2194 	  case '2':
2195 	    kind = gnu_v3_base_object_dtor;
2196 	    break;
2197           /*  digit '3' is not used */
2198 	  case '4':
2199 	    kind = gnu_v3_unified_dtor;
2200 	    break;
2201 	  case '5':
2202 	    kind = gnu_v3_object_dtor_group;
2203 	    break;
2204 	  default:
2205 	    return NULL;
2206 	  }
2207 	d_advance (di, 2);
2208 	return d_make_dtor (di, kind, di->last_name);
2209       }
2210 
2211     default:
2212       return NULL;
2213     }
2214 }
2215 
2216 /* <type> ::= <builtin-type>
2217           ::= <function-type>
2218           ::= <class-enum-type>
2219           ::= <array-type>
2220           ::= <pointer-to-member-type>
2221           ::= <template-param>
2222           ::= <template-template-param> <template-args>
2223           ::= <substitution>
2224           ::= <CV-qualifiers> <type>
2225           ::= P <type>
2226           ::= R <type>
2227           ::= O <type> (C++0x)
2228           ::= C <type>
2229           ::= G <type>
2230           ::= U <source-name> <type>
2231 
2232    <builtin-type> ::= various one letter codes
2233                   ::= u <source-name>
2234 */
2235 
2236 CP_STATIC_IF_GLIBCPP_V3
2237 const struct demangle_builtin_type_info
2238 cplus_demangle_builtin_types[D_BUILTIN_TYPE_COUNT] =
2239 {
2240   /* a */ { NL ("signed char"),	NL ("signed char"),	D_PRINT_DEFAULT },
2241   /* b */ { NL ("bool"),	NL ("boolean"),		D_PRINT_BOOL },
2242   /* c */ { NL ("char"),	NL ("byte"),		D_PRINT_DEFAULT },
2243   /* d */ { NL ("double"),	NL ("double"),		D_PRINT_FLOAT },
2244   /* e */ { NL ("long double"),	NL ("long double"),	D_PRINT_FLOAT },
2245   /* f */ { NL ("float"),	NL ("float"),		D_PRINT_FLOAT },
2246   /* g */ { NL ("__float128"),	NL ("__float128"),	D_PRINT_FLOAT },
2247   /* h */ { NL ("unsigned char"), NL ("unsigned char"),	D_PRINT_DEFAULT },
2248   /* i */ { NL ("int"),		NL ("int"),		D_PRINT_INT },
2249   /* j */ { NL ("unsigned int"), NL ("unsigned"),	D_PRINT_UNSIGNED },
2250   /* k */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2251   /* l */ { NL ("long"),	NL ("long"),		D_PRINT_LONG },
2252   /* m */ { NL ("unsigned long"), NL ("unsigned long"),	D_PRINT_UNSIGNED_LONG },
2253   /* n */ { NL ("__int128"),	NL ("__int128"),	D_PRINT_DEFAULT },
2254   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"),
2255 	    D_PRINT_DEFAULT },
2256   /* p */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2257   /* q */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2258   /* r */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2259   /* s */ { NL ("short"),	NL ("short"),		D_PRINT_DEFAULT },
2260   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_DEFAULT },
2261   /* u */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2262   /* v */ { NL ("void"),	NL ("void"),		D_PRINT_VOID },
2263   /* w */ { NL ("wchar_t"),	NL ("char"),		D_PRINT_DEFAULT },
2264   /* x */ { NL ("long long"),	NL ("long"),		D_PRINT_LONG_LONG },
2265   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"),
2266 	    D_PRINT_UNSIGNED_LONG_LONG },
2267   /* z */ { NL ("..."),		NL ("..."),		D_PRINT_DEFAULT },
2268   /* 26 */ { NL ("decimal32"),	NL ("decimal32"),	D_PRINT_DEFAULT },
2269   /* 27 */ { NL ("decimal64"),	NL ("decimal64"),	D_PRINT_DEFAULT },
2270   /* 28 */ { NL ("decimal128"),	NL ("decimal128"),	D_PRINT_DEFAULT },
2271   /* 29 */ { NL ("half"),	NL ("half"),		D_PRINT_FLOAT },
2272   /* 30 */ { NL ("char16_t"),	NL ("char16_t"),	D_PRINT_DEFAULT },
2273   /* 31 */ { NL ("char32_t"),	NL ("char32_t"),	D_PRINT_DEFAULT },
2274   /* 32 */ { NL ("decltype(nullptr)"),	NL ("decltype(nullptr)"),
2275 	     D_PRINT_DEFAULT },
2276 };
2277 
2278 CP_STATIC_IF_GLIBCPP_V3
2279 struct demangle_component *
2280 cplus_demangle_type (struct d_info *di)
2281 {
2282   char peek;
2283   struct demangle_component *ret;
2284   int can_subst;
2285 
2286   /* The ABI specifies that when CV-qualifiers are used, the base type
2287      is substitutable, and the fully qualified type is substitutable,
2288      but the base type with a strict subset of the CV-qualifiers is
2289      not substitutable.  The natural recursive implementation of the
2290      CV-qualifiers would cause subsets to be substitutable, so instead
2291      we pull them all off now.
2292 
2293      FIXME: The ABI says that order-insensitive vendor qualifiers
2294      should be handled in the same way, but we have no way to tell
2295      which vendor qualifiers are order-insensitive and which are
2296      order-sensitive.  So we just assume that they are all
2297      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
2298      __vector, and it treats it as order-sensitive when mangling
2299      names.  */
2300 
2301   peek = d_peek_char (di);
2302   if (peek == 'r' || peek == 'V' || peek == 'K'
2303       || (peek == 'D' && d_peek_next_char (di) == 'x'))
2304     {
2305       struct demangle_component **pret;
2306 
2307       pret = d_cv_qualifiers (di, &ret, 0);
2308       if (pret == NULL)
2309 	return NULL;
2310       if (d_peek_char (di) == 'F')
2311 	{
2312 	  /* cv-qualifiers before a function type apply to 'this',
2313 	     so avoid adding the unqualified function type to
2314 	     the substitution list.  */
2315 	  *pret = d_function_type (di);
2316 	}
2317       else
2318 	*pret = cplus_demangle_type (di);
2319       if (!*pret)
2320 	return NULL;
2321       if ((*pret)->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
2322 	  || (*pret)->type == DEMANGLE_COMPONENT_REFERENCE_THIS)
2323 	{
2324 	  /* Move the ref-qualifier outside the cv-qualifiers so that
2325 	     they are printed in the right order.  */
2326 	  struct demangle_component *fn = d_left (*pret);
2327 	  d_left (*pret) = ret;
2328 	  ret = *pret;
2329 	  *pret = fn;
2330 	}
2331       if (! d_add_substitution (di, ret))
2332 	return NULL;
2333       return ret;
2334     }
2335 
2336   can_subst = 1;
2337 
2338   switch (peek)
2339     {
2340     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2341     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
2342     case 'o':                               case 's': case 't':
2343     case 'v': case 'w': case 'x': case 'y': case 'z':
2344       ret = d_make_builtin_type (di,
2345 				 &cplus_demangle_builtin_types[peek - 'a']);
2346       di->expansion += ret->u.s_builtin.type->len;
2347       can_subst = 0;
2348       d_advance (di, 1);
2349       break;
2350 
2351     case 'u':
2352       d_advance (di, 1);
2353       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE,
2354 			 d_source_name (di), NULL);
2355       break;
2356 
2357     case 'F':
2358       ret = d_function_type (di);
2359       break;
2360 
2361     case '0': case '1': case '2': case '3': case '4':
2362     case '5': case '6': case '7': case '8': case '9':
2363     case 'N':
2364     case 'Z':
2365       ret = d_class_enum_type (di);
2366       break;
2367 
2368     case 'A':
2369       ret = d_array_type (di);
2370       break;
2371 
2372     case 'M':
2373       ret = d_pointer_to_member_type (di);
2374       break;
2375 
2376     case 'T':
2377       ret = d_template_param (di);
2378       if (d_peek_char (di) == 'I')
2379 	{
2380 	  /* This may be <template-template-param> <template-args>.
2381 	     If this is the type for a conversion operator, we can
2382 	     have a <template-template-param> here only by following
2383 	     a derivation like this:
2384 
2385 	     <nested-name>
2386 	     -> <template-prefix> <template-args>
2387 	     -> <prefix> <template-unqualified-name> <template-args>
2388 	     -> <unqualified-name> <template-unqualified-name> <template-args>
2389 	     -> <source-name> <template-unqualified-name> <template-args>
2390 	     -> <source-name> <operator-name> <template-args>
2391 	     -> <source-name> cv <type> <template-args>
2392 	     -> <source-name> cv <template-template-param> <template-args> <template-args>
2393 
2394 	     where the <template-args> is followed by another.
2395 	     Otherwise, we must have a derivation like this:
2396 
2397 	     <nested-name>
2398 	     -> <template-prefix> <template-args>
2399 	     -> <prefix> <template-unqualified-name> <template-args>
2400 	     -> <unqualified-name> <template-unqualified-name> <template-args>
2401 	     -> <source-name> <template-unqualified-name> <template-args>
2402 	     -> <source-name> <operator-name> <template-args>
2403 	     -> <source-name> cv <type> <template-args>
2404 	     -> <source-name> cv <template-param> <template-args>
2405 
2406 	     where we need to leave the <template-args> to be processed
2407 	     by d_prefix (following the <template-prefix>).
2408 
2409 	     The <template-template-param> part is a substitution
2410 	     candidate.  */
2411 	  if (! di->is_conversion)
2412 	    {
2413 	      if (! d_add_substitution (di, ret))
2414 		return NULL;
2415 	      ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2416 				 d_template_args (di));
2417 	    }
2418 	  else
2419 	    {
2420 	      struct demangle_component *args;
2421 	      struct d_info_checkpoint checkpoint;
2422 
2423 	      d_checkpoint (di, &checkpoint);
2424 	      args = d_template_args (di);
2425 	      if (d_peek_char (di) == 'I')
2426 		{
2427 		  if (! d_add_substitution (di, ret))
2428 		    return NULL;
2429 		  ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2430 				     args);
2431 		}
2432 	      else
2433 		d_backtrack (di, &checkpoint);
2434 	    }
2435 	}
2436       break;
2437 
2438     case 'S':
2439       /* If this is a special substitution, then it is the start of
2440 	 <class-enum-type>.  */
2441       {
2442 	char peek_next;
2443 
2444 	peek_next = d_peek_next_char (di);
2445 	if (IS_DIGIT (peek_next)
2446 	    || peek_next == '_'
2447 	    || IS_UPPER (peek_next))
2448 	  {
2449 	    ret = d_substitution (di, 0);
2450 	    /* The substituted name may have been a template name and
2451 	       may be followed by tepmlate args.  */
2452 	    if (d_peek_char (di) == 'I')
2453 	      ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2454 				 d_template_args (di));
2455 	    else
2456 	      can_subst = 0;
2457 	  }
2458 	else
2459 	  {
2460 	    ret = d_class_enum_type (di);
2461 	    /* If the substitution was a complete type, then it is not
2462 	       a new substitution candidate.  However, if the
2463 	       substitution was followed by template arguments, then
2464 	       the whole thing is a substitution candidate.  */
2465 	    if (ret != NULL && ret->type == DEMANGLE_COMPONENT_SUB_STD)
2466 	      can_subst = 0;
2467 	  }
2468       }
2469       break;
2470 
2471     case 'O':
2472       d_advance (di, 1);
2473       ret = d_make_comp (di, DEMANGLE_COMPONENT_RVALUE_REFERENCE,
2474                          cplus_demangle_type (di), NULL);
2475       break;
2476 
2477     case 'P':
2478       d_advance (di, 1);
2479       ret = d_make_comp (di, DEMANGLE_COMPONENT_POINTER,
2480 			 cplus_demangle_type (di), NULL);
2481       break;
2482 
2483     case 'R':
2484       d_advance (di, 1);
2485       ret = d_make_comp (di, DEMANGLE_COMPONENT_REFERENCE,
2486                          cplus_demangle_type (di), NULL);
2487       break;
2488 
2489     case 'C':
2490       d_advance (di, 1);
2491       ret = d_make_comp (di, DEMANGLE_COMPONENT_COMPLEX,
2492 			 cplus_demangle_type (di), NULL);
2493       break;
2494 
2495     case 'G':
2496       d_advance (di, 1);
2497       ret = d_make_comp (di, DEMANGLE_COMPONENT_IMAGINARY,
2498 			 cplus_demangle_type (di), NULL);
2499       break;
2500 
2501     case 'U':
2502       d_advance (di, 1);
2503       ret = d_source_name (di);
2504       if (d_peek_char (di) == 'I')
2505 	ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2506 			   d_template_args (di));
2507       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL,
2508 			 cplus_demangle_type (di), ret);
2509       break;
2510 
2511     case 'D':
2512       can_subst = 0;
2513       d_advance (di, 1);
2514       peek = d_next_char (di);
2515       switch (peek)
2516 	{
2517 	case 'T':
2518 	case 't':
2519 	  /* decltype (expression) */
2520 	  ret = d_make_comp (di, DEMANGLE_COMPONENT_DECLTYPE,
2521 			     d_expression (di), NULL);
2522 	  if (ret && d_next_char (di) != 'E')
2523 	    ret = NULL;
2524 	  can_subst = 1;
2525 	  break;
2526 
2527 	case 'p':
2528 	  /* Pack expansion.  */
2529 	  ret = d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
2530 			     cplus_demangle_type (di), NULL);
2531 	  can_subst = 1;
2532 	  break;
2533 
2534 	case 'a':
2535 	  /* auto */
2536 	  ret = d_make_name (di, "auto", 4);
2537 	  break;
2538 
2539 	case 'f':
2540 	  /* 32-bit decimal floating point */
2541 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[26]);
2542 	  di->expansion += ret->u.s_builtin.type->len;
2543 	  break;
2544 	case 'd':
2545 	  /* 64-bit DFP */
2546 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[27]);
2547 	  di->expansion += ret->u.s_builtin.type->len;
2548 	  break;
2549 	case 'e':
2550 	  /* 128-bit DFP */
2551 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[28]);
2552 	  di->expansion += ret->u.s_builtin.type->len;
2553 	  break;
2554 	case 'h':
2555 	  /* 16-bit half-precision FP */
2556 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[29]);
2557 	  di->expansion += ret->u.s_builtin.type->len;
2558 	  break;
2559 	case 's':
2560 	  /* char16_t */
2561 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[30]);
2562 	  di->expansion += ret->u.s_builtin.type->len;
2563 	  break;
2564 	case 'i':
2565 	  /* char32_t */
2566 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[31]);
2567 	  di->expansion += ret->u.s_builtin.type->len;
2568 	  break;
2569 
2570 	case 'F':
2571 	  /* Fixed point types. DF<int bits><length><fract bits><sat>  */
2572 	  ret = d_make_empty (di);
2573 	  ret->type = DEMANGLE_COMPONENT_FIXED_TYPE;
2574 	  if ((ret->u.s_fixed.accum = IS_DIGIT (d_peek_char (di))))
2575 	    /* For demangling we don't care about the bits.  */
2576 	    d_number (di);
2577 	  ret->u.s_fixed.length = cplus_demangle_type (di);
2578 	  if (ret->u.s_fixed.length == NULL)
2579 	    return NULL;
2580 	  d_number (di);
2581 	  peek = d_next_char (di);
2582 	  ret->u.s_fixed.sat = (peek == 's');
2583 	  break;
2584 
2585 	case 'v':
2586 	  ret = d_vector_type (di);
2587 	  can_subst = 1;
2588 	  break;
2589 
2590         case 'n':
2591           /* decltype(nullptr) */
2592 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[32]);
2593 	  di->expansion += ret->u.s_builtin.type->len;
2594 	  break;
2595 
2596 	default:
2597 	  return NULL;
2598 	}
2599       break;
2600 
2601     default:
2602       return NULL;
2603     }
2604 
2605   if (can_subst)
2606     {
2607       if (! d_add_substitution (di, ret))
2608 	return NULL;
2609     }
2610 
2611   return ret;
2612 }
2613 
2614 /* <CV-qualifiers> ::= [r] [V] [K] [Dx] */
2615 
2616 static struct demangle_component **
2617 d_cv_qualifiers (struct d_info *di,
2618                  struct demangle_component **pret, int member_fn)
2619 {
2620   struct demangle_component **pstart;
2621   char peek;
2622 
2623   pstart = pret;
2624   peek = d_peek_char (di);
2625   while (peek == 'r' || peek == 'V' || peek == 'K'
2626 	 || (peek == 'D' && d_peek_next_char (di) == 'x'))
2627     {
2628       enum demangle_component_type t;
2629 
2630       d_advance (di, 1);
2631       if (peek == 'r')
2632 	{
2633 	  t = (member_fn
2634 	       ? DEMANGLE_COMPONENT_RESTRICT_THIS
2635 	       : DEMANGLE_COMPONENT_RESTRICT);
2636 	  di->expansion += sizeof "restrict";
2637 	}
2638       else if (peek == 'V')
2639 	{
2640 	  t = (member_fn
2641 	       ? DEMANGLE_COMPONENT_VOLATILE_THIS
2642 	       : DEMANGLE_COMPONENT_VOLATILE);
2643 	  di->expansion += sizeof "volatile";
2644 	}
2645       else if (peek == 'K')
2646 	{
2647 	  t = (member_fn
2648 	       ? DEMANGLE_COMPONENT_CONST_THIS
2649 	       : DEMANGLE_COMPONENT_CONST);
2650 	  di->expansion += sizeof "const";
2651 	}
2652       else
2653 	{
2654 	  t = DEMANGLE_COMPONENT_TRANSACTION_SAFE;
2655 	  di->expansion += sizeof "transaction_safe";
2656 	  d_advance (di, 1);
2657 	}
2658 
2659       *pret = d_make_comp (di, t, NULL, NULL);
2660       if (*pret == NULL)
2661 	return NULL;
2662       pret = &d_left (*pret);
2663 
2664       peek = d_peek_char (di);
2665     }
2666 
2667   if (!member_fn && peek == 'F')
2668     {
2669       while (pstart != pret)
2670 	{
2671 	  switch ((*pstart)->type)
2672 	    {
2673 	    case DEMANGLE_COMPONENT_RESTRICT:
2674 	      (*pstart)->type = DEMANGLE_COMPONENT_RESTRICT_THIS;
2675 	      break;
2676 	    case DEMANGLE_COMPONENT_VOLATILE:
2677 	      (*pstart)->type = DEMANGLE_COMPONENT_VOLATILE_THIS;
2678 	      break;
2679 	    case DEMANGLE_COMPONENT_CONST:
2680 	      (*pstart)->type = DEMANGLE_COMPONENT_CONST_THIS;
2681 	      break;
2682 	    default:
2683 	      break;
2684 	    }
2685 	  pstart = &d_left (*pstart);
2686 	}
2687     }
2688 
2689   return pret;
2690 }
2691 
2692 /* <ref-qualifier> ::= R
2693                    ::= O */
2694 
2695 static struct demangle_component *
2696 d_ref_qualifier (struct d_info *di, struct demangle_component *sub)
2697 {
2698   struct demangle_component *ret = sub;
2699   char peek;
2700 
2701   peek = d_peek_char (di);
2702   if (peek == 'R' || peek == 'O')
2703     {
2704       enum demangle_component_type t;
2705       if (peek == 'R')
2706 	{
2707 	  t = DEMANGLE_COMPONENT_REFERENCE_THIS;
2708 	  di->expansion += sizeof "&";
2709 	}
2710       else
2711 	{
2712 	  t = DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS;
2713 	  di->expansion += sizeof "&&";
2714 	}
2715       d_advance (di, 1);
2716 
2717       ret = d_make_comp (di, t, ret, NULL);
2718     }
2719 
2720   return ret;
2721 }
2722 
2723 /* <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] [T] E  */
2724 
2725 static struct demangle_component *
2726 d_function_type (struct d_info *di)
2727 {
2728   struct demangle_component *ret;
2729 
2730   if (! d_check_char (di, 'F'))
2731     return NULL;
2732   if (d_peek_char (di) == 'Y')
2733     {
2734       /* Function has C linkage.  We don't print this information.
2735 	 FIXME: We should print it in verbose mode.  */
2736       d_advance (di, 1);
2737     }
2738   ret = d_bare_function_type (di, 1);
2739   ret = d_ref_qualifier (di, ret);
2740 
2741   if (! d_check_char (di, 'E'))
2742     return NULL;
2743   return ret;
2744 }
2745 
2746 /* <type>+ */
2747 
2748 static struct demangle_component *
2749 d_parmlist (struct d_info *di)
2750 {
2751   struct demangle_component *tl;
2752   struct demangle_component **ptl;
2753 
2754   tl = NULL;
2755   ptl = &tl;
2756   while (1)
2757     {
2758       struct demangle_component *type;
2759 
2760       char peek = d_peek_char (di);
2761       if (peek == '\0' || peek == 'E' || peek == '.')
2762 	break;
2763       if ((peek == 'R' || peek == 'O')
2764 	  && d_peek_next_char (di) == 'E')
2765 	/* Function ref-qualifier, not a ref prefix for a parameter type.  */
2766 	break;
2767       type = cplus_demangle_type (di);
2768       if (type == NULL)
2769 	return NULL;
2770       *ptl = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, type, NULL);
2771       if (*ptl == NULL)
2772 	return NULL;
2773       ptl = &d_right (*ptl);
2774     }
2775 
2776   /* There should be at least one parameter type besides the optional
2777      return type.  A function which takes no arguments will have a
2778      single parameter type void.  */
2779   if (tl == NULL)
2780     return NULL;
2781 
2782   /* If we have a single parameter type void, omit it.  */
2783   if (d_right (tl) == NULL
2784       && d_left (tl)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2785       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2786     {
2787       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2788       d_left (tl) = NULL;
2789     }
2790 
2791   return tl;
2792 }
2793 
2794 /* <bare-function-type> ::= [J]<type>+  */
2795 
2796 static struct demangle_component *
2797 d_bare_function_type (struct d_info *di, int has_return_type)
2798 {
2799   struct demangle_component *return_type;
2800   struct demangle_component *tl;
2801   char peek;
2802 
2803   /* Detect special qualifier indicating that the first argument
2804      is the return type.  */
2805   peek = d_peek_char (di);
2806   if (peek == 'J')
2807     {
2808       d_advance (di, 1);
2809       has_return_type = 1;
2810     }
2811 
2812   if (has_return_type)
2813     {
2814       return_type = cplus_demangle_type (di);
2815       if (return_type == NULL)
2816 	return NULL;
2817     }
2818   else
2819     return_type = NULL;
2820 
2821   tl = d_parmlist (di);
2822   if (tl == NULL)
2823     return NULL;
2824 
2825   return d_make_comp (di, DEMANGLE_COMPONENT_FUNCTION_TYPE,
2826 		      return_type, tl);
2827 }
2828 
2829 /* <class-enum-type> ::= <name>  */
2830 
2831 static struct demangle_component *
2832 d_class_enum_type (struct d_info *di)
2833 {
2834   return d_name (di);
2835 }
2836 
2837 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2838                 ::= A [<(dimension) expression>] _ <(element) type>
2839 */
2840 
2841 static struct demangle_component *
2842 d_array_type (struct d_info *di)
2843 {
2844   char peek;
2845   struct demangle_component *dim;
2846 
2847   if (! d_check_char (di, 'A'))
2848     return NULL;
2849 
2850   peek = d_peek_char (di);
2851   if (peek == '_')
2852     dim = NULL;
2853   else if (IS_DIGIT (peek))
2854     {
2855       const char *s;
2856 
2857       s = d_str (di);
2858       do
2859 	{
2860 	  d_advance (di, 1);
2861 	  peek = d_peek_char (di);
2862 	}
2863       while (IS_DIGIT (peek));
2864       dim = d_make_name (di, s, d_str (di) - s);
2865       if (dim == NULL)
2866 	return NULL;
2867     }
2868   else
2869     {
2870       dim = d_expression (di);
2871       if (dim == NULL)
2872 	return NULL;
2873     }
2874 
2875   if (! d_check_char (di, '_'))
2876     return NULL;
2877 
2878   return d_make_comp (di, DEMANGLE_COMPONENT_ARRAY_TYPE, dim,
2879 		      cplus_demangle_type (di));
2880 }
2881 
2882 /* <vector-type> ::= Dv <number> _ <type>
2883                  ::= Dv _ <expression> _ <type> */
2884 
2885 static struct demangle_component *
2886 d_vector_type (struct d_info *di)
2887 {
2888   char peek;
2889   struct demangle_component *dim;
2890 
2891   peek = d_peek_char (di);
2892   if (peek == '_')
2893     {
2894       d_advance (di, 1);
2895       dim = d_expression (di);
2896     }
2897   else
2898     dim = d_number_component (di);
2899 
2900   if (dim == NULL)
2901     return NULL;
2902 
2903   if (! d_check_char (di, '_'))
2904     return NULL;
2905 
2906   return d_make_comp (di, DEMANGLE_COMPONENT_VECTOR_TYPE, dim,
2907 		      cplus_demangle_type (di));
2908 }
2909 
2910 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2911 
2912 static struct demangle_component *
2913 d_pointer_to_member_type (struct d_info *di)
2914 {
2915   struct demangle_component *cl;
2916   struct demangle_component *mem;
2917 
2918   if (! d_check_char (di, 'M'))
2919     return NULL;
2920 
2921   cl = cplus_demangle_type (di);
2922   if (cl == NULL)
2923     return NULL;
2924 
2925   /* The ABI says, "The type of a non-static member function is considered
2926      to be different, for the purposes of substitution, from the type of a
2927      namespace-scope or static member function whose type appears
2928      similar. The types of two non-static member functions are considered
2929      to be different, for the purposes of substitution, if the functions
2930      are members of different classes. In other words, for the purposes of
2931      substitution, the class of which the function is a member is
2932      considered part of the type of function."
2933 
2934      For a pointer to member function, this call to cplus_demangle_type
2935      will end up adding a (possibly qualified) non-member function type to
2936      the substitution table, which is not correct; however, the member
2937      function type will never be used in a substitution, so putting the
2938      wrong type in the substitution table is harmless.  */
2939 
2940   mem = cplus_demangle_type (di);
2941   if (mem == NULL)
2942     return NULL;
2943 
2944   return d_make_comp (di, DEMANGLE_COMPONENT_PTRMEM_TYPE, cl, mem);
2945 }
2946 
2947 /* <non-negative number> _ */
2948 
2949 static long
2950 d_compact_number (struct d_info *di)
2951 {
2952   long num;
2953   if (d_peek_char (di) == '_')
2954     num = 0;
2955   else if (d_peek_char (di) == 'n')
2956     return -1;
2957   else
2958     num = d_number (di) + 1;
2959 
2960   if (! d_check_char (di, '_'))
2961     return -1;
2962   return num;
2963 }
2964 
2965 /* <template-param> ::= T_
2966                     ::= T <(parameter-2 non-negative) number> _
2967 */
2968 
2969 static struct demangle_component *
2970 d_template_param (struct d_info *di)
2971 {
2972   long param;
2973 
2974   if (! d_check_char (di, 'T'))
2975     return NULL;
2976 
2977   param = d_compact_number (di);
2978   if (param < 0)
2979     return NULL;
2980 
2981   ++di->did_subs;
2982 
2983   return d_make_template_param (di, param);
2984 }
2985 
2986 /* <template-args> ::= I <template-arg>+ E  */
2987 
2988 static struct demangle_component *
2989 d_template_args (struct d_info *di)
2990 {
2991   struct demangle_component *hold_last_name;
2992   struct demangle_component *al;
2993   struct demangle_component **pal;
2994 
2995   /* Preserve the last name we saw--don't let the template arguments
2996      clobber it, as that would give us the wrong name for a subsequent
2997      constructor or destructor.  */
2998   hold_last_name = di->last_name;
2999 
3000   if (d_peek_char (di) != 'I'
3001       && d_peek_char (di) != 'J')
3002     return NULL;
3003   d_advance (di, 1);
3004 
3005   if (d_peek_char (di) == 'E')
3006     {
3007       /* An argument pack can be empty.  */
3008       d_advance (di, 1);
3009       return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, NULL, NULL);
3010     }
3011 
3012   al = NULL;
3013   pal = &al;
3014   while (1)
3015     {
3016       struct demangle_component *a;
3017 
3018       a = d_template_arg (di);
3019       if (a == NULL)
3020 	return NULL;
3021 
3022       *pal = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, a, NULL);
3023       if (*pal == NULL)
3024 	return NULL;
3025       pal = &d_right (*pal);
3026 
3027       if (d_peek_char (di) == 'E')
3028 	{
3029 	  d_advance (di, 1);
3030 	  break;
3031 	}
3032     }
3033 
3034   di->last_name = hold_last_name;
3035 
3036   return al;
3037 }
3038 
3039 /* <template-arg> ::= <type>
3040                   ::= X <expression> E
3041                   ::= <expr-primary>
3042 */
3043 
3044 static struct demangle_component *
3045 d_template_arg (struct d_info *di)
3046 {
3047   struct demangle_component *ret;
3048 
3049   switch (d_peek_char (di))
3050     {
3051     case 'X':
3052       d_advance (di, 1);
3053       ret = d_expression (di);
3054       if (! d_check_char (di, 'E'))
3055 	return NULL;
3056       return ret;
3057 
3058     case 'L':
3059       return d_expr_primary (di);
3060 
3061     case 'I':
3062     case 'J':
3063       /* An argument pack.  */
3064       return d_template_args (di);
3065 
3066     default:
3067       return cplus_demangle_type (di);
3068     }
3069 }
3070 
3071 /* Parse a sequence of expressions until we hit the terminator
3072    character.  */
3073 
3074 static struct demangle_component *
3075 d_exprlist (struct d_info *di, char terminator)
3076 {
3077   struct demangle_component *list = NULL;
3078   struct demangle_component **p = &list;
3079 
3080   if (d_peek_char (di) == terminator)
3081     {
3082       d_advance (di, 1);
3083       return d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, NULL, NULL);
3084     }
3085 
3086   while (1)
3087     {
3088       struct demangle_component *arg = d_expression (di);
3089       if (arg == NULL)
3090 	return NULL;
3091 
3092       *p = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, arg, NULL);
3093       if (*p == NULL)
3094 	return NULL;
3095       p = &d_right (*p);
3096 
3097       if (d_peek_char (di) == terminator)
3098 	{
3099 	  d_advance (di, 1);
3100 	  break;
3101 	}
3102     }
3103 
3104   return list;
3105 }
3106 
3107 /* Returns nonzero iff OP is an operator for a C++ cast: const_cast,
3108    dynamic_cast, static_cast or reinterpret_cast.  */
3109 
3110 static int
3111 op_is_new_cast (struct demangle_component *op)
3112 {
3113   const char *code = op->u.s_operator.op->code;
3114   return (code[1] == 'c'
3115 	  && (code[0] == 's' || code[0] == 'd'
3116 	      || code[0] == 'c' || code[0] == 'r'));
3117 }
3118 
3119 /* <expression> ::= <(unary) operator-name> <expression>
3120                 ::= <(binary) operator-name> <expression> <expression>
3121                 ::= <(trinary) operator-name> <expression> <expression> <expression>
3122 		::= cl <expression>+ E
3123                 ::= st <type>
3124                 ::= <template-param>
3125                 ::= sr <type> <unqualified-name>
3126                 ::= sr <type> <unqualified-name> <template-args>
3127                 ::= <expr-primary>
3128 */
3129 
3130 static inline struct demangle_component *
3131 d_expression_1 (struct d_info *di)
3132 {
3133   char peek;
3134 
3135   peek = d_peek_char (di);
3136   if (peek == 'L')
3137     return d_expr_primary (di);
3138   else if (peek == 'T')
3139     return d_template_param (di);
3140   else if (peek == 's' && d_peek_next_char (di) == 'r')
3141     {
3142       struct demangle_component *type;
3143       struct demangle_component *name;
3144 
3145       d_advance (di, 2);
3146       type = cplus_demangle_type (di);
3147       name = d_unqualified_name (di);
3148       if (d_peek_char (di) != 'I')
3149 	return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type, name);
3150       else
3151 	return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type,
3152 			    d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3153 					 d_template_args (di)));
3154     }
3155   else if (peek == 's' && d_peek_next_char (di) == 'p')
3156     {
3157       d_advance (di, 2);
3158       return d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
3159 			  d_expression_1 (di), NULL);
3160     }
3161   else if (peek == 'f' && d_peek_next_char (di) == 'p')
3162     {
3163       /* Function parameter used in a late-specified return type.  */
3164       int index;
3165       d_advance (di, 2);
3166       if (d_peek_char (di) == 'T')
3167 	{
3168 	  /* 'this' parameter.  */
3169 	  d_advance (di, 1);
3170 	  index = 0;
3171 	}
3172       else
3173 	{
3174 	  index = d_compact_number (di) + 1;
3175 	  if (index == 0)
3176 	    return NULL;
3177 	}
3178       return d_make_function_param (di, index);
3179     }
3180   else if (IS_DIGIT (peek)
3181 	   || (peek == 'o' && d_peek_next_char (di) == 'n'))
3182     {
3183       /* We can get an unqualified name as an expression in the case of
3184          a dependent function call, i.e. decltype(f(t)).  */
3185       struct demangle_component *name;
3186 
3187       if (peek == 'o')
3188 	/* operator-function-id, i.e. operator+(t).  */
3189 	d_advance (di, 2);
3190 
3191       name = d_unqualified_name (di);
3192       if (name == NULL)
3193 	return NULL;
3194       if (d_peek_char (di) == 'I')
3195 	return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3196 			    d_template_args (di));
3197       else
3198 	return name;
3199     }
3200   else if ((peek == 'i' || peek == 't')
3201 	   && d_peek_next_char (di) == 'l')
3202     {
3203       /* Brace-enclosed initializer list, untyped or typed.  */
3204       struct demangle_component *type = NULL;
3205       if (peek == 't')
3206 	type = cplus_demangle_type (di);
3207       if (!d_peek_next_char (di))
3208 	return NULL;
3209       d_advance (di, 2);
3210       return d_make_comp (di, DEMANGLE_COMPONENT_INITIALIZER_LIST,
3211 			  type, d_exprlist (di, 'E'));
3212     }
3213   else
3214     {
3215       struct demangle_component *op;
3216       const char *code = NULL;
3217       int args;
3218 
3219       op = d_operator_name (di);
3220       if (op == NULL)
3221 	return NULL;
3222 
3223       if (op->type == DEMANGLE_COMPONENT_OPERATOR)
3224 	{
3225 	  code = op->u.s_operator.op->code;
3226 	  di->expansion += op->u.s_operator.op->len - 2;
3227 	  if (strcmp (code, "st") == 0)
3228 	    return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3229 				cplus_demangle_type (di));
3230 	}
3231 
3232       switch (op->type)
3233 	{
3234 	default:
3235 	  return NULL;
3236 	case DEMANGLE_COMPONENT_OPERATOR:
3237 	  args = op->u.s_operator.op->args;
3238 	  break;
3239 	case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3240 	  args = op->u.s_extended_operator.args;
3241 	  break;
3242 	case DEMANGLE_COMPONENT_CAST:
3243 	  args = 1;
3244 	  break;
3245 	}
3246 
3247       switch (args)
3248 	{
3249 	case 0:
3250 	  return d_make_comp (di, DEMANGLE_COMPONENT_NULLARY, op, NULL);
3251 
3252 	case 1:
3253 	  {
3254 	    struct demangle_component *operand;
3255 	    int suffix = 0;
3256 
3257 	    if (code && (code[0] == 'p' || code[0] == 'm')
3258 		&& code[1] == code[0])
3259 	      /* pp_ and mm_ are the prefix variants.  */
3260 	      suffix = !d_check_char (di, '_');
3261 
3262 	    if (op->type == DEMANGLE_COMPONENT_CAST
3263 		&& d_check_char (di, '_'))
3264 	      operand = d_exprlist (di, 'E');
3265 	    else
3266 	      operand = d_expression_1 (di);
3267 
3268 	    if (suffix)
3269 	      /* Indicate the suffix variant for d_print_comp.  */
3270 	      return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3271 				  d_make_comp (di,
3272 					       DEMANGLE_COMPONENT_BINARY_ARGS,
3273 					       operand, operand));
3274 	    else
3275 	      return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3276 				  operand);
3277 	  }
3278 	case 2:
3279 	  {
3280 	    struct demangle_component *left;
3281 	    struct demangle_component *right;
3282 
3283 	    if (code == NULL)
3284 	      return NULL;
3285 	    if (op_is_new_cast (op))
3286 	      left = cplus_demangle_type (di);
3287 	    else
3288 	      left = d_expression_1 (di);
3289 	    if (!strcmp (code, "cl"))
3290 	      right = d_exprlist (di, 'E');
3291 	    else if (!strcmp (code, "dt") || !strcmp (code, "pt"))
3292 	      {
3293 		right = d_unqualified_name (di);
3294 		if (d_peek_char (di) == 'I')
3295 		  right = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE,
3296 				       right, d_template_args (di));
3297 	      }
3298 	    else
3299 	      right = d_expression_1 (di);
3300 
3301 	    return d_make_comp (di, DEMANGLE_COMPONENT_BINARY, op,
3302 				d_make_comp (di,
3303 					     DEMANGLE_COMPONENT_BINARY_ARGS,
3304 					     left, right));
3305 	  }
3306 	case 3:
3307 	  {
3308 	    struct demangle_component *first;
3309 	    struct demangle_component *second;
3310 	    struct demangle_component *third;
3311 
3312 	    if (code == NULL)
3313 	      return NULL;
3314 	    else if (!strcmp (code, "qu"))
3315 	      {
3316 		/* ?: expression.  */
3317 		first = d_expression_1 (di);
3318 		second = d_expression_1 (di);
3319 		third = d_expression_1 (di);
3320 	      }
3321 	    else if (code[0] == 'n')
3322 	      {
3323 		/* new-expression.  */
3324 		if (code[1] != 'w' && code[1] != 'a')
3325 		  return NULL;
3326 		first = d_exprlist (di, '_');
3327 		second = cplus_demangle_type (di);
3328 		if (d_peek_char (di) == 'E')
3329 		  {
3330 		    d_advance (di, 1);
3331 		    third = NULL;
3332 		  }
3333 		else if (d_peek_char (di) == 'p'
3334 			 && d_peek_next_char (di) == 'i')
3335 		  {
3336 		    /* Parenthesized initializer.  */
3337 		    d_advance (di, 2);
3338 		    third = d_exprlist (di, 'E');
3339 		  }
3340 		else if (d_peek_char (di) == 'i'
3341 			 && d_peek_next_char (di) == 'l')
3342 		  /* initializer-list.  */
3343 		  third = d_expression_1 (di);
3344 		else
3345 		  return NULL;
3346 	      }
3347 	    else
3348 	      return NULL;
3349 	    return d_make_comp (di, DEMANGLE_COMPONENT_TRINARY, op,
3350 				d_make_comp (di,
3351 					     DEMANGLE_COMPONENT_TRINARY_ARG1,
3352 					     first,
3353 					     d_make_comp (di,
3354 							  DEMANGLE_COMPONENT_TRINARY_ARG2,
3355 							  second, third)));
3356 	  }
3357 	default:
3358 	  return NULL;
3359 	}
3360     }
3361 }
3362 
3363 static struct demangle_component *
3364 d_expression (struct d_info *di)
3365 {
3366   struct demangle_component *ret;
3367   int was_expression = di->is_expression;
3368 
3369   di->is_expression = 1;
3370   ret = d_expression_1 (di);
3371   di->is_expression = was_expression;
3372   return ret;
3373 }
3374 
3375 /* <expr-primary> ::= L <type> <(value) number> E
3376                   ::= L <type> <(value) float> E
3377                   ::= L <mangled-name> E
3378 */
3379 
3380 static struct demangle_component *
3381 d_expr_primary (struct d_info *di)
3382 {
3383   struct demangle_component *ret;
3384 
3385   if (! d_check_char (di, 'L'))
3386     return NULL;
3387   if (d_peek_char (di) == '_'
3388       /* Workaround for G++ bug; see comment in write_template_arg.  */
3389       || d_peek_char (di) == 'Z')
3390     ret = cplus_demangle_mangled_name (di, 0);
3391   else
3392     {
3393       struct demangle_component *type;
3394       enum demangle_component_type t;
3395       const char *s;
3396 
3397       type = cplus_demangle_type (di);
3398       if (type == NULL)
3399 	return NULL;
3400 
3401       /* If we have a type we know how to print, we aren't going to
3402 	 print the type name itself.  */
3403       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
3404 	  && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
3405 	di->expansion -= type->u.s_builtin.type->len;
3406 
3407       /* Rather than try to interpret the literal value, we just
3408 	 collect it as a string.  Note that it's possible to have a
3409 	 floating point literal here.  The ABI specifies that the
3410 	 format of such literals is machine independent.  That's fine,
3411 	 but what's not fine is that versions of g++ up to 3.2 with
3412 	 -fabi-version=1 used upper case letters in the hex constant,
3413 	 and dumped out gcc's internal representation.  That makes it
3414 	 hard to tell where the constant ends, and hard to dump the
3415 	 constant in any readable form anyhow.  We don't attempt to
3416 	 handle these cases.  */
3417 
3418       t = DEMANGLE_COMPONENT_LITERAL;
3419       if (d_peek_char (di) == 'n')
3420 	{
3421 	  t = DEMANGLE_COMPONENT_LITERAL_NEG;
3422 	  d_advance (di, 1);
3423 	}
3424       s = d_str (di);
3425       while (d_peek_char (di) != 'E')
3426 	{
3427 	  if (d_peek_char (di) == '\0')
3428 	    return NULL;
3429 	  d_advance (di, 1);
3430 	}
3431       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
3432     }
3433   if (! d_check_char (di, 'E'))
3434     return NULL;
3435   return ret;
3436 }
3437 
3438 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
3439                 ::= Z <(function) encoding> E s [<discriminator>]
3440                 ::= Z <(function) encoding> E d [<parameter> number>] _ <entity name>
3441 */
3442 
3443 static struct demangle_component *
3444 d_local_name (struct d_info *di)
3445 {
3446   struct demangle_component *function;
3447 
3448   if (! d_check_char (di, 'Z'))
3449     return NULL;
3450 
3451   function = d_encoding (di, 0);
3452 
3453   if (! d_check_char (di, 'E'))
3454     return NULL;
3455 
3456   if (d_peek_char (di) == 's')
3457     {
3458       d_advance (di, 1);
3459       if (! d_discriminator (di))
3460 	return NULL;
3461       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function,
3462 			  d_make_name (di, "string literal",
3463 				       sizeof "string literal" - 1));
3464     }
3465   else
3466     {
3467       struct demangle_component *name;
3468       int num = -1;
3469 
3470       if (d_peek_char (di) == 'd')
3471 	{
3472 	  /* Default argument scope: d <number> _.  */
3473 	  d_advance (di, 1);
3474 	  num = d_compact_number (di);
3475 	  if (num < 0)
3476 	    return NULL;
3477 	}
3478 
3479       name = d_name (di);
3480       if (name)
3481 	switch (name->type)
3482 	  {
3483 	    /* Lambdas and unnamed types have internal discriminators.  */
3484 	  case DEMANGLE_COMPONENT_LAMBDA:
3485 	  case DEMANGLE_COMPONENT_UNNAMED_TYPE:
3486 	    break;
3487 	  default:
3488 	    if (! d_discriminator (di))
3489 	      return NULL;
3490 	  }
3491       if (num >= 0)
3492 	name = d_make_default_arg (di, num, name);
3493       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function, name);
3494     }
3495 }
3496 
3497 /* <discriminator> ::= _ <(non-negative) number>
3498 
3499    We demangle the discriminator, but we don't print it out.  FIXME:
3500    We should print it out in verbose mode.  */
3501 
3502 static int
3503 d_discriminator (struct d_info *di)
3504 {
3505   long discrim;
3506 
3507   if (d_peek_char (di) != '_')
3508     return 1;
3509   d_advance (di, 1);
3510   discrim = d_number (di);
3511   if (discrim < 0)
3512     return 0;
3513   return 1;
3514 }
3515 
3516 /* <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ */
3517 
3518 static struct demangle_component *
3519 d_lambda (struct d_info *di)
3520 {
3521   struct demangle_component *tl;
3522   struct demangle_component *ret;
3523   int num;
3524 
3525   if (! d_check_char (di, 'U'))
3526     return NULL;
3527   if (! d_check_char (di, 'l'))
3528     return NULL;
3529 
3530   tl = d_parmlist (di);
3531   if (tl == NULL)
3532     return NULL;
3533 
3534   if (! d_check_char (di, 'E'))
3535     return NULL;
3536 
3537   num = d_compact_number (di);
3538   if (num < 0)
3539     return NULL;
3540 
3541   ret = d_make_empty (di);
3542   if (ret)
3543     {
3544       ret->type = DEMANGLE_COMPONENT_LAMBDA;
3545       ret->u.s_unary_num.sub = tl;
3546       ret->u.s_unary_num.num = num;
3547     }
3548 
3549   if (! d_add_substitution (di, ret))
3550     return NULL;
3551 
3552   return ret;
3553 }
3554 
3555 /* <unnamed-type-name> ::= Ut [ <nonnegative number> ] _ */
3556 
3557 static struct demangle_component *
3558 d_unnamed_type (struct d_info *di)
3559 {
3560   struct demangle_component *ret;
3561   long num;
3562 
3563   if (! d_check_char (di, 'U'))
3564     return NULL;
3565   if (! d_check_char (di, 't'))
3566     return NULL;
3567 
3568   num = d_compact_number (di);
3569   if (num < 0)
3570     return NULL;
3571 
3572   ret = d_make_empty (di);
3573   if (ret)
3574     {
3575       ret->type = DEMANGLE_COMPONENT_UNNAMED_TYPE;
3576       ret->u.s_number.number = num;
3577     }
3578 
3579   if (! d_add_substitution (di, ret))
3580     return NULL;
3581 
3582   return ret;
3583 }
3584 
3585 /* <clone-suffix> ::= [ . <clone-type-identifier> ] [ . <nonnegative number> ]*
3586 */
3587 
3588 static struct demangle_component *
3589 d_clone_suffix (struct d_info *di, struct demangle_component *encoding)
3590 {
3591   const char *suffix = d_str (di);
3592   const char *pend = suffix;
3593   struct demangle_component *n;
3594 
3595   if (*pend == '.' && (IS_LOWER (pend[1]) || pend[1] == '_'))
3596     {
3597       pend += 2;
3598       while (IS_LOWER (*pend) || *pend == '_')
3599 	++pend;
3600     }
3601   while (*pend == '.' && IS_DIGIT (pend[1]))
3602     {
3603       pend += 2;
3604       while (IS_DIGIT (*pend))
3605 	++pend;
3606     }
3607   d_advance (di, pend - suffix);
3608   n = d_make_name (di, suffix, pend - suffix);
3609   return d_make_comp (di, DEMANGLE_COMPONENT_CLONE, encoding, n);
3610 }
3611 
3612 /* Add a new substitution.  */
3613 
3614 static int
3615 d_add_substitution (struct d_info *di, struct demangle_component *dc)
3616 {
3617   if (dc == NULL)
3618     return 0;
3619   if (di->next_sub >= di->num_subs)
3620     return 0;
3621   di->subs[di->next_sub] = dc;
3622   ++di->next_sub;
3623   return 1;
3624 }
3625 
3626 /* <substitution> ::= S <seq-id> _
3627                   ::= S_
3628                   ::= St
3629                   ::= Sa
3630                   ::= Sb
3631                   ::= Ss
3632                   ::= Si
3633                   ::= So
3634                   ::= Sd
3635 
3636    If PREFIX is non-zero, then this type is being used as a prefix in
3637    a qualified name.  In this case, for the standard substitutions, we
3638    need to check whether we are being used as a prefix for a
3639    constructor or destructor, and return a full template name.
3640    Otherwise we will get something like std::iostream::~iostream()
3641    which does not correspond particularly well to any function which
3642    actually appears in the source.
3643 */
3644 
3645 static const struct d_standard_sub_info standard_subs[] =
3646 {
3647   { 't', NL ("std"),
3648     NL ("std"),
3649     NULL, 0 },
3650   { 'a', NL ("std::allocator"),
3651     NL ("std::allocator"),
3652     NL ("allocator") },
3653   { 'b', NL ("std::basic_string"),
3654     NL ("std::basic_string"),
3655     NL ("basic_string") },
3656   { 's', NL ("std::string"),
3657     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
3658     NL ("basic_string") },
3659   { 'i', NL ("std::istream"),
3660     NL ("std::basic_istream<char, std::char_traits<char> >"),
3661     NL ("basic_istream") },
3662   { 'o', NL ("std::ostream"),
3663     NL ("std::basic_ostream<char, std::char_traits<char> >"),
3664     NL ("basic_ostream") },
3665   { 'd', NL ("std::iostream"),
3666     NL ("std::basic_iostream<char, std::char_traits<char> >"),
3667     NL ("basic_iostream") }
3668 };
3669 
3670 static struct demangle_component *
3671 d_substitution (struct d_info *di, int prefix)
3672 {
3673   char c;
3674 
3675   if (! d_check_char (di, 'S'))
3676     return NULL;
3677 
3678   c = d_next_char (di);
3679   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
3680     {
3681       unsigned int id;
3682 
3683       id = 0;
3684       if (c != '_')
3685 	{
3686 	  do
3687 	    {
3688 	      unsigned int new_id;
3689 
3690 	      if (IS_DIGIT (c))
3691 		new_id = id * 36 + c - '0';
3692 	      else if (IS_UPPER (c))
3693 		new_id = id * 36 + c - 'A' + 10;
3694 	      else
3695 		return NULL;
3696 	      if (new_id < id)
3697 		return NULL;
3698 	      id = new_id;
3699 	      c = d_next_char (di);
3700 	    }
3701 	  while (c != '_');
3702 
3703 	  ++id;
3704 	}
3705 
3706       if (id >= (unsigned int) di->next_sub)
3707 	return NULL;
3708 
3709       ++di->did_subs;
3710 
3711       return di->subs[id];
3712     }
3713   else
3714     {
3715       int verbose;
3716       const struct d_standard_sub_info *p;
3717       const struct d_standard_sub_info *pend;
3718 
3719       verbose = (di->options & DMGL_VERBOSE) != 0;
3720       if (! verbose && prefix)
3721 	{
3722 	  char peek;
3723 
3724 	  peek = d_peek_char (di);
3725 	  if (peek == 'C' || peek == 'D')
3726 	    verbose = 1;
3727 	}
3728 
3729       pend = (&standard_subs[0]
3730 	      + sizeof standard_subs / sizeof standard_subs[0]);
3731       for (p = &standard_subs[0]; p < pend; ++p)
3732 	{
3733 	  if (c == p->code)
3734 	    {
3735 	      const char *s;
3736 	      int len;
3737 	      struct demangle_component *c;
3738 
3739 	      if (p->set_last_name != NULL)
3740 		di->last_name = d_make_sub (di, p->set_last_name,
3741 					    p->set_last_name_len);
3742 	      if (verbose)
3743 		{
3744 		  s = p->full_expansion;
3745 		  len = p->full_len;
3746 		}
3747 	      else
3748 		{
3749 		  s = p->simple_expansion;
3750 		  len = p->simple_len;
3751 		}
3752 	      di->expansion += len;
3753 	      c = d_make_sub (di, s, len);
3754 	      if (d_peek_char (di) == 'B')
3755 		{
3756 		  /* If there are ABI tags on the abbreviation, it becomes
3757 		     a substitution candidate.  */
3758 		  c = d_abi_tags (di, c);
3759 		  d_add_substitution (di, c);
3760 		}
3761 	      return c;
3762 	    }
3763 	}
3764 
3765       return NULL;
3766     }
3767 }
3768 
3769 static void
3770 d_checkpoint (struct d_info *di, struct d_info_checkpoint *checkpoint)
3771 {
3772   checkpoint->n = di->n;
3773   checkpoint->next_comp = di->next_comp;
3774   checkpoint->next_sub = di->next_sub;
3775   checkpoint->did_subs = di->did_subs;
3776   checkpoint->expansion = di->expansion;
3777 }
3778 
3779 static void
3780 d_backtrack (struct d_info *di, struct d_info_checkpoint *checkpoint)
3781 {
3782   di->n = checkpoint->n;
3783   di->next_comp = checkpoint->next_comp;
3784   di->next_sub = checkpoint->next_sub;
3785   di->did_subs = checkpoint->did_subs;
3786   di->expansion = checkpoint->expansion;
3787 }
3788 
3789 /* Initialize a growable string.  */
3790 
3791 static void
3792 d_growable_string_init (struct d_growable_string *dgs, size_t estimate)
3793 {
3794   dgs->buf = NULL;
3795   dgs->len = 0;
3796   dgs->alc = 0;
3797   dgs->allocation_failure = 0;
3798 
3799   if (estimate > 0)
3800     d_growable_string_resize (dgs, estimate);
3801 }
3802 
3803 /* Grow a growable string to a given size.  */
3804 
3805 static inline void
3806 d_growable_string_resize (struct d_growable_string *dgs, size_t need)
3807 {
3808   size_t newalc;
3809   char *newbuf;
3810 
3811   if (dgs->allocation_failure)
3812     return;
3813 
3814   /* Start allocation at two bytes to avoid any possibility of confusion
3815      with the special value of 1 used as a return in *palc to indicate
3816      allocation failures.  */
3817   newalc = dgs->alc > 0 ? dgs->alc : 2;
3818   while (newalc < need)
3819     newalc <<= 1;
3820 
3821   newbuf = (char *) realloc (dgs->buf, newalc);
3822   if (newbuf == NULL)
3823     {
3824       free (dgs->buf);
3825       dgs->buf = NULL;
3826       dgs->len = 0;
3827       dgs->alc = 0;
3828       dgs->allocation_failure = 1;
3829       return;
3830     }
3831   dgs->buf = newbuf;
3832   dgs->alc = newalc;
3833 }
3834 
3835 /* Append a buffer to a growable string.  */
3836 
3837 static inline void
3838 d_growable_string_append_buffer (struct d_growable_string *dgs,
3839                                  const char *s, size_t l)
3840 {
3841   size_t need;
3842 
3843   need = dgs->len + l + 1;
3844   if (need > dgs->alc)
3845     d_growable_string_resize (dgs, need);
3846 
3847   if (dgs->allocation_failure)
3848     return;
3849 
3850   memcpy (dgs->buf + dgs->len, s, l);
3851   dgs->buf[dgs->len + l] = '\0';
3852   dgs->len += l;
3853 }
3854 
3855 /* Bridge growable strings to the callback mechanism.  */
3856 
3857 static void
3858 d_growable_string_callback_adapter (const char *s, size_t l, void *opaque)
3859 {
3860   struct d_growable_string *dgs = (struct d_growable_string*) opaque;
3861 
3862   d_growable_string_append_buffer (dgs, s, l);
3863 }
3864 
3865 /* Walk the tree, counting the number of templates encountered, and
3866    the number of times a scope might be saved.  These counts will be
3867    used to allocate data structures for d_print_comp, so the logic
3868    here must mirror the logic d_print_comp will use.  It is not
3869    important that the resulting numbers are exact, so long as they
3870    are larger than the actual numbers encountered.  */
3871 
3872 static void
3873 d_count_templates_scopes (int *num_templates, int *num_scopes,
3874 			  const struct demangle_component *dc)
3875 {
3876   if (dc == NULL)
3877     return;
3878 
3879   switch (dc->type)
3880     {
3881     case DEMANGLE_COMPONENT_NAME:
3882     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
3883     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
3884     case DEMANGLE_COMPONENT_SUB_STD:
3885     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
3886     case DEMANGLE_COMPONENT_OPERATOR:
3887     case DEMANGLE_COMPONENT_CHARACTER:
3888     case DEMANGLE_COMPONENT_NUMBER:
3889     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
3890       break;
3891 
3892     case DEMANGLE_COMPONENT_TEMPLATE:
3893       (*num_templates)++;
3894       goto recurse_left_right;
3895 
3896     case DEMANGLE_COMPONENT_REFERENCE:
3897     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
3898       if (d_left (dc)->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
3899 	(*num_scopes)++;
3900       goto recurse_left_right;
3901 
3902     case DEMANGLE_COMPONENT_QUAL_NAME:
3903     case DEMANGLE_COMPONENT_LOCAL_NAME:
3904     case DEMANGLE_COMPONENT_TYPED_NAME:
3905     case DEMANGLE_COMPONENT_VTABLE:
3906     case DEMANGLE_COMPONENT_VTT:
3907     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
3908     case DEMANGLE_COMPONENT_TYPEINFO:
3909     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
3910     case DEMANGLE_COMPONENT_TYPEINFO_FN:
3911     case DEMANGLE_COMPONENT_THUNK:
3912     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
3913     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
3914     case DEMANGLE_COMPONENT_JAVA_CLASS:
3915     case DEMANGLE_COMPONENT_GUARD:
3916     case DEMANGLE_COMPONENT_TLS_INIT:
3917     case DEMANGLE_COMPONENT_TLS_WRAPPER:
3918     case DEMANGLE_COMPONENT_REFTEMP:
3919     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
3920     case DEMANGLE_COMPONENT_RESTRICT:
3921     case DEMANGLE_COMPONENT_VOLATILE:
3922     case DEMANGLE_COMPONENT_CONST:
3923     case DEMANGLE_COMPONENT_RESTRICT_THIS:
3924     case DEMANGLE_COMPONENT_VOLATILE_THIS:
3925     case DEMANGLE_COMPONENT_CONST_THIS:
3926     case DEMANGLE_COMPONENT_REFERENCE_THIS:
3927     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
3928     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
3929     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3930     case DEMANGLE_COMPONENT_POINTER:
3931     case DEMANGLE_COMPONENT_COMPLEX:
3932     case DEMANGLE_COMPONENT_IMAGINARY:
3933     case DEMANGLE_COMPONENT_VENDOR_TYPE:
3934     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
3935     case DEMANGLE_COMPONENT_ARRAY_TYPE:
3936     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3937     case DEMANGLE_COMPONENT_VECTOR_TYPE:
3938     case DEMANGLE_COMPONENT_ARGLIST:
3939     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
3940     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
3941     case DEMANGLE_COMPONENT_CAST:
3942     case DEMANGLE_COMPONENT_CONVERSION:
3943     case DEMANGLE_COMPONENT_NULLARY:
3944     case DEMANGLE_COMPONENT_UNARY:
3945     case DEMANGLE_COMPONENT_BINARY:
3946     case DEMANGLE_COMPONENT_BINARY_ARGS:
3947     case DEMANGLE_COMPONENT_TRINARY:
3948     case DEMANGLE_COMPONENT_TRINARY_ARG1:
3949     case DEMANGLE_COMPONENT_TRINARY_ARG2:
3950     case DEMANGLE_COMPONENT_LITERAL:
3951     case DEMANGLE_COMPONENT_LITERAL_NEG:
3952     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
3953     case DEMANGLE_COMPONENT_COMPOUND_NAME:
3954     case DEMANGLE_COMPONENT_DECLTYPE:
3955     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
3956     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
3957     case DEMANGLE_COMPONENT_PACK_EXPANSION:
3958     case DEMANGLE_COMPONENT_TAGGED_NAME:
3959     case DEMANGLE_COMPONENT_CLONE:
3960     recurse_left_right:
3961       d_count_templates_scopes (num_templates, num_scopes,
3962 				d_left (dc));
3963       d_count_templates_scopes (num_templates, num_scopes,
3964 				d_right (dc));
3965       break;
3966 
3967     case DEMANGLE_COMPONENT_CTOR:
3968       d_count_templates_scopes (num_templates, num_scopes,
3969 				dc->u.s_ctor.name);
3970       break;
3971 
3972     case DEMANGLE_COMPONENT_DTOR:
3973       d_count_templates_scopes (num_templates, num_scopes,
3974 				dc->u.s_dtor.name);
3975       break;
3976 
3977     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3978       d_count_templates_scopes (num_templates, num_scopes,
3979 				dc->u.s_extended_operator.name);
3980       break;
3981 
3982     case DEMANGLE_COMPONENT_FIXED_TYPE:
3983       d_count_templates_scopes (num_templates, num_scopes,
3984                                 dc->u.s_fixed.length);
3985       break;
3986 
3987     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
3988     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
3989       d_count_templates_scopes (num_templates, num_scopes,
3990 				d_left (dc));
3991       break;
3992 
3993     case DEMANGLE_COMPONENT_LAMBDA:
3994     case DEMANGLE_COMPONENT_DEFAULT_ARG:
3995       d_count_templates_scopes (num_templates, num_scopes,
3996 				dc->u.s_unary_num.sub);
3997       break;
3998     }
3999 }
4000 
4001 /* Initialize a print information structure.  */
4002 
4003 static void
4004 d_print_init (struct d_print_info *dpi, demangle_callbackref callback,
4005 	      void *opaque, const struct demangle_component *dc)
4006 {
4007   dpi->len = 0;
4008   dpi->last_char = '\0';
4009   dpi->templates = NULL;
4010   dpi->modifiers = NULL;
4011   dpi->pack_index = 0;
4012   dpi->flush_count = 0;
4013 
4014   dpi->callback = callback;
4015   dpi->opaque = opaque;
4016 
4017   dpi->demangle_failure = 0;
4018 
4019   dpi->component_stack = NULL;
4020 
4021   dpi->saved_scopes = NULL;
4022   dpi->next_saved_scope = 0;
4023   dpi->num_saved_scopes = 0;
4024 
4025   dpi->copy_templates = NULL;
4026   dpi->next_copy_template = 0;
4027   dpi->num_copy_templates = 0;
4028 
4029   d_count_templates_scopes (&dpi->num_copy_templates,
4030 			    &dpi->num_saved_scopes, dc);
4031   dpi->num_copy_templates *= dpi->num_saved_scopes;
4032 
4033   dpi->current_template = NULL;
4034 }
4035 
4036 /* Indicate that an error occurred during printing, and test for error.  */
4037 
4038 static inline void
4039 d_print_error (struct d_print_info *dpi)
4040 {
4041   dpi->demangle_failure = 1;
4042 }
4043 
4044 static inline int
4045 d_print_saw_error (struct d_print_info *dpi)
4046 {
4047   return dpi->demangle_failure != 0;
4048 }
4049 
4050 /* Flush buffered characters to the callback.  */
4051 
4052 static inline void
4053 d_print_flush (struct d_print_info *dpi)
4054 {
4055   dpi->buf[dpi->len] = '\0';
4056   dpi->callback (dpi->buf, dpi->len, dpi->opaque);
4057   dpi->len = 0;
4058   dpi->flush_count++;
4059 }
4060 
4061 /* Append characters and buffers for printing.  */
4062 
4063 static inline void
4064 d_append_char (struct d_print_info *dpi, char c)
4065 {
4066   if (dpi->len == sizeof (dpi->buf) - 1)
4067     d_print_flush (dpi);
4068 
4069   dpi->buf[dpi->len++] = c;
4070   dpi->last_char = c;
4071 }
4072 
4073 static inline void
4074 d_append_buffer (struct d_print_info *dpi, const char *s, size_t l)
4075 {
4076   size_t i;
4077 
4078   for (i = 0; i < l; i++)
4079     d_append_char (dpi, s[i]);
4080 }
4081 
4082 static inline void
4083 d_append_string (struct d_print_info *dpi, const char *s)
4084 {
4085   d_append_buffer (dpi, s, strlen (s));
4086 }
4087 
4088 static inline void
4089 d_append_num (struct d_print_info *dpi, long l)
4090 {
4091   char buf[25];
4092   sprintf (buf,"%ld", l);
4093   d_append_string (dpi, buf);
4094 }
4095 
4096 static inline char
4097 d_last_char (struct d_print_info *dpi)
4098 {
4099   return dpi->last_char;
4100 }
4101 
4102 /* Turn components into a human readable string.  OPTIONS is the
4103    options bits passed to the demangler.  DC is the tree to print.
4104    CALLBACK is a function to call to flush demangled string segments
4105    as they fill the intermediate buffer, and OPAQUE is a generalized
4106    callback argument.  On success, this returns 1.  On failure,
4107    it returns 0, indicating a bad parse.  It does not use heap
4108    memory to build an output string, so cannot encounter memory
4109    allocation failure.  */
4110 
4111 CP_STATIC_IF_GLIBCPP_V3
4112 int
4113 cplus_demangle_print_callback (int options,
4114                                const struct demangle_component *dc,
4115                                demangle_callbackref callback, void *opaque)
4116 {
4117   struct d_print_info dpi;
4118 
4119   d_print_init (&dpi, callback, opaque, dc);
4120 
4121   {
4122 #ifdef CP_DYNAMIC_ARRAYS
4123     __extension__ struct d_saved_scope scopes[dpi.num_saved_scopes];
4124     __extension__ struct d_print_template temps[dpi.num_copy_templates];
4125 
4126     dpi.saved_scopes = scopes;
4127     dpi.copy_templates = temps;
4128 #else
4129     dpi.saved_scopes = alloca (dpi.num_saved_scopes
4130 			       * sizeof (*dpi.saved_scopes));
4131     dpi.copy_templates = alloca (dpi.num_copy_templates
4132 				 * sizeof (*dpi.copy_templates));
4133 #endif
4134 
4135     d_print_comp (&dpi, options, dc);
4136   }
4137 
4138   d_print_flush (&dpi);
4139 
4140   return ! d_print_saw_error (&dpi);
4141 }
4142 
4143 /* Turn components into a human readable string.  OPTIONS is the
4144    options bits passed to the demangler.  DC is the tree to print.
4145    ESTIMATE is a guess at the length of the result.  This returns a
4146    string allocated by malloc, or NULL on error.  On success, this
4147    sets *PALC to the size of the allocated buffer.  On failure, this
4148    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
4149    failure.  */
4150 
4151 CP_STATIC_IF_GLIBCPP_V3
4152 char *
4153 cplus_demangle_print (int options, const struct demangle_component *dc,
4154                       int estimate, size_t *palc)
4155 {
4156   struct d_growable_string dgs;
4157 
4158   d_growable_string_init (&dgs, estimate);
4159 
4160   if (! cplus_demangle_print_callback (options, dc,
4161                                        d_growable_string_callback_adapter,
4162                                        &dgs))
4163     {
4164       free (dgs.buf);
4165       *palc = 0;
4166       return NULL;
4167     }
4168 
4169   *palc = dgs.allocation_failure ? 1 : dgs.alc;
4170   return dgs.buf;
4171 }
4172 
4173 /* Returns the I'th element of the template arglist ARGS, or NULL on
4174    failure.  */
4175 
4176 static struct demangle_component *
4177 d_index_template_argument (struct demangle_component *args, int i)
4178 {
4179   struct demangle_component *a;
4180 
4181   for (a = args;
4182        a != NULL;
4183        a = d_right (a))
4184     {
4185       if (a->type != DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4186 	return NULL;
4187       if (i <= 0)
4188 	break;
4189       --i;
4190     }
4191   if (i != 0 || a == NULL)
4192     return NULL;
4193 
4194   return d_left (a);
4195 }
4196 
4197 /* Returns the template argument from the current context indicated by DC,
4198    which is a DEMANGLE_COMPONENT_TEMPLATE_PARAM, or NULL.  */
4199 
4200 static struct demangle_component *
4201 d_lookup_template_argument (struct d_print_info *dpi,
4202 			    const struct demangle_component *dc)
4203 {
4204   if (dpi->templates == NULL)
4205     {
4206       d_print_error (dpi);
4207       return NULL;
4208     }
4209 
4210   return d_index_template_argument
4211     (d_right (dpi->templates->template_decl),
4212      dc->u.s_number.number);
4213 }
4214 
4215 /* Returns a template argument pack used in DC (any will do), or NULL.  */
4216 
4217 static struct demangle_component *
4218 d_find_pack (struct d_print_info *dpi,
4219 	     const struct demangle_component *dc)
4220 {
4221   struct demangle_component *a;
4222   if (dc == NULL)
4223     return NULL;
4224 
4225   switch (dc->type)
4226     {
4227     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4228       a = d_lookup_template_argument (dpi, dc);
4229       if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4230 	return a;
4231       return NULL;
4232 
4233     case DEMANGLE_COMPONENT_PACK_EXPANSION:
4234       return NULL;
4235 
4236     case DEMANGLE_COMPONENT_LAMBDA:
4237     case DEMANGLE_COMPONENT_NAME:
4238     case DEMANGLE_COMPONENT_TAGGED_NAME:
4239     case DEMANGLE_COMPONENT_OPERATOR:
4240     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4241     case DEMANGLE_COMPONENT_SUB_STD:
4242     case DEMANGLE_COMPONENT_CHARACTER:
4243     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
4244     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
4245     case DEMANGLE_COMPONENT_FIXED_TYPE:
4246     case DEMANGLE_COMPONENT_DEFAULT_ARG:
4247     case DEMANGLE_COMPONENT_NUMBER:
4248       return NULL;
4249 
4250     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4251       return d_find_pack (dpi, dc->u.s_extended_operator.name);
4252     case DEMANGLE_COMPONENT_CTOR:
4253       return d_find_pack (dpi, dc->u.s_ctor.name);
4254     case DEMANGLE_COMPONENT_DTOR:
4255       return d_find_pack (dpi, dc->u.s_dtor.name);
4256 
4257     default:
4258       a = d_find_pack (dpi, d_left (dc));
4259       if (a)
4260 	return a;
4261       return d_find_pack (dpi, d_right (dc));
4262     }
4263 }
4264 
4265 /* Returns the length of the template argument pack DC.  */
4266 
4267 static int
4268 d_pack_length (const struct demangle_component *dc)
4269 {
4270   int count = 0;
4271   while (dc && dc->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST
4272 	 && d_left (dc) != NULL)
4273     {
4274       ++count;
4275       dc = d_right (dc);
4276     }
4277   return count;
4278 }
4279 
4280 /* DC is a component of a mangled expression.  Print it, wrapped in parens
4281    if needed.  */
4282 
4283 static void
4284 d_print_subexpr (struct d_print_info *dpi, int options,
4285 		 const struct demangle_component *dc)
4286 {
4287   int simple = 0;
4288   if (dc->type == DEMANGLE_COMPONENT_NAME
4289       || dc->type == DEMANGLE_COMPONENT_QUAL_NAME
4290       || dc->type == DEMANGLE_COMPONENT_INITIALIZER_LIST
4291       || dc->type == DEMANGLE_COMPONENT_FUNCTION_PARAM)
4292     simple = 1;
4293   if (!simple)
4294     d_append_char (dpi, '(');
4295   d_print_comp (dpi, options, dc);
4296   if (!simple)
4297     d_append_char (dpi, ')');
4298 }
4299 
4300 /* Save the current scope.  */
4301 
4302 static void
4303 d_save_scope (struct d_print_info *dpi,
4304 	      const struct demangle_component *container)
4305 {
4306   struct d_saved_scope *scope;
4307   struct d_print_template *src, **link;
4308 
4309   if (dpi->next_saved_scope >= dpi->num_saved_scopes)
4310     {
4311       d_print_error (dpi);
4312       return;
4313     }
4314   scope = &dpi->saved_scopes[dpi->next_saved_scope];
4315   dpi->next_saved_scope++;
4316 
4317   scope->container = container;
4318   link = &scope->templates;
4319 
4320   for (src = dpi->templates; src != NULL; src = src->next)
4321     {
4322       struct d_print_template *dst;
4323 
4324       if (dpi->next_copy_template >= dpi->num_copy_templates)
4325 	{
4326 	  d_print_error (dpi);
4327 	  return;
4328 	}
4329       dst = &dpi->copy_templates[dpi->next_copy_template];
4330       dpi->next_copy_template++;
4331 
4332       dst->template_decl = src->template_decl;
4333       *link = dst;
4334       link = &dst->next;
4335     }
4336 
4337   *link = NULL;
4338 }
4339 
4340 /* Attempt to locate a previously saved scope.  Returns NULL if no
4341    corresponding saved scope was found.  */
4342 
4343 static struct d_saved_scope *
4344 d_get_saved_scope (struct d_print_info *dpi,
4345 		   const struct demangle_component *container)
4346 {
4347   int i;
4348 
4349   for (i = 0; i < dpi->next_saved_scope; i++)
4350     if (dpi->saved_scopes[i].container == container)
4351       return &dpi->saved_scopes[i];
4352 
4353   return NULL;
4354 }
4355 
4356 /* Subroutine to handle components.  */
4357 
4358 static void
4359 d_print_comp_inner (struct d_print_info *dpi, int options,
4360 		  const struct demangle_component *dc)
4361 {
4362   /* Magic variable to let reference smashing skip over the next modifier
4363      without needing to modify *dc.  */
4364   const struct demangle_component *mod_inner = NULL;
4365 
4366   /* Variable used to store the current templates while a previously
4367      captured scope is used.  */
4368   struct d_print_template *saved_templates;
4369 
4370   /* Nonzero if templates have been stored in the above variable.  */
4371   int need_template_restore = 0;
4372 
4373   if (dc == NULL)
4374     {
4375       d_print_error (dpi);
4376       return;
4377     }
4378   if (d_print_saw_error (dpi))
4379     return;
4380 
4381   switch (dc->type)
4382     {
4383     case DEMANGLE_COMPONENT_NAME:
4384       if ((options & DMGL_JAVA) == 0)
4385 	d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
4386       else
4387 	d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
4388       return;
4389 
4390     case DEMANGLE_COMPONENT_TAGGED_NAME:
4391       d_print_comp (dpi, options, d_left (dc));
4392       d_append_string (dpi, "[abi:");
4393       d_print_comp (dpi, options, d_right (dc));
4394       d_append_char (dpi, ']');
4395       return;
4396 
4397     case DEMANGLE_COMPONENT_QUAL_NAME:
4398     case DEMANGLE_COMPONENT_LOCAL_NAME:
4399       d_print_comp (dpi, options, d_left (dc));
4400       if ((options & DMGL_JAVA) == 0)
4401 	d_append_string (dpi, "::");
4402       else
4403 	d_append_char (dpi, '.');
4404       {
4405 	struct demangle_component *local_name = d_right (dc);
4406 	if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4407 	  {
4408 	    d_append_string (dpi, "{default arg#");
4409 	    d_append_num (dpi, local_name->u.s_unary_num.num + 1);
4410 	    d_append_string (dpi, "}::");
4411 	    local_name = local_name->u.s_unary_num.sub;
4412 	  }
4413 	d_print_comp (dpi, options, local_name);
4414       }
4415       return;
4416 
4417     case DEMANGLE_COMPONENT_TYPED_NAME:
4418       {
4419 	struct d_print_mod *hold_modifiers;
4420 	struct demangle_component *typed_name;
4421 	struct d_print_mod adpm[4];
4422 	unsigned int i;
4423 	struct d_print_template dpt;
4424 
4425 	/* Pass the name down to the type so that it can be printed in
4426 	   the right place for the type.  We also have to pass down
4427 	   any CV-qualifiers, which apply to the this parameter.  */
4428 	hold_modifiers = dpi->modifiers;
4429 	dpi->modifiers = 0;
4430 	i = 0;
4431 	typed_name = d_left (dc);
4432 	while (typed_name != NULL)
4433 	  {
4434 	    if (i >= sizeof adpm / sizeof adpm[0])
4435 	      {
4436 		d_print_error (dpi);
4437 		return;
4438 	      }
4439 
4440 	    adpm[i].next = dpi->modifiers;
4441 	    dpi->modifiers = &adpm[i];
4442 	    adpm[i].mod = typed_name;
4443 	    adpm[i].printed = 0;
4444 	    adpm[i].templates = dpi->templates;
4445 	    ++i;
4446 
4447 	    if (typed_name->type != DEMANGLE_COMPONENT_RESTRICT_THIS
4448 		&& typed_name->type != DEMANGLE_COMPONENT_VOLATILE_THIS
4449 		&& typed_name->type != DEMANGLE_COMPONENT_CONST_THIS
4450 		&& typed_name->type != DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
4451 		&& typed_name->type != DEMANGLE_COMPONENT_TRANSACTION_SAFE
4452 		&& typed_name->type != DEMANGLE_COMPONENT_REFERENCE_THIS)
4453 	      break;
4454 
4455 	    typed_name = d_left (typed_name);
4456 	  }
4457 
4458 	if (typed_name == NULL)
4459 	  {
4460 	    d_print_error (dpi);
4461 	    return;
4462 	  }
4463 
4464 	/* If typed_name is a template, then it applies to the
4465 	   function type as well.  */
4466 	if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
4467 	  {
4468 	    dpt.next = dpi->templates;
4469 	    dpi->templates = &dpt;
4470 	    dpt.template_decl = typed_name;
4471 	  }
4472 
4473 	/* If typed_name is a DEMANGLE_COMPONENT_LOCAL_NAME, then
4474 	   there may be CV-qualifiers on its right argument which
4475 	   really apply here; this happens when parsing a class which
4476 	   is local to a function.  */
4477 	if (typed_name->type == DEMANGLE_COMPONENT_LOCAL_NAME)
4478 	  {
4479 	    struct demangle_component *local_name;
4480 
4481 	    local_name = d_right (typed_name);
4482 	    if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4483 	      local_name = local_name->u.s_unary_num.sub;
4484 	    if (local_name == NULL)
4485 	      {
4486 		d_print_error (dpi);
4487 		return;
4488 	      }
4489 	    while (local_name->type == DEMANGLE_COMPONENT_RESTRICT_THIS
4490 		   || local_name->type == DEMANGLE_COMPONENT_VOLATILE_THIS
4491 		   || local_name->type == DEMANGLE_COMPONENT_CONST_THIS
4492 		   || local_name->type == DEMANGLE_COMPONENT_REFERENCE_THIS
4493 		   || local_name->type == DEMANGLE_COMPONENT_TRANSACTION_SAFE
4494 		   || (local_name->type
4495 		       == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS))
4496 	      {
4497 		if (i >= sizeof adpm / sizeof adpm[0])
4498 		  {
4499 		    d_print_error (dpi);
4500 		    return;
4501 		  }
4502 
4503 		adpm[i] = adpm[i - 1];
4504 		adpm[i].next = &adpm[i - 1];
4505 		dpi->modifiers = &adpm[i];
4506 
4507 		adpm[i - 1].mod = local_name;
4508 		adpm[i - 1].printed = 0;
4509 		adpm[i - 1].templates = dpi->templates;
4510 		++i;
4511 
4512 		local_name = d_left (local_name);
4513 	      }
4514 	  }
4515 
4516 	d_print_comp (dpi, options, d_right (dc));
4517 
4518 	if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
4519 	  dpi->templates = dpt.next;
4520 
4521 	/* If the modifiers didn't get printed by the type, print them
4522 	   now.  */
4523 	while (i > 0)
4524 	  {
4525 	    --i;
4526 	    if (! adpm[i].printed)
4527 	      {
4528 		d_append_char (dpi, ' ');
4529 		d_print_mod (dpi, options, adpm[i].mod);
4530 	      }
4531 	  }
4532 
4533 	dpi->modifiers = hold_modifiers;
4534 
4535 	return;
4536       }
4537 
4538     case DEMANGLE_COMPONENT_TEMPLATE:
4539       {
4540 	struct d_print_mod *hold_dpm;
4541 	struct demangle_component *dcl;
4542 	const struct demangle_component *hold_current;
4543 
4544 	/* This template may need to be referenced by a cast operator
4545 	   contained in its subtree.  */
4546 	hold_current = dpi->current_template;
4547 	dpi->current_template = dc;
4548 
4549 	/* Don't push modifiers into a template definition.  Doing so
4550 	   could give the wrong definition for a template argument.
4551 	   Instead, treat the template essentially as a name.  */
4552 
4553 	hold_dpm = dpi->modifiers;
4554 	dpi->modifiers = NULL;
4555 
4556         dcl = d_left (dc);
4557 
4558         if ((options & DMGL_JAVA) != 0
4559             && dcl->type == DEMANGLE_COMPONENT_NAME
4560             && dcl->u.s_name.len == 6
4561             && strncmp (dcl->u.s_name.s, "JArray", 6) == 0)
4562           {
4563             /* Special-case Java arrays, so that JArray<TYPE> appears
4564                instead as TYPE[].  */
4565 
4566             d_print_comp (dpi, options, d_right (dc));
4567             d_append_string (dpi, "[]");
4568           }
4569         else
4570           {
4571 	    d_print_comp (dpi, options, dcl);
4572 	    if (d_last_char (dpi) == '<')
4573 	      d_append_char (dpi, ' ');
4574 	    d_append_char (dpi, '<');
4575 	    d_print_comp (dpi, options, d_right (dc));
4576 	    /* Avoid generating two consecutive '>' characters, to avoid
4577 	       the C++ syntactic ambiguity.  */
4578 	    if (d_last_char (dpi) == '>')
4579 	      d_append_char (dpi, ' ');
4580 	    d_append_char (dpi, '>');
4581           }
4582 
4583 	dpi->modifiers = hold_dpm;
4584 	dpi->current_template = hold_current;
4585 
4586 	return;
4587       }
4588 
4589     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4590       {
4591 	struct d_print_template *hold_dpt;
4592 	struct demangle_component *a = d_lookup_template_argument (dpi, dc);
4593 
4594 	if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4595 	  a = d_index_template_argument (a, dpi->pack_index);
4596 
4597 	if (a == NULL)
4598 	  {
4599 	    d_print_error (dpi);
4600 	    return;
4601 	  }
4602 
4603 	/* While processing this parameter, we need to pop the list of
4604 	   templates.  This is because the template parameter may
4605 	   itself be a reference to a parameter of an outer
4606 	   template.  */
4607 
4608 	hold_dpt = dpi->templates;
4609 	dpi->templates = hold_dpt->next;
4610 
4611 	d_print_comp (dpi, options, a);
4612 
4613 	dpi->templates = hold_dpt;
4614 
4615 	return;
4616       }
4617 
4618     case DEMANGLE_COMPONENT_CTOR:
4619       d_print_comp (dpi, options, dc->u.s_ctor.name);
4620       return;
4621 
4622     case DEMANGLE_COMPONENT_DTOR:
4623       d_append_char (dpi, '~');
4624       d_print_comp (dpi, options, dc->u.s_dtor.name);
4625       return;
4626 
4627     case DEMANGLE_COMPONENT_VTABLE:
4628       d_append_string (dpi, "vtable for ");
4629       d_print_comp (dpi, options, d_left (dc));
4630       return;
4631 
4632     case DEMANGLE_COMPONENT_VTT:
4633       d_append_string (dpi, "VTT for ");
4634       d_print_comp (dpi, options, d_left (dc));
4635       return;
4636 
4637     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
4638       d_append_string (dpi, "construction vtable for ");
4639       d_print_comp (dpi, options, d_left (dc));
4640       d_append_string (dpi, "-in-");
4641       d_print_comp (dpi, options, d_right (dc));
4642       return;
4643 
4644     case DEMANGLE_COMPONENT_TYPEINFO:
4645       d_append_string (dpi, "typeinfo for ");
4646       d_print_comp (dpi, options, d_left (dc));
4647       return;
4648 
4649     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
4650       d_append_string (dpi, "typeinfo name for ");
4651       d_print_comp (dpi, options, d_left (dc));
4652       return;
4653 
4654     case DEMANGLE_COMPONENT_TYPEINFO_FN:
4655       d_append_string (dpi, "typeinfo fn for ");
4656       d_print_comp (dpi, options, d_left (dc));
4657       return;
4658 
4659     case DEMANGLE_COMPONENT_THUNK:
4660       d_append_string (dpi, "non-virtual thunk to ");
4661       d_print_comp (dpi, options, d_left (dc));
4662       return;
4663 
4664     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
4665       d_append_string (dpi, "virtual thunk to ");
4666       d_print_comp (dpi, options, d_left (dc));
4667       return;
4668 
4669     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
4670       d_append_string (dpi, "covariant return thunk to ");
4671       d_print_comp (dpi, options, d_left (dc));
4672       return;
4673 
4674     case DEMANGLE_COMPONENT_JAVA_CLASS:
4675       d_append_string (dpi, "java Class for ");
4676       d_print_comp (dpi, options, d_left (dc));
4677       return;
4678 
4679     case DEMANGLE_COMPONENT_GUARD:
4680       d_append_string (dpi, "guard variable for ");
4681       d_print_comp (dpi, options, d_left (dc));
4682       return;
4683 
4684     case DEMANGLE_COMPONENT_TLS_INIT:
4685       d_append_string (dpi, "TLS init function for ");
4686       d_print_comp (dpi, options, d_left (dc));
4687       return;
4688 
4689     case DEMANGLE_COMPONENT_TLS_WRAPPER:
4690       d_append_string (dpi, "TLS wrapper function for ");
4691       d_print_comp (dpi, options, d_left (dc));
4692       return;
4693 
4694     case DEMANGLE_COMPONENT_REFTEMP:
4695       d_append_string (dpi, "reference temporary #");
4696       d_print_comp (dpi, options, d_right (dc));
4697       d_append_string (dpi, " for ");
4698       d_print_comp (dpi, options, d_left (dc));
4699       return;
4700 
4701     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4702       d_append_string (dpi, "hidden alias for ");
4703       d_print_comp (dpi, options, d_left (dc));
4704       return;
4705 
4706     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4707       d_append_string (dpi, "transaction clone for ");
4708       d_print_comp (dpi, options, d_left (dc));
4709       return;
4710 
4711     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4712       d_append_string (dpi, "non-transaction clone for ");
4713       d_print_comp (dpi, options, d_left (dc));
4714       return;
4715 
4716     case DEMANGLE_COMPONENT_SUB_STD:
4717       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
4718       return;
4719 
4720     case DEMANGLE_COMPONENT_RESTRICT:
4721     case DEMANGLE_COMPONENT_VOLATILE:
4722     case DEMANGLE_COMPONENT_CONST:
4723       {
4724 	struct d_print_mod *pdpm;
4725 
4726 	/* When printing arrays, it's possible to have cases where the
4727 	   same CV-qualifier gets pushed on the stack multiple times.
4728 	   We only need to print it once.  */
4729 
4730 	for (pdpm = dpi->modifiers; pdpm != NULL; pdpm = pdpm->next)
4731 	  {
4732 	    if (! pdpm->printed)
4733 	      {
4734 		if (pdpm->mod->type != DEMANGLE_COMPONENT_RESTRICT
4735 		    && pdpm->mod->type != DEMANGLE_COMPONENT_VOLATILE
4736 		    && pdpm->mod->type != DEMANGLE_COMPONENT_CONST)
4737 		  break;
4738 		if (pdpm->mod->type == dc->type)
4739 		  {
4740 		    d_print_comp (dpi, options, d_left (dc));
4741 		    return;
4742 		  }
4743 	      }
4744 	  }
4745       }
4746       goto modifier;
4747 
4748     case DEMANGLE_COMPONENT_REFERENCE:
4749     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
4750       {
4751 	/* Handle reference smashing: & + && = &.  */
4752 	const struct demangle_component *sub = d_left (dc);
4753 	if (sub->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
4754 	  {
4755 	    struct d_saved_scope *scope = d_get_saved_scope (dpi, sub);
4756 	    struct demangle_component *a;
4757 
4758 	    if (scope == NULL)
4759 	      {
4760 		/* This is the first time SUB has been traversed.
4761 		   We need to capture the current templates so
4762 		   they can be restored if SUB is reentered as a
4763 		   substitution.  */
4764 		d_save_scope (dpi, sub);
4765 		if (d_print_saw_error (dpi))
4766 		  return;
4767 	      }
4768 	    else
4769 	      {
4770 		const struct d_component_stack *dcse;
4771 		int found_self_or_parent = 0;
4772 
4773 		/* This traversal is reentering SUB as a substition.
4774 		   If we are not beneath SUB or DC in the tree then we
4775 		   need to restore SUB's template stack temporarily.  */
4776 		for (dcse = dpi->component_stack; dcse != NULL;
4777 		     dcse = dcse->parent)
4778 		  {
4779 		    if (dcse->dc == sub
4780 			|| (dcse->dc == dc
4781 			    && dcse != dpi->component_stack))
4782 		      {
4783 			found_self_or_parent = 1;
4784 			break;
4785 		      }
4786 		  }
4787 
4788 		if (!found_self_or_parent)
4789 		  {
4790 		    saved_templates = dpi->templates;
4791 		    dpi->templates = scope->templates;
4792 		    need_template_restore = 1;
4793 		  }
4794 	      }
4795 
4796 	    a = d_lookup_template_argument (dpi, sub);
4797 	    if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4798 	      a = d_index_template_argument (a, dpi->pack_index);
4799 
4800 	    if (a == NULL)
4801 	      {
4802 		if (need_template_restore)
4803 		  dpi->templates = saved_templates;
4804 
4805 		d_print_error (dpi);
4806 		return;
4807 	      }
4808 
4809 	    sub = a;
4810 	  }
4811 
4812 	if (sub->type == DEMANGLE_COMPONENT_REFERENCE
4813 	    || sub->type == dc->type)
4814 	  dc = sub;
4815 	else if (sub->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE)
4816 	  mod_inner = d_left (sub);
4817       }
4818       /* Fall through.  */
4819 
4820     case DEMANGLE_COMPONENT_RESTRICT_THIS:
4821     case DEMANGLE_COMPONENT_VOLATILE_THIS:
4822     case DEMANGLE_COMPONENT_CONST_THIS:
4823     case DEMANGLE_COMPONENT_REFERENCE_THIS:
4824     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
4825     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
4826     case DEMANGLE_COMPONENT_POINTER:
4827     case DEMANGLE_COMPONENT_COMPLEX:
4828     case DEMANGLE_COMPONENT_IMAGINARY:
4829     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
4830     modifier:
4831       {
4832 	/* We keep a list of modifiers on the stack.  */
4833 	struct d_print_mod dpm;
4834 
4835 	dpm.next = dpi->modifiers;
4836 	dpi->modifiers = &dpm;
4837 	dpm.mod = dc;
4838 	dpm.printed = 0;
4839 	dpm.templates = dpi->templates;
4840 
4841 	if (!mod_inner)
4842 	  mod_inner = d_left (dc);
4843 
4844 	d_print_comp (dpi, options, mod_inner);
4845 
4846 	/* If the modifier didn't get printed by the type, print it
4847 	   now.  */
4848 	if (! dpm.printed)
4849 	  d_print_mod (dpi, options, dc);
4850 
4851 	dpi->modifiers = dpm.next;
4852 
4853 	if (need_template_restore)
4854 	  dpi->templates = saved_templates;
4855 
4856 	return;
4857       }
4858 
4859     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4860       if ((options & DMGL_JAVA) == 0)
4861 	d_append_buffer (dpi, dc->u.s_builtin.type->name,
4862 			 dc->u.s_builtin.type->len);
4863       else
4864 	d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
4865 			 dc->u.s_builtin.type->java_len);
4866       return;
4867 
4868     case DEMANGLE_COMPONENT_VENDOR_TYPE:
4869       d_print_comp (dpi, options, d_left (dc));
4870       return;
4871 
4872     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
4873       {
4874 	if ((options & DMGL_RET_POSTFIX) != 0)
4875 	  d_print_function_type (dpi,
4876 				 options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4877 				 dc, dpi->modifiers);
4878 
4879 	/* Print return type if present */
4880 	if (d_left (dc) != NULL && (options & DMGL_RET_POSTFIX) != 0)
4881 	  d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4882 			d_left (dc));
4883 	else if (d_left (dc) != NULL && (options & DMGL_RET_DROP) == 0)
4884 	  {
4885 	    struct d_print_mod dpm;
4886 
4887 	    /* We must pass this type down as a modifier in order to
4888 	       print it in the right location.  */
4889 	    dpm.next = dpi->modifiers;
4890 	    dpi->modifiers = &dpm;
4891 	    dpm.mod = dc;
4892 	    dpm.printed = 0;
4893 	    dpm.templates = dpi->templates;
4894 
4895 	    d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4896 			  d_left (dc));
4897 
4898 	    dpi->modifiers = dpm.next;
4899 
4900 	    if (dpm.printed)
4901 	      return;
4902 
4903 	    /* In standard prefix notation, there is a space between the
4904 	       return type and the function signature.  */
4905 	    if ((options & DMGL_RET_POSTFIX) == 0)
4906 	      d_append_char (dpi, ' ');
4907 	  }
4908 
4909 	if ((options & DMGL_RET_POSTFIX) == 0)
4910 	  d_print_function_type (dpi,
4911 				 options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4912 				 dc, dpi->modifiers);
4913 
4914 	return;
4915       }
4916 
4917     case DEMANGLE_COMPONENT_ARRAY_TYPE:
4918       {
4919 	struct d_print_mod *hold_modifiers;
4920 	struct d_print_mod adpm[4];
4921 	unsigned int i;
4922 	struct d_print_mod *pdpm;
4923 
4924 	/* We must pass this type down as a modifier in order to print
4925 	   multi-dimensional arrays correctly.  If the array itself is
4926 	   CV-qualified, we act as though the element type were
4927 	   CV-qualified.  We do this by copying the modifiers down
4928 	   rather than fiddling pointers, so that we don't wind up
4929 	   with a d_print_mod higher on the stack pointing into our
4930 	   stack frame after we return.  */
4931 
4932 	hold_modifiers = dpi->modifiers;
4933 
4934 	adpm[0].next = hold_modifiers;
4935 	dpi->modifiers = &adpm[0];
4936 	adpm[0].mod = dc;
4937 	adpm[0].printed = 0;
4938 	adpm[0].templates = dpi->templates;
4939 
4940 	i = 1;
4941 	pdpm = hold_modifiers;
4942 	while (pdpm != NULL
4943 	       && (pdpm->mod->type == DEMANGLE_COMPONENT_RESTRICT
4944 		   || pdpm->mod->type == DEMANGLE_COMPONENT_VOLATILE
4945 		   || pdpm->mod->type == DEMANGLE_COMPONENT_CONST))
4946 	  {
4947 	    if (! pdpm->printed)
4948 	      {
4949 		if (i >= sizeof adpm / sizeof adpm[0])
4950 		  {
4951 		    d_print_error (dpi);
4952 		    return;
4953 		  }
4954 
4955 		adpm[i] = *pdpm;
4956 		adpm[i].next = dpi->modifiers;
4957 		dpi->modifiers = &adpm[i];
4958 		pdpm->printed = 1;
4959 		++i;
4960 	      }
4961 
4962 	    pdpm = pdpm->next;
4963 	  }
4964 
4965 	d_print_comp (dpi, options, d_right (dc));
4966 
4967 	dpi->modifiers = hold_modifiers;
4968 
4969 	if (adpm[0].printed)
4970 	  return;
4971 
4972 	while (i > 1)
4973 	  {
4974 	    --i;
4975 	    d_print_mod (dpi, options, adpm[i].mod);
4976 	  }
4977 
4978 	d_print_array_type (dpi, options, dc, dpi->modifiers);
4979 
4980 	return;
4981       }
4982 
4983     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
4984     case DEMANGLE_COMPONENT_VECTOR_TYPE:
4985       {
4986 	struct d_print_mod dpm;
4987 
4988 	dpm.next = dpi->modifiers;
4989 	dpi->modifiers = &dpm;
4990 	dpm.mod = dc;
4991 	dpm.printed = 0;
4992 	dpm.templates = dpi->templates;
4993 
4994 	d_print_comp (dpi, options, d_right (dc));
4995 
4996 	/* If the modifier didn't get printed by the type, print it
4997 	   now.  */
4998 	if (! dpm.printed)
4999 	  d_print_mod (dpi, options, dc);
5000 
5001 	dpi->modifiers = dpm.next;
5002 
5003 	return;
5004       }
5005 
5006     case DEMANGLE_COMPONENT_FIXED_TYPE:
5007       if (dc->u.s_fixed.sat)
5008 	d_append_string (dpi, "_Sat ");
5009       /* Don't print "int _Accum".  */
5010       if (dc->u.s_fixed.length->u.s_builtin.type
5011 	  != &cplus_demangle_builtin_types['i'-'a'])
5012 	{
5013 	  d_print_comp (dpi, options, dc->u.s_fixed.length);
5014 	  d_append_char (dpi, ' ');
5015 	}
5016       if (dc->u.s_fixed.accum)
5017 	d_append_string (dpi, "_Accum");
5018       else
5019 	d_append_string (dpi, "_Fract");
5020       return;
5021 
5022     case DEMANGLE_COMPONENT_ARGLIST:
5023     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
5024       if (d_left (dc) != NULL)
5025 	d_print_comp (dpi, options, d_left (dc));
5026       if (d_right (dc) != NULL)
5027 	{
5028 	  size_t len;
5029 	  unsigned long int flush_count;
5030 	  /* Make sure ", " isn't flushed by d_append_string, otherwise
5031 	     dpi->len -= 2 wouldn't work.  */
5032 	  if (dpi->len >= sizeof (dpi->buf) - 2)
5033 	    d_print_flush (dpi);
5034 	  d_append_string (dpi, ", ");
5035 	  len = dpi->len;
5036 	  flush_count = dpi->flush_count;
5037 	  d_print_comp (dpi, options, d_right (dc));
5038 	  /* If that didn't print anything (which can happen with empty
5039 	     template argument packs), remove the comma and space.  */
5040 	  if (dpi->flush_count == flush_count && dpi->len == len)
5041 	    dpi->len -= 2;
5042 	}
5043       return;
5044 
5045     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
5046       {
5047 	struct demangle_component *type = d_left (dc);
5048 	struct demangle_component *list = d_right (dc);
5049 
5050 	if (type)
5051 	  d_print_comp (dpi, options, type);
5052 	d_append_char (dpi, '{');
5053 	d_print_comp (dpi, options, list);
5054 	d_append_char (dpi, '}');
5055       }
5056       return;
5057 
5058     case DEMANGLE_COMPONENT_OPERATOR:
5059       {
5060 	const struct demangle_operator_info *op = dc->u.s_operator.op;
5061 	int len = op->len;
5062 
5063 	d_append_string (dpi, "operator");
5064 	/* Add a space before new/delete.  */
5065 	if (IS_LOWER (op->name[0]))
5066 	  d_append_char (dpi, ' ');
5067 	/* Omit a trailing space.  */
5068 	if (op->name[len-1] == ' ')
5069 	  --len;
5070 	d_append_buffer (dpi, op->name, len);
5071 	return;
5072       }
5073 
5074     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
5075       d_append_string (dpi, "operator ");
5076       d_print_comp (dpi, options, dc->u.s_extended_operator.name);
5077       return;
5078 
5079     case DEMANGLE_COMPONENT_CONVERSION:
5080       d_append_string (dpi, "operator ");
5081       d_print_conversion (dpi, options, dc);
5082       return;
5083 
5084     case DEMANGLE_COMPONENT_NULLARY:
5085       d_print_expr_op (dpi, options, d_left (dc));
5086       return;
5087 
5088     case DEMANGLE_COMPONENT_UNARY:
5089       {
5090 	struct demangle_component *op = d_left (dc);
5091 	struct demangle_component *operand = d_right (dc);
5092 	const char *code = NULL;
5093 
5094 	if (op->type == DEMANGLE_COMPONENT_OPERATOR)
5095 	  {
5096 	    code = op->u.s_operator.op->code;
5097 	    if (!strcmp (code, "ad"))
5098 	      {
5099 		/* Don't print the argument list for the address of a
5100 		   function.  */
5101 		if (operand->type == DEMANGLE_COMPONENT_TYPED_NAME
5102 		    && d_left (operand)->type == DEMANGLE_COMPONENT_QUAL_NAME
5103 		    && d_right (operand)->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
5104 		  operand = d_left (operand);
5105 	      }
5106 	    if (operand->type == DEMANGLE_COMPONENT_BINARY_ARGS)
5107 	      {
5108 		/* This indicates a suffix operator.  */
5109 		operand = d_left (operand);
5110 		d_print_subexpr (dpi, options, operand);
5111 		d_print_expr_op (dpi, options, op);
5112 		return;
5113 	      }
5114 	  }
5115 
5116 	if (op->type != DEMANGLE_COMPONENT_CAST)
5117 	  d_print_expr_op (dpi, options, op);
5118 	else
5119 	  {
5120 	    d_append_char (dpi, '(');
5121 	    d_print_cast (dpi, options, op);
5122 	    d_append_char (dpi, ')');
5123 	  }
5124 	if (code && !strcmp (code, "gs"))
5125 	  /* Avoid parens after '::'.  */
5126 	  d_print_comp (dpi, options, operand);
5127 	else if (code && !strcmp (code, "st"))
5128 	  /* Always print parens for sizeof (type).  */
5129 	  {
5130 	    d_append_char (dpi, '(');
5131 	    d_print_comp (dpi, options, operand);
5132 	    d_append_char (dpi, ')');
5133 	  }
5134 	else
5135 	  d_print_subexpr (dpi, options, operand);
5136       }
5137       return;
5138 
5139     case DEMANGLE_COMPONENT_BINARY:
5140       if (d_right (dc)->type != DEMANGLE_COMPONENT_BINARY_ARGS)
5141 	{
5142 	  d_print_error (dpi);
5143 	  return;
5144 	}
5145 
5146       if (op_is_new_cast (d_left (dc)))
5147 	{
5148 	  d_print_expr_op (dpi, options, d_left (dc));
5149 	  d_append_char (dpi, '<');
5150 	  d_print_comp (dpi, options, d_left (d_right (dc)));
5151 	  d_append_string (dpi, ">(");
5152 	  d_print_comp (dpi, options, d_right (d_right (dc)));
5153 	  d_append_char (dpi, ')');
5154 	  return;
5155 	}
5156 
5157       /* We wrap an expression which uses the greater-than operator in
5158 	 an extra layer of parens so that it does not get confused
5159 	 with the '>' which ends the template parameters.  */
5160       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5161 	  && d_left (dc)->u.s_operator.op->len == 1
5162 	  && d_left (dc)->u.s_operator.op->name[0] == '>')
5163 	d_append_char (dpi, '(');
5164 
5165       if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") == 0
5166           && d_left (d_right (dc))->type == DEMANGLE_COMPONENT_TYPED_NAME)
5167 	{
5168 	  /* Function call used in an expression should not have printed types
5169 	     of the function arguments.  Values of the function arguments still
5170 	     get printed below.  */
5171 
5172 	  const struct demangle_component *func = d_left (d_right (dc));
5173 
5174 	  if (d_right (func)->type != DEMANGLE_COMPONENT_FUNCTION_TYPE)
5175 	    d_print_error (dpi);
5176 	  d_print_subexpr (dpi, options, d_left (func));
5177 	}
5178       else
5179 	d_print_subexpr (dpi, options, d_left (d_right (dc)));
5180       if (strcmp (d_left (dc)->u.s_operator.op->code, "ix") == 0)
5181 	{
5182 	  d_append_char (dpi, '[');
5183 	  d_print_comp (dpi, options, d_right (d_right (dc)));
5184 	  d_append_char (dpi, ']');
5185 	}
5186       else
5187 	{
5188 	  if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") != 0)
5189 	    d_print_expr_op (dpi, options, d_left (dc));
5190 	  d_print_subexpr (dpi, options, d_right (d_right (dc)));
5191 	}
5192 
5193       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5194 	  && d_left (dc)->u.s_operator.op->len == 1
5195 	  && d_left (dc)->u.s_operator.op->name[0] == '>')
5196 	d_append_char (dpi, ')');
5197 
5198       return;
5199 
5200     case DEMANGLE_COMPONENT_BINARY_ARGS:
5201       /* We should only see this as part of DEMANGLE_COMPONENT_BINARY.  */
5202       d_print_error (dpi);
5203       return;
5204 
5205     case DEMANGLE_COMPONENT_TRINARY:
5206       if (d_right (dc)->type != DEMANGLE_COMPONENT_TRINARY_ARG1
5207 	  || d_right (d_right (dc))->type != DEMANGLE_COMPONENT_TRINARY_ARG2)
5208 	{
5209 	  d_print_error (dpi);
5210 	  return;
5211 	}
5212       {
5213 	struct demangle_component *op = d_left (dc);
5214 	struct demangle_component *first = d_left (d_right (dc));
5215 	struct demangle_component *second = d_left (d_right (d_right (dc)));
5216 	struct demangle_component *third = d_right (d_right (d_right (dc)));
5217 
5218 	if (!strcmp (op->u.s_operator.op->code, "qu"))
5219 	  {
5220 	    d_print_subexpr (dpi, options, first);
5221 	    d_print_expr_op (dpi, options, op);
5222 	    d_print_subexpr (dpi, options, second);
5223 	    d_append_string (dpi, " : ");
5224 	    d_print_subexpr (dpi, options, third);
5225 	  }
5226 	else
5227 	  {
5228 	    d_append_string (dpi, "new ");
5229 	    if (d_left (first) != NULL)
5230 	      {
5231 		d_print_subexpr (dpi, options, first);
5232 		d_append_char (dpi, ' ');
5233 	      }
5234 	    d_print_comp (dpi, options, second);
5235 	    if (third)
5236 	      d_print_subexpr (dpi, options, third);
5237 	  }
5238       }
5239       return;
5240 
5241     case DEMANGLE_COMPONENT_TRINARY_ARG1:
5242     case DEMANGLE_COMPONENT_TRINARY_ARG2:
5243       /* We should only see these are part of DEMANGLE_COMPONENT_TRINARY.  */
5244       d_print_error (dpi);
5245       return;
5246 
5247     case DEMANGLE_COMPONENT_LITERAL:
5248     case DEMANGLE_COMPONENT_LITERAL_NEG:
5249       {
5250 	enum d_builtin_type_print tp;
5251 
5252 	/* For some builtin types, produce simpler output.  */
5253 	tp = D_PRINT_DEFAULT;
5254 	if (d_left (dc)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE)
5255 	  {
5256 	    tp = d_left (dc)->u.s_builtin.type->print;
5257 	    switch (tp)
5258 	      {
5259 	      case D_PRINT_INT:
5260 	      case D_PRINT_UNSIGNED:
5261 	      case D_PRINT_LONG:
5262 	      case D_PRINT_UNSIGNED_LONG:
5263 	      case D_PRINT_LONG_LONG:
5264 	      case D_PRINT_UNSIGNED_LONG_LONG:
5265 		if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME)
5266 		  {
5267 		    if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5268 		      d_append_char (dpi, '-');
5269 		    d_print_comp (dpi, options, d_right (dc));
5270 		    switch (tp)
5271 		      {
5272 		      default:
5273 			break;
5274 		      case D_PRINT_UNSIGNED:
5275 			d_append_char (dpi, 'u');
5276 			break;
5277 		      case D_PRINT_LONG:
5278 			d_append_char (dpi, 'l');
5279 			break;
5280 		      case D_PRINT_UNSIGNED_LONG:
5281 			d_append_string (dpi, "ul");
5282 			break;
5283 		      case D_PRINT_LONG_LONG:
5284 			d_append_string (dpi, "ll");
5285 			break;
5286 		      case D_PRINT_UNSIGNED_LONG_LONG:
5287 			d_append_string (dpi, "ull");
5288 			break;
5289 		      }
5290 		    return;
5291 		  }
5292 		break;
5293 
5294 	      case D_PRINT_BOOL:
5295 		if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME
5296 		    && d_right (dc)->u.s_name.len == 1
5297 		    && dc->type == DEMANGLE_COMPONENT_LITERAL)
5298 		  {
5299 		    switch (d_right (dc)->u.s_name.s[0])
5300 		      {
5301 		      case '0':
5302 			d_append_string (dpi, "false");
5303 			return;
5304 		      case '1':
5305 			d_append_string (dpi, "true");
5306 			return;
5307 		      default:
5308 			break;
5309 		      }
5310 		  }
5311 		break;
5312 
5313 	      default:
5314 		break;
5315 	      }
5316 	  }
5317 
5318 	d_append_char (dpi, '(');
5319 	d_print_comp (dpi, options, d_left (dc));
5320 	d_append_char (dpi, ')');
5321 	if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5322 	  d_append_char (dpi, '-');
5323 	if (tp == D_PRINT_FLOAT)
5324 	  d_append_char (dpi, '[');
5325 	d_print_comp (dpi, options, d_right (dc));
5326 	if (tp == D_PRINT_FLOAT)
5327 	  d_append_char (dpi, ']');
5328       }
5329       return;
5330 
5331     case DEMANGLE_COMPONENT_NUMBER:
5332       d_append_num (dpi, dc->u.s_number.number);
5333       return;
5334 
5335     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
5336       d_append_string (dpi, "java resource ");
5337       d_print_comp (dpi, options, d_left (dc));
5338       return;
5339 
5340     case DEMANGLE_COMPONENT_COMPOUND_NAME:
5341       d_print_comp (dpi, options, d_left (dc));
5342       d_print_comp (dpi, options, d_right (dc));
5343       return;
5344 
5345     case DEMANGLE_COMPONENT_CHARACTER:
5346       d_append_char (dpi, dc->u.s_character.character);
5347       return;
5348 
5349     case DEMANGLE_COMPONENT_DECLTYPE:
5350       d_append_string (dpi, "decltype (");
5351       d_print_comp (dpi, options, d_left (dc));
5352       d_append_char (dpi, ')');
5353       return;
5354 
5355     case DEMANGLE_COMPONENT_PACK_EXPANSION:
5356       {
5357 	int len;
5358 	int i;
5359 	struct demangle_component *a = d_find_pack (dpi, d_left (dc));
5360 	if (a == NULL)
5361 	  {
5362 	    /* d_find_pack won't find anything if the only packs involved
5363 	       in this expansion are function parameter packs; in that
5364 	       case, just print the pattern and "...".  */
5365 	    d_print_subexpr (dpi, options, d_left (dc));
5366 	    d_append_string (dpi, "...");
5367 	    return;
5368 	  }
5369 
5370 	len = d_pack_length (a);
5371 	dc = d_left (dc);
5372 	for (i = 0; i < len; ++i)
5373 	  {
5374 	    dpi->pack_index = i;
5375 	    d_print_comp (dpi, options, dc);
5376 	    if (i < len-1)
5377 	      d_append_string (dpi, ", ");
5378 	  }
5379       }
5380       return;
5381 
5382     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
5383       {
5384 	long num = dc->u.s_number.number;
5385 	if (num == 0)
5386 	  d_append_string (dpi, "this");
5387 	else
5388 	  {
5389 	    d_append_string (dpi, "{parm#");
5390 	    d_append_num (dpi, num);
5391 	    d_append_char (dpi, '}');
5392 	  }
5393       }
5394       return;
5395 
5396     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
5397       d_append_string (dpi, "global constructors keyed to ");
5398       d_print_comp (dpi, options, dc->u.s_binary.left);
5399       return;
5400 
5401     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
5402       d_append_string (dpi, "global destructors keyed to ");
5403       d_print_comp (dpi, options, dc->u.s_binary.left);
5404       return;
5405 
5406     case DEMANGLE_COMPONENT_LAMBDA:
5407       d_append_string (dpi, "{lambda(");
5408       d_print_comp (dpi, options, dc->u.s_unary_num.sub);
5409       d_append_string (dpi, ")#");
5410       d_append_num (dpi, dc->u.s_unary_num.num + 1);
5411       d_append_char (dpi, '}');
5412       return;
5413 
5414     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
5415       d_append_string (dpi, "{unnamed type#");
5416       d_append_num (dpi, dc->u.s_number.number + 1);
5417       d_append_char (dpi, '}');
5418       return;
5419 
5420     case DEMANGLE_COMPONENT_CLONE:
5421       d_print_comp (dpi, options, d_left (dc));
5422       d_append_string (dpi, " [clone ");
5423       d_print_comp (dpi, options, d_right (dc));
5424       d_append_char (dpi, ']');
5425       return;
5426 
5427     default:
5428       d_print_error (dpi);
5429       return;
5430     }
5431 }
5432 
5433 static void
5434 d_print_comp (struct d_print_info *dpi, int options,
5435 	      const struct demangle_component *dc)
5436 {
5437   struct d_component_stack self;
5438 
5439   self.dc = dc;
5440   self.parent = dpi->component_stack;
5441   dpi->component_stack = &self;
5442 
5443   d_print_comp_inner (dpi, options, dc);
5444 
5445   dpi->component_stack = self.parent;
5446 }
5447 
5448 /* Print a Java dentifier.  For Java we try to handle encoded extended
5449    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
5450    so we don't it for C++.  Characters are encoded as
5451    __U<hex-char>+_.  */
5452 
5453 static void
5454 d_print_java_identifier (struct d_print_info *dpi, const char *name, int len)
5455 {
5456   const char *p;
5457   const char *end;
5458 
5459   end = name + len;
5460   for (p = name; p < end; ++p)
5461     {
5462       if (end - p > 3
5463 	  && p[0] == '_'
5464 	  && p[1] == '_'
5465 	  && p[2] == 'U')
5466 	{
5467 	  unsigned long c;
5468 	  const char *q;
5469 
5470 	  c = 0;
5471 	  for (q = p + 3; q < end; ++q)
5472 	    {
5473 	      int dig;
5474 
5475 	      if (IS_DIGIT (*q))
5476 		dig = *q - '0';
5477 	      else if (*q >= 'A' && *q <= 'F')
5478 		dig = *q - 'A' + 10;
5479 	      else if (*q >= 'a' && *q <= 'f')
5480 		dig = *q - 'a' + 10;
5481 	      else
5482 		break;
5483 
5484 	      c = c * 16 + dig;
5485 	    }
5486 	  /* If the Unicode character is larger than 256, we don't try
5487 	     to deal with it here.  FIXME.  */
5488 	  if (q < end && *q == '_' && c < 256)
5489 	    {
5490 	      d_append_char (dpi, c);
5491 	      p = q;
5492 	      continue;
5493 	    }
5494 	}
5495 
5496       d_append_char (dpi, *p);
5497     }
5498 }
5499 
5500 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
5501    qualifiers on this after printing a function.  */
5502 
5503 static void
5504 d_print_mod_list (struct d_print_info *dpi, int options,
5505                   struct d_print_mod *mods, int suffix)
5506 {
5507   struct d_print_template *hold_dpt;
5508 
5509   if (mods == NULL || d_print_saw_error (dpi))
5510     return;
5511 
5512   if (mods->printed
5513       || (! suffix
5514 	  && (mods->mod->type == DEMANGLE_COMPONENT_RESTRICT_THIS
5515 	      || mods->mod->type == DEMANGLE_COMPONENT_VOLATILE_THIS
5516 	      || mods->mod->type == DEMANGLE_COMPONENT_CONST_THIS
5517 	      || mods->mod->type == DEMANGLE_COMPONENT_REFERENCE_THIS
5518 	      || mods->mod->type == DEMANGLE_COMPONENT_TRANSACTION_SAFE
5519 	      || (mods->mod->type
5520 		  == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS))))
5521     {
5522       d_print_mod_list (dpi, options, mods->next, suffix);
5523       return;
5524     }
5525 
5526   mods->printed = 1;
5527 
5528   hold_dpt = dpi->templates;
5529   dpi->templates = mods->templates;
5530 
5531   if (mods->mod->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
5532     {
5533       d_print_function_type (dpi, options, mods->mod, mods->next);
5534       dpi->templates = hold_dpt;
5535       return;
5536     }
5537   else if (mods->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
5538     {
5539       d_print_array_type (dpi, options, mods->mod, mods->next);
5540       dpi->templates = hold_dpt;
5541       return;
5542     }
5543   else if (mods->mod->type == DEMANGLE_COMPONENT_LOCAL_NAME)
5544     {
5545       struct d_print_mod *hold_modifiers;
5546       struct demangle_component *dc;
5547 
5548       /* When this is on the modifier stack, we have pulled any
5549 	 qualifiers off the right argument already.  Otherwise, we
5550 	 print it as usual, but don't let the left argument see any
5551 	 modifiers.  */
5552 
5553       hold_modifiers = dpi->modifiers;
5554       dpi->modifiers = NULL;
5555       d_print_comp (dpi, options, d_left (mods->mod));
5556       dpi->modifiers = hold_modifiers;
5557 
5558       if ((options & DMGL_JAVA) == 0)
5559 	d_append_string (dpi, "::");
5560       else
5561 	d_append_char (dpi, '.');
5562 
5563       dc = d_right (mods->mod);
5564 
5565       if (dc->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
5566 	{
5567 	  d_append_string (dpi, "{default arg#");
5568 	  d_append_num (dpi, dc->u.s_unary_num.num + 1);
5569 	  d_append_string (dpi, "}::");
5570 	  dc = dc->u.s_unary_num.sub;
5571 	}
5572 
5573       while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
5574 	     || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
5575 	     || dc->type == DEMANGLE_COMPONENT_CONST_THIS
5576 	     || dc->type == DEMANGLE_COMPONENT_REFERENCE_THIS
5577 	     || dc->type == DEMANGLE_COMPONENT_TRANSACTION_SAFE
5578 	     || dc->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
5579 	dc = d_left (dc);
5580 
5581       d_print_comp (dpi, options, dc);
5582 
5583       dpi->templates = hold_dpt;
5584       return;
5585     }
5586 
5587   d_print_mod (dpi, options, mods->mod);
5588 
5589   dpi->templates = hold_dpt;
5590 
5591   d_print_mod_list (dpi, options, mods->next, suffix);
5592 }
5593 
5594 /* Print a modifier.  */
5595 
5596 static void
5597 d_print_mod (struct d_print_info *dpi, int options,
5598              const struct demangle_component *mod)
5599 {
5600   switch (mod->type)
5601     {
5602     case DEMANGLE_COMPONENT_RESTRICT:
5603     case DEMANGLE_COMPONENT_RESTRICT_THIS:
5604       d_append_string (dpi, " restrict");
5605       return;
5606     case DEMANGLE_COMPONENT_VOLATILE:
5607     case DEMANGLE_COMPONENT_VOLATILE_THIS:
5608       d_append_string (dpi, " volatile");
5609       return;
5610     case DEMANGLE_COMPONENT_CONST:
5611     case DEMANGLE_COMPONENT_CONST_THIS:
5612       d_append_string (dpi, " const");
5613       return;
5614     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
5615       d_append_string (dpi, " transaction_safe");
5616       return;
5617     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5618       d_append_char (dpi, ' ');
5619       d_print_comp (dpi, options, d_right (mod));
5620       return;
5621     case DEMANGLE_COMPONENT_POINTER:
5622       /* There is no pointer symbol in Java.  */
5623       if ((options & DMGL_JAVA) == 0)
5624 	d_append_char (dpi, '*');
5625       return;
5626     case DEMANGLE_COMPONENT_REFERENCE_THIS:
5627       /* For the ref-qualifier, put a space before the &.  */
5628       d_append_char (dpi, ' ');
5629     case DEMANGLE_COMPONENT_REFERENCE:
5630       d_append_char (dpi, '&');
5631       return;
5632     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
5633       d_append_char (dpi, ' ');
5634     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5635       d_append_string (dpi, "&&");
5636       return;
5637     case DEMANGLE_COMPONENT_COMPLEX:
5638       d_append_string (dpi, "complex ");
5639       return;
5640     case DEMANGLE_COMPONENT_IMAGINARY:
5641       d_append_string (dpi, "imaginary ");
5642       return;
5643     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5644       if (d_last_char (dpi) != '(')
5645 	d_append_char (dpi, ' ');
5646       d_print_comp (dpi, options, d_left (mod));
5647       d_append_string (dpi, "::*");
5648       return;
5649     case DEMANGLE_COMPONENT_TYPED_NAME:
5650       d_print_comp (dpi, options, d_left (mod));
5651       return;
5652     case DEMANGLE_COMPONENT_VECTOR_TYPE:
5653       d_append_string (dpi, " __vector(");
5654       d_print_comp (dpi, options, d_left (mod));
5655       d_append_char (dpi, ')');
5656       return;
5657 
5658     default:
5659       /* Otherwise, we have something that won't go back on the
5660 	 modifier stack, so we can just print it.  */
5661       d_print_comp (dpi, options, mod);
5662       return;
5663     }
5664 }
5665 
5666 /* Print a function type, except for the return type.  */
5667 
5668 static void
5669 d_print_function_type (struct d_print_info *dpi, int options,
5670                        const struct demangle_component *dc,
5671                        struct d_print_mod *mods)
5672 {
5673   int need_paren;
5674   int need_space;
5675   struct d_print_mod *p;
5676   struct d_print_mod *hold_modifiers;
5677 
5678   need_paren = 0;
5679   need_space = 0;
5680   for (p = mods; p != NULL; p = p->next)
5681     {
5682       if (p->printed)
5683 	break;
5684 
5685       switch (p->mod->type)
5686 	{
5687 	case DEMANGLE_COMPONENT_POINTER:
5688 	case DEMANGLE_COMPONENT_REFERENCE:
5689 	case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5690 	  need_paren = 1;
5691 	  break;
5692 	case DEMANGLE_COMPONENT_RESTRICT:
5693 	case DEMANGLE_COMPONENT_VOLATILE:
5694 	case DEMANGLE_COMPONENT_CONST:
5695 	case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5696 	case DEMANGLE_COMPONENT_COMPLEX:
5697 	case DEMANGLE_COMPONENT_IMAGINARY:
5698 	case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5699 	  need_space = 1;
5700 	  need_paren = 1;
5701 	  break;
5702 	case DEMANGLE_COMPONENT_RESTRICT_THIS:
5703 	case DEMANGLE_COMPONENT_VOLATILE_THIS:
5704 	case DEMANGLE_COMPONENT_CONST_THIS:
5705 	case DEMANGLE_COMPONENT_REFERENCE_THIS:
5706 	case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
5707 	case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
5708 	  break;
5709 	default:
5710 	  break;
5711 	}
5712       if (need_paren)
5713 	break;
5714     }
5715 
5716   if (need_paren)
5717     {
5718       if (! need_space)
5719 	{
5720 	  if (d_last_char (dpi) != '('
5721 	      && d_last_char (dpi) != '*')
5722 	    need_space = 1;
5723 	}
5724       if (need_space && d_last_char (dpi) != ' ')
5725 	d_append_char (dpi, ' ');
5726       d_append_char (dpi, '(');
5727     }
5728 
5729   hold_modifiers = dpi->modifiers;
5730   dpi->modifiers = NULL;
5731 
5732   d_print_mod_list (dpi, options, mods, 0);
5733 
5734   if (need_paren)
5735     d_append_char (dpi, ')');
5736 
5737   d_append_char (dpi, '(');
5738 
5739   if (d_right (dc) != NULL)
5740     d_print_comp (dpi, options, d_right (dc));
5741 
5742   d_append_char (dpi, ')');
5743 
5744   d_print_mod_list (dpi, options, mods, 1);
5745 
5746   dpi->modifiers = hold_modifiers;
5747 }
5748 
5749 /* Print an array type, except for the element type.  */
5750 
5751 static void
5752 d_print_array_type (struct d_print_info *dpi, int options,
5753                     const struct demangle_component *dc,
5754                     struct d_print_mod *mods)
5755 {
5756   int need_space;
5757 
5758   need_space = 1;
5759   if (mods != NULL)
5760     {
5761       int need_paren;
5762       struct d_print_mod *p;
5763 
5764       need_paren = 0;
5765       for (p = mods; p != NULL; p = p->next)
5766 	{
5767 	  if (! p->printed)
5768 	    {
5769 	      if (p->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
5770 		{
5771 		  need_space = 0;
5772 		  break;
5773 		}
5774 	      else
5775 		{
5776 		  need_paren = 1;
5777 		  need_space = 1;
5778 		  break;
5779 		}
5780 	    }
5781 	}
5782 
5783       if (need_paren)
5784 	d_append_string (dpi, " (");
5785 
5786       d_print_mod_list (dpi, options, mods, 0);
5787 
5788       if (need_paren)
5789 	d_append_char (dpi, ')');
5790     }
5791 
5792   if (need_space)
5793     d_append_char (dpi, ' ');
5794 
5795   d_append_char (dpi, '[');
5796 
5797   if (d_left (dc) != NULL)
5798     d_print_comp (dpi, options, d_left (dc));
5799 
5800   d_append_char (dpi, ']');
5801 }
5802 
5803 /* Print an operator in an expression.  */
5804 
5805 static void
5806 d_print_expr_op (struct d_print_info *dpi, int options,
5807                  const struct demangle_component *dc)
5808 {
5809   if (dc->type == DEMANGLE_COMPONENT_OPERATOR)
5810     d_append_buffer (dpi, dc->u.s_operator.op->name,
5811 		     dc->u.s_operator.op->len);
5812   else
5813     d_print_comp (dpi, options, dc);
5814 }
5815 
5816 /* Print a cast.  */
5817 
5818 static void
5819 d_print_cast (struct d_print_info *dpi, int options,
5820 		    const struct demangle_component *dc)
5821 {
5822   d_print_comp (dpi, options, d_left (dc));
5823 }
5824 
5825 /* Print a conversion operator.  */
5826 
5827 static void
5828 d_print_conversion (struct d_print_info *dpi, int options,
5829 		    const struct demangle_component *dc)
5830 {
5831   struct d_print_template dpt;
5832 
5833   /* For a conversion operator, we need the template parameters from
5834      the enclosing template in scope for processing the type.  */
5835   if (dpi->current_template != NULL)
5836     {
5837       dpt.next = dpi->templates;
5838       dpi->templates = &dpt;
5839       dpt.template_decl = dpi->current_template;
5840     }
5841 
5842   if (d_left (dc)->type != DEMANGLE_COMPONENT_TEMPLATE)
5843     {
5844       d_print_comp (dpi, options, d_left (dc));
5845       if (dpi->current_template != NULL)
5846 	dpi->templates = dpt.next;
5847     }
5848   else
5849     {
5850       d_print_comp (dpi, options, d_left (d_left (dc)));
5851 
5852       /* For a templated cast operator, we need to remove the template
5853 	 parameters from scope after printing the operator name,
5854 	 so we need to handle the template printing here.  */
5855       if (dpi->current_template != NULL)
5856 	dpi->templates = dpt.next;
5857 
5858       if (d_last_char (dpi) == '<')
5859 	d_append_char (dpi, ' ');
5860       d_append_char (dpi, '<');
5861       d_print_comp (dpi, options, d_right (d_left (dc)));
5862       /* Avoid generating two consecutive '>' characters, to avoid
5863 	 the C++ syntactic ambiguity.  */
5864       if (d_last_char (dpi) == '>')
5865 	d_append_char (dpi, ' ');
5866       d_append_char (dpi, '>');
5867     }
5868 }
5869 
5870 /* Initialize the information structure we use to pass around
5871    information.  */
5872 
5873 CP_STATIC_IF_GLIBCPP_V3
5874 void
5875 cplus_demangle_init_info (const char *mangled, int options, size_t len,
5876                           struct d_info *di)
5877 {
5878   di->s = mangled;
5879   di->send = mangled + len;
5880   di->options = options;
5881 
5882   di->n = mangled;
5883 
5884   /* We can not need more components than twice the number of chars in
5885      the mangled string.  Most components correspond directly to
5886      chars, but the ARGLIST types are exceptions.  */
5887   di->num_comps = 2 * len;
5888   di->next_comp = 0;
5889 
5890   /* Similarly, we can not need more substitutions than there are
5891      chars in the mangled string.  */
5892   di->num_subs = len;
5893   di->next_sub = 0;
5894   di->did_subs = 0;
5895 
5896   di->last_name = NULL;
5897 
5898   di->expansion = 0;
5899   di->is_expression = 0;
5900   di->is_conversion = 0;
5901 }
5902 
5903 /* Internal implementation for the demangler.  If MANGLED is a g++ v3 ABI
5904    mangled name, return strings in repeated callback giving the demangled
5905    name.  OPTIONS is the usual libiberty demangler options.  On success,
5906    this returns 1.  On failure, returns 0.  */
5907 
5908 static int
5909 d_demangle_callback (const char *mangled, int options,
5910                      demangle_callbackref callback, void *opaque)
5911 {
5912   enum
5913     {
5914       DCT_TYPE,
5915       DCT_MANGLED,
5916       DCT_GLOBAL_CTORS,
5917       DCT_GLOBAL_DTORS
5918     }
5919   type;
5920   struct d_info di;
5921   struct demangle_component *dc;
5922   int status;
5923 
5924   if (mangled[0] == '_' && mangled[1] == 'Z')
5925     type = DCT_MANGLED;
5926   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
5927 	   && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
5928 	   && (mangled[9] == 'D' || mangled[9] == 'I')
5929 	   && mangled[10] == '_')
5930     type = mangled[9] == 'I' ? DCT_GLOBAL_CTORS : DCT_GLOBAL_DTORS;
5931   else
5932     {
5933       if ((options & DMGL_TYPES) == 0)
5934 	return 0;
5935       type = DCT_TYPE;
5936     }
5937 
5938   cplus_demangle_init_info (mangled, options, strlen (mangled), &di);
5939 
5940   {
5941 #ifdef CP_DYNAMIC_ARRAYS
5942     __extension__ struct demangle_component comps[di.num_comps];
5943     __extension__ struct demangle_component *subs[di.num_subs];
5944 
5945     di.comps = comps;
5946     di.subs = subs;
5947 #else
5948     di.comps = alloca (di.num_comps * sizeof (*di.comps));
5949     di.subs = alloca (di.num_subs * sizeof (*di.subs));
5950 #endif
5951 
5952     switch (type)
5953       {
5954       case DCT_TYPE:
5955 	dc = cplus_demangle_type (&di);
5956 	break;
5957       case DCT_MANGLED:
5958 	dc = cplus_demangle_mangled_name (&di, 1);
5959 	break;
5960       case DCT_GLOBAL_CTORS:
5961       case DCT_GLOBAL_DTORS:
5962 	d_advance (&di, 11);
5963 	dc = d_make_comp (&di,
5964 			  (type == DCT_GLOBAL_CTORS
5965 			   ? DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS
5966 			   : DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS),
5967 			  d_make_demangle_mangled_name (&di, d_str (&di)),
5968 			  NULL);
5969 	d_advance (&di, strlen (d_str (&di)));
5970 	break;
5971       default:
5972 	abort (); /* We have listed all the cases.  */
5973       }
5974 
5975     /* If DMGL_PARAMS is set, then if we didn't consume the entire
5976        mangled string, then we didn't successfully demangle it.  If
5977        DMGL_PARAMS is not set, we didn't look at the trailing
5978        parameters.  */
5979     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
5980       dc = NULL;
5981 
5982 #ifdef CP_DEMANGLE_DEBUG
5983     d_dump (dc, 0);
5984 #endif
5985 
5986     status = (dc != NULL)
5987              ? cplus_demangle_print_callback (options, dc, callback, opaque)
5988              : 0;
5989   }
5990 
5991   return status;
5992 }
5993 
5994 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
5995    name, return a buffer allocated with malloc holding the demangled
5996    name.  OPTIONS is the usual libiberty demangler options.  On
5997    success, this sets *PALC to the allocated size of the returned
5998    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
5999    a memory allocation failure, and returns NULL.  */
6000 
6001 static char *
6002 d_demangle (const char *mangled, int options, size_t *palc)
6003 {
6004   struct d_growable_string dgs;
6005   int status;
6006 
6007   d_growable_string_init (&dgs, 0);
6008 
6009   status = d_demangle_callback (mangled, options,
6010                                 d_growable_string_callback_adapter, &dgs);
6011   if (status == 0)
6012     {
6013       free (dgs.buf);
6014       *palc = 0;
6015       return NULL;
6016     }
6017 
6018   *palc = dgs.allocation_failure ? 1 : dgs.alc;
6019   return dgs.buf;
6020 }
6021 
6022 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
6023 
6024 extern char *__cxa_demangle (const char *, char *, size_t *, int *);
6025 
6026 /* ia64 ABI-mandated entry point in the C++ runtime library for
6027    performing demangling.  MANGLED_NAME is a NUL-terminated character
6028    string containing the name to be demangled.
6029 
6030    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
6031    *LENGTH bytes, into which the demangled name is stored.  If
6032    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
6033    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
6034    is placed in a region of memory allocated with malloc.
6035 
6036    If LENGTH is non-NULL, the length of the buffer containing the
6037    demangled name, is placed in *LENGTH.
6038 
6039    The return value is a pointer to the start of the NUL-terminated
6040    demangled name, or NULL if the demangling fails.  The caller is
6041    responsible for deallocating this memory using free.
6042 
6043    *STATUS is set to one of the following values:
6044       0: The demangling operation succeeded.
6045      -1: A memory allocation failure occurred.
6046      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
6047      -3: One of the arguments is invalid.
6048 
6049    The demangling is performed using the C++ ABI mangling rules, with
6050    GNU extensions.  */
6051 
6052 char *
6053 __cxa_demangle (const char *mangled_name, char *output_buffer,
6054                 size_t *length, int *status)
6055 {
6056   char *demangled;
6057   size_t alc;
6058 
6059   if (mangled_name == NULL)
6060     {
6061       if (status != NULL)
6062 	*status = -3;
6063       return NULL;
6064     }
6065 
6066   if (output_buffer != NULL && length == NULL)
6067     {
6068       if (status != NULL)
6069 	*status = -3;
6070       return NULL;
6071     }
6072 
6073   demangled = d_demangle (mangled_name, DMGL_PARAMS | DMGL_TYPES, &alc);
6074 
6075   if (demangled == NULL)
6076     {
6077       if (status != NULL)
6078 	{
6079 	  if (alc == 1)
6080 	    *status = -1;
6081 	  else
6082 	    *status = -2;
6083 	}
6084       return NULL;
6085     }
6086 
6087   if (output_buffer == NULL)
6088     {
6089       if (length != NULL)
6090 	*length = alc;
6091     }
6092   else
6093     {
6094       if (strlen (demangled) < *length)
6095 	{
6096 	  strcpy (output_buffer, demangled);
6097 	  free (demangled);
6098 	  demangled = output_buffer;
6099 	}
6100       else
6101 	{
6102 	  free (output_buffer);
6103 	  *length = alc;
6104 	}
6105     }
6106 
6107   if (status != NULL)
6108     *status = 0;
6109 
6110   return demangled;
6111 }
6112 
6113 extern int __gcclibcxx_demangle_callback (const char *,
6114                                           void (*)
6115                                             (const char *, size_t, void *),
6116                                           void *);
6117 
6118 /* Alternative, allocationless entry point in the C++ runtime library
6119    for performing demangling.  MANGLED_NAME is a NUL-terminated character
6120    string containing the name to be demangled.
6121 
6122    CALLBACK is a callback function, called with demangled string
6123    segments as demangling progresses; it is called at least once,
6124    but may be called more than once.  OPAQUE is a generalized pointer
6125    used as a callback argument.
6126 
6127    The return code is one of the following values, equivalent to
6128    the STATUS values of __cxa_demangle() (excluding -1, since this
6129    function performs no memory allocations):
6130       0: The demangling operation succeeded.
6131      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
6132      -3: One of the arguments is invalid.
6133 
6134    The demangling is performed using the C++ ABI mangling rules, with
6135    GNU extensions.  */
6136 
6137 int
6138 __gcclibcxx_demangle_callback (const char *mangled_name,
6139                                void (*callback) (const char *, size_t, void *),
6140                                void *opaque)
6141 {
6142   int status;
6143 
6144   if (mangled_name == NULL || callback == NULL)
6145     return -3;
6146 
6147   status = d_demangle_callback (mangled_name, DMGL_PARAMS | DMGL_TYPES,
6148                                 callback, opaque);
6149   if (status == 0)
6150     return -2;
6151 
6152   return 0;
6153 }
6154 
6155 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
6156 
6157 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
6158    mangled name, return a buffer allocated with malloc holding the
6159    demangled name.  Otherwise, return NULL.  */
6160 
6161 char *
6162 cplus_demangle_v3 (const char *mangled, int options)
6163 {
6164   size_t alc;
6165 
6166   return d_demangle (mangled, options, &alc);
6167 }
6168 
6169 int
6170 cplus_demangle_v3_callback (const char *mangled, int options,
6171                             demangle_callbackref callback, void *opaque)
6172 {
6173   return d_demangle_callback (mangled, options, callback, opaque);
6174 }
6175 
6176 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling
6177    conventions, but the output formatting is a little different.
6178    This instructs the C++ demangler not to emit pointer characters ("*"), to
6179    use Java's namespace separator symbol ("." instead of "::"), and to output
6180    JArray<TYPE> as TYPE[].  */
6181 
6182 char *
6183 java_demangle_v3 (const char *mangled)
6184 {
6185   size_t alc;
6186 
6187   return d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX, &alc);
6188 }
6189 
6190 int
6191 java_demangle_v3_callback (const char *mangled,
6192                            demangle_callbackref callback, void *opaque)
6193 {
6194   return d_demangle_callback (mangled,
6195                               DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX,
6196                               callback, opaque);
6197 }
6198 
6199 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
6200 
6201 #ifndef IN_GLIBCPP_V3
6202 
6203 /* Demangle a string in order to find out whether it is a constructor
6204    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
6205    *DTOR_KIND appropriately.  */
6206 
6207 static int
6208 is_ctor_or_dtor (const char *mangled,
6209                  enum gnu_v3_ctor_kinds *ctor_kind,
6210                  enum gnu_v3_dtor_kinds *dtor_kind)
6211 {
6212   struct d_info di;
6213   struct demangle_component *dc;
6214   int ret;
6215 
6216   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
6217   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
6218 
6219   cplus_demangle_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
6220 
6221   {
6222 #ifdef CP_DYNAMIC_ARRAYS
6223     __extension__ struct demangle_component comps[di.num_comps];
6224     __extension__ struct demangle_component *subs[di.num_subs];
6225 
6226     di.comps = comps;
6227     di.subs = subs;
6228 #else
6229     di.comps = alloca (di.num_comps * sizeof (*di.comps));
6230     di.subs = alloca (di.num_subs * sizeof (*di.subs));
6231 #endif
6232 
6233     dc = cplus_demangle_mangled_name (&di, 1);
6234 
6235     /* Note that because we did not pass DMGL_PARAMS, we don't expect
6236        to demangle the entire string.  */
6237 
6238     ret = 0;
6239     while (dc != NULL)
6240       {
6241 	switch (dc->type)
6242 	  {
6243 	    /* These cannot appear on a constructor or destructor.  */
6244 	  case DEMANGLE_COMPONENT_RESTRICT_THIS:
6245 	  case DEMANGLE_COMPONENT_VOLATILE_THIS:
6246 	  case DEMANGLE_COMPONENT_CONST_THIS:
6247 	  case DEMANGLE_COMPONENT_REFERENCE_THIS:
6248 	  case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
6249 	  case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
6250 	  default:
6251 	    dc = NULL;
6252 	    break;
6253 	  case DEMANGLE_COMPONENT_TYPED_NAME:
6254 	  case DEMANGLE_COMPONENT_TEMPLATE:
6255 	    dc = d_left (dc);
6256 	    break;
6257 	  case DEMANGLE_COMPONENT_QUAL_NAME:
6258 	  case DEMANGLE_COMPONENT_LOCAL_NAME:
6259 	    dc = d_right (dc);
6260 	    break;
6261 	  case DEMANGLE_COMPONENT_CTOR:
6262 	    *ctor_kind = dc->u.s_ctor.kind;
6263 	    ret = 1;
6264 	    dc = NULL;
6265 	    break;
6266 	  case DEMANGLE_COMPONENT_DTOR:
6267 	    *dtor_kind = dc->u.s_dtor.kind;
6268 	    ret = 1;
6269 	    dc = NULL;
6270 	    break;
6271 	  }
6272       }
6273   }
6274 
6275   return ret;
6276 }
6277 
6278 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
6279    name.  A non-zero return indicates the type of constructor.  */
6280 
6281 enum gnu_v3_ctor_kinds
6282 is_gnu_v3_mangled_ctor (const char *name)
6283 {
6284   enum gnu_v3_ctor_kinds ctor_kind;
6285   enum gnu_v3_dtor_kinds dtor_kind;
6286 
6287   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6288     return (enum gnu_v3_ctor_kinds) 0;
6289   return ctor_kind;
6290 }
6291 
6292 
6293 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
6294    name.  A non-zero return indicates the type of destructor.  */
6295 
6296 enum gnu_v3_dtor_kinds
6297 is_gnu_v3_mangled_dtor (const char *name)
6298 {
6299   enum gnu_v3_ctor_kinds ctor_kind;
6300   enum gnu_v3_dtor_kinds dtor_kind;
6301 
6302   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6303     return (enum gnu_v3_dtor_kinds) 0;
6304   return dtor_kind;
6305 }
6306 
6307 #endif /* IN_GLIBCPP_V3 */
6308 
6309 #ifdef STANDALONE_DEMANGLER
6310 
6311 #include "getopt.h"
6312 #include "dyn-string.h"
6313 
6314 static void print_usage (FILE* fp, int exit_value);
6315 
6316 #define IS_ALPHA(CHAR)                                                  \
6317   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
6318    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
6319 
6320 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
6321 #define is_mangled_char(CHAR)                                           \
6322   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
6323    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
6324 
6325 /* The name of this program, as invoked.  */
6326 const char* program_name;
6327 
6328 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
6329 
6330 static void
6331 print_usage (FILE* fp, int exit_value)
6332 {
6333   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
6334   fprintf (fp, "Options:\n");
6335   fprintf (fp, "  -h,--help       Display this message.\n");
6336   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
6337   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
6338   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
6339 
6340   exit (exit_value);
6341 }
6342 
6343 /* Option specification for getopt_long.  */
6344 static const struct option long_options[] =
6345 {
6346   { "help",	 no_argument, NULL, 'h' },
6347   { "no-params", no_argument, NULL, 'p' },
6348   { "verbose",   no_argument, NULL, 'v' },
6349   { NULL,        no_argument, NULL, 0   },
6350 };
6351 
6352 /* Main entry for a demangling filter executable.  It will demangle
6353    its command line arguments, if any.  If none are provided, it will
6354    filter stdin to stdout, replacing any recognized mangled C++ names
6355    with their demangled equivalents.  */
6356 
6357 int
6358 main (int argc, char *argv[])
6359 {
6360   int i;
6361   int opt_char;
6362   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
6363 
6364   /* Use the program name of this program, as invoked.  */
6365   program_name = argv[0];
6366 
6367   /* Parse options.  */
6368   do
6369     {
6370       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
6371       switch (opt_char)
6372 	{
6373 	case '?':  /* Unrecognized option.  */
6374 	  print_usage (stderr, 1);
6375 	  break;
6376 
6377 	case 'h':
6378 	  print_usage (stdout, 0);
6379 	  break;
6380 
6381 	case 'p':
6382 	  options &= ~ DMGL_PARAMS;
6383 	  break;
6384 
6385 	case 'v':
6386 	  options |= DMGL_VERBOSE;
6387 	  break;
6388 	}
6389     }
6390   while (opt_char != -1);
6391 
6392   if (optind == argc)
6393     /* No command line arguments were provided.  Filter stdin.  */
6394     {
6395       dyn_string_t mangled = dyn_string_new (3);
6396       char *s;
6397 
6398       /* Read all of input.  */
6399       while (!feof (stdin))
6400 	{
6401 	  char c;
6402 
6403 	  /* Pile characters into mangled until we hit one that can't
6404 	     occur in a mangled name.  */
6405 	  c = getchar ();
6406 	  while (!feof (stdin) && is_mangled_char (c))
6407 	    {
6408 	      dyn_string_append_char (mangled, c);
6409 	      if (feof (stdin))
6410 		break;
6411 	      c = getchar ();
6412 	    }
6413 
6414 	  if (dyn_string_length (mangled) > 0)
6415 	    {
6416 #ifdef IN_GLIBCPP_V3
6417 	      s = __cxa_demangle (dyn_string_buf (mangled), NULL, NULL, NULL);
6418 #else
6419 	      s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
6420 #endif
6421 
6422 	      if (s != NULL)
6423 		{
6424 		  fputs (s, stdout);
6425 		  free (s);
6426 		}
6427 	      else
6428 		{
6429 		  /* It might not have been a mangled name.  Print the
6430 		     original text.  */
6431 		  fputs (dyn_string_buf (mangled), stdout);
6432 		}
6433 
6434 	      dyn_string_clear (mangled);
6435 	    }
6436 
6437 	  /* If we haven't hit EOF yet, we've read one character that
6438 	     can't occur in a mangled name, so print it out.  */
6439 	  if (!feof (stdin))
6440 	    putchar (c);
6441 	}
6442 
6443       dyn_string_delete (mangled);
6444     }
6445   else
6446     /* Demangle command line arguments.  */
6447     {
6448       /* Loop over command line arguments.  */
6449       for (i = optind; i < argc; ++i)
6450 	{
6451 	  char *s;
6452 #ifdef IN_GLIBCPP_V3
6453 	  int status;
6454 #endif
6455 
6456 	  /* Attempt to demangle.  */
6457 #ifdef IN_GLIBCPP_V3
6458 	  s = __cxa_demangle (argv[i], NULL, NULL, &status);
6459 #else
6460 	  s = cplus_demangle_v3 (argv[i], options);
6461 #endif
6462 
6463 	  /* If it worked, print the demangled name.  */
6464 	  if (s != NULL)
6465 	    {
6466 	      printf ("%s\n", s);
6467 	      free (s);
6468 	    }
6469 	  else
6470 	    {
6471 #ifdef IN_GLIBCPP_V3
6472 	      fprintf (stderr, "Failed: %s (status %d)\n", argv[i], status);
6473 #else
6474 	      fprintf (stderr, "Failed: %s\n", argv[i]);
6475 #endif
6476 	    }
6477 	}
6478     }
6479 
6480   return 0;
6481 }
6482 
6483 #endif /* STANDALONE_DEMANGLER */
6484