]> Git Repo - binutils.git/blob - gdb/gdbtypes.c
Simplify Ada catchpoints
[binutils.git] / gdb / gdbtypes.c
1 /* Support routines for manipulating internal types for GDB.
2
3    Copyright (C) 1992-2022 Free Software Foundation, Inc.
4
5    Contributed by Cygnus Support, using pieces from other GDB modules.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "bfd.h"
24 #include "symtab.h"
25 #include "symfile.h"
26 #include "objfiles.h"
27 #include "gdbtypes.h"
28 #include "expression.h"
29 #include "language.h"
30 #include "target.h"
31 #include "value.h"
32 #include "demangle.h"
33 #include "complaints.h"
34 #include "gdbcmd.h"
35 #include "cp-abi.h"
36 #include "hashtab.h"
37 #include "cp-support.h"
38 #include "bcache.h"
39 #include "dwarf2/loc.h"
40 #include "dwarf2/read.h"
41 #include "gdbcore.h"
42 #include "floatformat.h"
43 #include "f-lang.h"
44 #include <algorithm>
45 #include "gmp-utils.h"
46
47 /* Initialize BADNESS constants.  */
48
49 const struct rank LENGTH_MISMATCH_BADNESS = {100,0};
50
51 const struct rank TOO_FEW_PARAMS_BADNESS = {100,0};
52 const struct rank INCOMPATIBLE_TYPE_BADNESS = {100,0};
53
54 const struct rank EXACT_MATCH_BADNESS = {0,0};
55
56 const struct rank INTEGER_PROMOTION_BADNESS = {1,0};
57 const struct rank FLOAT_PROMOTION_BADNESS = {1,0};
58 const struct rank BASE_PTR_CONVERSION_BADNESS = {1,0};
59 const struct rank CV_CONVERSION_BADNESS = {1, 0};
60 const struct rank INTEGER_CONVERSION_BADNESS = {2,0};
61 const struct rank FLOAT_CONVERSION_BADNESS = {2,0};
62 const struct rank INT_FLOAT_CONVERSION_BADNESS = {2,0};
63 const struct rank VOID_PTR_CONVERSION_BADNESS = {2,0};
64 const struct rank BOOL_CONVERSION_BADNESS = {3,0};
65 const struct rank BASE_CONVERSION_BADNESS = {2,0};
66 const struct rank REFERENCE_CONVERSION_BADNESS = {2,0};
67 const struct rank REFERENCE_SEE_THROUGH_BADNESS = {0,1};
68 const struct rank NULL_POINTER_CONVERSION_BADNESS = {2,0};
69 const struct rank NS_POINTER_CONVERSION_BADNESS = {10,0};
70 const struct rank NS_INTEGER_POINTER_CONVERSION_BADNESS = {3,0};
71
72 /* Floatformat pairs.  */
73 const struct floatformat *floatformats_ieee_half[BFD_ENDIAN_UNKNOWN] = {
74   &floatformat_ieee_half_big,
75   &floatformat_ieee_half_little
76 };
77 const struct floatformat *floatformats_ieee_single[BFD_ENDIAN_UNKNOWN] = {
78   &floatformat_ieee_single_big,
79   &floatformat_ieee_single_little
80 };
81 const struct floatformat *floatformats_ieee_double[BFD_ENDIAN_UNKNOWN] = {
82   &floatformat_ieee_double_big,
83   &floatformat_ieee_double_little
84 };
85 const struct floatformat *floatformats_ieee_double_littlebyte_bigword[BFD_ENDIAN_UNKNOWN] = {
86   &floatformat_ieee_double_big,
87   &floatformat_ieee_double_littlebyte_bigword
88 };
89 const struct floatformat *floatformats_i387_ext[BFD_ENDIAN_UNKNOWN] = {
90   &floatformat_i387_ext,
91   &floatformat_i387_ext
92 };
93 const struct floatformat *floatformats_m68881_ext[BFD_ENDIAN_UNKNOWN] = {
94   &floatformat_m68881_ext,
95   &floatformat_m68881_ext
96 };
97 const struct floatformat *floatformats_arm_ext[BFD_ENDIAN_UNKNOWN] = {
98   &floatformat_arm_ext_big,
99   &floatformat_arm_ext_littlebyte_bigword
100 };
101 const struct floatformat *floatformats_ia64_spill[BFD_ENDIAN_UNKNOWN] = {
102   &floatformat_ia64_spill_big,
103   &floatformat_ia64_spill_little
104 };
105 const struct floatformat *floatformats_ia64_quad[BFD_ENDIAN_UNKNOWN] = {
106   &floatformat_ia64_quad_big,
107   &floatformat_ia64_quad_little
108 };
109 const struct floatformat *floatformats_vax_f[BFD_ENDIAN_UNKNOWN] = {
110   &floatformat_vax_f,
111   &floatformat_vax_f
112 };
113 const struct floatformat *floatformats_vax_d[BFD_ENDIAN_UNKNOWN] = {
114   &floatformat_vax_d,
115   &floatformat_vax_d
116 };
117 const struct floatformat *floatformats_ibm_long_double[BFD_ENDIAN_UNKNOWN] = {
118   &floatformat_ibm_long_double_big,
119   &floatformat_ibm_long_double_little
120 };
121 const struct floatformat *floatformats_bfloat16[BFD_ENDIAN_UNKNOWN] = {
122   &floatformat_bfloat16_big,
123   &floatformat_bfloat16_little
124 };
125
126 /* Should opaque types be resolved?  */
127
128 static bool opaque_type_resolution = true;
129
130 /* See gdbtypes.h.  */
131
132 unsigned int overload_debug = 0;
133
134 /* A flag to enable strict type checking.  */
135
136 static bool strict_type_checking = true;
137
138 /* A function to show whether opaque types are resolved.  */
139
140 static void
141 show_opaque_type_resolution (struct ui_file *file, int from_tty,
142                              struct cmd_list_element *c, 
143                              const char *value)
144 {
145   fprintf_filtered (file, _("Resolution of opaque struct/class/union types "
146                             "(if set before loading symbols) is %s.\n"),
147                     value);
148 }
149
150 /* A function to show whether C++ overload debugging is enabled.  */
151
152 static void
153 show_overload_debug (struct ui_file *file, int from_tty,
154                      struct cmd_list_element *c, const char *value)
155 {
156   fprintf_filtered (file, _("Debugging of C++ overloading is %s.\n"), 
157                     value);
158 }
159
160 /* A function to show the status of strict type checking.  */
161
162 static void
163 show_strict_type_checking (struct ui_file *file, int from_tty,
164                            struct cmd_list_element *c, const char *value)
165 {
166   fprintf_filtered (file, _("Strict type checking is %s.\n"), value);
167 }
168
169 \f
170 /* Allocate a new OBJFILE-associated type structure and fill it
171    with some defaults.  Space for the type structure is allocated
172    on the objfile's objfile_obstack.  */
173
174 struct type *
175 alloc_type (struct objfile *objfile)
176 {
177   struct type *type;
178
179   gdb_assert (objfile != NULL);
180
181   /* Alloc the structure and start off with all fields zeroed.  */
182   type = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct type);
183   TYPE_MAIN_TYPE (type) = OBSTACK_ZALLOC (&objfile->objfile_obstack,
184                                           struct main_type);
185   OBJSTAT (objfile, n_types++);
186
187   type->set_owner (objfile);
188
189   /* Initialize the fields that might not be zero.  */
190
191   type->set_code (TYPE_CODE_UNDEF);
192   TYPE_CHAIN (type) = type;     /* Chain back to itself.  */
193
194   return type;
195 }
196
197 /* Allocate a new GDBARCH-associated type structure and fill it
198    with some defaults.  Space for the type structure is allocated
199    on the obstack associated with GDBARCH.  */
200
201 struct type *
202 alloc_type_arch (struct gdbarch *gdbarch)
203 {
204   struct type *type;
205
206   gdb_assert (gdbarch != NULL);
207
208   /* Alloc the structure and start off with all fields zeroed.  */
209
210   type = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct type);
211   TYPE_MAIN_TYPE (type) = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct main_type);
212
213   type->set_owner (gdbarch);
214
215   /* Initialize the fields that might not be zero.  */
216
217   type->set_code (TYPE_CODE_UNDEF);
218   TYPE_CHAIN (type) = type;     /* Chain back to itself.  */
219
220   return type;
221 }
222
223 /* If TYPE is objfile-associated, allocate a new type structure
224    associated with the same objfile.  If TYPE is gdbarch-associated,
225    allocate a new type structure associated with the same gdbarch.  */
226
227 struct type *
228 alloc_type_copy (const struct type *type)
229 {
230   if (type->is_objfile_owned ())
231     return alloc_type (type->objfile_owner ());
232   else
233     return alloc_type_arch (type->arch_owner ());
234 }
235
236 /* See gdbtypes.h.  */
237
238 gdbarch *
239 type::arch () const
240 {
241   struct gdbarch *arch;
242
243   if (this->is_objfile_owned ())
244     arch = this->objfile_owner ()->arch ();
245   else
246     arch = this->arch_owner ();
247
248   /* The ARCH can be NULL if TYPE is associated with neither an objfile nor
249      a gdbarch, however, this is very rare, and even then, in most cases
250      that type::arch is called, we assume that a non-NULL value is
251      returned.  */
252   gdb_assert (arch != nullptr);
253   return arch;
254 }
255
256 /* See gdbtypes.h.  */
257
258 struct type *
259 get_target_type (struct type *type)
260 {
261   if (type != NULL)
262     {
263       type = TYPE_TARGET_TYPE (type);
264       if (type != NULL)
265         type = check_typedef (type);
266     }
267
268   return type;
269 }
270
271 /* See gdbtypes.h.  */
272
273 unsigned int
274 type_length_units (struct type *type)
275 {
276   int unit_size = gdbarch_addressable_memory_unit_size (type->arch ());
277
278   return TYPE_LENGTH (type) / unit_size;
279 }
280
281 /* Alloc a new type instance structure, fill it with some defaults,
282    and point it at OLDTYPE.  Allocate the new type instance from the
283    same place as OLDTYPE.  */
284
285 static struct type *
286 alloc_type_instance (struct type *oldtype)
287 {
288   struct type *type;
289
290   /* Allocate the structure.  */
291
292   if (!oldtype->is_objfile_owned ())
293     type = GDBARCH_OBSTACK_ZALLOC (oldtype->arch_owner (), struct type);
294   else
295     type = OBSTACK_ZALLOC (&oldtype->objfile_owner ()->objfile_obstack,
296                            struct type);
297
298   TYPE_MAIN_TYPE (type) = TYPE_MAIN_TYPE (oldtype);
299
300   TYPE_CHAIN (type) = type;     /* Chain back to itself for now.  */
301
302   return type;
303 }
304
305 /* Clear all remnants of the previous type at TYPE, in preparation for
306    replacing it with something else.  Preserve owner information.  */
307
308 static void
309 smash_type (struct type *type)
310 {
311   bool objfile_owned = type->is_objfile_owned ();
312   objfile *objfile = type->objfile_owner ();
313   gdbarch *arch = type->arch_owner ();
314
315   memset (TYPE_MAIN_TYPE (type), 0, sizeof (struct main_type));
316
317   /* Restore owner information.  */
318   if (objfile_owned)
319     type->set_owner (objfile);
320   else
321     type->set_owner (arch);
322
323   /* For now, delete the rings.  */
324   TYPE_CHAIN (type) = type;
325
326   /* For now, leave the pointer/reference types alone.  */
327 }
328
329 /* Lookup a pointer to a type TYPE.  TYPEPTR, if nonzero, points
330    to a pointer to memory where the pointer type should be stored.
331    If *TYPEPTR is zero, update it to point to the pointer type we return.
332    We allocate new memory if needed.  */
333
334 struct type *
335 make_pointer_type (struct type *type, struct type **typeptr)
336 {
337   struct type *ntype;   /* New type */
338   struct type *chain;
339
340   ntype = TYPE_POINTER_TYPE (type);
341
342   if (ntype)
343     {
344       if (typeptr == 0)
345         return ntype;           /* Don't care about alloc, 
346                                    and have new type.  */
347       else if (*typeptr == 0)
348         {
349           *typeptr = ntype;     /* Tracking alloc, and have new type.  */
350           return ntype;
351         }
352     }
353
354   if (typeptr == 0 || *typeptr == 0)    /* We'll need to allocate one.  */
355     {
356       ntype = alloc_type_copy (type);
357       if (typeptr)
358         *typeptr = ntype;
359     }
360   else                  /* We have storage, but need to reset it.  */
361     {
362       ntype = *typeptr;
363       chain = TYPE_CHAIN (ntype);
364       smash_type (ntype);
365       TYPE_CHAIN (ntype) = chain;
366     }
367
368   TYPE_TARGET_TYPE (ntype) = type;
369   TYPE_POINTER_TYPE (type) = ntype;
370
371   /* FIXME!  Assumes the machine has only one representation for pointers!  */
372
373   TYPE_LENGTH (ntype) = gdbarch_ptr_bit (type->arch ()) / TARGET_CHAR_BIT;
374   ntype->set_code (TYPE_CODE_PTR);
375
376   /* Mark pointers as unsigned.  The target converts between pointers
377      and addresses (CORE_ADDRs) using gdbarch_pointer_to_address and
378      gdbarch_address_to_pointer.  */
379   ntype->set_is_unsigned (true);
380
381   /* Update the length of all the other variants of this type.  */
382   chain = TYPE_CHAIN (ntype);
383   while (chain != ntype)
384     {
385       TYPE_LENGTH (chain) = TYPE_LENGTH (ntype);
386       chain = TYPE_CHAIN (chain);
387     }
388
389   return ntype;
390 }
391
392 /* Given a type TYPE, return a type of pointers to that type.
393    May need to construct such a type if this is the first use.  */
394
395 struct type *
396 lookup_pointer_type (struct type *type)
397 {
398   return make_pointer_type (type, (struct type **) 0);
399 }
400
401 /* Lookup a C++ `reference' to a type TYPE.  TYPEPTR, if nonzero,
402    points to a pointer to memory where the reference type should be
403    stored.  If *TYPEPTR is zero, update it to point to the reference
404    type we return.  We allocate new memory if needed. REFCODE denotes
405    the kind of reference type to lookup (lvalue or rvalue reference).  */
406
407 struct type *
408 make_reference_type (struct type *type, struct type **typeptr,
409                       enum type_code refcode)
410 {
411   struct type *ntype;   /* New type */
412   struct type **reftype;
413   struct type *chain;
414
415   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
416
417   ntype = (refcode == TYPE_CODE_REF ? TYPE_REFERENCE_TYPE (type)
418            : TYPE_RVALUE_REFERENCE_TYPE (type));
419
420   if (ntype)
421     {
422       if (typeptr == 0)
423         return ntype;           /* Don't care about alloc, 
424                                    and have new type.  */
425       else if (*typeptr == 0)
426         {
427           *typeptr = ntype;     /* Tracking alloc, and have new type.  */
428           return ntype;
429         }
430     }
431
432   if (typeptr == 0 || *typeptr == 0)    /* We'll need to allocate one.  */
433     {
434       ntype = alloc_type_copy (type);
435       if (typeptr)
436         *typeptr = ntype;
437     }
438   else                  /* We have storage, but need to reset it.  */
439     {
440       ntype = *typeptr;
441       chain = TYPE_CHAIN (ntype);
442       smash_type (ntype);
443       TYPE_CHAIN (ntype) = chain;
444     }
445
446   TYPE_TARGET_TYPE (ntype) = type;
447   reftype = (refcode == TYPE_CODE_REF ? &TYPE_REFERENCE_TYPE (type)
448              : &TYPE_RVALUE_REFERENCE_TYPE (type));
449
450   *reftype = ntype;
451
452   /* FIXME!  Assume the machine has only one representation for
453      references, and that it matches the (only) representation for
454      pointers!  */
455
456   TYPE_LENGTH (ntype) = gdbarch_ptr_bit (type->arch ()) / TARGET_CHAR_BIT;
457   ntype->set_code (refcode);
458
459   *reftype = ntype;
460
461   /* Update the length of all the other variants of this type.  */
462   chain = TYPE_CHAIN (ntype);
463   while (chain != ntype)
464     {
465       TYPE_LENGTH (chain) = TYPE_LENGTH (ntype);
466       chain = TYPE_CHAIN (chain);
467     }
468
469   return ntype;
470 }
471
472 /* Same as above, but caller doesn't care about memory allocation
473    details.  */
474
475 struct type *
476 lookup_reference_type (struct type *type, enum type_code refcode)
477 {
478   return make_reference_type (type, (struct type **) 0, refcode);
479 }
480
481 /* Lookup the lvalue reference type for the type TYPE.  */
482
483 struct type *
484 lookup_lvalue_reference_type (struct type *type)
485 {
486   return lookup_reference_type (type, TYPE_CODE_REF);
487 }
488
489 /* Lookup the rvalue reference type for the type TYPE.  */
490
491 struct type *
492 lookup_rvalue_reference_type (struct type *type)
493 {
494   return lookup_reference_type (type, TYPE_CODE_RVALUE_REF);
495 }
496
497 /* Lookup a function type that returns type TYPE.  TYPEPTR, if
498    nonzero, points to a pointer to memory where the function type
499    should be stored.  If *TYPEPTR is zero, update it to point to the
500    function type we return.  We allocate new memory if needed.  */
501
502 struct type *
503 make_function_type (struct type *type, struct type **typeptr)
504 {
505   struct type *ntype;   /* New type */
506
507   if (typeptr == 0 || *typeptr == 0)    /* We'll need to allocate one.  */
508     {
509       ntype = alloc_type_copy (type);
510       if (typeptr)
511         *typeptr = ntype;
512     }
513   else                  /* We have storage, but need to reset it.  */
514     {
515       ntype = *typeptr;
516       smash_type (ntype);
517     }
518
519   TYPE_TARGET_TYPE (ntype) = type;
520
521   TYPE_LENGTH (ntype) = 1;
522   ntype->set_code (TYPE_CODE_FUNC);
523
524   INIT_FUNC_SPECIFIC (ntype);
525
526   return ntype;
527 }
528
529 /* Given a type TYPE, return a type of functions that return that type.
530    May need to construct such a type if this is the first use.  */
531
532 struct type *
533 lookup_function_type (struct type *type)
534 {
535   return make_function_type (type, (struct type **) 0);
536 }
537
538 /* Given a type TYPE and argument types, return the appropriate
539    function type.  If the final type in PARAM_TYPES is NULL, make a
540    varargs function.  */
541
542 struct type *
543 lookup_function_type_with_arguments (struct type *type,
544                                      int nparams,
545                                      struct type **param_types)
546 {
547   struct type *fn = make_function_type (type, (struct type **) 0);
548   int i;
549
550   if (nparams > 0)
551     {
552       if (param_types[nparams - 1] == NULL)
553         {
554           --nparams;
555           fn->set_has_varargs (true);
556         }
557       else if (check_typedef (param_types[nparams - 1])->code ()
558                == TYPE_CODE_VOID)
559         {
560           --nparams;
561           /* Caller should have ensured this.  */
562           gdb_assert (nparams == 0);
563           fn->set_is_prototyped (true);
564         }
565       else
566         fn->set_is_prototyped (true);
567     }
568
569   fn->set_num_fields (nparams);
570   fn->set_fields
571     ((struct field *) TYPE_ZALLOC (fn, nparams * sizeof (struct field)));
572   for (i = 0; i < nparams; ++i)
573     fn->field (i).set_type (param_types[i]);
574
575   return fn;
576 }
577
578 /* Identify address space identifier by name -- return a
579    type_instance_flags.  */
580
581 type_instance_flags
582 address_space_name_to_type_instance_flags (struct gdbarch *gdbarch,
583                                            const char *space_identifier)
584 {
585   type_instance_flags type_flags;
586
587   /* Check for known address space delimiters.  */
588   if (!strcmp (space_identifier, "code"))
589     return TYPE_INSTANCE_FLAG_CODE_SPACE;
590   else if (!strcmp (space_identifier, "data"))
591     return TYPE_INSTANCE_FLAG_DATA_SPACE;
592   else if (gdbarch_address_class_name_to_type_flags_p (gdbarch)
593            && gdbarch_address_class_name_to_type_flags (gdbarch,
594                                                         space_identifier,
595                                                         &type_flags))
596     return type_flags;
597   else
598     error (_("Unknown address space specifier: \"%s\""), space_identifier);
599 }
600
601 /* Identify address space identifier by type_instance_flags and return
602    the string version of the adress space name.  */
603
604 const char *
605 address_space_type_instance_flags_to_name (struct gdbarch *gdbarch,
606                                            type_instance_flags space_flag)
607 {
608   if (space_flag & TYPE_INSTANCE_FLAG_CODE_SPACE)
609     return "code";
610   else if (space_flag & TYPE_INSTANCE_FLAG_DATA_SPACE)
611     return "data";
612   else if ((space_flag & TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
613            && gdbarch_address_class_type_flags_to_name_p (gdbarch))
614     return gdbarch_address_class_type_flags_to_name (gdbarch, space_flag);
615   else
616     return NULL;
617 }
618
619 /* Create a new type with instance flags NEW_FLAGS, based on TYPE.
620
621    If STORAGE is non-NULL, create the new type instance there.
622    STORAGE must be in the same obstack as TYPE.  */
623
624 static struct type *
625 make_qualified_type (struct type *type, type_instance_flags new_flags,
626                      struct type *storage)
627 {
628   struct type *ntype;
629
630   ntype = type;
631   do
632     {
633       if (ntype->instance_flags () == new_flags)
634         return ntype;
635       ntype = TYPE_CHAIN (ntype);
636     }
637   while (ntype != type);
638
639   /* Create a new type instance.  */
640   if (storage == NULL)
641     ntype = alloc_type_instance (type);
642   else
643     {
644       /* If STORAGE was provided, it had better be in the same objfile
645          as TYPE.  Otherwise, we can't link it into TYPE's cv chain:
646          if one objfile is freed and the other kept, we'd have
647          dangling pointers.  */
648       gdb_assert (type->objfile_owner () == storage->objfile_owner ());
649
650       ntype = storage;
651       TYPE_MAIN_TYPE (ntype) = TYPE_MAIN_TYPE (type);
652       TYPE_CHAIN (ntype) = ntype;
653     }
654
655   /* Pointers or references to the original type are not relevant to
656      the new type.  */
657   TYPE_POINTER_TYPE (ntype) = (struct type *) 0;
658   TYPE_REFERENCE_TYPE (ntype) = (struct type *) 0;
659
660   /* Chain the new qualified type to the old type.  */
661   TYPE_CHAIN (ntype) = TYPE_CHAIN (type);
662   TYPE_CHAIN (type) = ntype;
663
664   /* Now set the instance flags and return the new type.  */
665   ntype->set_instance_flags (new_flags);
666
667   /* Set length of new type to that of the original type.  */
668   TYPE_LENGTH (ntype) = TYPE_LENGTH (type);
669
670   return ntype;
671 }
672
673 /* Make an address-space-delimited variant of a type -- a type that
674    is identical to the one supplied except that it has an address
675    space attribute attached to it (such as "code" or "data").
676
677    The space attributes "code" and "data" are for Harvard
678    architectures.  The address space attributes are for architectures
679    which have alternately sized pointers or pointers with alternate
680    representations.  */
681
682 struct type *
683 make_type_with_address_space (struct type *type,
684                               type_instance_flags space_flag)
685 {
686   type_instance_flags new_flags = ((type->instance_flags ()
687                                     & ~(TYPE_INSTANCE_FLAG_CODE_SPACE
688                                         | TYPE_INSTANCE_FLAG_DATA_SPACE
689                                         | TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL))
690                                    | space_flag);
691
692   return make_qualified_type (type, new_flags, NULL);
693 }
694
695 /* Make a "c-v" variant of a type -- a type that is identical to the
696    one supplied except that it may have const or volatile attributes
697    CNST is a flag for setting the const attribute
698    VOLTL is a flag for setting the volatile attribute
699    TYPE is the base type whose variant we are creating.
700
701    If TYPEPTR and *TYPEPTR are non-zero, then *TYPEPTR points to
702    storage to hold the new qualified type; *TYPEPTR and TYPE must be
703    in the same objfile.  Otherwise, allocate fresh memory for the new
704    type whereever TYPE lives.  If TYPEPTR is non-zero, set it to the
705    new type we construct.  */
706
707 struct type *
708 make_cv_type (int cnst, int voltl, 
709               struct type *type, 
710               struct type **typeptr)
711 {
712   struct type *ntype;   /* New type */
713
714   type_instance_flags new_flags = (type->instance_flags ()
715                                    & ~(TYPE_INSTANCE_FLAG_CONST
716                                        | TYPE_INSTANCE_FLAG_VOLATILE));
717
718   if (cnst)
719     new_flags |= TYPE_INSTANCE_FLAG_CONST;
720
721   if (voltl)
722     new_flags |= TYPE_INSTANCE_FLAG_VOLATILE;
723
724   if (typeptr && *typeptr != NULL)
725     {
726       /* TYPE and *TYPEPTR must be in the same objfile.  We can't have
727          a C-V variant chain that threads across objfiles: if one
728          objfile gets freed, then the other has a broken C-V chain.
729
730          This code used to try to copy over the main type from TYPE to
731          *TYPEPTR if they were in different objfiles, but that's
732          wrong, too: TYPE may have a field list or member function
733          lists, which refer to types of their own, etc. etc.  The
734          whole shebang would need to be copied over recursively; you
735          can't have inter-objfile pointers.  The only thing to do is
736          to leave stub types as stub types, and look them up afresh by
737          name each time you encounter them.  */
738       gdb_assert ((*typeptr)->objfile_owner () == type->objfile_owner ());
739     }
740   
741   ntype = make_qualified_type (type, new_flags, 
742                                typeptr ? *typeptr : NULL);
743
744   if (typeptr != NULL)
745     *typeptr = ntype;
746
747   return ntype;
748 }
749
750 /* Make a 'restrict'-qualified version of TYPE.  */
751
752 struct type *
753 make_restrict_type (struct type *type)
754 {
755   return make_qualified_type (type,
756                               (type->instance_flags ()
757                                | TYPE_INSTANCE_FLAG_RESTRICT),
758                               NULL);
759 }
760
761 /* Make a type without const, volatile, or restrict.  */
762
763 struct type *
764 make_unqualified_type (struct type *type)
765 {
766   return make_qualified_type (type,
767                               (type->instance_flags ()
768                                & ~(TYPE_INSTANCE_FLAG_CONST
769                                    | TYPE_INSTANCE_FLAG_VOLATILE
770                                    | TYPE_INSTANCE_FLAG_RESTRICT)),
771                               NULL);
772 }
773
774 /* Make a '_Atomic'-qualified version of TYPE.  */
775
776 struct type *
777 make_atomic_type (struct type *type)
778 {
779   return make_qualified_type (type,
780                               (type->instance_flags ()
781                                | TYPE_INSTANCE_FLAG_ATOMIC),
782                               NULL);
783 }
784
785 /* Replace the contents of ntype with the type *type.  This changes the
786    contents, rather than the pointer for TYPE_MAIN_TYPE (ntype); thus
787    the changes are propogated to all types in the TYPE_CHAIN.
788
789    In order to build recursive types, it's inevitable that we'll need
790    to update types in place --- but this sort of indiscriminate
791    smashing is ugly, and needs to be replaced with something more
792    controlled.  TYPE_MAIN_TYPE is a step in this direction; it's not
793    clear if more steps are needed.  */
794
795 void
796 replace_type (struct type *ntype, struct type *type)
797 {
798   struct type *chain;
799
800   /* These two types had better be in the same objfile.  Otherwise,
801      the assignment of one type's main type structure to the other
802      will produce a type with references to objects (names; field
803      lists; etc.) allocated on an objfile other than its own.  */
804   gdb_assert (ntype->objfile_owner () == type->objfile_owner ());
805
806   *TYPE_MAIN_TYPE (ntype) = *TYPE_MAIN_TYPE (type);
807
808   /* The type length is not a part of the main type.  Update it for
809      each type on the variant chain.  */
810   chain = ntype;
811   do
812     {
813       /* Assert that this element of the chain has no address-class bits
814          set in its flags.  Such type variants might have type lengths
815          which are supposed to be different from the non-address-class
816          variants.  This assertion shouldn't ever be triggered because
817          symbol readers which do construct address-class variants don't
818          call replace_type().  */
819       gdb_assert (TYPE_ADDRESS_CLASS_ALL (chain) == 0);
820
821       TYPE_LENGTH (chain) = TYPE_LENGTH (type);
822       chain = TYPE_CHAIN (chain);
823     }
824   while (ntype != chain);
825
826   /* Assert that the two types have equivalent instance qualifiers.
827      This should be true for at least all of our debug readers.  */
828   gdb_assert (ntype->instance_flags () == type->instance_flags ());
829 }
830
831 /* Implement direct support for MEMBER_TYPE in GNU C++.
832    May need to construct such a type if this is the first use.
833    The TYPE is the type of the member.  The DOMAIN is the type
834    of the aggregate that the member belongs to.  */
835
836 struct type *
837 lookup_memberptr_type (struct type *type, struct type *domain)
838 {
839   struct type *mtype;
840
841   mtype = alloc_type_copy (type);
842   smash_to_memberptr_type (mtype, domain, type);
843   return mtype;
844 }
845
846 /* Return a pointer-to-method type, for a method of type TO_TYPE.  */
847
848 struct type *
849 lookup_methodptr_type (struct type *to_type)
850 {
851   struct type *mtype;
852
853   mtype = alloc_type_copy (to_type);
854   smash_to_methodptr_type (mtype, to_type);
855   return mtype;
856 }
857
858 /* Allocate a stub method whose return type is TYPE.  This apparently
859    happens for speed of symbol reading, since parsing out the
860    arguments to the method is cpu-intensive, the way we are doing it.
861    So, we will fill in arguments later.  This always returns a fresh
862    type.  */
863
864 struct type *
865 allocate_stub_method (struct type *type)
866 {
867   struct type *mtype;
868
869   mtype = alloc_type_copy (type);
870   mtype->set_code (TYPE_CODE_METHOD);
871   TYPE_LENGTH (mtype) = 1;
872   mtype->set_is_stub (true);
873   TYPE_TARGET_TYPE (mtype) = type;
874   /* TYPE_SELF_TYPE (mtype) = unknown yet */
875   return mtype;
876 }
877
878 /* See gdbtypes.h.  */
879
880 bool
881 operator== (const dynamic_prop &l, const dynamic_prop &r)
882 {
883   if (l.kind () != r.kind ())
884     return false;
885
886   switch (l.kind ())
887     {
888     case PROP_UNDEFINED:
889       return true;
890     case PROP_CONST:
891       return l.const_val () == r.const_val ();
892     case PROP_ADDR_OFFSET:
893     case PROP_LOCEXPR:
894     case PROP_LOCLIST:
895       return l.baton () == r.baton ();
896     case PROP_VARIANT_PARTS:
897       return l.variant_parts () == r.variant_parts ();
898     case PROP_TYPE:
899       return l.original_type () == r.original_type ();
900     }
901
902   gdb_assert_not_reached ("unhandled dynamic_prop kind");
903 }
904
905 /* See gdbtypes.h.  */
906
907 bool
908 operator== (const range_bounds &l, const range_bounds &r)
909 {
910 #define FIELD_EQ(FIELD) (l.FIELD == r.FIELD)
911
912   return (FIELD_EQ (low)
913           && FIELD_EQ (high)
914           && FIELD_EQ (flag_upper_bound_is_count)
915           && FIELD_EQ (flag_bound_evaluated)
916           && FIELD_EQ (bias));
917
918 #undef FIELD_EQ
919 }
920
921 /* Create a range type with a dynamic range from LOW_BOUND to
922    HIGH_BOUND, inclusive.  See create_range_type for further details. */
923
924 struct type *
925 create_range_type (struct type *result_type, struct type *index_type,
926                    const struct dynamic_prop *low_bound,
927                    const struct dynamic_prop *high_bound,
928                    LONGEST bias)
929 {
930   /* The INDEX_TYPE should be a type capable of holding the upper and lower
931      bounds, as such a zero sized, or void type makes no sense.  */
932   gdb_assert (index_type->code () != TYPE_CODE_VOID);
933   gdb_assert (TYPE_LENGTH (index_type) > 0);
934
935   if (result_type == NULL)
936     result_type = alloc_type_copy (index_type);
937   result_type->set_code (TYPE_CODE_RANGE);
938   TYPE_TARGET_TYPE (result_type) = index_type;
939   if (index_type->is_stub ())
940     result_type->set_target_is_stub (true);
941   else
942     TYPE_LENGTH (result_type) = TYPE_LENGTH (check_typedef (index_type));
943
944   range_bounds *bounds
945     = (struct range_bounds *) TYPE_ZALLOC (result_type, sizeof (range_bounds));
946   bounds->low = *low_bound;
947   bounds->high = *high_bound;
948   bounds->bias = bias;
949   bounds->stride.set_const_val (0);
950
951   result_type->set_bounds (bounds);
952
953   if (index_type->code () == TYPE_CODE_FIXED_POINT)
954     result_type->set_is_unsigned (index_type->is_unsigned ());
955   /* Note that the signed-ness of a range type can't simply be copied
956      from the underlying type.  Consider a case where the underlying
957      type is 'int', but the range type can hold 0..65535, and where
958      the range is further specified to fit into 16 bits.  In this
959      case, if we copy the underlying type's sign, then reading some
960      range values will cause an unwanted sign extension.  So, we have
961      some heuristics here instead.  */
962   else if (low_bound->kind () == PROP_CONST && low_bound->const_val () >= 0)
963     result_type->set_is_unsigned (true);
964   /* Ada allows the declaration of range types whose upper bound is
965      less than the lower bound, so checking the lower bound is not
966      enough.  Make sure we do not mark a range type whose upper bound
967      is negative as unsigned.  */
968   if (high_bound->kind () == PROP_CONST && high_bound->const_val () < 0)
969     result_type->set_is_unsigned (false);
970
971   result_type->set_endianity_is_not_default
972     (index_type->endianity_is_not_default ());
973
974   return result_type;
975 }
976
977 /* See gdbtypes.h.  */
978
979 struct type *
980 create_range_type_with_stride (struct type *result_type,
981                                struct type *index_type,
982                                const struct dynamic_prop *low_bound,
983                                const struct dynamic_prop *high_bound,
984                                LONGEST bias,
985                                const struct dynamic_prop *stride,
986                                bool byte_stride_p)
987 {
988   result_type = create_range_type (result_type, index_type, low_bound,
989                                    high_bound, bias);
990
991   gdb_assert (stride != nullptr);
992   result_type->bounds ()->stride = *stride;
993   result_type->bounds ()->flag_is_byte_stride = byte_stride_p;
994
995   return result_type;
996 }
997
998
999
1000 /* Create a range type using either a blank type supplied in
1001    RESULT_TYPE, or creating a new type, inheriting the objfile from
1002    INDEX_TYPE.
1003
1004    Indices will be of type INDEX_TYPE, and will range from LOW_BOUND
1005    to HIGH_BOUND, inclusive.
1006
1007    FIXME: Maybe we should check the TYPE_CODE of RESULT_TYPE to make
1008    sure it is TYPE_CODE_UNDEF before we bash it into a range type?  */
1009
1010 struct type *
1011 create_static_range_type (struct type *result_type, struct type *index_type,
1012                           LONGEST low_bound, LONGEST high_bound)
1013 {
1014   struct dynamic_prop low, high;
1015
1016   low.set_const_val (low_bound);
1017   high.set_const_val (high_bound);
1018
1019   result_type = create_range_type (result_type, index_type, &low, &high, 0);
1020
1021   return result_type;
1022 }
1023
1024 /* Predicate tests whether BOUNDS are static.  Returns 1 if all bounds values
1025    are static, otherwise returns 0.  */
1026
1027 static bool
1028 has_static_range (const struct range_bounds *bounds)
1029 {
1030   /* If the range doesn't have a defined stride then its stride field will
1031      be initialized to the constant 0.  */
1032   return (bounds->low.kind () == PROP_CONST
1033           && bounds->high.kind () == PROP_CONST
1034           && bounds->stride.kind () == PROP_CONST);
1035 }
1036
1037 /* See gdbtypes.h.  */
1038
1039 gdb::optional<LONGEST>
1040 get_discrete_low_bound (struct type *type)
1041 {
1042   type = check_typedef (type);
1043   switch (type->code ())
1044     {
1045     case TYPE_CODE_RANGE:
1046       {
1047         /* This function only works for ranges with a constant low bound.  */
1048         if (type->bounds ()->low.kind () != PROP_CONST)
1049           return {};
1050
1051         LONGEST low = type->bounds ()->low.const_val ();
1052
1053         if (TYPE_TARGET_TYPE (type)->code () == TYPE_CODE_ENUM)
1054           {
1055             gdb::optional<LONGEST> low_pos
1056               = discrete_position (TYPE_TARGET_TYPE (type), low);
1057
1058             if (low_pos.has_value ())
1059               low = *low_pos;
1060           }
1061
1062         return low;
1063       }
1064
1065     case TYPE_CODE_ENUM:
1066       {
1067         if (type->num_fields () > 0)
1068           {
1069             /* The enums may not be sorted by value, so search all
1070                entries.  */
1071             LONGEST low = type->field (0).loc_enumval ();
1072
1073             for (int i = 0; i < type->num_fields (); i++)
1074               {
1075                 if (type->field (i).loc_enumval () < low)
1076                   low = type->field (i).loc_enumval ();
1077               }
1078
1079             /* Set unsigned indicator if warranted.  */
1080             if (low >= 0)
1081               type->set_is_unsigned (true);
1082
1083             return low;
1084           }
1085         else
1086           return 0;
1087       }
1088
1089     case TYPE_CODE_BOOL:
1090       return 0;
1091
1092     case TYPE_CODE_INT:
1093       if (TYPE_LENGTH (type) > sizeof (LONGEST))        /* Too big */
1094         return {};
1095
1096       if (!type->is_unsigned ())
1097         return -(1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1));
1098
1099       /* fall through */
1100     case TYPE_CODE_CHAR:
1101       return 0;
1102
1103     default:
1104       return {};
1105     }
1106 }
1107
1108 /* See gdbtypes.h.  */
1109
1110 gdb::optional<LONGEST>
1111 get_discrete_high_bound (struct type *type)
1112 {
1113   type = check_typedef (type);
1114   switch (type->code ())
1115     {
1116     case TYPE_CODE_RANGE:
1117       {
1118         /* This function only works for ranges with a constant high bound.  */
1119         if (type->bounds ()->high.kind () != PROP_CONST)
1120           return {};
1121
1122         LONGEST high = type->bounds ()->high.const_val ();
1123
1124         if (TYPE_TARGET_TYPE (type)->code () == TYPE_CODE_ENUM)
1125           {
1126             gdb::optional<LONGEST> high_pos
1127               = discrete_position (TYPE_TARGET_TYPE (type), high);
1128
1129             if (high_pos.has_value ())
1130               high = *high_pos;
1131           }
1132
1133         return high;
1134       }
1135
1136     case TYPE_CODE_ENUM:
1137       {
1138         if (type->num_fields () > 0)
1139           {
1140             /* The enums may not be sorted by value, so search all
1141                entries.  */
1142             LONGEST high = type->field (0).loc_enumval ();
1143
1144             for (int i = 0; i < type->num_fields (); i++)
1145               {
1146                 if (type->field (i).loc_enumval () > high)
1147                   high = type->field (i).loc_enumval ();
1148               }
1149
1150             return high;
1151           }
1152         else
1153           return -1;
1154       }
1155
1156     case TYPE_CODE_BOOL:
1157       return 1;
1158
1159     case TYPE_CODE_INT:
1160       if (TYPE_LENGTH (type) > sizeof (LONGEST))        /* Too big */
1161         return {};
1162
1163       if (!type->is_unsigned ())
1164         {
1165           LONGEST low = -(1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1));
1166           return -low - 1;
1167         }
1168
1169       /* fall through */
1170     case TYPE_CODE_CHAR:
1171       {
1172         /* This round-about calculation is to avoid shifting by
1173            TYPE_LENGTH (type) * TARGET_CHAR_BIT, which will not work
1174            if TYPE_LENGTH (type) == sizeof (LONGEST).  */
1175         LONGEST high = 1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1);
1176         return (high - 1) | high;
1177       }
1178
1179     default:
1180       return {};
1181     }
1182 }
1183
1184 /* See gdbtypes.h.  */
1185
1186 bool
1187 get_discrete_bounds (struct type *type, LONGEST *lowp, LONGEST *highp)
1188 {
1189   gdb::optional<LONGEST> low = get_discrete_low_bound (type);
1190   if (!low.has_value ())
1191     return false;
1192
1193   gdb::optional<LONGEST> high = get_discrete_high_bound (type);
1194   if (!high.has_value ())
1195     return false;
1196
1197   *lowp = *low;
1198   *highp = *high;
1199
1200   return true;
1201 }
1202
1203 /* See gdbtypes.h  */
1204
1205 bool
1206 get_array_bounds (struct type *type, LONGEST *low_bound, LONGEST *high_bound)
1207 {
1208   struct type *index = type->index_type ();
1209   LONGEST low = 0;
1210   LONGEST high = 0;
1211
1212   if (index == NULL)
1213     return false;
1214
1215   if (!get_discrete_bounds (index, &low, &high))
1216     return false;
1217
1218   if (low_bound)
1219     *low_bound = low;
1220
1221   if (high_bound)
1222     *high_bound = high;
1223
1224   return true;
1225 }
1226
1227 /* Assuming that TYPE is a discrete type and VAL is a valid integer
1228    representation of a value of this type, save the corresponding
1229    position number in POS.
1230
1231    Its differs from VAL only in the case of enumeration types.  In
1232    this case, the position number of the value of the first listed
1233    enumeration literal is zero; the position number of the value of
1234    each subsequent enumeration literal is one more than that of its
1235    predecessor in the list.
1236
1237    Return 1 if the operation was successful.  Return zero otherwise,
1238    in which case the value of POS is unmodified.
1239 */
1240
1241 gdb::optional<LONGEST>
1242 discrete_position (struct type *type, LONGEST val)
1243 {
1244   if (type->code () == TYPE_CODE_RANGE)
1245     type = TYPE_TARGET_TYPE (type);
1246
1247   if (type->code () == TYPE_CODE_ENUM)
1248     {
1249       int i;
1250
1251       for (i = 0; i < type->num_fields (); i += 1)
1252         {
1253           if (val == type->field (i).loc_enumval ())
1254             return i;
1255         }
1256
1257       /* Invalid enumeration value.  */
1258       return {};
1259     }
1260   else
1261     return val;
1262 }
1263
1264 /* If the array TYPE has static bounds calculate and update its
1265    size, then return true.  Otherwise return false and leave TYPE
1266    unchanged.  */
1267
1268 static bool
1269 update_static_array_size (struct type *type)
1270 {
1271   gdb_assert (type->code () == TYPE_CODE_ARRAY);
1272
1273   struct type *range_type = type->index_type ();
1274
1275   if (type->dyn_prop (DYN_PROP_BYTE_STRIDE) == nullptr
1276       && has_static_range (range_type->bounds ())
1277       && (!type_not_associated (type)
1278           && !type_not_allocated (type)))
1279     {
1280       LONGEST low_bound, high_bound;
1281       int stride;
1282       struct type *element_type;
1283
1284       stride = type->bit_stride ();
1285
1286       if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
1287         low_bound = high_bound = 0;
1288
1289       element_type = check_typedef (TYPE_TARGET_TYPE (type));
1290       /* Be careful when setting the array length.  Ada arrays can be
1291          empty arrays with the high_bound being smaller than the low_bound.
1292          In such cases, the array length should be zero.  */
1293       if (high_bound < low_bound)
1294         TYPE_LENGTH (type) = 0;
1295       else if (stride != 0)
1296         {
1297           /* Ensure that the type length is always positive, even in the
1298              case where (for example in Fortran) we have a negative
1299              stride.  It is possible to have a single element array with a
1300              negative stride in Fortran (this doesn't mean anything
1301              special, it's still just a single element array) so do
1302              consider that case when touching this code.  */
1303           LONGEST element_count = std::abs (high_bound - low_bound + 1);
1304           TYPE_LENGTH (type)
1305             = ((std::abs (stride) * element_count) + 7) / 8;
1306         }
1307       else
1308         TYPE_LENGTH (type) =
1309           TYPE_LENGTH (element_type) * (high_bound - low_bound + 1);
1310
1311       /* If this array's element is itself an array with a bit stride,
1312          then we want to update this array's bit stride to reflect the
1313          size of the sub-array.  Otherwise, we'll end up using the
1314          wrong size when trying to find elements of the outer
1315          array.  */
1316       if (element_type->code () == TYPE_CODE_ARRAY
1317           && TYPE_LENGTH (element_type) != 0
1318           && TYPE_FIELD_BITSIZE (element_type, 0) != 0
1319           && get_array_bounds (element_type, &low_bound, &high_bound)
1320           && high_bound >= low_bound)
1321         TYPE_FIELD_BITSIZE (type, 0)
1322           = ((high_bound - low_bound + 1)
1323              * TYPE_FIELD_BITSIZE (element_type, 0));
1324
1325       return true;
1326     }
1327
1328   return false;
1329 }
1330
1331 /* Create an array type using either a blank type supplied in
1332    RESULT_TYPE, or creating a new type, inheriting the objfile from
1333    RANGE_TYPE.
1334
1335    Elements will be of type ELEMENT_TYPE, the indices will be of type
1336    RANGE_TYPE.
1337
1338    BYTE_STRIDE_PROP, when not NULL, provides the array's byte stride.
1339    This byte stride property is added to the resulting array type
1340    as a DYN_PROP_BYTE_STRIDE.  As a consequence, the BYTE_STRIDE_PROP
1341    argument can only be used to create types that are objfile-owned
1342    (see add_dyn_prop), meaning that either this function must be called
1343    with an objfile-owned RESULT_TYPE, or an objfile-owned RANGE_TYPE.
1344
1345    BIT_STRIDE is taken into account only when BYTE_STRIDE_PROP is NULL.
1346    If BIT_STRIDE is not zero, build a packed array type whose element
1347    size is BIT_STRIDE.  Otherwise, ignore this parameter.
1348
1349    FIXME: Maybe we should check the TYPE_CODE of RESULT_TYPE to make
1350    sure it is TYPE_CODE_UNDEF before we bash it into an array
1351    type?  */
1352
1353 struct type *
1354 create_array_type_with_stride (struct type *result_type,
1355                                struct type *element_type,
1356                                struct type *range_type,
1357                                struct dynamic_prop *byte_stride_prop,
1358                                unsigned int bit_stride)
1359 {
1360   if (byte_stride_prop != NULL
1361       && byte_stride_prop->kind () == PROP_CONST)
1362     {
1363       /* The byte stride is actually not dynamic.  Pretend we were
1364          called with bit_stride set instead of byte_stride_prop.
1365          This will give us the same result type, while avoiding
1366          the need to handle this as a special case.  */
1367       bit_stride = byte_stride_prop->const_val () * 8;
1368       byte_stride_prop = NULL;
1369     }
1370
1371   if (result_type == NULL)
1372     result_type = alloc_type_copy (range_type);
1373
1374   result_type->set_code (TYPE_CODE_ARRAY);
1375   TYPE_TARGET_TYPE (result_type) = element_type;
1376
1377   result_type->set_num_fields (1);
1378   result_type->set_fields
1379     ((struct field *) TYPE_ZALLOC (result_type, sizeof (struct field)));
1380   result_type->set_index_type (range_type);
1381   if (byte_stride_prop != NULL)
1382     result_type->add_dyn_prop (DYN_PROP_BYTE_STRIDE, *byte_stride_prop);
1383   else if (bit_stride > 0)
1384     TYPE_FIELD_BITSIZE (result_type, 0) = bit_stride;
1385
1386   if (!update_static_array_size (result_type))
1387     {
1388       /* This type is dynamic and its length needs to be computed
1389          on demand.  In the meantime, avoid leaving the TYPE_LENGTH
1390          undefined by setting it to zero.  Although we are not expected
1391          to trust TYPE_LENGTH in this case, setting the size to zero
1392          allows us to avoid allocating objects of random sizes in case
1393          we accidently do.  */
1394       TYPE_LENGTH (result_type) = 0;
1395     }
1396
1397   /* TYPE_TARGET_STUB will take care of zero length arrays.  */
1398   if (TYPE_LENGTH (result_type) == 0)
1399     result_type->set_target_is_stub (true);
1400
1401   return result_type;
1402 }
1403
1404 /* Same as create_array_type_with_stride but with no bit_stride
1405    (BIT_STRIDE = 0), thus building an unpacked array.  */
1406
1407 struct type *
1408 create_array_type (struct type *result_type,
1409                    struct type *element_type,
1410                    struct type *range_type)
1411 {
1412   return create_array_type_with_stride (result_type, element_type,
1413                                         range_type, NULL, 0);
1414 }
1415
1416 struct type *
1417 lookup_array_range_type (struct type *element_type,
1418                          LONGEST low_bound, LONGEST high_bound)
1419 {
1420   struct type *index_type;
1421   struct type *range_type;
1422
1423   if (element_type->is_objfile_owned ())
1424     index_type = objfile_type (element_type->objfile_owner ())->builtin_int;
1425   else
1426     index_type = builtin_type (element_type->arch_owner ())->builtin_int;
1427
1428   range_type = create_static_range_type (NULL, index_type,
1429                                          low_bound, high_bound);
1430
1431   return create_array_type (NULL, element_type, range_type);
1432 }
1433
1434 /* Create a string type using either a blank type supplied in
1435    RESULT_TYPE, or creating a new type.  String types are similar
1436    enough to array of char types that we can use create_array_type to
1437    build the basic type and then bash it into a string type.
1438
1439    For fixed length strings, the range type contains 0 as the lower
1440    bound and the length of the string minus one as the upper bound.
1441
1442    FIXME: Maybe we should check the TYPE_CODE of RESULT_TYPE to make
1443    sure it is TYPE_CODE_UNDEF before we bash it into a string
1444    type?  */
1445
1446 struct type *
1447 create_string_type (struct type *result_type,
1448                     struct type *string_char_type,
1449                     struct type *range_type)
1450 {
1451   result_type = create_array_type (result_type,
1452                                    string_char_type,
1453                                    range_type);
1454   result_type->set_code (TYPE_CODE_STRING);
1455   return result_type;
1456 }
1457
1458 struct type *
1459 lookup_string_range_type (struct type *string_char_type,
1460                           LONGEST low_bound, LONGEST high_bound)
1461 {
1462   struct type *result_type;
1463
1464   result_type = lookup_array_range_type (string_char_type,
1465                                          low_bound, high_bound);
1466   result_type->set_code (TYPE_CODE_STRING);
1467   return result_type;
1468 }
1469
1470 struct type *
1471 create_set_type (struct type *result_type, struct type *domain_type)
1472 {
1473   if (result_type == NULL)
1474     result_type = alloc_type_copy (domain_type);
1475
1476   result_type->set_code (TYPE_CODE_SET);
1477   result_type->set_num_fields (1);
1478   result_type->set_fields
1479     ((struct field *) TYPE_ZALLOC (result_type, sizeof (struct field)));
1480
1481   if (!domain_type->is_stub ())
1482     {
1483       LONGEST low_bound, high_bound, bit_length;
1484
1485       if (!get_discrete_bounds (domain_type, &low_bound, &high_bound))
1486         low_bound = high_bound = 0;
1487
1488       bit_length = high_bound - low_bound + 1;
1489       TYPE_LENGTH (result_type)
1490         = (bit_length + TARGET_CHAR_BIT - 1) / TARGET_CHAR_BIT;
1491       if (low_bound >= 0)
1492         result_type->set_is_unsigned (true);
1493     }
1494   result_type->field (0).set_type (domain_type);
1495
1496   return result_type;
1497 }
1498
1499 /* Convert ARRAY_TYPE to a vector type.  This may modify ARRAY_TYPE
1500    and any array types nested inside it.  */
1501
1502 void
1503 make_vector_type (struct type *array_type)
1504 {
1505   struct type *inner_array, *elt_type;
1506
1507   /* Find the innermost array type, in case the array is
1508      multi-dimensional.  */
1509   inner_array = array_type;
1510   while (TYPE_TARGET_TYPE (inner_array)->code () == TYPE_CODE_ARRAY)
1511     inner_array = TYPE_TARGET_TYPE (inner_array);
1512
1513   elt_type = TYPE_TARGET_TYPE (inner_array);
1514   if (elt_type->code () == TYPE_CODE_INT)
1515     {
1516       type_instance_flags flags
1517         = elt_type->instance_flags () | TYPE_INSTANCE_FLAG_NOTTEXT;
1518       elt_type = make_qualified_type (elt_type, flags, NULL);
1519       TYPE_TARGET_TYPE (inner_array) = elt_type;
1520     }
1521
1522   array_type->set_is_vector (true);
1523 }
1524
1525 struct type *
1526 init_vector_type (struct type *elt_type, int n)
1527 {
1528   struct type *array_type;
1529
1530   array_type = lookup_array_range_type (elt_type, 0, n - 1);
1531   make_vector_type (array_type);
1532   return array_type;
1533 }
1534
1535 /* Internal routine called by TYPE_SELF_TYPE to return the type that TYPE
1536    belongs to.  In c++ this is the class of "this", but TYPE_THIS_TYPE is too
1537    confusing.  "self" is a common enough replacement for "this".
1538    TYPE must be one of TYPE_CODE_METHODPTR, TYPE_CODE_MEMBERPTR, or
1539    TYPE_CODE_METHOD.  */
1540
1541 struct type *
1542 internal_type_self_type (struct type *type)
1543 {
1544   switch (type->code ())
1545     {
1546     case TYPE_CODE_METHODPTR:
1547     case TYPE_CODE_MEMBERPTR:
1548       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1549         return NULL;
1550       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_SELF_TYPE);
1551       return TYPE_MAIN_TYPE (type)->type_specific.self_type;
1552     case TYPE_CODE_METHOD:
1553       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1554         return NULL;
1555       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FUNC);
1556       return TYPE_MAIN_TYPE (type)->type_specific.func_stuff->self_type;
1557     default:
1558       gdb_assert_not_reached ("bad type");
1559     }
1560 }
1561
1562 /* Set the type of the class that TYPE belongs to.
1563    In c++ this is the class of "this".
1564    TYPE must be one of TYPE_CODE_METHODPTR, TYPE_CODE_MEMBERPTR, or
1565    TYPE_CODE_METHOD.  */
1566
1567 void
1568 set_type_self_type (struct type *type, struct type *self_type)
1569 {
1570   switch (type->code ())
1571     {
1572     case TYPE_CODE_METHODPTR:
1573     case TYPE_CODE_MEMBERPTR:
1574       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1575         TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_SELF_TYPE;
1576       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_SELF_TYPE);
1577       TYPE_MAIN_TYPE (type)->type_specific.self_type = self_type;
1578       break;
1579     case TYPE_CODE_METHOD:
1580       if (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_NONE)
1581         INIT_FUNC_SPECIFIC (type);
1582       gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FUNC);
1583       TYPE_MAIN_TYPE (type)->type_specific.func_stuff->self_type = self_type;
1584       break;
1585     default:
1586       gdb_assert_not_reached ("bad type");
1587     }
1588 }
1589
1590 /* Smash TYPE to be a type of pointers to members of SELF_TYPE with type
1591    TO_TYPE.  A member pointer is a wierd thing -- it amounts to a
1592    typed offset into a struct, e.g. "an int at offset 8".  A MEMBER
1593    TYPE doesn't include the offset (that's the value of the MEMBER
1594    itself), but does include the structure type into which it points
1595    (for some reason).
1596
1597    When "smashing" the type, we preserve the objfile that the old type
1598    pointed to, since we aren't changing where the type is actually
1599    allocated.  */
1600
1601 void
1602 smash_to_memberptr_type (struct type *type, struct type *self_type,
1603                          struct type *to_type)
1604 {
1605   smash_type (type);
1606   type->set_code (TYPE_CODE_MEMBERPTR);
1607   TYPE_TARGET_TYPE (type) = to_type;
1608   set_type_self_type (type, self_type);
1609   /* Assume that a data member pointer is the same size as a normal
1610      pointer.  */
1611   TYPE_LENGTH (type) = gdbarch_ptr_bit (to_type->arch ()) / TARGET_CHAR_BIT;
1612 }
1613
1614 /* Smash TYPE to be a type of pointer to methods type TO_TYPE.
1615
1616    When "smashing" the type, we preserve the objfile that the old type
1617    pointed to, since we aren't changing where the type is actually
1618    allocated.  */
1619
1620 void
1621 smash_to_methodptr_type (struct type *type, struct type *to_type)
1622 {
1623   smash_type (type);
1624   type->set_code (TYPE_CODE_METHODPTR);
1625   TYPE_TARGET_TYPE (type) = to_type;
1626   set_type_self_type (type, TYPE_SELF_TYPE (to_type));
1627   TYPE_LENGTH (type) = cplus_method_ptr_size (to_type);
1628 }
1629
1630 /* Smash TYPE to be a type of method of SELF_TYPE with type TO_TYPE.
1631    METHOD just means `function that gets an extra "this" argument'.
1632
1633    When "smashing" the type, we preserve the objfile that the old type
1634    pointed to, since we aren't changing where the type is actually
1635    allocated.  */
1636
1637 void
1638 smash_to_method_type (struct type *type, struct type *self_type,
1639                       struct type *to_type, struct field *args,
1640                       int nargs, int varargs)
1641 {
1642   smash_type (type);
1643   type->set_code (TYPE_CODE_METHOD);
1644   TYPE_TARGET_TYPE (type) = to_type;
1645   set_type_self_type (type, self_type);
1646   type->set_fields (args);
1647   type->set_num_fields (nargs);
1648   if (varargs)
1649     type->set_has_varargs (true);
1650   TYPE_LENGTH (type) = 1;       /* In practice, this is never needed.  */
1651 }
1652
1653 /* A wrapper of TYPE_NAME which calls error if the type is anonymous.
1654    Since GCC PR debug/47510 DWARF provides associated information to detect the
1655    anonymous class linkage name from its typedef.
1656
1657    Parameter TYPE should not yet have CHECK_TYPEDEF applied, this function will
1658    apply it itself.  */
1659
1660 const char *
1661 type_name_or_error (struct type *type)
1662 {
1663   struct type *saved_type = type;
1664   const char *name;
1665   struct objfile *objfile;
1666
1667   type = check_typedef (type);
1668
1669   name = type->name ();
1670   if (name != NULL)
1671     return name;
1672
1673   name = saved_type->name ();
1674   objfile = saved_type->objfile_owner ();
1675   error (_("Invalid anonymous type %s [in module %s], GCC PR debug/47510 bug?"),
1676          name ? name : "<anonymous>",
1677          objfile ? objfile_name (objfile) : "<arch>");
1678 }
1679
1680 /* Lookup a typedef or primitive type named NAME, visible in lexical
1681    block BLOCK.  If NOERR is nonzero, return zero if NAME is not
1682    suitably defined.  */
1683
1684 struct type *
1685 lookup_typename (const struct language_defn *language,
1686                  const char *name,
1687                  const struct block *block, int noerr)
1688 {
1689   struct symbol *sym;
1690
1691   sym = lookup_symbol_in_language (name, block, VAR_DOMAIN,
1692                                    language->la_language, NULL).symbol;
1693   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
1694     return SYMBOL_TYPE (sym);
1695
1696   if (noerr)
1697     return NULL;
1698   error (_("No type named %s."), name);
1699 }
1700
1701 struct type *
1702 lookup_unsigned_typename (const struct language_defn *language,
1703                           const char *name)
1704 {
1705   char *uns = (char *) alloca (strlen (name) + 10);
1706
1707   strcpy (uns, "unsigned ");
1708   strcpy (uns + 9, name);
1709   return lookup_typename (language, uns, NULL, 0);
1710 }
1711
1712 struct type *
1713 lookup_signed_typename (const struct language_defn *language, const char *name)
1714 {
1715   struct type *t;
1716   char *uns = (char *) alloca (strlen (name) + 8);
1717
1718   strcpy (uns, "signed ");
1719   strcpy (uns + 7, name);
1720   t = lookup_typename (language, uns, NULL, 1);
1721   /* If we don't find "signed FOO" just try again with plain "FOO".  */
1722   if (t != NULL)
1723     return t;
1724   return lookup_typename (language, name, NULL, 0);
1725 }
1726
1727 /* Lookup a structure type named "struct NAME",
1728    visible in lexical block BLOCK.  */
1729
1730 struct type *
1731 lookup_struct (const char *name, const struct block *block)
1732 {
1733   struct symbol *sym;
1734
1735   sym = lookup_symbol (name, block, STRUCT_DOMAIN, 0).symbol;
1736
1737   if (sym == NULL)
1738     {
1739       error (_("No struct type named %s."), name);
1740     }
1741   if (SYMBOL_TYPE (sym)->code () != TYPE_CODE_STRUCT)
1742     {
1743       error (_("This context has class, union or enum %s, not a struct."),
1744              name);
1745     }
1746   return (SYMBOL_TYPE (sym));
1747 }
1748
1749 /* Lookup a union type named "union NAME",
1750    visible in lexical block BLOCK.  */
1751
1752 struct type *
1753 lookup_union (const char *name, const struct block *block)
1754 {
1755   struct symbol *sym;
1756   struct type *t;
1757
1758   sym = lookup_symbol (name, block, STRUCT_DOMAIN, 0).symbol;
1759
1760   if (sym == NULL)
1761     error (_("No union type named %s."), name);
1762
1763   t = SYMBOL_TYPE (sym);
1764
1765   if (t->code () == TYPE_CODE_UNION)
1766     return t;
1767
1768   /* If we get here, it's not a union.  */
1769   error (_("This context has class, struct or enum %s, not a union."), 
1770          name);
1771 }
1772
1773 /* Lookup an enum type named "enum NAME",
1774    visible in lexical block BLOCK.  */
1775
1776 struct type *
1777 lookup_enum (const char *name, const struct block *block)
1778 {
1779   struct symbol *sym;
1780
1781   sym = lookup_symbol (name, block, STRUCT_DOMAIN, 0).symbol;
1782   if (sym == NULL)
1783     {
1784       error (_("No enum type named %s."), name);
1785     }
1786   if (SYMBOL_TYPE (sym)->code () != TYPE_CODE_ENUM)
1787     {
1788       error (_("This context has class, struct or union %s, not an enum."), 
1789              name);
1790     }
1791   return (SYMBOL_TYPE (sym));
1792 }
1793
1794 /* Lookup a template type named "template NAME<TYPE>",
1795    visible in lexical block BLOCK.  */
1796
1797 struct type *
1798 lookup_template_type (const char *name, struct type *type, 
1799                       const struct block *block)
1800 {
1801   struct symbol *sym;
1802   char *nam = (char *) 
1803     alloca (strlen (name) + strlen (type->name ()) + 4);
1804
1805   strcpy (nam, name);
1806   strcat (nam, "<");
1807   strcat (nam, type->name ());
1808   strcat (nam, " >");   /* FIXME, extra space still introduced in gcc?  */
1809
1810   sym = lookup_symbol (nam, block, VAR_DOMAIN, 0).symbol;
1811
1812   if (sym == NULL)
1813     {
1814       error (_("No template type named %s."), name);
1815     }
1816   if (SYMBOL_TYPE (sym)->code () != TYPE_CODE_STRUCT)
1817     {
1818       error (_("This context has class, union or enum %s, not a struct."),
1819              name);
1820     }
1821   return (SYMBOL_TYPE (sym));
1822 }
1823
1824 /* See gdbtypes.h.  */
1825
1826 struct_elt
1827 lookup_struct_elt (struct type *type, const char *name, int noerr)
1828 {
1829   int i;
1830
1831   for (;;)
1832     {
1833       type = check_typedef (type);
1834       if (type->code () != TYPE_CODE_PTR
1835           && type->code () != TYPE_CODE_REF)
1836         break;
1837       type = TYPE_TARGET_TYPE (type);
1838     }
1839
1840   if (type->code () != TYPE_CODE_STRUCT
1841       && type->code () != TYPE_CODE_UNION)
1842     {
1843       std::string type_name = type_to_string (type);
1844       error (_("Type %s is not a structure or union type."),
1845              type_name.c_str ());
1846     }
1847
1848   for (i = type->num_fields () - 1; i >= TYPE_N_BASECLASSES (type); i--)
1849     {
1850       const char *t_field_name = type->field (i).name ();
1851
1852       if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
1853         {
1854           return {&type->field (i), type->field (i).loc_bitpos ()};
1855         }
1856       else if (!t_field_name || *t_field_name == '\0')
1857         {
1858           struct_elt elt
1859             = lookup_struct_elt (type->field (i).type (), name, 1);
1860           if (elt.field != NULL)
1861             {
1862               elt.offset += type->field (i).loc_bitpos ();
1863               return elt;
1864             }
1865         }
1866     }
1867
1868   /* OK, it's not in this class.  Recursively check the baseclasses.  */
1869   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
1870     {
1871       struct_elt elt = lookup_struct_elt (TYPE_BASECLASS (type, i), name, 1);
1872       if (elt.field != NULL)
1873         return elt;
1874     }
1875
1876   if (noerr)
1877     return {nullptr, 0};
1878
1879   std::string type_name = type_to_string (type);
1880   error (_("Type %s has no component named %s."), type_name.c_str (), name);
1881 }
1882
1883 /* See gdbtypes.h.  */
1884
1885 struct type *
1886 lookup_struct_elt_type (struct type *type, const char *name, int noerr)
1887 {
1888   struct_elt elt = lookup_struct_elt (type, name, noerr);
1889   if (elt.field != NULL)
1890     return elt.field->type ();
1891   else
1892     return NULL;
1893 }
1894
1895 /* Return the largest number representable by unsigned integer type TYPE.  */
1896
1897 ULONGEST
1898 get_unsigned_type_max (struct type *type)
1899 {
1900   unsigned int n;
1901
1902   type = check_typedef (type);
1903   gdb_assert (type->code () == TYPE_CODE_INT && type->is_unsigned ());
1904   gdb_assert (TYPE_LENGTH (type) <= sizeof (ULONGEST));
1905
1906   /* Written this way to avoid overflow.  */
1907   n = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
1908   return ((((ULONGEST) 1 << (n - 1)) - 1) << 1) | 1;
1909 }
1910
1911 /* Store in *MIN, *MAX the smallest and largest numbers representable by
1912    signed integer type TYPE.  */
1913
1914 void
1915 get_signed_type_minmax (struct type *type, LONGEST *min, LONGEST *max)
1916 {
1917   unsigned int n;
1918
1919   type = check_typedef (type);
1920   gdb_assert (type->code () == TYPE_CODE_INT && !type->is_unsigned ());
1921   gdb_assert (TYPE_LENGTH (type) <= sizeof (LONGEST));
1922
1923   n = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
1924   *min = -((ULONGEST) 1 << (n - 1));
1925   *max = ((ULONGEST) 1 << (n - 1)) - 1;
1926 }
1927
1928 /* Return the largest value representable by pointer type TYPE. */
1929
1930 CORE_ADDR
1931 get_pointer_type_max (struct type *type)
1932 {
1933   unsigned int n;
1934
1935   type = check_typedef (type);
1936   gdb_assert (type->code () == TYPE_CODE_PTR);
1937   gdb_assert (TYPE_LENGTH (type) <= sizeof (CORE_ADDR));
1938
1939   n = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
1940   return ((((CORE_ADDR) 1 << (n - 1)) - 1) << 1) | 1;
1941 }
1942
1943 /* Internal routine called by TYPE_VPTR_FIELDNO to return the value of
1944    cplus_stuff.vptr_fieldno.
1945
1946    cplus_stuff is initialized to cplus_struct_default which does not
1947    set vptr_fieldno to -1 for portability reasons (IWBN to use C99
1948    designated initializers).  We cope with that here.  */
1949
1950 int
1951 internal_type_vptr_fieldno (struct type *type)
1952 {
1953   type = check_typedef (type);
1954   gdb_assert (type->code () == TYPE_CODE_STRUCT
1955               || type->code () == TYPE_CODE_UNION);
1956   if (!HAVE_CPLUS_STRUCT (type))
1957     return -1;
1958   return TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_fieldno;
1959 }
1960
1961 /* Set the value of cplus_stuff.vptr_fieldno.  */
1962
1963 void
1964 set_type_vptr_fieldno (struct type *type, int fieldno)
1965 {
1966   type = check_typedef (type);
1967   gdb_assert (type->code () == TYPE_CODE_STRUCT
1968               || type->code () == TYPE_CODE_UNION);
1969   if (!HAVE_CPLUS_STRUCT (type))
1970     ALLOCATE_CPLUS_STRUCT_TYPE (type);
1971   TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_fieldno = fieldno;
1972 }
1973
1974 /* Internal routine called by TYPE_VPTR_BASETYPE to return the value of
1975    cplus_stuff.vptr_basetype.  */
1976
1977 struct type *
1978 internal_type_vptr_basetype (struct type *type)
1979 {
1980   type = check_typedef (type);
1981   gdb_assert (type->code () == TYPE_CODE_STRUCT
1982               || type->code () == TYPE_CODE_UNION);
1983   gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_CPLUS_STUFF);
1984   return TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_basetype;
1985 }
1986
1987 /* Set the value of cplus_stuff.vptr_basetype.  */
1988
1989 void
1990 set_type_vptr_basetype (struct type *type, struct type *basetype)
1991 {
1992   type = check_typedef (type);
1993   gdb_assert (type->code () == TYPE_CODE_STRUCT
1994               || type->code () == TYPE_CODE_UNION);
1995   if (!HAVE_CPLUS_STRUCT (type))
1996     ALLOCATE_CPLUS_STRUCT_TYPE (type);
1997   TYPE_RAW_CPLUS_SPECIFIC (type)->vptr_basetype = basetype;
1998 }
1999
2000 /* Lookup the vptr basetype/fieldno values for TYPE.
2001    If found store vptr_basetype in *BASETYPEP if non-NULL, and return
2002    vptr_fieldno.  Also, if found and basetype is from the same objfile,
2003    cache the results.
2004    If not found, return -1 and ignore BASETYPEP.
2005    Callers should be aware that in some cases (for example,
2006    the type or one of its baseclasses is a stub type and we are
2007    debugging a .o file, or the compiler uses DWARF-2 and is not GCC),
2008    this function will not be able to find the
2009    virtual function table pointer, and vptr_fieldno will remain -1 and
2010    vptr_basetype will remain NULL or incomplete.  */
2011
2012 int
2013 get_vptr_fieldno (struct type *type, struct type **basetypep)
2014 {
2015   type = check_typedef (type);
2016
2017   if (TYPE_VPTR_FIELDNO (type) < 0)
2018     {
2019       int i;
2020
2021       /* We must start at zero in case the first (and only) baseclass
2022          is virtual (and hence we cannot share the table pointer).  */
2023       for (i = 0; i < TYPE_N_BASECLASSES (type); i++)
2024         {
2025           struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2026           int fieldno;
2027           struct type *basetype;
2028
2029           fieldno = get_vptr_fieldno (baseclass, &basetype);
2030           if (fieldno >= 0)
2031             {
2032               /* If the type comes from a different objfile we can't cache
2033                  it, it may have a different lifetime.  PR 2384 */
2034               if (type->objfile_owner () == basetype->objfile_owner ())
2035                 {
2036                   set_type_vptr_fieldno (type, fieldno);
2037                   set_type_vptr_basetype (type, basetype);
2038                 }
2039               if (basetypep)
2040                 *basetypep = basetype;
2041               return fieldno;
2042             }
2043         }
2044
2045       /* Not found.  */
2046       return -1;
2047     }
2048   else
2049     {
2050       if (basetypep)
2051         *basetypep = TYPE_VPTR_BASETYPE (type);
2052       return TYPE_VPTR_FIELDNO (type);
2053     }
2054 }
2055
2056 static void
2057 stub_noname_complaint (void)
2058 {
2059   complaint (_("stub type has NULL name"));
2060 }
2061
2062 /* Return nonzero if TYPE has a DYN_PROP_BYTE_STRIDE dynamic property
2063    attached to it, and that property has a non-constant value.  */
2064
2065 static int
2066 array_type_has_dynamic_stride (struct type *type)
2067 {
2068   struct dynamic_prop *prop = type->dyn_prop (DYN_PROP_BYTE_STRIDE);
2069
2070   return (prop != NULL && prop->kind () != PROP_CONST);
2071 }
2072
2073 /* Worker for is_dynamic_type.  */
2074
2075 static int
2076 is_dynamic_type_internal (struct type *type, int top_level)
2077 {
2078   type = check_typedef (type);
2079
2080   /* We only want to recognize references at the outermost level.  */
2081   if (top_level && type->code () == TYPE_CODE_REF)
2082     type = check_typedef (TYPE_TARGET_TYPE (type));
2083
2084   /* Types that have a dynamic TYPE_DATA_LOCATION are considered
2085      dynamic, even if the type itself is statically defined.
2086      From a user's point of view, this may appear counter-intuitive;
2087      but it makes sense in this context, because the point is to determine
2088      whether any part of the type needs to be resolved before it can
2089      be exploited.  */
2090   if (TYPE_DATA_LOCATION (type) != NULL
2091       && (TYPE_DATA_LOCATION_KIND (type) == PROP_LOCEXPR
2092           || TYPE_DATA_LOCATION_KIND (type) == PROP_LOCLIST))
2093     return 1;
2094
2095   if (TYPE_ASSOCIATED_PROP (type))
2096     return 1;
2097
2098   if (TYPE_ALLOCATED_PROP (type))
2099     return 1;
2100
2101   struct dynamic_prop *prop = type->dyn_prop (DYN_PROP_VARIANT_PARTS);
2102   if (prop != nullptr && prop->kind () != PROP_TYPE)
2103     return 1;
2104
2105   if (TYPE_HAS_DYNAMIC_LENGTH (type))
2106     return 1;
2107
2108   switch (type->code ())
2109     {
2110     case TYPE_CODE_RANGE:
2111       {
2112         /* A range type is obviously dynamic if it has at least one
2113            dynamic bound.  But also consider the range type to be
2114            dynamic when its subtype is dynamic, even if the bounds
2115            of the range type are static.  It allows us to assume that
2116            the subtype of a static range type is also static.  */
2117         return (!has_static_range (type->bounds ())
2118                 || is_dynamic_type_internal (TYPE_TARGET_TYPE (type), 0));
2119       }
2120
2121     case TYPE_CODE_STRING:
2122       /* Strings are very much like an array of characters, and can be
2123          treated as one here.  */
2124     case TYPE_CODE_ARRAY:
2125       {
2126         gdb_assert (type->num_fields () == 1);
2127
2128         /* The array is dynamic if either the bounds are dynamic...  */
2129         if (is_dynamic_type_internal (type->index_type (), 0))
2130           return 1;
2131         /* ... or the elements it contains have a dynamic contents...  */
2132         if (is_dynamic_type_internal (TYPE_TARGET_TYPE (type), 0))
2133           return 1;
2134         /* ... or if it has a dynamic stride...  */
2135         if (array_type_has_dynamic_stride (type))
2136           return 1;
2137         return 0;
2138       }
2139
2140     case TYPE_CODE_STRUCT:
2141     case TYPE_CODE_UNION:
2142       {
2143         int i;
2144
2145         bool is_cplus = HAVE_CPLUS_STRUCT (type);
2146
2147         for (i = 0; i < type->num_fields (); ++i)
2148           {
2149             /* Static fields can be ignored here.  */
2150             if (field_is_static (&type->field (i)))
2151               continue;
2152             /* If the field has dynamic type, then so does TYPE.  */
2153             if (is_dynamic_type_internal (type->field (i).type (), 0))
2154               return 1;
2155             /* If the field is at a fixed offset, then it is not
2156                dynamic.  */
2157             if (type->field (i).loc_kind () != FIELD_LOC_KIND_DWARF_BLOCK)
2158               continue;
2159             /* Do not consider C++ virtual base types to be dynamic
2160                due to the field's offset being dynamic; these are
2161                handled via other means.  */
2162             if (is_cplus && BASETYPE_VIA_VIRTUAL (type, i))
2163               continue;
2164             return 1;
2165           }
2166       }
2167       break;
2168     }
2169
2170   return 0;
2171 }
2172
2173 /* See gdbtypes.h.  */
2174
2175 int
2176 is_dynamic_type (struct type *type)
2177 {
2178   return is_dynamic_type_internal (type, 1);
2179 }
2180
2181 static struct type *resolve_dynamic_type_internal
2182   (struct type *type, struct property_addr_info *addr_stack, int top_level);
2183
2184 /* Given a dynamic range type (dyn_range_type) and a stack of
2185    struct property_addr_info elements, return a static version
2186    of that type.
2187
2188    When RESOLVE_P is true then the returned static range is created by
2189    actually evaluating any dynamic properties within the range type, while
2190    when RESOLVE_P is false the returned static range has all of the bounds
2191    and stride information set to undefined.  The RESOLVE_P set to false
2192    case will be used when evaluating a dynamic array that is not
2193    allocated, or not associated, i.e. the bounds information might not be
2194    initialized yet.  */
2195
2196 static struct type *
2197 resolve_dynamic_range (struct type *dyn_range_type,
2198                        struct property_addr_info *addr_stack,
2199                        bool resolve_p = true)
2200 {
2201   CORE_ADDR value;
2202   struct type *static_range_type, *static_target_type;
2203   struct dynamic_prop low_bound, high_bound, stride;
2204
2205   gdb_assert (dyn_range_type->code () == TYPE_CODE_RANGE);
2206
2207   const struct dynamic_prop *prop = &dyn_range_type->bounds ()->low;
2208   if (resolve_p && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2209     low_bound.set_const_val (value);
2210   else
2211     low_bound.set_undefined ();
2212
2213   prop = &dyn_range_type->bounds ()->high;
2214   if (resolve_p && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2215     {
2216       high_bound.set_const_val (value);
2217
2218       if (dyn_range_type->bounds ()->flag_upper_bound_is_count)
2219         high_bound.set_const_val
2220           (low_bound.const_val () + high_bound.const_val () - 1);
2221     }
2222   else
2223     high_bound.set_undefined ();
2224
2225   bool byte_stride_p = dyn_range_type->bounds ()->flag_is_byte_stride;
2226   prop = &dyn_range_type->bounds ()->stride;
2227   if (resolve_p && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2228     {
2229       stride.set_const_val (value);
2230
2231       /* If we have a bit stride that is not an exact number of bytes then
2232          I really don't think this is going to work with current GDB, the
2233          array indexing code in GDB seems to be pretty heavily tied to byte
2234          offsets right now.  Assuming 8 bits in a byte.  */
2235       struct gdbarch *gdbarch = dyn_range_type->arch ();
2236       int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
2237       if (!byte_stride_p && (value % (unit_size * 8)) != 0)
2238         error (_("bit strides that are not a multiple of the byte size "
2239                  "are currently not supported"));
2240     }
2241   else
2242     {
2243       stride.set_undefined ();
2244       byte_stride_p = true;
2245     }
2246
2247   static_target_type
2248     = resolve_dynamic_type_internal (TYPE_TARGET_TYPE (dyn_range_type),
2249                                      addr_stack, 0);
2250   LONGEST bias = dyn_range_type->bounds ()->bias;
2251   static_range_type = create_range_type_with_stride
2252     (copy_type (dyn_range_type), static_target_type,
2253      &low_bound, &high_bound, bias, &stride, byte_stride_p);
2254   static_range_type->bounds ()->flag_bound_evaluated = 1;
2255   return static_range_type;
2256 }
2257
2258 /* Resolves dynamic bound values of an array or string type TYPE to static
2259    ones.  ADDR_STACK is a stack of struct property_addr_info to be used if
2260    needed during the dynamic resolution.
2261
2262    When RESOLVE_P is true then the dynamic properties of TYPE are
2263    evaluated, otherwise the dynamic properties of TYPE are not evaluated,
2264    instead we assume the array is not allocated/associated yet.  */
2265
2266 static struct type *
2267 resolve_dynamic_array_or_string (struct type *type,
2268                                  struct property_addr_info *addr_stack,
2269                                  bool resolve_p = true)
2270 {
2271   CORE_ADDR value;
2272   struct type *elt_type;
2273   struct type *range_type;
2274   struct type *ary_dim;
2275   struct dynamic_prop *prop;
2276   unsigned int bit_stride = 0;
2277
2278   /* For dynamic type resolution strings can be treated like arrays of
2279      characters.  */
2280   gdb_assert (type->code () == TYPE_CODE_ARRAY
2281               || type->code () == TYPE_CODE_STRING);
2282
2283   type = copy_type (type);
2284
2285   /* Resolve the allocated and associated properties before doing anything
2286      else.  If an array is not allocated or not associated then (at least
2287      for Fortran) there is no guarantee that the data to define the upper
2288      bound, lower bound, or stride will be correct.  If RESOLVE_P is
2289      already false at this point then this is not the first dimension of
2290      the array and a more outer dimension has already marked this array as
2291      not allocated/associated, as such we just ignore this property.  This
2292      is fine as GDB only checks the allocated/associated on the outer most
2293      dimension of the array.  */
2294   prop = TYPE_ALLOCATED_PROP (type);
2295   if (prop != NULL && resolve_p
2296       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2297     {
2298       prop->set_const_val (value);
2299       if (value == 0)
2300         resolve_p = false;
2301     }
2302
2303   prop = TYPE_ASSOCIATED_PROP (type);
2304   if (prop != NULL && resolve_p
2305       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2306     {
2307       prop->set_const_val (value);
2308       if (value == 0)
2309         resolve_p = false;
2310     }
2311
2312   range_type = check_typedef (type->index_type ());
2313   range_type = resolve_dynamic_range (range_type, addr_stack, resolve_p);
2314
2315   ary_dim = check_typedef (TYPE_TARGET_TYPE (type));
2316   if (ary_dim != NULL && ary_dim->code () == TYPE_CODE_ARRAY)
2317     elt_type = resolve_dynamic_array_or_string (ary_dim, addr_stack, resolve_p);
2318   else
2319     elt_type = TYPE_TARGET_TYPE (type);
2320
2321   prop = type->dyn_prop (DYN_PROP_BYTE_STRIDE);
2322   if (prop != NULL && resolve_p)
2323     {
2324       if (dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2325         {
2326           type->remove_dyn_prop (DYN_PROP_BYTE_STRIDE);
2327           bit_stride = (unsigned int) (value * 8);
2328         }
2329       else
2330         {
2331           /* Could be a bug in our code, but it could also happen
2332              if the DWARF info is not correct.  Issue a warning,
2333              and assume no byte/bit stride (leave bit_stride = 0).  */
2334           warning (_("cannot determine array stride for type %s"),
2335                    type->name () ? type->name () : "<no name>");
2336         }
2337     }
2338   else
2339     bit_stride = TYPE_FIELD_BITSIZE (type, 0);
2340
2341   return create_array_type_with_stride (type, elt_type, range_type, NULL,
2342                                         bit_stride);
2343 }
2344
2345 /* Resolve dynamic bounds of members of the union TYPE to static
2346    bounds.  ADDR_STACK is a stack of struct property_addr_info
2347    to be used if needed during the dynamic resolution.  */
2348
2349 static struct type *
2350 resolve_dynamic_union (struct type *type,
2351                        struct property_addr_info *addr_stack)
2352 {
2353   struct type *resolved_type;
2354   int i;
2355   unsigned int max_len = 0;
2356
2357   gdb_assert (type->code () == TYPE_CODE_UNION);
2358
2359   resolved_type = copy_type (type);
2360   resolved_type->set_fields
2361     ((struct field *)
2362      TYPE_ALLOC (resolved_type,
2363                  resolved_type->num_fields () * sizeof (struct field)));
2364   memcpy (resolved_type->fields (),
2365           type->fields (),
2366           resolved_type->num_fields () * sizeof (struct field));
2367   for (i = 0; i < resolved_type->num_fields (); ++i)
2368     {
2369       struct type *t;
2370
2371       if (field_is_static (&type->field (i)))
2372         continue;
2373
2374       t = resolve_dynamic_type_internal (resolved_type->field (i).type (),
2375                                          addr_stack, 0);
2376       resolved_type->field (i).set_type (t);
2377
2378       struct type *real_type = check_typedef (t);
2379       if (TYPE_LENGTH (real_type) > max_len)
2380         max_len = TYPE_LENGTH (real_type);
2381     }
2382
2383   TYPE_LENGTH (resolved_type) = max_len;
2384   return resolved_type;
2385 }
2386
2387 /* See gdbtypes.h.  */
2388
2389 bool
2390 variant::matches (ULONGEST value, bool is_unsigned) const
2391 {
2392   for (const discriminant_range &range : discriminants)
2393     if (range.contains (value, is_unsigned))
2394       return true;
2395   return false;
2396 }
2397
2398 static void
2399 compute_variant_fields_inner (struct type *type,
2400                               struct property_addr_info *addr_stack,
2401                               const variant_part &part,
2402                               std::vector<bool> &flags);
2403
2404 /* A helper function to determine which variant fields will be active.
2405    This handles both the variant's direct fields, and any variant
2406    parts embedded in this variant.  TYPE is the type we're examining.
2407    ADDR_STACK holds information about the concrete object.  VARIANT is
2408    the current variant to be handled.  FLAGS is where the results are
2409    stored -- this function sets the Nth element in FLAGS if the
2410    corresponding field is enabled.  ENABLED is whether this variant is
2411    enabled or not.  */
2412
2413 static void
2414 compute_variant_fields_recurse (struct type *type,
2415                                 struct property_addr_info *addr_stack,
2416                                 const variant &variant,
2417                                 std::vector<bool> &flags,
2418                                 bool enabled)
2419 {
2420   for (int field = variant.first_field; field < variant.last_field; ++field)
2421     flags[field] = enabled;
2422
2423   for (const variant_part &new_part : variant.parts)
2424     {
2425       if (enabled)
2426         compute_variant_fields_inner (type, addr_stack, new_part, flags);
2427       else
2428         {
2429           for (const auto &sub_variant : new_part.variants)
2430             compute_variant_fields_recurse (type, addr_stack, sub_variant,
2431                                             flags, enabled);
2432         }
2433     }
2434 }
2435
2436 /* A helper function to determine which variant fields will be active.
2437    This evaluates the discriminant, decides which variant (if any) is
2438    active, and then updates FLAGS to reflect which fields should be
2439    available.  TYPE is the type we're examining.  ADDR_STACK holds
2440    information about the concrete object.  VARIANT is the current
2441    variant to be handled.  FLAGS is where the results are stored --
2442    this function sets the Nth element in FLAGS if the corresponding
2443    field is enabled.  */
2444
2445 static void
2446 compute_variant_fields_inner (struct type *type,
2447                               struct property_addr_info *addr_stack,
2448                               const variant_part &part,
2449                               std::vector<bool> &flags)
2450 {
2451   /* Evaluate the discriminant.  */
2452   gdb::optional<ULONGEST> discr_value;
2453   if (part.discriminant_index != -1)
2454     {
2455       int idx = part.discriminant_index;
2456
2457       if (type->field (idx).loc_kind () != FIELD_LOC_KIND_BITPOS)
2458         error (_("Cannot determine struct field location"
2459                  " (invalid location kind)"));
2460
2461       if (addr_stack->valaddr.data () != NULL)
2462         discr_value = unpack_field_as_long (type, addr_stack->valaddr.data (),
2463                                             idx);
2464       else
2465         {
2466           CORE_ADDR addr = (addr_stack->addr
2467                             + (type->field (idx).loc_bitpos ()
2468                                / TARGET_CHAR_BIT));
2469
2470           LONGEST bitsize = TYPE_FIELD_BITSIZE (type, idx);
2471           LONGEST size = bitsize / 8;
2472           if (size == 0)
2473             size = TYPE_LENGTH (type->field (idx).type ());
2474
2475           gdb_byte bits[sizeof (ULONGEST)];
2476           read_memory (addr, bits, size);
2477
2478           LONGEST bitpos = (type->field (idx).loc_bitpos ()
2479                             % TARGET_CHAR_BIT);
2480
2481           discr_value = unpack_bits_as_long (type->field (idx).type (),
2482                                              bits, bitpos, bitsize);
2483         }
2484     }
2485
2486   /* Go through each variant and see which applies.  */
2487   const variant *default_variant = nullptr;
2488   const variant *applied_variant = nullptr;
2489   for (const auto &variant : part.variants)
2490     {
2491       if (variant.is_default ())
2492         default_variant = &variant;
2493       else if (discr_value.has_value ()
2494                && variant.matches (*discr_value, part.is_unsigned))
2495         {
2496           applied_variant = &variant;
2497           break;
2498         }
2499     }
2500   if (applied_variant == nullptr)
2501     applied_variant = default_variant;
2502
2503   for (const auto &variant : part.variants)
2504     compute_variant_fields_recurse (type, addr_stack, variant,
2505                                     flags, applied_variant == &variant);
2506 }  
2507
2508 /* Determine which variant fields are available in TYPE.  The enabled
2509    fields are stored in RESOLVED_TYPE.  ADDR_STACK holds information
2510    about the concrete object.  PARTS describes the top-level variant
2511    parts for this type.  */
2512
2513 static void
2514 compute_variant_fields (struct type *type,
2515                         struct type *resolved_type,
2516                         struct property_addr_info *addr_stack,
2517                         const gdb::array_view<variant_part> &parts)
2518 {
2519   /* Assume all fields are included by default.  */
2520   std::vector<bool> flags (resolved_type->num_fields (), true);
2521
2522   /* Now disable fields based on the variants that control them.  */
2523   for (const auto &part : parts)
2524     compute_variant_fields_inner (type, addr_stack, part, flags);
2525
2526   resolved_type->set_num_fields
2527     (std::count (flags.begin (), flags.end (), true));
2528   resolved_type->set_fields
2529     ((struct field *)
2530      TYPE_ALLOC (resolved_type,
2531                  resolved_type->num_fields () * sizeof (struct field)));
2532
2533   int out = 0;
2534   for (int i = 0; i < type->num_fields (); ++i)
2535     {
2536       if (!flags[i])
2537         continue;
2538
2539       resolved_type->field (out) = type->field (i);
2540       ++out;
2541     }
2542 }
2543
2544 /* Resolve dynamic bounds of members of the struct TYPE to static
2545    bounds.  ADDR_STACK is a stack of struct property_addr_info to
2546    be used if needed during the dynamic resolution.  */
2547
2548 static struct type *
2549 resolve_dynamic_struct (struct type *type,
2550                         struct property_addr_info *addr_stack)
2551 {
2552   struct type *resolved_type;
2553   int i;
2554   unsigned resolved_type_bit_length = 0;
2555
2556   gdb_assert (type->code () == TYPE_CODE_STRUCT);
2557
2558   resolved_type = copy_type (type);
2559
2560   dynamic_prop *variant_prop = resolved_type->dyn_prop (DYN_PROP_VARIANT_PARTS);
2561   if (variant_prop != nullptr && variant_prop->kind () == PROP_VARIANT_PARTS)
2562     {
2563       compute_variant_fields (type, resolved_type, addr_stack,
2564                               *variant_prop->variant_parts ());
2565       /* We want to leave the property attached, so that the Rust code
2566          can tell whether the type was originally an enum.  */
2567       variant_prop->set_original_type (type);
2568     }
2569   else
2570     {
2571       resolved_type->set_fields
2572         ((struct field *)
2573          TYPE_ALLOC (resolved_type,
2574                      resolved_type->num_fields () * sizeof (struct field)));
2575       if (type->num_fields () > 0)
2576         memcpy (resolved_type->fields (),
2577                 type->fields (),
2578                 resolved_type->num_fields () * sizeof (struct field));
2579     }
2580
2581   for (i = 0; i < resolved_type->num_fields (); ++i)
2582     {
2583       unsigned new_bit_length;
2584       struct property_addr_info pinfo;
2585
2586       if (field_is_static (&resolved_type->field (i)))
2587         continue;
2588
2589       if (resolved_type->field (i).loc_kind () == FIELD_LOC_KIND_DWARF_BLOCK)
2590         {
2591           struct dwarf2_property_baton baton;
2592           baton.property_type
2593             = lookup_pointer_type (resolved_type->field (i).type ());
2594           baton.locexpr = *resolved_type->field (i).loc_dwarf_block ();
2595
2596           struct dynamic_prop prop;
2597           prop.set_locexpr (&baton);
2598
2599           CORE_ADDR addr;
2600           if (dwarf2_evaluate_property (&prop, nullptr, addr_stack, &addr,
2601                                         true))
2602             resolved_type->field (i).set_loc_bitpos
2603               (TARGET_CHAR_BIT * (addr - addr_stack->addr));
2604         }
2605
2606       /* As we know this field is not a static field, the field's
2607          field_loc_kind should be FIELD_LOC_KIND_BITPOS.  Verify
2608          this is the case, but only trigger a simple error rather
2609          than an internal error if that fails.  While failing
2610          that verification indicates a bug in our code, the error
2611          is not severe enough to suggest to the user he stops
2612          his debugging session because of it.  */
2613       if (resolved_type->field (i).loc_kind () != FIELD_LOC_KIND_BITPOS)
2614         error (_("Cannot determine struct field location"
2615                  " (invalid location kind)"));
2616
2617       pinfo.type = check_typedef (resolved_type->field (i).type ());
2618       size_t offset = resolved_type->field (i).loc_bitpos () / TARGET_CHAR_BIT;
2619       pinfo.valaddr = addr_stack->valaddr;
2620       if (!pinfo.valaddr.empty ())
2621         pinfo.valaddr = pinfo.valaddr.slice (offset);
2622       pinfo.addr = addr_stack->addr + offset;
2623       pinfo.next = addr_stack;
2624
2625       resolved_type->field (i).set_type
2626         (resolve_dynamic_type_internal (resolved_type->field (i).type (),
2627                                         &pinfo, 0));
2628       gdb_assert (resolved_type->field (i).loc_kind ()
2629                   == FIELD_LOC_KIND_BITPOS);
2630
2631       new_bit_length = resolved_type->field (i).loc_bitpos ();
2632       if (TYPE_FIELD_BITSIZE (resolved_type, i) != 0)
2633         new_bit_length += TYPE_FIELD_BITSIZE (resolved_type, i);
2634       else
2635         {
2636           struct type *real_type
2637             = check_typedef (resolved_type->field (i).type ());
2638
2639           new_bit_length += (TYPE_LENGTH (real_type) * TARGET_CHAR_BIT);
2640         }
2641
2642       /* Normally, we would use the position and size of the last field
2643          to determine the size of the enclosing structure.  But GCC seems
2644          to be encoding the position of some fields incorrectly when
2645          the struct contains a dynamic field that is not placed last.
2646          So we compute the struct size based on the field that has
2647          the highest position + size - probably the best we can do.  */
2648       if (new_bit_length > resolved_type_bit_length)
2649         resolved_type_bit_length = new_bit_length;
2650     }
2651
2652   /* The length of a type won't change for fortran, but it does for C and Ada.
2653      For fortran the size of dynamic fields might change over time but not the
2654      type length of the structure.  If we adapt it, we run into problems
2655      when calculating the element offset for arrays of structs.  */
2656   if (current_language->la_language != language_fortran)
2657     TYPE_LENGTH (resolved_type)
2658       = (resolved_type_bit_length + TARGET_CHAR_BIT - 1) / TARGET_CHAR_BIT;
2659
2660   /* The Ada language uses this field as a cache for static fixed types: reset
2661      it as RESOLVED_TYPE must have its own static fixed type.  */
2662   TYPE_TARGET_TYPE (resolved_type) = NULL;
2663
2664   return resolved_type;
2665 }
2666
2667 /* Worker for resolved_dynamic_type.  */
2668
2669 static struct type *
2670 resolve_dynamic_type_internal (struct type *type,
2671                                struct property_addr_info *addr_stack,
2672                                int top_level)
2673 {
2674   struct type *real_type = check_typedef (type);
2675   struct type *resolved_type = nullptr;
2676   struct dynamic_prop *prop;
2677   CORE_ADDR value;
2678
2679   if (!is_dynamic_type_internal (real_type, top_level))
2680     return type;
2681
2682   gdb::optional<CORE_ADDR> type_length;
2683   prop = TYPE_DYNAMIC_LENGTH (type);
2684   if (prop != NULL
2685       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2686     type_length = value;
2687
2688   if (type->code () == TYPE_CODE_TYPEDEF)
2689     {
2690       resolved_type = copy_type (type);
2691       TYPE_TARGET_TYPE (resolved_type)
2692         = resolve_dynamic_type_internal (TYPE_TARGET_TYPE (type), addr_stack,
2693                                          top_level);
2694     }
2695   else 
2696     {
2697       /* Before trying to resolve TYPE, make sure it is not a stub.  */
2698       type = real_type;
2699
2700       switch (type->code ())
2701         {
2702         case TYPE_CODE_REF:
2703           {
2704             struct property_addr_info pinfo;
2705
2706             pinfo.type = check_typedef (TYPE_TARGET_TYPE (type));
2707             pinfo.valaddr = {};
2708             if (addr_stack->valaddr.data () != NULL)
2709               pinfo.addr = extract_typed_address (addr_stack->valaddr.data (),
2710                                                   type);
2711             else
2712               pinfo.addr = read_memory_typed_address (addr_stack->addr, type);
2713             pinfo.next = addr_stack;
2714
2715             resolved_type = copy_type (type);
2716             TYPE_TARGET_TYPE (resolved_type)
2717               = resolve_dynamic_type_internal (TYPE_TARGET_TYPE (type),
2718                                                &pinfo, top_level);
2719             break;
2720           }
2721
2722         case TYPE_CODE_STRING:
2723           /* Strings are very much like an array of characters, and can be
2724              treated as one here.  */
2725         case TYPE_CODE_ARRAY:
2726           resolved_type = resolve_dynamic_array_or_string (type, addr_stack);
2727           break;
2728
2729         case TYPE_CODE_RANGE:
2730           resolved_type = resolve_dynamic_range (type, addr_stack);
2731           break;
2732
2733         case TYPE_CODE_UNION:
2734           resolved_type = resolve_dynamic_union (type, addr_stack);
2735           break;
2736
2737         case TYPE_CODE_STRUCT:
2738           resolved_type = resolve_dynamic_struct (type, addr_stack);
2739           break;
2740         }
2741     }
2742
2743   if (resolved_type == nullptr)
2744     return type;
2745
2746   if (type_length.has_value ())
2747     {
2748       TYPE_LENGTH (resolved_type) = *type_length;
2749       resolved_type->remove_dyn_prop (DYN_PROP_BYTE_SIZE);
2750     }
2751
2752   /* Resolve data_location attribute.  */
2753   prop = TYPE_DATA_LOCATION (resolved_type);
2754   if (prop != NULL
2755       && dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
2756     {
2757       /* Start of Fortran hack.  See comment in f-lang.h for what is going
2758          on here.*/
2759       if (current_language->la_language == language_fortran
2760           && resolved_type->code () == TYPE_CODE_ARRAY)
2761         value = fortran_adjust_dynamic_array_base_address_hack (resolved_type,
2762                                                                 value);
2763       /* End of Fortran hack.  */
2764       prop->set_const_val (value);
2765     }
2766
2767   return resolved_type;
2768 }
2769
2770 /* See gdbtypes.h  */
2771
2772 struct type *
2773 resolve_dynamic_type (struct type *type,
2774                       gdb::array_view<const gdb_byte> valaddr,
2775                       CORE_ADDR addr)
2776 {
2777   struct property_addr_info pinfo
2778     = {check_typedef (type), valaddr, addr, NULL};
2779
2780   return resolve_dynamic_type_internal (type, &pinfo, 1);
2781 }
2782
2783 /* See gdbtypes.h  */
2784
2785 dynamic_prop *
2786 type::dyn_prop (dynamic_prop_node_kind prop_kind) const
2787 {
2788   dynamic_prop_list *node = this->main_type->dyn_prop_list;
2789
2790   while (node != NULL)
2791     {
2792       if (node->prop_kind == prop_kind)
2793         return &node->prop;
2794       node = node->next;
2795     }
2796   return NULL;
2797 }
2798
2799 /* See gdbtypes.h  */
2800
2801 void
2802 type::add_dyn_prop (dynamic_prop_node_kind prop_kind, dynamic_prop prop)
2803 {
2804   struct dynamic_prop_list *temp;
2805
2806   gdb_assert (this->is_objfile_owned ());
2807
2808   temp = XOBNEW (&this->objfile_owner ()->objfile_obstack,
2809                  struct dynamic_prop_list);
2810   temp->prop_kind = prop_kind;
2811   temp->prop = prop;
2812   temp->next = this->main_type->dyn_prop_list;
2813
2814   this->main_type->dyn_prop_list = temp;
2815 }
2816
2817 /* See gdbtypes.h.  */
2818
2819 void
2820 type::remove_dyn_prop (dynamic_prop_node_kind kind)
2821 {
2822   struct dynamic_prop_list *prev_node, *curr_node;
2823
2824   curr_node = this->main_type->dyn_prop_list;
2825   prev_node = NULL;
2826
2827   while (NULL != curr_node)
2828     {
2829       if (curr_node->prop_kind == kind)
2830         {
2831           /* Update the linked list but don't free anything.
2832              The property was allocated on objstack and it is not known
2833              if we are on top of it.  Nevertheless, everything is released
2834              when the complete objstack is freed.  */
2835           if (NULL == prev_node)
2836             this->main_type->dyn_prop_list = curr_node->next;
2837           else
2838             prev_node->next = curr_node->next;
2839
2840           return;
2841         }
2842
2843       prev_node = curr_node;
2844       curr_node = curr_node->next;
2845     }
2846 }
2847
2848 /* Find the real type of TYPE.  This function returns the real type,
2849    after removing all layers of typedefs, and completing opaque or stub
2850    types.  Completion changes the TYPE argument, but stripping of
2851    typedefs does not.
2852
2853    Instance flags (e.g. const/volatile) are preserved as typedefs are
2854    stripped.  If necessary a new qualified form of the underlying type
2855    is created.
2856
2857    NOTE: This will return a typedef if TYPE_TARGET_TYPE for the typedef has
2858    not been computed and we're either in the middle of reading symbols, or
2859    there was no name for the typedef in the debug info.
2860
2861    NOTE: Lookup of opaque types can throw errors for invalid symbol files.
2862    QUITs in the symbol reading code can also throw.
2863    Thus this function can throw an exception.
2864
2865    If TYPE is a TYPE_CODE_TYPEDEF, its length is updated to the length of
2866    the target type.
2867
2868    If this is a stubbed struct (i.e. declared as struct foo *), see if
2869    we can find a full definition in some other file.  If so, copy this
2870    definition, so we can use it in future.  There used to be a comment
2871    (but not any code) that if we don't find a full definition, we'd
2872    set a flag so we don't spend time in the future checking the same
2873    type.  That would be a mistake, though--we might load in more
2874    symbols which contain a full definition for the type.  */
2875
2876 struct type *
2877 check_typedef (struct type *type)
2878 {
2879   struct type *orig_type = type;
2880
2881   gdb_assert (type);
2882
2883   /* While we're removing typedefs, we don't want to lose qualifiers.
2884      E.g., const/volatile.  */
2885   type_instance_flags instance_flags = type->instance_flags ();
2886
2887   while (type->code () == TYPE_CODE_TYPEDEF)
2888     {
2889       if (!TYPE_TARGET_TYPE (type))
2890         {
2891           const char *name;
2892           struct symbol *sym;
2893
2894           /* It is dangerous to call lookup_symbol if we are currently
2895              reading a symtab.  Infinite recursion is one danger.  */
2896           if (currently_reading_symtab)
2897             return make_qualified_type (type, instance_flags, NULL);
2898
2899           name = type->name ();
2900           /* FIXME: shouldn't we look in STRUCT_DOMAIN and/or
2901              VAR_DOMAIN as appropriate?  */
2902           if (name == NULL)
2903             {
2904               stub_noname_complaint ();
2905               return make_qualified_type (type, instance_flags, NULL);
2906             }
2907           sym = lookup_symbol (name, 0, STRUCT_DOMAIN, 0).symbol;
2908           if (sym)
2909             TYPE_TARGET_TYPE (type) = SYMBOL_TYPE (sym);
2910           else                                  /* TYPE_CODE_UNDEF */
2911             TYPE_TARGET_TYPE (type) = alloc_type_arch (type->arch ());
2912         }
2913       type = TYPE_TARGET_TYPE (type);
2914
2915       /* Preserve the instance flags as we traverse down the typedef chain.
2916
2917          Handling address spaces/classes is nasty, what do we do if there's a
2918          conflict?
2919          E.g., what if an outer typedef marks the type as class_1 and an inner
2920          typedef marks the type as class_2?
2921          This is the wrong place to do such error checking.  We leave it to
2922          the code that created the typedef in the first place to flag the
2923          error.  We just pick the outer address space (akin to letting the
2924          outer cast in a chain of casting win), instead of assuming
2925          "it can't happen".  */
2926       {
2927         const type_instance_flags ALL_SPACES
2928           = (TYPE_INSTANCE_FLAG_CODE_SPACE
2929              | TYPE_INSTANCE_FLAG_DATA_SPACE);
2930         const type_instance_flags ALL_CLASSES
2931           = TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL;
2932
2933         type_instance_flags new_instance_flags = type->instance_flags ();
2934
2935         /* Treat code vs data spaces and address classes separately.  */
2936         if ((instance_flags & ALL_SPACES) != 0)
2937           new_instance_flags &= ~ALL_SPACES;
2938         if ((instance_flags & ALL_CLASSES) != 0)
2939           new_instance_flags &= ~ALL_CLASSES;
2940
2941         instance_flags |= new_instance_flags;
2942       }
2943     }
2944
2945   /* If this is a struct/class/union with no fields, then check
2946      whether a full definition exists somewhere else.  This is for
2947      systems where a type definition with no fields is issued for such
2948      types, instead of identifying them as stub types in the first
2949      place.  */
2950
2951   if (TYPE_IS_OPAQUE (type) 
2952       && opaque_type_resolution 
2953       && !currently_reading_symtab)
2954     {
2955       const char *name = type->name ();
2956       struct type *newtype;
2957
2958       if (name == NULL)
2959         {
2960           stub_noname_complaint ();
2961           return make_qualified_type (type, instance_flags, NULL);
2962         }
2963       newtype = lookup_transparent_type (name);
2964
2965       if (newtype)
2966         {
2967           /* If the resolved type and the stub are in the same
2968              objfile, then replace the stub type with the real deal.
2969              But if they're in separate objfiles, leave the stub
2970              alone; we'll just look up the transparent type every time
2971              we call check_typedef.  We can't create pointers between
2972              types allocated to different objfiles, since they may
2973              have different lifetimes.  Trying to copy NEWTYPE over to
2974              TYPE's objfile is pointless, too, since you'll have to
2975              move over any other types NEWTYPE refers to, which could
2976              be an unbounded amount of stuff.  */
2977           if (newtype->objfile_owner () == type->objfile_owner ())
2978             type = make_qualified_type (newtype, type->instance_flags (), type);
2979           else
2980             type = newtype;
2981         }
2982     }
2983   /* Otherwise, rely on the stub flag being set for opaque/stubbed
2984      types.  */
2985   else if (type->is_stub () && !currently_reading_symtab)
2986     {
2987       const char *name = type->name ();
2988       /* FIXME: shouldn't we look in STRUCT_DOMAIN and/or VAR_DOMAIN
2989          as appropriate?  */
2990       struct symbol *sym;
2991
2992       if (name == NULL)
2993         {
2994           stub_noname_complaint ();
2995           return make_qualified_type (type, instance_flags, NULL);
2996         }
2997       sym = lookup_symbol (name, 0, STRUCT_DOMAIN, 0).symbol;
2998       if (sym)
2999         {
3000           /* Same as above for opaque types, we can replace the stub
3001              with the complete type only if they are in the same
3002              objfile.  */
3003           if (SYMBOL_TYPE (sym)->objfile_owner () == type->objfile_owner ())
3004             type = make_qualified_type (SYMBOL_TYPE (sym),
3005                                         type->instance_flags (), type);
3006           else
3007             type = SYMBOL_TYPE (sym);
3008         }
3009     }
3010
3011   if (type->target_is_stub ())
3012     {
3013       struct type *target_type = check_typedef (TYPE_TARGET_TYPE (type));
3014
3015       if (target_type->is_stub () || target_type->target_is_stub ())
3016         {
3017           /* Nothing we can do.  */
3018         }
3019       else if (type->code () == TYPE_CODE_RANGE)
3020         {
3021           TYPE_LENGTH (type) = TYPE_LENGTH (target_type);
3022           type->set_target_is_stub (false);
3023         }
3024       else if (type->code () == TYPE_CODE_ARRAY
3025                && update_static_array_size (type))
3026         type->set_target_is_stub (false);
3027     }
3028
3029   type = make_qualified_type (type, instance_flags, NULL);
3030
3031   /* Cache TYPE_LENGTH for future use.  */
3032   TYPE_LENGTH (orig_type) = TYPE_LENGTH (type);
3033
3034   return type;
3035 }
3036
3037 /* Parse a type expression in the string [P..P+LENGTH).  If an error
3038    occurs, silently return a void type.  */
3039
3040 static struct type *
3041 safe_parse_type (struct gdbarch *gdbarch, const char *p, int length)
3042 {
3043   struct ui_file *saved_gdb_stderr;
3044   struct type *type = NULL; /* Initialize to keep gcc happy.  */
3045
3046   /* Suppress error messages.  */
3047   saved_gdb_stderr = gdb_stderr;
3048   gdb_stderr = &null_stream;
3049
3050   /* Call parse_and_eval_type() without fear of longjmp()s.  */
3051   try
3052     {
3053       type = parse_and_eval_type (p, length);
3054     }
3055   catch (const gdb_exception_error &except)
3056     {
3057       type = builtin_type (gdbarch)->builtin_void;
3058     }
3059
3060   /* Stop suppressing error messages.  */
3061   gdb_stderr = saved_gdb_stderr;
3062
3063   return type;
3064 }
3065
3066 /* Ugly hack to convert method stubs into method types.
3067
3068    He ain't kiddin'.  This demangles the name of the method into a
3069    string including argument types, parses out each argument type,
3070    generates a string casting a zero to that type, evaluates the
3071    string, and stuffs the resulting type into an argtype vector!!!
3072    Then it knows the type of the whole function (including argument
3073    types for overloading), which info used to be in the stab's but was
3074    removed to hack back the space required for them.  */
3075
3076 static void
3077 check_stub_method (struct type *type, int method_id, int signature_id)
3078 {
3079   struct gdbarch *gdbarch = type->arch ();
3080   struct fn_field *f;
3081   char *mangled_name = gdb_mangle_name (type, method_id, signature_id);
3082   gdb::unique_xmalloc_ptr<char> demangled_name
3083     = gdb_demangle (mangled_name, DMGL_PARAMS | DMGL_ANSI);
3084   char *argtypetext, *p;
3085   int depth = 0, argcount = 1;
3086   struct field *argtypes;
3087   struct type *mtype;
3088
3089   /* Make sure we got back a function string that we can use.  */
3090   if (demangled_name)
3091     p = strchr (demangled_name.get (), '(');
3092   else
3093     p = NULL;
3094
3095   if (demangled_name == NULL || p == NULL)
3096     error (_("Internal: Cannot demangle mangled name `%s'."), 
3097            mangled_name);
3098
3099   /* Now, read in the parameters that define this type.  */
3100   p += 1;
3101   argtypetext = p;
3102   while (*p)
3103     {
3104       if (*p == '(' || *p == '<')
3105         {
3106           depth += 1;
3107         }
3108       else if (*p == ')' || *p == '>')
3109         {
3110           depth -= 1;
3111         }
3112       else if (*p == ',' && depth == 0)
3113         {
3114           argcount += 1;
3115         }
3116
3117       p += 1;
3118     }
3119
3120   /* If we read one argument and it was ``void'', don't count it.  */
3121   if (startswith (argtypetext, "(void)"))
3122     argcount -= 1;
3123
3124   /* We need one extra slot, for the THIS pointer.  */
3125
3126   argtypes = (struct field *)
3127     TYPE_ALLOC (type, (argcount + 1) * sizeof (struct field));
3128   p = argtypetext;
3129
3130   /* Add THIS pointer for non-static methods.  */
3131   f = TYPE_FN_FIELDLIST1 (type, method_id);
3132   if (TYPE_FN_FIELD_STATIC_P (f, signature_id))
3133     argcount = 0;
3134   else
3135     {
3136       argtypes[0].set_type (lookup_pointer_type (type));
3137       argcount = 1;
3138     }
3139
3140   if (*p != ')')                /* () means no args, skip while.  */
3141     {
3142       depth = 0;
3143       while (*p)
3144         {
3145           if (depth <= 0 && (*p == ',' || *p == ')'))
3146             {
3147               /* Avoid parsing of ellipsis, they will be handled below.
3148                  Also avoid ``void'' as above.  */
3149               if (strncmp (argtypetext, "...", p - argtypetext) != 0
3150                   && strncmp (argtypetext, "void", p - argtypetext) != 0)
3151                 {
3152                   argtypes[argcount].set_type
3153                     (safe_parse_type (gdbarch, argtypetext, p - argtypetext));
3154                   argcount += 1;
3155                 }
3156               argtypetext = p + 1;
3157             }
3158
3159           if (*p == '(' || *p == '<')
3160             {
3161               depth += 1;
3162             }
3163           else if (*p == ')' || *p == '>')
3164             {
3165               depth -= 1;
3166             }
3167
3168           p += 1;
3169         }
3170     }
3171
3172   TYPE_FN_FIELD_PHYSNAME (f, signature_id) = mangled_name;
3173
3174   /* Now update the old "stub" type into a real type.  */
3175   mtype = TYPE_FN_FIELD_TYPE (f, signature_id);
3176   /* MTYPE may currently be a function (TYPE_CODE_FUNC).
3177      We want a method (TYPE_CODE_METHOD).  */
3178   smash_to_method_type (mtype, type, TYPE_TARGET_TYPE (mtype),
3179                         argtypes, argcount, p[-2] == '.');
3180   mtype->set_is_stub (false);
3181   TYPE_FN_FIELD_STUB (f, signature_id) = 0;
3182 }
3183
3184 /* This is the external interface to check_stub_method, above.  This
3185    function unstubs all of the signatures for TYPE's METHOD_ID method
3186    name.  After calling this function TYPE_FN_FIELD_STUB will be
3187    cleared for each signature and TYPE_FN_FIELDLIST_NAME will be
3188    correct.
3189
3190    This function unfortunately can not die until stabs do.  */
3191
3192 void
3193 check_stub_method_group (struct type *type, int method_id)
3194 {
3195   int len = TYPE_FN_FIELDLIST_LENGTH (type, method_id);
3196   struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
3197
3198   for (int j = 0; j < len; j++)
3199     {
3200       if (TYPE_FN_FIELD_STUB (f, j))
3201         check_stub_method (type, method_id, j);
3202     }
3203 }
3204
3205 /* Ensure it is in .rodata (if available) by working around GCC PR 44690.  */
3206 const struct cplus_struct_type cplus_struct_default = { };
3207
3208 void
3209 allocate_cplus_struct_type (struct type *type)
3210 {
3211   if (HAVE_CPLUS_STRUCT (type))
3212     /* Structure was already allocated.  Nothing more to do.  */
3213     return;
3214
3215   TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_CPLUS_STUFF;
3216   TYPE_RAW_CPLUS_SPECIFIC (type) = (struct cplus_struct_type *)
3217     TYPE_ALLOC (type, sizeof (struct cplus_struct_type));
3218   *(TYPE_RAW_CPLUS_SPECIFIC (type)) = cplus_struct_default;
3219   set_type_vptr_fieldno (type, -1);
3220 }
3221
3222 const struct gnat_aux_type gnat_aux_default =
3223   { NULL };
3224
3225 /* Set the TYPE's type-specific kind to TYPE_SPECIFIC_GNAT_STUFF,
3226    and allocate the associated gnat-specific data.  The gnat-specific
3227    data is also initialized to gnat_aux_default.  */
3228
3229 void
3230 allocate_gnat_aux_type (struct type *type)
3231 {
3232   TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_GNAT_STUFF;
3233   TYPE_GNAT_SPECIFIC (type) = (struct gnat_aux_type *)
3234     TYPE_ALLOC (type, sizeof (struct gnat_aux_type));
3235   *(TYPE_GNAT_SPECIFIC (type)) = gnat_aux_default;
3236 }
3237
3238 /* Helper function to initialize a newly allocated type.  Set type code
3239    to CODE and initialize the type-specific fields accordingly.  */
3240
3241 static void
3242 set_type_code (struct type *type, enum type_code code)
3243 {
3244   type->set_code (code);
3245
3246   switch (code)
3247     {
3248       case TYPE_CODE_STRUCT:
3249       case TYPE_CODE_UNION:
3250       case TYPE_CODE_NAMESPACE:
3251         INIT_CPLUS_SPECIFIC (type);
3252         break;
3253       case TYPE_CODE_FLT:
3254         TYPE_SPECIFIC_FIELD (type) = TYPE_SPECIFIC_FLOATFORMAT;
3255         break;
3256       case TYPE_CODE_FUNC:
3257         INIT_FUNC_SPECIFIC (type);
3258         break;
3259       case TYPE_CODE_FIXED_POINT:
3260         INIT_FIXED_POINT_SPECIFIC (type);
3261         break;
3262     }
3263 }
3264
3265 /* Helper function to verify floating-point format and size.
3266    BIT is the type size in bits; if BIT equals -1, the size is
3267    determined by the floatformat.  Returns size to be used.  */
3268
3269 static int
3270 verify_floatformat (int bit, const struct floatformat *floatformat)
3271 {
3272   gdb_assert (floatformat != NULL);
3273
3274   if (bit == -1)
3275     bit = floatformat->totalsize;
3276
3277   gdb_assert (bit >= 0);
3278   gdb_assert (bit >= floatformat->totalsize);
3279
3280   return bit;
3281 }
3282
3283 /* Return the floating-point format for a floating-point variable of
3284    type TYPE.  */
3285
3286 const struct floatformat *
3287 floatformat_from_type (const struct type *type)
3288 {
3289   gdb_assert (type->code () == TYPE_CODE_FLT);
3290   gdb_assert (TYPE_FLOATFORMAT (type));
3291   return TYPE_FLOATFORMAT (type);
3292 }
3293
3294 /* Helper function to initialize the standard scalar types.
3295
3296    If NAME is non-NULL, then it is used to initialize the type name.
3297    Note that NAME is not copied; it is required to have a lifetime at
3298    least as long as OBJFILE.  */
3299
3300 struct type *
3301 init_type (struct objfile *objfile, enum type_code code, int bit,
3302            const char *name)
3303 {
3304   struct type *type;
3305
3306   type = alloc_type (objfile);
3307   set_type_code (type, code);
3308   gdb_assert ((bit % TARGET_CHAR_BIT) == 0);
3309   TYPE_LENGTH (type) = bit / TARGET_CHAR_BIT;
3310   type->set_name (name);
3311
3312   return type;
3313 }
3314
3315 /* Allocate a TYPE_CODE_ERROR type structure associated with OBJFILE,
3316    to use with variables that have no debug info.  NAME is the type
3317    name.  */
3318
3319 static struct type *
3320 init_nodebug_var_type (struct objfile *objfile, const char *name)
3321 {
3322   return init_type (objfile, TYPE_CODE_ERROR, 0, name);
3323 }
3324
3325 /* Allocate a TYPE_CODE_INT type structure associated with OBJFILE.
3326    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
3327    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
3328
3329 struct type *
3330 init_integer_type (struct objfile *objfile,
3331                    int bit, int unsigned_p, const char *name)
3332 {
3333   struct type *t;
3334
3335   t = init_type (objfile, TYPE_CODE_INT, bit, name);
3336   if (unsigned_p)
3337     t->set_is_unsigned (true);
3338
3339   TYPE_SPECIFIC_FIELD (t) = TYPE_SPECIFIC_INT;
3340   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_size = bit;
3341   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_offset = 0;
3342
3343   return t;
3344 }
3345
3346 /* Allocate a TYPE_CODE_CHAR type structure associated with OBJFILE.
3347    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
3348    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
3349
3350 struct type *
3351 init_character_type (struct objfile *objfile,
3352                      int bit, int unsigned_p, const char *name)
3353 {
3354   struct type *t;
3355
3356   t = init_type (objfile, TYPE_CODE_CHAR, bit, name);
3357   if (unsigned_p)
3358     t->set_is_unsigned (true);
3359
3360   return t;
3361 }
3362
3363 /* Allocate a TYPE_CODE_BOOL type structure associated with OBJFILE.
3364    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
3365    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
3366
3367 struct type *
3368 init_boolean_type (struct objfile *objfile,
3369                    int bit, int unsigned_p, const char *name)
3370 {
3371   struct type *t;
3372
3373   t = init_type (objfile, TYPE_CODE_BOOL, bit, name);
3374   if (unsigned_p)
3375     t->set_is_unsigned (true);
3376
3377   TYPE_SPECIFIC_FIELD (t) = TYPE_SPECIFIC_INT;
3378   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_size = bit;
3379   TYPE_MAIN_TYPE (t)->type_specific.int_stuff.bit_offset = 0;
3380
3381   return t;
3382 }
3383
3384 /* Allocate a TYPE_CODE_FLT type structure associated with OBJFILE.
3385    BIT is the type size in bits; if BIT equals -1, the size is
3386    determined by the floatformat.  NAME is the type name.  Set the
3387    TYPE_FLOATFORMAT from FLOATFORMATS.  BYTE_ORDER is the byte order
3388    to use.  If it is BFD_ENDIAN_UNKNOWN (the default), then the byte
3389    order of the objfile's architecture is used.  */
3390
3391 struct type *
3392 init_float_type (struct objfile *objfile,
3393                  int bit, const char *name,
3394                  const struct floatformat **floatformats,
3395                  enum bfd_endian byte_order)
3396 {
3397   if (byte_order == BFD_ENDIAN_UNKNOWN)
3398     {
3399       struct gdbarch *gdbarch = objfile->arch ();
3400       byte_order = gdbarch_byte_order (gdbarch);
3401     }
3402   const struct floatformat *fmt = floatformats[byte_order];
3403   struct type *t;
3404
3405   bit = verify_floatformat (bit, fmt);
3406   t = init_type (objfile, TYPE_CODE_FLT, bit, name);
3407   TYPE_FLOATFORMAT (t) = fmt;
3408
3409   return t;
3410 }
3411
3412 /* Allocate a TYPE_CODE_DECFLOAT type structure associated with OBJFILE.
3413    BIT is the type size in bits.  NAME is the type name.  */
3414
3415 struct type *
3416 init_decfloat_type (struct objfile *objfile, int bit, const char *name)
3417 {
3418   struct type *t;
3419
3420   t = init_type (objfile, TYPE_CODE_DECFLOAT, bit, name);
3421   return t;
3422 }
3423
3424 /* Return true if init_complex_type can be called with TARGET_TYPE.  */
3425
3426 bool
3427 can_create_complex_type (struct type *target_type)
3428 {
3429   return (target_type->code () == TYPE_CODE_INT
3430           || target_type->code () == TYPE_CODE_FLT);
3431 }
3432
3433 /* Allocate a TYPE_CODE_COMPLEX type structure.  NAME is the type
3434    name.  TARGET_TYPE is the component type.  */
3435
3436 struct type *
3437 init_complex_type (const char *name, struct type *target_type)
3438 {
3439   struct type *t;
3440
3441   gdb_assert (can_create_complex_type (target_type));
3442
3443   if (TYPE_MAIN_TYPE (target_type)->flds_bnds.complex_type == nullptr)
3444     {
3445       if (name == nullptr && target_type->name () != nullptr)
3446         {
3447           char *new_name
3448             = (char *) TYPE_ALLOC (target_type,
3449                                    strlen (target_type->name ())
3450                                    + strlen ("_Complex ") + 1);
3451           strcpy (new_name, "_Complex ");
3452           strcat (new_name, target_type->name ());
3453           name = new_name;
3454         }
3455
3456       t = alloc_type_copy (target_type);
3457       set_type_code (t, TYPE_CODE_COMPLEX);
3458       TYPE_LENGTH (t) = 2 * TYPE_LENGTH (target_type);
3459       t->set_name (name);
3460
3461       TYPE_TARGET_TYPE (t) = target_type;
3462       TYPE_MAIN_TYPE (target_type)->flds_bnds.complex_type = t;
3463     }
3464
3465   return TYPE_MAIN_TYPE (target_type)->flds_bnds.complex_type;
3466 }
3467
3468 /* Allocate a TYPE_CODE_PTR type structure associated with OBJFILE.
3469    BIT is the pointer type size in bits.  NAME is the type name.
3470    TARGET_TYPE is the pointer target type.  Always sets the pointer type's
3471    TYPE_UNSIGNED flag.  */
3472
3473 struct type *
3474 init_pointer_type (struct objfile *objfile,
3475                    int bit, const char *name, struct type *target_type)
3476 {
3477   struct type *t;
3478
3479   t = init_type (objfile, TYPE_CODE_PTR, bit, name);
3480   TYPE_TARGET_TYPE (t) = target_type;
3481   t->set_is_unsigned (true);
3482   return t;
3483 }
3484
3485 /* Allocate a TYPE_CODE_FIXED_POINT type structure associated with OBJFILE.
3486    BIT is the pointer type size in bits.
3487    UNSIGNED_P should be nonzero if the type is unsigned.
3488    NAME is the type name.  */
3489
3490 struct type *
3491 init_fixed_point_type (struct objfile *objfile,
3492                        int bit, int unsigned_p, const char *name)
3493 {
3494   struct type *t;
3495
3496   t = init_type (objfile, TYPE_CODE_FIXED_POINT, bit, name);
3497   if (unsigned_p)
3498     t->set_is_unsigned (true);
3499
3500   return t;
3501 }
3502
3503 /* See gdbtypes.h.  */
3504
3505 unsigned
3506 type_raw_align (struct type *type)
3507 {
3508   if (type->align_log2 != 0)
3509     return 1 << (type->align_log2 - 1);
3510   return 0;
3511 }
3512
3513 /* See gdbtypes.h.  */
3514
3515 unsigned
3516 type_align (struct type *type)
3517 {
3518   /* Check alignment provided in the debug information.  */
3519   unsigned raw_align = type_raw_align (type);
3520   if (raw_align != 0)
3521     return raw_align;
3522
3523   /* Allow the architecture to provide an alignment.  */
3524   ULONGEST align = gdbarch_type_align (type->arch (), type);
3525   if (align != 0)
3526     return align;
3527
3528   switch (type->code ())
3529     {
3530     case TYPE_CODE_PTR:
3531     case TYPE_CODE_FUNC:
3532     case TYPE_CODE_FLAGS:
3533     case TYPE_CODE_INT:
3534     case TYPE_CODE_RANGE:
3535     case TYPE_CODE_FLT:
3536     case TYPE_CODE_ENUM:
3537     case TYPE_CODE_REF:
3538     case TYPE_CODE_RVALUE_REF:
3539     case TYPE_CODE_CHAR:
3540     case TYPE_CODE_BOOL:
3541     case TYPE_CODE_DECFLOAT:
3542     case TYPE_CODE_METHODPTR:
3543     case TYPE_CODE_MEMBERPTR:
3544       align = type_length_units (check_typedef (type));
3545       break;
3546
3547     case TYPE_CODE_ARRAY:
3548     case TYPE_CODE_COMPLEX:
3549     case TYPE_CODE_TYPEDEF:
3550       align = type_align (TYPE_TARGET_TYPE (type));
3551       break;
3552
3553     case TYPE_CODE_STRUCT:
3554     case TYPE_CODE_UNION:
3555       {
3556         int number_of_non_static_fields = 0;
3557         for (unsigned i = 0; i < type->num_fields (); ++i)
3558           {
3559             if (!field_is_static (&type->field (i)))
3560               {
3561                 number_of_non_static_fields++;
3562                 ULONGEST f_align = type_align (type->field (i).type ());
3563                 if (f_align == 0)
3564                   {
3565                     /* Don't pretend we know something we don't.  */
3566                     align = 0;
3567                     break;
3568                   }
3569                 if (f_align > align)
3570                   align = f_align;
3571               }
3572           }
3573         /* A struct with no fields, or with only static fields has an
3574            alignment of 1.  */
3575         if (number_of_non_static_fields == 0)
3576           align = 1;
3577       }
3578       break;
3579
3580     case TYPE_CODE_SET:
3581     case TYPE_CODE_STRING:
3582       /* Not sure what to do here, and these can't appear in C or C++
3583          anyway.  */
3584       break;
3585
3586     case TYPE_CODE_VOID:
3587       align = 1;
3588       break;
3589
3590     case TYPE_CODE_ERROR:
3591     case TYPE_CODE_METHOD:
3592     default:
3593       break;
3594     }
3595
3596   if ((align & (align - 1)) != 0)
3597     {
3598       /* Not a power of 2, so pass.  */
3599       align = 0;
3600     }
3601
3602   return align;
3603 }
3604
3605 /* See gdbtypes.h.  */
3606
3607 bool
3608 set_type_align (struct type *type, ULONGEST align)
3609 {
3610   /* Must be a power of 2.  Zero is ok.  */
3611   gdb_assert ((align & (align - 1)) == 0);
3612
3613   unsigned result = 0;
3614   while (align != 0)
3615     {
3616       ++result;
3617       align >>= 1;
3618     }
3619
3620   if (result >= (1 << TYPE_ALIGN_BITS))
3621     return false;
3622
3623   type->align_log2 = result;
3624   return true;
3625 }
3626
3627 \f
3628 /* Queries on types.  */
3629
3630 int
3631 can_dereference (struct type *t)
3632 {
3633   /* FIXME: Should we return true for references as well as
3634      pointers?  */
3635   t = check_typedef (t);
3636   return
3637     (t != NULL
3638      && t->code () == TYPE_CODE_PTR
3639      && TYPE_TARGET_TYPE (t)->code () != TYPE_CODE_VOID);
3640 }
3641
3642 int
3643 is_integral_type (struct type *t)
3644 {
3645   t = check_typedef (t);
3646   return
3647     ((t != NULL)
3648      && !is_fixed_point_type (t)
3649      && ((t->code () == TYPE_CODE_INT)
3650          || (t->code () == TYPE_CODE_ENUM)
3651          || (t->code () == TYPE_CODE_FLAGS)
3652          || (t->code () == TYPE_CODE_CHAR)
3653          || (t->code () == TYPE_CODE_RANGE)
3654          || (t->code () == TYPE_CODE_BOOL)));
3655 }
3656
3657 int
3658 is_floating_type (struct type *t)
3659 {
3660   t = check_typedef (t);
3661   return
3662     ((t != NULL)
3663      && ((t->code () == TYPE_CODE_FLT)
3664          || (t->code () == TYPE_CODE_DECFLOAT)));
3665 }
3666
3667 /* Return true if TYPE is scalar.  */
3668
3669 int
3670 is_scalar_type (struct type *type)
3671 {
3672   type = check_typedef (type);
3673
3674   if (is_fixed_point_type (type))
3675     return 0; /* Implemented as a scalar, but more like a floating point.  */
3676
3677   switch (type->code ())
3678     {
3679     case TYPE_CODE_ARRAY:
3680     case TYPE_CODE_STRUCT:
3681     case TYPE_CODE_UNION:
3682     case TYPE_CODE_SET:
3683     case TYPE_CODE_STRING:
3684       return 0;
3685     default:
3686       return 1;
3687     }
3688 }
3689
3690 /* Return true if T is scalar, or a composite type which in practice has
3691    the memory layout of a scalar type.  E.g., an array or struct with only
3692    one scalar element inside it, or a union with only scalar elements.  */
3693
3694 int
3695 is_scalar_type_recursive (struct type *t)
3696 {
3697   t = check_typedef (t);
3698
3699   if (is_scalar_type (t))
3700     return 1;
3701   /* Are we dealing with an array or string of known dimensions?  */
3702   else if ((t->code () == TYPE_CODE_ARRAY
3703             || t->code () == TYPE_CODE_STRING) && t->num_fields () == 1
3704            && t->index_type ()->code () == TYPE_CODE_RANGE)
3705     {
3706       LONGEST low_bound, high_bound;
3707       struct type *elt_type = check_typedef (TYPE_TARGET_TYPE (t));
3708
3709       if (get_discrete_bounds (t->index_type (), &low_bound, &high_bound))
3710         return (high_bound == low_bound
3711                 && is_scalar_type_recursive (elt_type));
3712       else
3713         return 0;
3714     }
3715   /* Are we dealing with a struct with one element?  */
3716   else if (t->code () == TYPE_CODE_STRUCT && t->num_fields () == 1)
3717     return is_scalar_type_recursive (t->field (0).type ());
3718   else if (t->code () == TYPE_CODE_UNION)
3719     {
3720       int i, n = t->num_fields ();
3721
3722       /* If all elements of the union are scalar, then the union is scalar.  */
3723       for (i = 0; i < n; i++)
3724         if (!is_scalar_type_recursive (t->field (i).type ()))
3725           return 0;
3726
3727       return 1;
3728     }
3729
3730   return 0;
3731 }
3732
3733 /* Return true is T is a class or a union.  False otherwise.  */
3734
3735 int
3736 class_or_union_p (const struct type *t)
3737 {
3738   return (t->code () == TYPE_CODE_STRUCT
3739           || t->code () == TYPE_CODE_UNION);
3740 }
3741
3742 /* A helper function which returns true if types A and B represent the
3743    "same" class type.  This is true if the types have the same main
3744    type, or the same name.  */
3745
3746 int
3747 class_types_same_p (const struct type *a, const struct type *b)
3748 {
3749   return (TYPE_MAIN_TYPE (a) == TYPE_MAIN_TYPE (b)
3750           || (a->name () && b->name ()
3751               && !strcmp (a->name (), b->name ())));
3752 }
3753
3754 /* If BASE is an ancestor of DCLASS return the distance between them.
3755    otherwise return -1;
3756    eg:
3757
3758    class A {};
3759    class B: public A {};
3760    class C: public B {};
3761    class D: C {};
3762
3763    distance_to_ancestor (A, A, 0) = 0
3764    distance_to_ancestor (A, B, 0) = 1
3765    distance_to_ancestor (A, C, 0) = 2
3766    distance_to_ancestor (A, D, 0) = 3
3767
3768    If PUBLIC is 1 then only public ancestors are considered,
3769    and the function returns the distance only if BASE is a public ancestor
3770    of DCLASS.
3771    Eg:
3772
3773    distance_to_ancestor (A, D, 1) = -1.  */
3774
3775 static int
3776 distance_to_ancestor (struct type *base, struct type *dclass, int is_public)
3777 {
3778   int i;
3779   int d;
3780
3781   base = check_typedef (base);
3782   dclass = check_typedef (dclass);
3783
3784   if (class_types_same_p (base, dclass))
3785     return 0;
3786
3787   for (i = 0; i < TYPE_N_BASECLASSES (dclass); i++)
3788     {
3789       if (is_public && ! BASETYPE_VIA_PUBLIC (dclass, i))
3790         continue;
3791
3792       d = distance_to_ancestor (base, TYPE_BASECLASS (dclass, i), is_public);
3793       if (d >= 0)
3794         return 1 + d;
3795     }
3796
3797   return -1;
3798 }
3799
3800 /* Check whether BASE is an ancestor or base class or DCLASS
3801    Return 1 if so, and 0 if not.
3802    Note: If BASE and DCLASS are of the same type, this function
3803    will return 1. So for some class A, is_ancestor (A, A) will
3804    return 1.  */
3805
3806 int
3807 is_ancestor (struct type *base, struct type *dclass)
3808 {
3809   return distance_to_ancestor (base, dclass, 0) >= 0;
3810 }
3811
3812 /* Like is_ancestor, but only returns true when BASE is a public
3813    ancestor of DCLASS.  */
3814
3815 int
3816 is_public_ancestor (struct type *base, struct type *dclass)
3817 {
3818   return distance_to_ancestor (base, dclass, 1) >= 0;
3819 }
3820
3821 /* A helper function for is_unique_ancestor.  */
3822
3823 static int
3824 is_unique_ancestor_worker (struct type *base, struct type *dclass,
3825                            int *offset,
3826                            const gdb_byte *valaddr, int embedded_offset,
3827                            CORE_ADDR address, struct value *val)
3828 {
3829   int i, count = 0;
3830
3831   base = check_typedef (base);
3832   dclass = check_typedef (dclass);
3833
3834   for (i = 0; i < TYPE_N_BASECLASSES (dclass) && count < 2; ++i)
3835     {
3836       struct type *iter;
3837       int this_offset;
3838
3839       iter = check_typedef (TYPE_BASECLASS (dclass, i));
3840
3841       this_offset = baseclass_offset (dclass, i, valaddr, embedded_offset,
3842                                       address, val);
3843
3844       if (class_types_same_p (base, iter))
3845         {
3846           /* If this is the first subclass, set *OFFSET and set count
3847              to 1.  Otherwise, if this is at the same offset as
3848              previous instances, do nothing.  Otherwise, increment
3849              count.  */
3850           if (*offset == -1)
3851             {
3852               *offset = this_offset;
3853               count = 1;
3854             }
3855           else if (this_offset == *offset)
3856             {
3857               /* Nothing.  */
3858             }
3859           else
3860             ++count;
3861         }
3862       else
3863         count += is_unique_ancestor_worker (base, iter, offset,
3864                                             valaddr,
3865                                             embedded_offset + this_offset,
3866                                             address, val);
3867     }
3868
3869   return count;
3870 }
3871
3872 /* Like is_ancestor, but only returns true if BASE is a unique base
3873    class of the type of VAL.  */
3874
3875 int
3876 is_unique_ancestor (struct type *base, struct value *val)
3877 {
3878   int offset = -1;
3879
3880   return is_unique_ancestor_worker (base, value_type (val), &offset,
3881                                     value_contents_for_printing (val).data (),
3882                                     value_embedded_offset (val),
3883                                     value_address (val), val) == 1;
3884 }
3885
3886 /* See gdbtypes.h.  */
3887
3888 enum bfd_endian
3889 type_byte_order (const struct type *type)
3890 {
3891   bfd_endian byteorder = gdbarch_byte_order (type->arch ());
3892   if (type->endianity_is_not_default ())
3893     {
3894       if (byteorder == BFD_ENDIAN_BIG)
3895         return BFD_ENDIAN_LITTLE;
3896       else
3897         {
3898           gdb_assert (byteorder == BFD_ENDIAN_LITTLE);
3899           return BFD_ENDIAN_BIG;
3900         }
3901     }
3902
3903   return byteorder;
3904 }
3905
3906 \f
3907 /* Overload resolution.  */
3908
3909 /* Return the sum of the rank of A with the rank of B.  */
3910
3911 struct rank
3912 sum_ranks (struct rank a, struct rank b)
3913 {
3914   struct rank c;
3915   c.rank = a.rank + b.rank;
3916   c.subrank = a.subrank + b.subrank;
3917   return c;
3918 }
3919
3920 /* Compare rank A and B and return:
3921    0 if a = b
3922    1 if a is better than b
3923   -1 if b is better than a.  */
3924
3925 int
3926 compare_ranks (struct rank a, struct rank b)
3927 {
3928   if (a.rank == b.rank)
3929     {
3930       if (a.subrank == b.subrank)
3931         return 0;
3932       if (a.subrank < b.subrank)
3933         return 1;
3934       if (a.subrank > b.subrank)
3935         return -1;
3936     }
3937
3938   if (a.rank < b.rank)
3939     return 1;
3940
3941   /* a.rank > b.rank */
3942   return -1;
3943 }
3944
3945 /* Functions for overload resolution begin here.  */
3946
3947 /* Compare two badness vectors A and B and return the result.
3948    0 => A and B are identical
3949    1 => A and B are incomparable
3950    2 => A is better than B
3951    3 => A is worse than B  */
3952
3953 int
3954 compare_badness (const badness_vector &a, const badness_vector &b)
3955 {
3956   int i;
3957   int tmp;
3958   short found_pos = 0;          /* any positives in c? */
3959   short found_neg = 0;          /* any negatives in c? */
3960
3961   /* differing sizes => incomparable */
3962   if (a.size () != b.size ())
3963     return 1;
3964
3965   /* Subtract b from a */
3966   for (i = 0; i < a.size (); i++)
3967     {
3968       tmp = compare_ranks (b[i], a[i]);
3969       if (tmp > 0)
3970         found_pos = 1;
3971       else if (tmp < 0)
3972         found_neg = 1;
3973     }
3974
3975   if (found_pos)
3976     {
3977       if (found_neg)
3978         return 1;               /* incomparable */
3979       else
3980         return 3;               /* A > B */
3981     }
3982   else
3983     /* no positives */
3984     {
3985       if (found_neg)
3986         return 2;               /* A < B */
3987       else
3988         return 0;               /* A == B */
3989     }
3990 }
3991
3992 /* Rank a function by comparing its parameter types (PARMS), to the
3993    types of an argument list (ARGS).  Return the badness vector.  This
3994    has ARGS.size() + 1 entries.  */
3995
3996 badness_vector
3997 rank_function (gdb::array_view<type *> parms,
3998                gdb::array_view<value *> args)
3999 {
4000   /* add 1 for the length-match rank.  */
4001   badness_vector bv;
4002   bv.reserve (1 + args.size ());
4003
4004   /* First compare the lengths of the supplied lists.
4005      If there is a mismatch, set it to a high value.  */
4006
4007   /* pai/1997-06-03 FIXME: when we have debug info about default
4008      arguments and ellipsis parameter lists, we should consider those
4009      and rank the length-match more finely.  */
4010
4011   bv.push_back ((args.size () != parms.size ())
4012                 ? LENGTH_MISMATCH_BADNESS
4013                 : EXACT_MATCH_BADNESS);
4014
4015   /* Now rank all the parameters of the candidate function.  */
4016   size_t min_len = std::min (parms.size (), args.size ());
4017
4018   for (size_t i = 0; i < min_len; i++)
4019     bv.push_back (rank_one_type (parms[i], value_type (args[i]),
4020                                  args[i]));
4021
4022   /* If more arguments than parameters, add dummy entries.  */
4023   for (size_t i = min_len; i < args.size (); i++)
4024     bv.push_back (TOO_FEW_PARAMS_BADNESS);
4025
4026   return bv;
4027 }
4028
4029 /* Compare the names of two integer types, assuming that any sign
4030    qualifiers have been checked already.  We do it this way because
4031    there may be an "int" in the name of one of the types.  */
4032
4033 static int
4034 integer_types_same_name_p (const char *first, const char *second)
4035 {
4036   int first_p, second_p;
4037
4038   /* If both are shorts, return 1; if neither is a short, keep
4039      checking.  */
4040   first_p = (strstr (first, "short") != NULL);
4041   second_p = (strstr (second, "short") != NULL);
4042   if (first_p && second_p)
4043     return 1;
4044   if (first_p || second_p)
4045     return 0;
4046
4047   /* Likewise for long.  */
4048   first_p = (strstr (first, "long") != NULL);
4049   second_p = (strstr (second, "long") != NULL);
4050   if (first_p && second_p)
4051     return 1;
4052   if (first_p || second_p)
4053     return 0;
4054
4055   /* Likewise for char.  */
4056   first_p = (strstr (first, "char") != NULL);
4057   second_p = (strstr (second, "char") != NULL);
4058   if (first_p && second_p)
4059     return 1;
4060   if (first_p || second_p)
4061     return 0;
4062
4063   /* They must both be ints.  */
4064   return 1;
4065 }
4066
4067 /* Compares type A to type B.  Returns true if they represent the same
4068    type, false otherwise.  */
4069
4070 bool
4071 types_equal (struct type *a, struct type *b)
4072 {
4073   /* Identical type pointers.  */
4074   /* However, this still doesn't catch all cases of same type for b
4075      and a.  The reason is that builtin types are different from
4076      the same ones constructed from the object.  */
4077   if (a == b)
4078     return true;
4079
4080   /* Resolve typedefs */
4081   if (a->code () == TYPE_CODE_TYPEDEF)
4082     a = check_typedef (a);
4083   if (b->code () == TYPE_CODE_TYPEDEF)
4084     b = check_typedef (b);
4085
4086   /* Check if identical after resolving typedefs.  */
4087   if (a == b)
4088     return true;
4089
4090   /* If after resolving typedefs a and b are not of the same type
4091      code then they are not equal.  */
4092   if (a->code () != b->code ())
4093     return false;
4094
4095   /* If a and b are both pointers types or both reference types then
4096      they are equal of the same type iff the objects they refer to are
4097      of the same type.  */
4098   if (a->code () == TYPE_CODE_PTR
4099       || a->code () == TYPE_CODE_REF)
4100     return types_equal (TYPE_TARGET_TYPE (a),
4101                         TYPE_TARGET_TYPE (b));
4102
4103   /* Well, damnit, if the names are exactly the same, I'll say they
4104      are exactly the same.  This happens when we generate method
4105      stubs.  The types won't point to the same address, but they
4106      really are the same.  */
4107
4108   if (a->name () && b->name ()
4109       && strcmp (a->name (), b->name ()) == 0)
4110     return true;
4111
4112   /* Two function types are equal if their argument and return types
4113      are equal.  */
4114   if (a->code () == TYPE_CODE_FUNC)
4115     {
4116       int i;
4117
4118       if (a->num_fields () != b->num_fields ())
4119         return false;
4120       
4121       if (!types_equal (TYPE_TARGET_TYPE (a), TYPE_TARGET_TYPE (b)))
4122         return false;
4123
4124       for (i = 0; i < a->num_fields (); ++i)
4125         if (!types_equal (a->field (i).type (), b->field (i).type ()))
4126           return false;
4127
4128       return true;
4129     }
4130
4131   return false;
4132 }
4133 \f
4134 /* Deep comparison of types.  */
4135
4136 /* An entry in the type-equality bcache.  */
4137
4138 struct type_equality_entry
4139 {
4140   type_equality_entry (struct type *t1, struct type *t2)
4141     : type1 (t1),
4142       type2 (t2)
4143   {
4144   }
4145
4146   struct type *type1, *type2;
4147 };
4148
4149 /* A helper function to compare two strings.  Returns true if they are
4150    the same, false otherwise.  Handles NULLs properly.  */
4151
4152 static bool
4153 compare_maybe_null_strings (const char *s, const char *t)
4154 {
4155   if (s == NULL || t == NULL)
4156     return s == t;
4157   return strcmp (s, t) == 0;
4158 }
4159
4160 /* A helper function for check_types_worklist that checks two types for
4161    "deep" equality.  Returns true if the types are considered the
4162    same, false otherwise.  */
4163
4164 static bool
4165 check_types_equal (struct type *type1, struct type *type2,
4166                    std::vector<type_equality_entry> *worklist)
4167 {
4168   type1 = check_typedef (type1);
4169   type2 = check_typedef (type2);
4170
4171   if (type1 == type2)
4172     return true;
4173
4174   if (type1->code () != type2->code ()
4175       || TYPE_LENGTH (type1) != TYPE_LENGTH (type2)
4176       || type1->is_unsigned () != type2->is_unsigned ()
4177       || type1->has_no_signedness () != type2->has_no_signedness ()
4178       || type1->endianity_is_not_default () != type2->endianity_is_not_default ()
4179       || type1->has_varargs () != type2->has_varargs ()
4180       || type1->is_vector () != type2->is_vector ()
4181       || TYPE_NOTTEXT (type1) != TYPE_NOTTEXT (type2)
4182       || type1->instance_flags () != type2->instance_flags ()
4183       || type1->num_fields () != type2->num_fields ())
4184     return false;
4185
4186   if (!compare_maybe_null_strings (type1->name (), type2->name ()))
4187     return false;
4188   if (!compare_maybe_null_strings (type1->name (), type2->name ()))
4189     return false;
4190
4191   if (type1->code () == TYPE_CODE_RANGE)
4192     {
4193       if (*type1->bounds () != *type2->bounds ())
4194         return false;
4195     }
4196   else
4197     {
4198       int i;
4199
4200       for (i = 0; i < type1->num_fields (); ++i)
4201         {
4202           const struct field *field1 = &type1->field (i);
4203           const struct field *field2 = &type2->field (i);
4204
4205           if (FIELD_ARTIFICIAL (*field1) != FIELD_ARTIFICIAL (*field2)
4206               || FIELD_BITSIZE (*field1) != FIELD_BITSIZE (*field2)
4207               || field1->loc_kind () != field2->loc_kind ())
4208             return false;
4209           if (!compare_maybe_null_strings (field1->name (), field2->name ()))
4210             return false;
4211           switch (field1->loc_kind ())
4212             {
4213             case FIELD_LOC_KIND_BITPOS:
4214               if (field1->loc_bitpos () != field2->loc_bitpos ())
4215                 return false;
4216               break;
4217             case FIELD_LOC_KIND_ENUMVAL:
4218               if (field1->loc_enumval () != field2->loc_enumval ())
4219                 return false;
4220               /* Don't compare types of enum fields, because they don't
4221                  have a type.  */
4222               continue;
4223             case FIELD_LOC_KIND_PHYSADDR:
4224               if (field1->loc_physaddr () != field2->loc_physaddr ())
4225                 return false;
4226               break;
4227             case FIELD_LOC_KIND_PHYSNAME:
4228               if (!compare_maybe_null_strings (field1->loc_physname (),
4229                                                field2->loc_physname ()))
4230                 return false;
4231               break;
4232             case FIELD_LOC_KIND_DWARF_BLOCK:
4233               {
4234                 struct dwarf2_locexpr_baton *block1, *block2;
4235
4236                 block1 = field1->loc_dwarf_block ();
4237                 block2 = field2->loc_dwarf_block ();
4238                 if (block1->per_cu != block2->per_cu
4239                     || block1->size != block2->size
4240                     || memcmp (block1->data, block2->data, block1->size) != 0)
4241                   return false;
4242               }
4243               break;
4244             default:
4245               internal_error (__FILE__, __LINE__, _("Unsupported field kind "
4246                                                     "%d by check_types_equal"),
4247                               field1->loc_kind ());
4248             }
4249
4250           worklist->emplace_back (field1->type (), field2->type ());
4251         }
4252     }
4253
4254   if (TYPE_TARGET_TYPE (type1) != NULL)
4255     {
4256       if (TYPE_TARGET_TYPE (type2) == NULL)
4257         return false;
4258
4259       worklist->emplace_back (TYPE_TARGET_TYPE (type1),
4260                               TYPE_TARGET_TYPE (type2));
4261     }
4262   else if (TYPE_TARGET_TYPE (type2) != NULL)
4263     return false;
4264
4265   return true;
4266 }
4267
4268 /* Check types on a worklist for equality.  Returns false if any pair
4269    is not equal, true if they are all considered equal.  */
4270
4271 static bool
4272 check_types_worklist (std::vector<type_equality_entry> *worklist,
4273                       gdb::bcache *cache)
4274 {
4275   while (!worklist->empty ())
4276     {
4277       bool added;
4278
4279       struct type_equality_entry entry = std::move (worklist->back ());
4280       worklist->pop_back ();
4281
4282       /* If the type pair has already been visited, we know it is
4283          ok.  */
4284       cache->insert (&entry, sizeof (entry), &added);
4285       if (!added)
4286         continue;
4287
4288       if (!check_types_equal (entry.type1, entry.type2, worklist))
4289         return false;
4290     }
4291
4292   return true;
4293 }
4294
4295 /* Return true if types TYPE1 and TYPE2 are equal, as determined by a
4296    "deep comparison".  Otherwise return false.  */
4297
4298 bool
4299 types_deeply_equal (struct type *type1, struct type *type2)
4300 {
4301   std::vector<type_equality_entry> worklist;
4302
4303   gdb_assert (type1 != NULL && type2 != NULL);
4304
4305   /* Early exit for the simple case.  */
4306   if (type1 == type2)
4307     return true;
4308
4309   gdb::bcache cache;
4310   worklist.emplace_back (type1, type2);
4311   return check_types_worklist (&worklist, &cache);
4312 }
4313
4314 /* Allocated status of type TYPE.  Return zero if type TYPE is allocated.
4315    Otherwise return one.  */
4316
4317 int
4318 type_not_allocated (const struct type *type)
4319 {
4320   struct dynamic_prop *prop = TYPE_ALLOCATED_PROP (type);
4321
4322   return (prop != nullptr && prop->kind () == PROP_CONST
4323           && prop->const_val () == 0);
4324 }
4325
4326 /* Associated status of type TYPE.  Return zero if type TYPE is associated.
4327    Otherwise return one.  */
4328
4329 int
4330 type_not_associated (const struct type *type)
4331 {
4332   struct dynamic_prop *prop = TYPE_ASSOCIATED_PROP (type);
4333
4334   return (prop != nullptr && prop->kind () == PROP_CONST
4335           && prop->const_val () == 0);
4336 }
4337
4338 /* rank_one_type helper for when PARM's type code is TYPE_CODE_PTR.  */
4339
4340 static struct rank
4341 rank_one_type_parm_ptr (struct type *parm, struct type *arg, struct value *value)
4342 {
4343   struct rank rank = {0,0};
4344
4345   switch (arg->code ())
4346     {
4347     case TYPE_CODE_PTR:
4348
4349       /* Allowed pointer conversions are:
4350          (a) pointer to void-pointer conversion.  */
4351       if (TYPE_TARGET_TYPE (parm)->code () == TYPE_CODE_VOID)
4352         return VOID_PTR_CONVERSION_BADNESS;
4353
4354       /* (b) pointer to ancestor-pointer conversion.  */
4355       rank.subrank = distance_to_ancestor (TYPE_TARGET_TYPE (parm),
4356                                            TYPE_TARGET_TYPE (arg),
4357                                            0);
4358       if (rank.subrank >= 0)
4359         return sum_ranks (BASE_PTR_CONVERSION_BADNESS, rank);
4360
4361       return INCOMPATIBLE_TYPE_BADNESS;
4362     case TYPE_CODE_ARRAY:
4363       {
4364         struct type *t1 = TYPE_TARGET_TYPE (parm);
4365         struct type *t2 = TYPE_TARGET_TYPE (arg);
4366
4367         if (types_equal (t1, t2))
4368           {
4369             /* Make sure they are CV equal.  */
4370             if (TYPE_CONST (t1) != TYPE_CONST (t2))
4371               rank.subrank |= CV_CONVERSION_CONST;
4372             if (TYPE_VOLATILE (t1) != TYPE_VOLATILE (t2))
4373               rank.subrank |= CV_CONVERSION_VOLATILE;
4374             if (rank.subrank != 0)
4375               return sum_ranks (CV_CONVERSION_BADNESS, rank);
4376             return EXACT_MATCH_BADNESS;
4377           }
4378         return INCOMPATIBLE_TYPE_BADNESS;
4379       }
4380     case TYPE_CODE_FUNC:
4381       return rank_one_type (TYPE_TARGET_TYPE (parm), arg, NULL);
4382     case TYPE_CODE_INT:
4383       if (value != NULL && value_type (value)->code () == TYPE_CODE_INT)
4384         {
4385           if (value_as_long (value) == 0)
4386             {
4387               /* Null pointer conversion: allow it to be cast to a pointer.
4388                  [4.10.1 of C++ standard draft n3290]  */
4389               return NULL_POINTER_CONVERSION_BADNESS;
4390             }
4391           else
4392             {
4393               /* If type checking is disabled, allow the conversion.  */
4394               if (!strict_type_checking)
4395                 return NS_INTEGER_POINTER_CONVERSION_BADNESS;
4396             }
4397         }
4398       /* fall through  */
4399     case TYPE_CODE_ENUM:
4400     case TYPE_CODE_FLAGS:
4401     case TYPE_CODE_CHAR:
4402     case TYPE_CODE_RANGE:
4403     case TYPE_CODE_BOOL:
4404     default:
4405       return INCOMPATIBLE_TYPE_BADNESS;
4406     }
4407 }
4408
4409 /* rank_one_type helper for when PARM's type code is TYPE_CODE_ARRAY.  */
4410
4411 static struct rank
4412 rank_one_type_parm_array (struct type *parm, struct type *arg, struct value *value)
4413 {
4414   switch (arg->code ())
4415     {
4416     case TYPE_CODE_PTR:
4417     case TYPE_CODE_ARRAY:
4418       return rank_one_type (TYPE_TARGET_TYPE (parm),
4419                             TYPE_TARGET_TYPE (arg), NULL);
4420     default:
4421       return INCOMPATIBLE_TYPE_BADNESS;
4422     }
4423 }
4424
4425 /* rank_one_type helper for when PARM's type code is TYPE_CODE_FUNC.  */
4426
4427 static struct rank
4428 rank_one_type_parm_func (struct type *parm, struct type *arg, struct value *value)
4429 {
4430   switch (arg->code ())
4431     {
4432     case TYPE_CODE_PTR: /* funcptr -> func */
4433       return rank_one_type (parm, TYPE_TARGET_TYPE (arg), NULL);
4434     default:
4435       return INCOMPATIBLE_TYPE_BADNESS;
4436     }
4437 }
4438
4439 /* rank_one_type helper for when PARM's type code is TYPE_CODE_INT.  */
4440
4441 static struct rank
4442 rank_one_type_parm_int (struct type *parm, struct type *arg, struct value *value)
4443 {
4444   switch (arg->code ())
4445     {
4446     case TYPE_CODE_INT:
4447       if (TYPE_LENGTH (arg) == TYPE_LENGTH (parm))
4448         {
4449           /* Deal with signed, unsigned, and plain chars and
4450              signed and unsigned ints.  */
4451           if (parm->has_no_signedness ())
4452             {
4453               /* This case only for character types.  */
4454               if (arg->has_no_signedness ())
4455                 return EXACT_MATCH_BADNESS;     /* plain char -> plain char */
4456               else              /* signed/unsigned char -> plain char */
4457                 return INTEGER_CONVERSION_BADNESS;
4458             }
4459           else if (parm->is_unsigned ())
4460             {
4461               if (arg->is_unsigned ())
4462                 {
4463                   /* unsigned int -> unsigned int, or
4464                      unsigned long -> unsigned long */
4465                   if (integer_types_same_name_p (parm->name (),
4466                                                  arg->name ()))
4467                     return EXACT_MATCH_BADNESS;
4468                   else if (integer_types_same_name_p (arg->name (),
4469                                                       "int")
4470                            && integer_types_same_name_p (parm->name (),
4471                                                          "long"))
4472                     /* unsigned int -> unsigned long */
4473                     return INTEGER_PROMOTION_BADNESS;
4474                   else
4475                     /* unsigned long -> unsigned int */
4476                     return INTEGER_CONVERSION_BADNESS;
4477                 }
4478               else
4479                 {
4480                   if (integer_types_same_name_p (arg->name (),
4481                                                  "long")
4482                       && integer_types_same_name_p (parm->name (),
4483                                                     "int"))
4484                     /* signed long -> unsigned int */
4485                     return INTEGER_CONVERSION_BADNESS;
4486                   else
4487                     /* signed int/long -> unsigned int/long */
4488                     return INTEGER_CONVERSION_BADNESS;
4489                 }
4490             }
4491           else if (!arg->has_no_signedness () && !arg->is_unsigned ())
4492             {
4493               if (integer_types_same_name_p (parm->name (),
4494                                              arg->name ()))
4495                 return EXACT_MATCH_BADNESS;
4496               else if (integer_types_same_name_p (arg->name (),
4497                                                   "int")
4498                        && integer_types_same_name_p (parm->name (),
4499                                                      "long"))
4500                 return INTEGER_PROMOTION_BADNESS;
4501               else
4502                 return INTEGER_CONVERSION_BADNESS;
4503             }
4504           else
4505             return INTEGER_CONVERSION_BADNESS;
4506         }
4507       else if (TYPE_LENGTH (arg) < TYPE_LENGTH (parm))
4508         return INTEGER_PROMOTION_BADNESS;
4509       else
4510         return INTEGER_CONVERSION_BADNESS;
4511     case TYPE_CODE_ENUM:
4512     case TYPE_CODE_FLAGS:
4513     case TYPE_CODE_CHAR:
4514     case TYPE_CODE_RANGE:
4515     case TYPE_CODE_BOOL:
4516       if (arg->is_declared_class ())
4517         return INCOMPATIBLE_TYPE_BADNESS;
4518       return INTEGER_PROMOTION_BADNESS;
4519     case TYPE_CODE_FLT:
4520       return INT_FLOAT_CONVERSION_BADNESS;
4521     case TYPE_CODE_PTR:
4522       return NS_POINTER_CONVERSION_BADNESS;
4523     default:
4524       return INCOMPATIBLE_TYPE_BADNESS;
4525     }
4526 }
4527
4528 /* rank_one_type helper for when PARM's type code is TYPE_CODE_ENUM.  */
4529
4530 static struct rank
4531 rank_one_type_parm_enum (struct type *parm, struct type *arg, struct value *value)
4532 {
4533   switch (arg->code ())
4534     {
4535     case TYPE_CODE_INT:
4536     case TYPE_CODE_CHAR:
4537     case TYPE_CODE_RANGE:
4538     case TYPE_CODE_BOOL:
4539     case TYPE_CODE_ENUM:
4540       if (parm->is_declared_class () || arg->is_declared_class ())
4541         return INCOMPATIBLE_TYPE_BADNESS;
4542       return INTEGER_CONVERSION_BADNESS;
4543     case TYPE_CODE_FLT:
4544       return INT_FLOAT_CONVERSION_BADNESS;
4545     default:
4546       return INCOMPATIBLE_TYPE_BADNESS;
4547     }
4548 }
4549
4550 /* rank_one_type helper for when PARM's type code is TYPE_CODE_CHAR.  */
4551
4552 static struct rank
4553 rank_one_type_parm_char (struct type *parm, struct type *arg, struct value *value)
4554 {
4555   switch (arg->code ())
4556     {
4557     case TYPE_CODE_RANGE:
4558     case TYPE_CODE_BOOL:
4559     case TYPE_CODE_ENUM:
4560       if (arg->is_declared_class ())
4561         return INCOMPATIBLE_TYPE_BADNESS;
4562       return INTEGER_CONVERSION_BADNESS;
4563     case TYPE_CODE_FLT:
4564       return INT_FLOAT_CONVERSION_BADNESS;
4565     case TYPE_CODE_INT:
4566       if (TYPE_LENGTH (arg) > TYPE_LENGTH (parm))
4567         return INTEGER_CONVERSION_BADNESS;
4568       else if (TYPE_LENGTH (arg) < TYPE_LENGTH (parm))
4569         return INTEGER_PROMOTION_BADNESS;
4570       /* fall through */
4571     case TYPE_CODE_CHAR:
4572       /* Deal with signed, unsigned, and plain chars for C++ and
4573          with int cases falling through from previous case.  */
4574       if (parm->has_no_signedness ())
4575         {
4576           if (arg->has_no_signedness ())
4577             return EXACT_MATCH_BADNESS;
4578           else
4579             return INTEGER_CONVERSION_BADNESS;
4580         }
4581       else if (parm->is_unsigned ())
4582         {
4583           if (arg->is_unsigned ())
4584             return EXACT_MATCH_BADNESS;
4585           else
4586             return INTEGER_PROMOTION_BADNESS;
4587         }
4588       else if (!arg->has_no_signedness () && !arg->is_unsigned ())
4589         return EXACT_MATCH_BADNESS;
4590       else
4591         return INTEGER_CONVERSION_BADNESS;
4592     default:
4593       return INCOMPATIBLE_TYPE_BADNESS;
4594     }
4595 }
4596
4597 /* rank_one_type helper for when PARM's type code is TYPE_CODE_RANGE.  */
4598
4599 static struct rank
4600 rank_one_type_parm_range (struct type *parm, struct type *arg, struct value *value)
4601 {
4602   switch (arg->code ())
4603     {
4604     case TYPE_CODE_INT:
4605     case TYPE_CODE_CHAR:
4606     case TYPE_CODE_RANGE:
4607     case TYPE_CODE_BOOL:
4608     case TYPE_CODE_ENUM:
4609       return INTEGER_CONVERSION_BADNESS;
4610     case TYPE_CODE_FLT:
4611       return INT_FLOAT_CONVERSION_BADNESS;
4612     default:
4613       return INCOMPATIBLE_TYPE_BADNESS;
4614     }
4615 }
4616
4617 /* rank_one_type helper for when PARM's type code is TYPE_CODE_BOOL.  */
4618
4619 static struct rank
4620 rank_one_type_parm_bool (struct type *parm, struct type *arg, struct value *value)
4621 {
4622   switch (arg->code ())
4623     {
4624       /* n3290 draft, section 4.12.1 (conv.bool):
4625
4626          "A prvalue of arithmetic, unscoped enumeration, pointer, or
4627          pointer to member type can be converted to a prvalue of type
4628          bool.  A zero value, null pointer value, or null member pointer
4629          value is converted to false; any other value is converted to
4630          true.  A prvalue of type std::nullptr_t can be converted to a
4631          prvalue of type bool; the resulting value is false."  */
4632     case TYPE_CODE_INT:
4633     case TYPE_CODE_CHAR:
4634     case TYPE_CODE_ENUM:
4635     case TYPE_CODE_FLT:
4636     case TYPE_CODE_MEMBERPTR:
4637     case TYPE_CODE_PTR:
4638       return BOOL_CONVERSION_BADNESS;
4639     case TYPE_CODE_RANGE:
4640       return INCOMPATIBLE_TYPE_BADNESS;
4641     case TYPE_CODE_BOOL:
4642       return EXACT_MATCH_BADNESS;
4643     default:
4644       return INCOMPATIBLE_TYPE_BADNESS;
4645     }
4646 }
4647
4648 /* rank_one_type helper for when PARM's type code is TYPE_CODE_FLOAT.  */
4649
4650 static struct rank
4651 rank_one_type_parm_float (struct type *parm, struct type *arg, struct value *value)
4652 {
4653   switch (arg->code ())
4654     {
4655     case TYPE_CODE_FLT:
4656       if (TYPE_LENGTH (arg) < TYPE_LENGTH (parm))
4657         return FLOAT_PROMOTION_BADNESS;
4658       else if (TYPE_LENGTH (arg) == TYPE_LENGTH (parm))
4659         return EXACT_MATCH_BADNESS;
4660       else
4661         return FLOAT_CONVERSION_BADNESS;
4662     case TYPE_CODE_INT:
4663     case TYPE_CODE_BOOL:
4664     case TYPE_CODE_ENUM:
4665     case TYPE_CODE_RANGE:
4666     case TYPE_CODE_CHAR:
4667       return INT_FLOAT_CONVERSION_BADNESS;
4668     default:
4669       return INCOMPATIBLE_TYPE_BADNESS;
4670     }
4671 }
4672
4673 /* rank_one_type helper for when PARM's type code is TYPE_CODE_COMPLEX.  */
4674
4675 static struct rank
4676 rank_one_type_parm_complex (struct type *parm, struct type *arg, struct value *value)
4677 {
4678   switch (arg->code ())
4679     {           /* Strictly not needed for C++, but...  */
4680     case TYPE_CODE_FLT:
4681       return FLOAT_PROMOTION_BADNESS;
4682     case TYPE_CODE_COMPLEX:
4683       return EXACT_MATCH_BADNESS;
4684     default:
4685       return INCOMPATIBLE_TYPE_BADNESS;
4686     }
4687 }
4688
4689 /* rank_one_type helper for when PARM's type code is TYPE_CODE_STRUCT.  */
4690
4691 static struct rank
4692 rank_one_type_parm_struct (struct type *parm, struct type *arg, struct value *value)
4693 {
4694   struct rank rank = {0, 0};
4695
4696   switch (arg->code ())
4697     {
4698     case TYPE_CODE_STRUCT:
4699       /* Check for derivation */
4700       rank.subrank = distance_to_ancestor (parm, arg, 0);
4701       if (rank.subrank >= 0)
4702         return sum_ranks (BASE_CONVERSION_BADNESS, rank);
4703       /* fall through */
4704     default:
4705       return INCOMPATIBLE_TYPE_BADNESS;
4706     }
4707 }
4708
4709 /* rank_one_type helper for when PARM's type code is TYPE_CODE_SET.  */
4710
4711 static struct rank
4712 rank_one_type_parm_set (struct type *parm, struct type *arg, struct value *value)
4713 {
4714   switch (arg->code ())
4715     {
4716       /* Not in C++ */
4717     case TYPE_CODE_SET:
4718       return rank_one_type (parm->field (0).type (),
4719                             arg->field (0).type (), NULL);
4720     default:
4721       return INCOMPATIBLE_TYPE_BADNESS;
4722     }
4723 }
4724
4725 /* Compare one type (PARM) for compatibility with another (ARG).
4726  * PARM is intended to be the parameter type of a function; and
4727  * ARG is the supplied argument's type.  This function tests if
4728  * the latter can be converted to the former.
4729  * VALUE is the argument's value or NULL if none (or called recursively)
4730  *
4731  * Return 0 if they are identical types;
4732  * Otherwise, return an integer which corresponds to how compatible
4733  * PARM is to ARG.  The higher the return value, the worse the match.
4734  * Generally the "bad" conversions are all uniformly assigned a 100.  */
4735
4736 struct rank
4737 rank_one_type (struct type *parm, struct type *arg, struct value *value)
4738 {
4739   struct rank rank = {0,0};
4740
4741   /* Resolve typedefs */
4742   if (parm->code () == TYPE_CODE_TYPEDEF)
4743     parm = check_typedef (parm);
4744   if (arg->code () == TYPE_CODE_TYPEDEF)
4745     arg = check_typedef (arg);
4746
4747   if (TYPE_IS_REFERENCE (parm) && value != NULL)
4748     {
4749       if (VALUE_LVAL (value) == not_lval)
4750         {
4751           /* Rvalues should preferably bind to rvalue references or const
4752              lvalue references.  */
4753           if (parm->code () == TYPE_CODE_RVALUE_REF)
4754             rank.subrank = REFERENCE_CONVERSION_RVALUE;
4755           else if (TYPE_CONST (TYPE_TARGET_TYPE (parm)))
4756             rank.subrank = REFERENCE_CONVERSION_CONST_LVALUE;
4757           else
4758             return INCOMPATIBLE_TYPE_BADNESS;
4759           return sum_ranks (rank, REFERENCE_CONVERSION_BADNESS);
4760         }
4761       else
4762         {
4763           /* It's illegal to pass an lvalue as an rvalue.  */
4764           if (parm->code () == TYPE_CODE_RVALUE_REF)
4765             return INCOMPATIBLE_TYPE_BADNESS;
4766         }
4767     }
4768
4769   if (types_equal (parm, arg))
4770     {
4771       struct type *t1 = parm;
4772       struct type *t2 = arg;
4773
4774       /* For pointers and references, compare target type.  */
4775       if (parm->is_pointer_or_reference ())
4776         {
4777           t1 = TYPE_TARGET_TYPE (parm);
4778           t2 = TYPE_TARGET_TYPE (arg);
4779         }
4780
4781       /* Make sure they are CV equal, too.  */
4782       if (TYPE_CONST (t1) != TYPE_CONST (t2))
4783         rank.subrank |= CV_CONVERSION_CONST;
4784       if (TYPE_VOLATILE (t1) != TYPE_VOLATILE (t2))
4785         rank.subrank |= CV_CONVERSION_VOLATILE;
4786       if (rank.subrank != 0)
4787         return sum_ranks (CV_CONVERSION_BADNESS, rank);
4788       return EXACT_MATCH_BADNESS;
4789     }
4790
4791   /* See through references, since we can almost make non-references
4792      references.  */
4793
4794   if (TYPE_IS_REFERENCE (arg))
4795     return (sum_ranks (rank_one_type (parm, TYPE_TARGET_TYPE (arg), NULL),
4796                        REFERENCE_SEE_THROUGH_BADNESS));
4797   if (TYPE_IS_REFERENCE (parm))
4798     return (sum_ranks (rank_one_type (TYPE_TARGET_TYPE (parm), arg, NULL),
4799                        REFERENCE_SEE_THROUGH_BADNESS));
4800   if (overload_debug)
4801     {
4802       /* Debugging only.  */
4803       fprintf_filtered (gdb_stderr,
4804                         "------ Arg is %s [%d], parm is %s [%d]\n",
4805                         arg->name (), arg->code (),
4806                         parm->name (), parm->code ());
4807     }
4808
4809   /* x -> y means arg of type x being supplied for parameter of type y.  */
4810
4811   switch (parm->code ())
4812     {
4813     case TYPE_CODE_PTR:
4814       return rank_one_type_parm_ptr (parm, arg, value);
4815     case TYPE_CODE_ARRAY:
4816       return rank_one_type_parm_array (parm, arg, value);
4817     case TYPE_CODE_FUNC:
4818       return rank_one_type_parm_func (parm, arg, value);
4819     case TYPE_CODE_INT:
4820       return rank_one_type_parm_int (parm, arg, value);
4821     case TYPE_CODE_ENUM:
4822       return rank_one_type_parm_enum (parm, arg, value);
4823     case TYPE_CODE_CHAR:
4824       return rank_one_type_parm_char (parm, arg, value);
4825     case TYPE_CODE_RANGE:
4826       return rank_one_type_parm_range (parm, arg, value);
4827     case TYPE_CODE_BOOL:
4828       return rank_one_type_parm_bool (parm, arg, value);
4829     case TYPE_CODE_FLT:
4830       return rank_one_type_parm_float (parm, arg, value);
4831     case TYPE_CODE_COMPLEX:
4832       return rank_one_type_parm_complex (parm, arg, value);
4833     case TYPE_CODE_STRUCT:
4834       return rank_one_type_parm_struct (parm, arg, value);
4835     case TYPE_CODE_SET:
4836       return rank_one_type_parm_set (parm, arg, value);
4837     default:
4838       return INCOMPATIBLE_TYPE_BADNESS;
4839     }                           /* switch (arg->code ()) */
4840 }
4841
4842 /* End of functions for overload resolution.  */
4843 \f
4844 /* Routines to pretty-print types.  */
4845
4846 static void
4847 print_bit_vector (B_TYPE *bits, int nbits)
4848 {
4849   int bitno;
4850
4851   for (bitno = 0; bitno < nbits; bitno++)
4852     {
4853       if ((bitno % 8) == 0)
4854         {
4855           puts_filtered (" ");
4856         }
4857       if (B_TST (bits, bitno))
4858         printf_filtered (("1"));
4859       else
4860         printf_filtered (("0"));
4861     }
4862 }
4863
4864 /* Note the first arg should be the "this" pointer, we may not want to
4865    include it since we may get into a infinitely recursive
4866    situation.  */
4867
4868 static void
4869 print_args (struct field *args, int nargs, int spaces)
4870 {
4871   if (args != NULL)
4872     {
4873       int i;
4874
4875       for (i = 0; i < nargs; i++)
4876         {
4877           printf_filtered
4878             ("%*s[%d] name '%s'\n", spaces, "", i,
4879              args[i].name () != NULL ? args[i].name () : "<NULL>");
4880           recursive_dump_type (args[i].type (), spaces + 2);
4881         }
4882     }
4883 }
4884
4885 int
4886 field_is_static (struct field *f)
4887 {
4888   /* "static" fields are the fields whose location is not relative
4889      to the address of the enclosing struct.  It would be nice to
4890      have a dedicated flag that would be set for static fields when
4891      the type is being created.  But in practice, checking the field
4892      loc_kind should give us an accurate answer.  */
4893   return (f->loc_kind () == FIELD_LOC_KIND_PHYSNAME
4894           || f->loc_kind () == FIELD_LOC_KIND_PHYSADDR);
4895 }
4896
4897 static void
4898 dump_fn_fieldlists (struct type *type, int spaces)
4899 {
4900   int method_idx;
4901   int overload_idx;
4902   struct fn_field *f;
4903
4904   printf_filtered ("%*sfn_fieldlists %s\n", spaces, "",
4905                    host_address_to_string (TYPE_FN_FIELDLISTS (type)));
4906   for (method_idx = 0; method_idx < TYPE_NFN_FIELDS (type); method_idx++)
4907     {
4908       f = TYPE_FN_FIELDLIST1 (type, method_idx);
4909       printf_filtered
4910         ("%*s[%d] name '%s' (%s) length %d\n", spaces + 2, "",
4911          method_idx,
4912          TYPE_FN_FIELDLIST_NAME (type, method_idx),
4913          host_address_to_string (TYPE_FN_FIELDLIST_NAME (type, method_idx)),
4914          TYPE_FN_FIELDLIST_LENGTH (type, method_idx));
4915       for (overload_idx = 0;
4916            overload_idx < TYPE_FN_FIELDLIST_LENGTH (type, method_idx);
4917            overload_idx++)
4918         {
4919           printf_filtered
4920             ("%*s[%d] physname '%s' (%s)\n",
4921              spaces + 4, "", overload_idx,
4922              TYPE_FN_FIELD_PHYSNAME (f, overload_idx),
4923              host_address_to_string (TYPE_FN_FIELD_PHYSNAME (f,
4924                                                              overload_idx)));
4925           printf_filtered
4926             ("%*stype %s\n", spaces + 8, "",
4927              host_address_to_string (TYPE_FN_FIELD_TYPE (f, overload_idx)));
4928
4929           recursive_dump_type (TYPE_FN_FIELD_TYPE (f, overload_idx),
4930                                spaces + 8 + 2);
4931
4932           printf_filtered
4933             ("%*sargs %s\n", spaces + 8, "",
4934              host_address_to_string (TYPE_FN_FIELD_ARGS (f, overload_idx)));
4935           print_args (TYPE_FN_FIELD_ARGS (f, overload_idx),
4936                       TYPE_FN_FIELD_TYPE (f, overload_idx)->num_fields (),
4937                       spaces + 8 + 2);
4938           printf_filtered
4939             ("%*sfcontext %s\n", spaces + 8, "",
4940              host_address_to_string (TYPE_FN_FIELD_FCONTEXT (f,
4941                                                              overload_idx)));
4942
4943           printf_filtered ("%*sis_const %d\n", spaces + 8, "",
4944                            TYPE_FN_FIELD_CONST (f, overload_idx));
4945           printf_filtered ("%*sis_volatile %d\n", spaces + 8, "",
4946                            TYPE_FN_FIELD_VOLATILE (f, overload_idx));
4947           printf_filtered ("%*sis_private %d\n", spaces + 8, "",
4948                            TYPE_FN_FIELD_PRIVATE (f, overload_idx));
4949           printf_filtered ("%*sis_protected %d\n", spaces + 8, "",
4950                            TYPE_FN_FIELD_PROTECTED (f, overload_idx));
4951           printf_filtered ("%*sis_stub %d\n", spaces + 8, "",
4952                            TYPE_FN_FIELD_STUB (f, overload_idx));
4953           printf_filtered ("%*sdefaulted %d\n", spaces + 8, "",
4954                            TYPE_FN_FIELD_DEFAULTED (f, overload_idx));
4955           printf_filtered ("%*sis_deleted %d\n", spaces + 8, "",
4956                            TYPE_FN_FIELD_DELETED (f, overload_idx));
4957           printf_filtered ("%*svoffset %u\n", spaces + 8, "",
4958                            TYPE_FN_FIELD_VOFFSET (f, overload_idx));
4959         }
4960     }
4961 }
4962
4963 static void
4964 print_cplus_stuff (struct type *type, int spaces)
4965 {
4966   printf_filtered ("%*svptr_fieldno %d\n", spaces, "",
4967                    TYPE_VPTR_FIELDNO (type));
4968   printf_filtered ("%*svptr_basetype %s\n", spaces, "",
4969                    host_address_to_string (TYPE_VPTR_BASETYPE (type)));
4970   if (TYPE_VPTR_BASETYPE (type) != NULL)
4971     recursive_dump_type (TYPE_VPTR_BASETYPE (type), spaces + 2);
4972
4973   printf_filtered ("%*sn_baseclasses %d\n", spaces, "",
4974                    TYPE_N_BASECLASSES (type));
4975   printf_filtered ("%*snfn_fields %d\n", spaces, "",
4976                    TYPE_NFN_FIELDS (type));
4977   if (TYPE_N_BASECLASSES (type) > 0)
4978     {
4979       printf_filtered
4980         ("%*svirtual_field_bits (%d bits at *%s)",
4981          spaces, "", TYPE_N_BASECLASSES (type),
4982          host_address_to_string (TYPE_FIELD_VIRTUAL_BITS (type)));
4983
4984       print_bit_vector (TYPE_FIELD_VIRTUAL_BITS (type),
4985                         TYPE_N_BASECLASSES (type));
4986       puts_filtered ("\n");
4987     }
4988   if (type->num_fields () > 0)
4989     {
4990       if (TYPE_FIELD_PRIVATE_BITS (type) != NULL)
4991         {
4992           printf_filtered
4993             ("%*sprivate_field_bits (%d bits at *%s)",
4994              spaces, "", type->num_fields (),
4995              host_address_to_string (TYPE_FIELD_PRIVATE_BITS (type)));
4996           print_bit_vector (TYPE_FIELD_PRIVATE_BITS (type),
4997                             type->num_fields ());
4998           puts_filtered ("\n");
4999         }
5000       if (TYPE_FIELD_PROTECTED_BITS (type) != NULL)
5001         {
5002           printf_filtered
5003             ("%*sprotected_field_bits (%d bits at *%s",
5004              spaces, "", type->num_fields (),
5005              host_address_to_string (TYPE_FIELD_PROTECTED_BITS (type)));
5006           print_bit_vector (TYPE_FIELD_PROTECTED_BITS (type),
5007                             type->num_fields ());
5008           puts_filtered ("\n");
5009         }
5010     }
5011   if (TYPE_NFN_FIELDS (type) > 0)
5012     {
5013       dump_fn_fieldlists (type, spaces);
5014     }
5015
5016   printf_filtered ("%*scalling_convention %d\n", spaces, "",
5017                    TYPE_CPLUS_CALLING_CONVENTION (type));
5018 }
5019
5020 /* Print the contents of the TYPE's type_specific union, assuming that
5021    its type-specific kind is TYPE_SPECIFIC_GNAT_STUFF.  */
5022
5023 static void
5024 print_gnat_stuff (struct type *type, int spaces)
5025 {
5026   struct type *descriptive_type = TYPE_DESCRIPTIVE_TYPE (type);
5027
5028   if (descriptive_type == NULL)
5029     printf_filtered ("%*sno descriptive type\n", spaces + 2, "");
5030   else
5031     {
5032       printf_filtered ("%*sdescriptive type\n", spaces + 2, "");
5033       recursive_dump_type (descriptive_type, spaces + 4);
5034     }
5035 }
5036
5037 /* Print the contents of the TYPE's type_specific union, assuming that
5038    its type-specific kind is TYPE_SPECIFIC_FIXED_POINT.  */
5039
5040 static void
5041 print_fixed_point_type_info (struct type *type, int spaces)
5042 {
5043   printf_filtered ("%*sscaling factor: %s\n", spaces + 2, "",
5044                    type->fixed_point_scaling_factor ().str ().c_str ());
5045 }
5046
5047 static struct obstack dont_print_type_obstack;
5048
5049 /* Print the dynamic_prop PROP.  */
5050
5051 static void
5052 dump_dynamic_prop (dynamic_prop const& prop)
5053 {
5054   switch (prop.kind ())
5055     {
5056     case PROP_CONST:
5057       printf_filtered ("%s", plongest (prop.const_val ()));
5058       break;
5059     case PROP_UNDEFINED:
5060       printf_filtered ("(undefined)");
5061       break;
5062     case PROP_LOCEXPR:
5063     case PROP_LOCLIST:
5064       printf_filtered ("(dynamic)");
5065       break;
5066     default:
5067       gdb_assert_not_reached ("unhandled prop kind");
5068       break;
5069     }
5070 }
5071
5072 void
5073 recursive_dump_type (struct type *type, int spaces)
5074 {
5075   int idx;
5076
5077   if (spaces == 0)
5078     obstack_begin (&dont_print_type_obstack, 0);
5079
5080   if (type->num_fields () > 0
5081       || (HAVE_CPLUS_STRUCT (type) && TYPE_NFN_FIELDS (type) > 0))
5082     {
5083       struct type **first_dont_print
5084         = (struct type **) obstack_base (&dont_print_type_obstack);
5085
5086       int i = (struct type **) 
5087         obstack_next_free (&dont_print_type_obstack) - first_dont_print;
5088
5089       while (--i >= 0)
5090         {
5091           if (type == first_dont_print[i])
5092             {
5093               printf_filtered ("%*stype node %s", spaces, "",
5094                                host_address_to_string (type));
5095               printf_filtered (_(" <same as already seen type>\n"));
5096               return;
5097             }
5098         }
5099
5100       obstack_ptr_grow (&dont_print_type_obstack, type);
5101     }
5102
5103   printf_filtered ("%*stype node %s\n", spaces, "",
5104                    host_address_to_string (type));
5105   printf_filtered ("%*sname '%s' (%s)\n", spaces, "",
5106                    type->name () ? type->name () : "<NULL>",
5107                    host_address_to_string (type->name ()));
5108   printf_filtered ("%*scode 0x%x ", spaces, "", type->code ());
5109   switch (type->code ())
5110     {
5111     case TYPE_CODE_UNDEF:
5112       printf_filtered ("(TYPE_CODE_UNDEF)");
5113       break;
5114     case TYPE_CODE_PTR:
5115       printf_filtered ("(TYPE_CODE_PTR)");
5116       break;
5117     case TYPE_CODE_ARRAY:
5118       printf_filtered ("(TYPE_CODE_ARRAY)");
5119       break;
5120     case TYPE_CODE_STRUCT:
5121       printf_filtered ("(TYPE_CODE_STRUCT)");
5122       break;
5123     case TYPE_CODE_UNION:
5124       printf_filtered ("(TYPE_CODE_UNION)");
5125       break;
5126     case TYPE_CODE_ENUM:
5127       printf_filtered ("(TYPE_CODE_ENUM)");
5128       break;
5129     case TYPE_CODE_FLAGS:
5130       printf_filtered ("(TYPE_CODE_FLAGS)");
5131       break;
5132     case TYPE_CODE_FUNC:
5133       printf_filtered ("(TYPE_CODE_FUNC)");
5134       break;
5135     case TYPE_CODE_INT:
5136       printf_filtered ("(TYPE_CODE_INT)");
5137       break;
5138     case TYPE_CODE_FLT:
5139       printf_filtered ("(TYPE_CODE_FLT)");
5140       break;
5141     case TYPE_CODE_VOID:
5142       printf_filtered ("(TYPE_CODE_VOID)");
5143       break;
5144     case TYPE_CODE_SET:
5145       printf_filtered ("(TYPE_CODE_SET)");
5146       break;
5147     case TYPE_CODE_RANGE:
5148       printf_filtered ("(TYPE_CODE_RANGE)");
5149       break;
5150     case TYPE_CODE_STRING:
5151       printf_filtered ("(TYPE_CODE_STRING)");
5152       break;
5153     case TYPE_CODE_ERROR:
5154       printf_filtered ("(TYPE_CODE_ERROR)");
5155       break;
5156     case TYPE_CODE_MEMBERPTR:
5157       printf_filtered ("(TYPE_CODE_MEMBERPTR)");
5158       break;
5159     case TYPE_CODE_METHODPTR:
5160       printf_filtered ("(TYPE_CODE_METHODPTR)");
5161       break;
5162     case TYPE_CODE_METHOD:
5163       printf_filtered ("(TYPE_CODE_METHOD)");
5164       break;
5165     case TYPE_CODE_REF:
5166       printf_filtered ("(TYPE_CODE_REF)");
5167       break;
5168     case TYPE_CODE_CHAR:
5169       printf_filtered ("(TYPE_CODE_CHAR)");
5170       break;
5171     case TYPE_CODE_BOOL:
5172       printf_filtered ("(TYPE_CODE_BOOL)");
5173       break;
5174     case TYPE_CODE_COMPLEX:
5175       printf_filtered ("(TYPE_CODE_COMPLEX)");
5176       break;
5177     case TYPE_CODE_TYPEDEF:
5178       printf_filtered ("(TYPE_CODE_TYPEDEF)");
5179       break;
5180     case TYPE_CODE_NAMESPACE:
5181       printf_filtered ("(TYPE_CODE_NAMESPACE)");
5182       break;
5183     case TYPE_CODE_FIXED_POINT:
5184       printf_filtered ("(TYPE_CODE_FIXED_POINT)");
5185       break;
5186     default:
5187       printf_filtered ("(UNKNOWN TYPE CODE)");
5188       break;
5189     }
5190   puts_filtered ("\n");
5191   printf_filtered ("%*slength %s\n", spaces, "",
5192                    pulongest (TYPE_LENGTH (type)));
5193   if (type->is_objfile_owned ())
5194     printf_filtered ("%*sobjfile %s\n", spaces, "",
5195                      host_address_to_string (type->objfile_owner ()));
5196   else
5197     printf_filtered ("%*sgdbarch %s\n", spaces, "",
5198                      host_address_to_string (type->arch_owner ()));
5199   printf_filtered ("%*starget_type %s\n", spaces, "",
5200                    host_address_to_string (TYPE_TARGET_TYPE (type)));
5201   if (TYPE_TARGET_TYPE (type) != NULL)
5202     {
5203       recursive_dump_type (TYPE_TARGET_TYPE (type), spaces + 2);
5204     }
5205   printf_filtered ("%*spointer_type %s\n", spaces, "",
5206                    host_address_to_string (TYPE_POINTER_TYPE (type)));
5207   printf_filtered ("%*sreference_type %s\n", spaces, "",
5208                    host_address_to_string (TYPE_REFERENCE_TYPE (type)));
5209   printf_filtered ("%*stype_chain %s\n", spaces, "",
5210                    host_address_to_string (TYPE_CHAIN (type)));
5211   printf_filtered ("%*sinstance_flags 0x%x", spaces, "", 
5212                    (unsigned) type->instance_flags ());
5213   if (TYPE_CONST (type))
5214     {
5215       puts_filtered (" TYPE_CONST");
5216     }
5217   if (TYPE_VOLATILE (type))
5218     {
5219       puts_filtered (" TYPE_VOLATILE");
5220     }
5221   if (TYPE_CODE_SPACE (type))
5222     {
5223       puts_filtered (" TYPE_CODE_SPACE");
5224     }
5225   if (TYPE_DATA_SPACE (type))
5226     {
5227       puts_filtered (" TYPE_DATA_SPACE");
5228     }
5229   if (TYPE_ADDRESS_CLASS_1 (type))
5230     {
5231       puts_filtered (" TYPE_ADDRESS_CLASS_1");
5232     }
5233   if (TYPE_ADDRESS_CLASS_2 (type))
5234     {
5235       puts_filtered (" TYPE_ADDRESS_CLASS_2");
5236     }
5237   if (TYPE_RESTRICT (type))
5238     {
5239       puts_filtered (" TYPE_RESTRICT");
5240     }
5241   if (TYPE_ATOMIC (type))
5242     {
5243       puts_filtered (" TYPE_ATOMIC");
5244     }
5245   puts_filtered ("\n");
5246
5247   printf_filtered ("%*sflags", spaces, "");
5248   if (type->is_unsigned ())
5249     {
5250       puts_filtered (" TYPE_UNSIGNED");
5251     }
5252   if (type->has_no_signedness ())
5253     {
5254       puts_filtered (" TYPE_NOSIGN");
5255     }
5256   if (type->endianity_is_not_default ())
5257     {
5258       puts_filtered (" TYPE_ENDIANITY_NOT_DEFAULT");
5259     }
5260   if (type->is_stub ())
5261     {
5262       puts_filtered (" TYPE_STUB");
5263     }
5264   if (type->target_is_stub ())
5265     {
5266       puts_filtered (" TYPE_TARGET_STUB");
5267     }
5268   if (type->is_prototyped ())
5269     {
5270       puts_filtered (" TYPE_PROTOTYPED");
5271     }
5272   if (type->has_varargs ())
5273     {
5274       puts_filtered (" TYPE_VARARGS");
5275     }
5276   /* This is used for things like AltiVec registers on ppc.  Gcc emits
5277      an attribute for the array type, which tells whether or not we
5278      have a vector, instead of a regular array.  */
5279   if (type->is_vector ())
5280     {
5281       puts_filtered (" TYPE_VECTOR");
5282     }
5283   if (type->is_fixed_instance ())
5284     {
5285       puts_filtered (" TYPE_FIXED_INSTANCE");
5286     }
5287   if (type->stub_is_supported ())
5288     {
5289       puts_filtered (" TYPE_STUB_SUPPORTED");
5290     }
5291   if (TYPE_NOTTEXT (type))
5292     {
5293       puts_filtered (" TYPE_NOTTEXT");
5294     }
5295   puts_filtered ("\n");
5296   printf_filtered ("%*snfields %d ", spaces, "", type->num_fields ());
5297   if (TYPE_ASSOCIATED_PROP (type) != nullptr
5298       || TYPE_ALLOCATED_PROP (type) != nullptr)
5299     {
5300       printf_filtered ("%*s", spaces, "");
5301       if (TYPE_ASSOCIATED_PROP (type) != nullptr)
5302         {
5303           printf_filtered ("associated ");
5304           dump_dynamic_prop (*TYPE_ASSOCIATED_PROP (type));
5305         }
5306       if (TYPE_ALLOCATED_PROP (type) != nullptr)
5307         {
5308           if (TYPE_ASSOCIATED_PROP (type) != nullptr)
5309             printf_filtered ("  ");
5310           printf_filtered ("allocated ");
5311           dump_dynamic_prop (*TYPE_ALLOCATED_PROP (type));
5312         }
5313       printf_filtered ("\n");
5314     }
5315   printf_filtered ("%s\n", host_address_to_string (type->fields ()));
5316   for (idx = 0; idx < type->num_fields (); idx++)
5317     {
5318       if (type->code () == TYPE_CODE_ENUM)
5319         printf_filtered ("%*s[%d] enumval %s type ", spaces + 2, "",
5320                          idx, plongest (type->field (idx).loc_enumval ()));
5321       else
5322         printf_filtered ("%*s[%d] bitpos %s bitsize %d type ", spaces + 2, "",
5323                          idx, plongest (type->field (idx).loc_bitpos ()),
5324                          TYPE_FIELD_BITSIZE (type, idx));
5325       printf_filtered ("%s name '%s' (%s)\n",
5326                        host_address_to_string (type->field (idx).type ()),
5327                        type->field (idx).name () != NULL
5328                        ? type->field (idx).name ()
5329                        : "<NULL>",
5330                        host_address_to_string (type->field (idx).name ()));
5331       if (type->field (idx).type () != NULL)
5332         {
5333           recursive_dump_type (type->field (idx).type (), spaces + 4);
5334         }
5335     }
5336   if (type->code () == TYPE_CODE_RANGE)
5337     {
5338       printf_filtered ("%*slow ", spaces, "");
5339       dump_dynamic_prop (type->bounds ()->low);
5340       printf_filtered ("  high ");
5341       dump_dynamic_prop (type->bounds ()->high);
5342       printf_filtered ("\n");
5343     }
5344
5345   switch (TYPE_SPECIFIC_FIELD (type))
5346     {
5347       case TYPE_SPECIFIC_CPLUS_STUFF:
5348         printf_filtered ("%*scplus_stuff %s\n", spaces, "",
5349                          host_address_to_string (TYPE_CPLUS_SPECIFIC (type)));
5350         print_cplus_stuff (type, spaces);
5351         break;
5352
5353       case TYPE_SPECIFIC_GNAT_STUFF:
5354         printf_filtered ("%*sgnat_stuff %s\n", spaces, "",
5355                          host_address_to_string (TYPE_GNAT_SPECIFIC (type)));
5356         print_gnat_stuff (type, spaces);
5357         break;
5358
5359       case TYPE_SPECIFIC_FLOATFORMAT:
5360         printf_filtered ("%*sfloatformat ", spaces, "");
5361         if (TYPE_FLOATFORMAT (type) == NULL
5362             || TYPE_FLOATFORMAT (type)->name == NULL)
5363           puts_filtered ("(null)");
5364         else
5365           puts_filtered (TYPE_FLOATFORMAT (type)->name);
5366         puts_filtered ("\n");
5367         break;
5368
5369       case TYPE_SPECIFIC_FUNC:
5370         printf_filtered ("%*scalling_convention %d\n", spaces, "",
5371                          TYPE_CALLING_CONVENTION (type));
5372         /* tail_call_list is not printed.  */
5373         break;
5374
5375       case TYPE_SPECIFIC_SELF_TYPE:
5376         printf_filtered ("%*sself_type %s\n", spaces, "",
5377                          host_address_to_string (TYPE_SELF_TYPE (type)));
5378         break;
5379
5380       case TYPE_SPECIFIC_FIXED_POINT:
5381         printf_filtered ("%*sfixed_point_info ", spaces, "");
5382         print_fixed_point_type_info (type, spaces);
5383         puts_filtered ("\n");
5384         break;
5385
5386     case TYPE_SPECIFIC_INT:
5387       if (type->bit_size_differs_p ())
5388         {
5389           unsigned bit_size = type->bit_size ();
5390           unsigned bit_off = type->bit_offset ();
5391           printf_filtered ("%*s bit size = %u, bit offset = %u\n", spaces, "",
5392                            bit_size, bit_off);
5393         }
5394       break;
5395     }
5396
5397   if (spaces == 0)
5398     obstack_free (&dont_print_type_obstack, NULL);
5399 }
5400 \f
5401 /* Trivial helpers for the libiberty hash table, for mapping one
5402    type to another.  */
5403
5404 struct type_pair : public allocate_on_obstack
5405 {
5406   type_pair (struct type *old_, struct type *newobj_)
5407     : old (old_), newobj (newobj_)
5408   {}
5409
5410   struct type * const old, * const newobj;
5411 };
5412
5413 static hashval_t
5414 type_pair_hash (const void *item)
5415 {
5416   const struct type_pair *pair = (const struct type_pair *) item;
5417
5418   return htab_hash_pointer (pair->old);
5419 }
5420
5421 static int
5422 type_pair_eq (const void *item_lhs, const void *item_rhs)
5423 {
5424   const struct type_pair *lhs = (const struct type_pair *) item_lhs;
5425   const struct type_pair *rhs = (const struct type_pair *) item_rhs;
5426
5427   return lhs->old == rhs->old;
5428 }
5429
5430 /* Allocate the hash table used by copy_type_recursive to walk
5431    types without duplicates.  We use OBJFILE's obstack, because
5432    OBJFILE is about to be deleted.  */
5433
5434 htab_up
5435 create_copied_types_hash (struct objfile *objfile)
5436 {
5437   return htab_up (htab_create_alloc_ex (1, type_pair_hash, type_pair_eq,
5438                                         NULL, &objfile->objfile_obstack,
5439                                         hashtab_obstack_allocate,
5440                                         dummy_obstack_deallocate));
5441 }
5442
5443 /* Recursively copy (deep copy) a dynamic attribute list of a type.  */
5444
5445 static struct dynamic_prop_list *
5446 copy_dynamic_prop_list (struct obstack *objfile_obstack,
5447                         struct dynamic_prop_list *list)
5448 {
5449   struct dynamic_prop_list *copy = list;
5450   struct dynamic_prop_list **node_ptr = &copy;
5451
5452   while (*node_ptr != NULL)
5453     {
5454       struct dynamic_prop_list *node_copy;
5455
5456       node_copy = ((struct dynamic_prop_list *)
5457                    obstack_copy (objfile_obstack, *node_ptr,
5458                                  sizeof (struct dynamic_prop_list)));
5459       node_copy->prop = (*node_ptr)->prop;
5460       *node_ptr = node_copy;
5461
5462       node_ptr = &node_copy->next;
5463     }
5464
5465   return copy;
5466 }
5467
5468 /* Recursively copy (deep copy) TYPE, if it is associated with
5469    OBJFILE.  Return a new type owned by the gdbarch associated with the type, a
5470    saved type if we have already visited TYPE (using COPIED_TYPES), or TYPE if
5471    it is not associated with OBJFILE.  */
5472
5473 struct type *
5474 copy_type_recursive (struct objfile *objfile, 
5475                      struct type *type,
5476                      htab_t copied_types)
5477 {
5478   void **slot;
5479   struct type *new_type;
5480
5481   if (!type->is_objfile_owned ())
5482     return type;
5483
5484   /* This type shouldn't be pointing to any types in other objfiles;
5485      if it did, the type might disappear unexpectedly.  */
5486   gdb_assert (type->objfile_owner () == objfile);
5487
5488   struct type_pair pair (type, nullptr);
5489
5490   slot = htab_find_slot (copied_types, &pair, INSERT);
5491   if (*slot != NULL)
5492     return ((struct type_pair *) *slot)->newobj;
5493
5494   new_type = alloc_type_arch (type->arch ());
5495
5496   /* We must add the new type to the hash table immediately, in case
5497      we encounter this type again during a recursive call below.  */
5498   struct type_pair *stored
5499     = new (&objfile->objfile_obstack) struct type_pair (type, new_type);
5500
5501   *slot = stored;
5502
5503   /* Copy the common fields of types.  For the main type, we simply
5504      copy the entire thing and then update specific fields as needed.  */
5505   *TYPE_MAIN_TYPE (new_type) = *TYPE_MAIN_TYPE (type);
5506
5507   new_type->set_owner (type->arch ());
5508
5509   if (type->name ())
5510     new_type->set_name (xstrdup (type->name ()));
5511
5512   new_type->set_instance_flags (type->instance_flags ());
5513   TYPE_LENGTH (new_type) = TYPE_LENGTH (type);
5514
5515   /* Copy the fields.  */
5516   if (type->num_fields ())
5517     {
5518       int i, nfields;
5519
5520       nfields = type->num_fields ();
5521       new_type->set_fields
5522         ((struct field *)
5523          TYPE_ZALLOC (new_type, nfields * sizeof (struct field)));
5524
5525       for (i = 0; i < nfields; i++)
5526         {
5527           TYPE_FIELD_ARTIFICIAL (new_type, i) = 
5528             TYPE_FIELD_ARTIFICIAL (type, i);
5529           TYPE_FIELD_BITSIZE (new_type, i) = TYPE_FIELD_BITSIZE (type, i);
5530           if (type->field (i).type ())
5531             new_type->field (i).set_type
5532               (copy_type_recursive (objfile, type->field (i).type (),
5533                                     copied_types));
5534           if (type->field (i).name ())
5535             new_type->field (i).set_name (xstrdup (type->field (i).name ()));
5536
5537           switch (type->field (i).loc_kind ())
5538             {
5539             case FIELD_LOC_KIND_BITPOS:
5540               new_type->field (i).set_loc_bitpos (type->field (i).loc_bitpos ());
5541               break;
5542             case FIELD_LOC_KIND_ENUMVAL:
5543               new_type->field (i).set_loc_enumval (type->field (i).loc_enumval ());
5544               break;
5545             case FIELD_LOC_KIND_PHYSADDR:
5546               new_type->field (i).set_loc_physaddr
5547                 (type->field (i).loc_physaddr ());
5548               break;
5549             case FIELD_LOC_KIND_PHYSNAME:
5550               new_type->field (i).set_loc_physname
5551                 (xstrdup (type->field (i).loc_physname ()));
5552               break;
5553             case FIELD_LOC_KIND_DWARF_BLOCK:
5554               new_type->field (i).set_loc_dwarf_block
5555                 (type->field (i).loc_dwarf_block ());
5556               break;
5557             default:
5558               internal_error (__FILE__, __LINE__,
5559                               _("Unexpected type field location kind: %d"),
5560                               type->field (i).loc_kind ());
5561             }
5562         }
5563     }
5564
5565   /* For range types, copy the bounds information.  */
5566   if (type->code () == TYPE_CODE_RANGE)
5567     {
5568       range_bounds *bounds
5569         = ((struct range_bounds *) TYPE_ALLOC
5570            (new_type, sizeof (struct range_bounds)));
5571
5572       *bounds = *type->bounds ();
5573       new_type->set_bounds (bounds);
5574     }
5575
5576   if (type->main_type->dyn_prop_list != NULL)
5577     new_type->main_type->dyn_prop_list
5578       = copy_dynamic_prop_list (&objfile->objfile_obstack,
5579                                 type->main_type->dyn_prop_list);
5580
5581
5582   /* Copy pointers to other types.  */
5583   if (TYPE_TARGET_TYPE (type))
5584     TYPE_TARGET_TYPE (new_type) = 
5585       copy_type_recursive (objfile, 
5586                            TYPE_TARGET_TYPE (type),
5587                            copied_types);
5588
5589   /* Maybe copy the type_specific bits.
5590
5591      NOTE drow/2005-12-09: We do not copy the C++-specific bits like
5592      base classes and methods.  There's no fundamental reason why we
5593      can't, but at the moment it is not needed.  */
5594
5595   switch (TYPE_SPECIFIC_FIELD (type))
5596     {
5597     case TYPE_SPECIFIC_NONE:
5598       break;
5599     case TYPE_SPECIFIC_FUNC:
5600       INIT_FUNC_SPECIFIC (new_type);
5601       TYPE_CALLING_CONVENTION (new_type) = TYPE_CALLING_CONVENTION (type);
5602       TYPE_NO_RETURN (new_type) = TYPE_NO_RETURN (type);
5603       TYPE_TAIL_CALL_LIST (new_type) = NULL;
5604       break;
5605     case TYPE_SPECIFIC_FLOATFORMAT:
5606       TYPE_FLOATFORMAT (new_type) = TYPE_FLOATFORMAT (type);
5607       break;
5608     case TYPE_SPECIFIC_CPLUS_STUFF:
5609       INIT_CPLUS_SPECIFIC (new_type);
5610       break;
5611     case TYPE_SPECIFIC_GNAT_STUFF:
5612       INIT_GNAT_SPECIFIC (new_type);
5613       break;
5614     case TYPE_SPECIFIC_SELF_TYPE:
5615       set_type_self_type (new_type,
5616                           copy_type_recursive (objfile, TYPE_SELF_TYPE (type),
5617                                                copied_types));
5618       break;
5619     case TYPE_SPECIFIC_FIXED_POINT:
5620       INIT_FIXED_POINT_SPECIFIC (new_type);
5621       new_type->fixed_point_info ().scaling_factor
5622         = type->fixed_point_info ().scaling_factor;
5623       break;
5624     case TYPE_SPECIFIC_INT:
5625       TYPE_SPECIFIC_FIELD (new_type) = TYPE_SPECIFIC_INT;
5626       TYPE_MAIN_TYPE (new_type)->type_specific.int_stuff
5627         = TYPE_MAIN_TYPE (type)->type_specific.int_stuff;
5628       break;
5629
5630     default:
5631       gdb_assert_not_reached ("bad type_specific_kind");
5632     }
5633
5634   return new_type;
5635 }
5636
5637 /* Make a copy of the given TYPE, except that the pointer & reference
5638    types are not preserved.
5639    
5640    This function assumes that the given type has an associated objfile.
5641    This objfile is used to allocate the new type.  */
5642
5643 struct type *
5644 copy_type (const struct type *type)
5645 {
5646   struct type *new_type;
5647
5648   gdb_assert (type->is_objfile_owned ());
5649
5650   new_type = alloc_type_copy (type);
5651   new_type->set_instance_flags (type->instance_flags ());
5652   TYPE_LENGTH (new_type) = TYPE_LENGTH (type);
5653   memcpy (TYPE_MAIN_TYPE (new_type), TYPE_MAIN_TYPE (type),
5654           sizeof (struct main_type));
5655   if (type->main_type->dyn_prop_list != NULL)
5656     new_type->main_type->dyn_prop_list
5657       = copy_dynamic_prop_list (&type->objfile_owner ()->objfile_obstack,
5658                                 type->main_type->dyn_prop_list);
5659
5660   return new_type;
5661 }
5662 \f
5663 /* Helper functions to initialize architecture-specific types.  */
5664
5665 /* Allocate a type structure associated with GDBARCH and set its
5666    CODE, LENGTH, and NAME fields.  */
5667
5668 struct type *
5669 arch_type (struct gdbarch *gdbarch,
5670            enum type_code code, int bit, const char *name)
5671 {
5672   struct type *type;
5673
5674   type = alloc_type_arch (gdbarch);
5675   set_type_code (type, code);
5676   gdb_assert ((bit % TARGET_CHAR_BIT) == 0);
5677   TYPE_LENGTH (type) = bit / TARGET_CHAR_BIT;
5678
5679   if (name)
5680     type->set_name (gdbarch_obstack_strdup (gdbarch, name));
5681
5682   return type;
5683 }
5684
5685 /* Allocate a TYPE_CODE_INT type structure associated with GDBARCH.
5686    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
5687    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
5688
5689 struct type *
5690 arch_integer_type (struct gdbarch *gdbarch,
5691                    int bit, int unsigned_p, const char *name)
5692 {
5693   struct type *t;
5694
5695   t = arch_type (gdbarch, TYPE_CODE_INT, bit, name);
5696   if (unsigned_p)
5697     t->set_is_unsigned (true);
5698
5699   return t;
5700 }
5701
5702 /* Allocate a TYPE_CODE_CHAR type structure associated with GDBARCH.
5703    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
5704    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
5705
5706 struct type *
5707 arch_character_type (struct gdbarch *gdbarch,
5708                      int bit, int unsigned_p, const char *name)
5709 {
5710   struct type *t;
5711
5712   t = arch_type (gdbarch, TYPE_CODE_CHAR, bit, name);
5713   if (unsigned_p)
5714     t->set_is_unsigned (true);
5715
5716   return t;
5717 }
5718
5719 /* Allocate a TYPE_CODE_BOOL type structure associated with GDBARCH.
5720    BIT is the type size in bits.  If UNSIGNED_P is non-zero, set
5721    the type's TYPE_UNSIGNED flag.  NAME is the type name.  */
5722
5723 struct type *
5724 arch_boolean_type (struct gdbarch *gdbarch,
5725                    int bit, int unsigned_p, const char *name)
5726 {
5727   struct type *t;
5728
5729   t = arch_type (gdbarch, TYPE_CODE_BOOL, bit, name);
5730   if (unsigned_p)
5731     t->set_is_unsigned (true);
5732
5733   return t;
5734 }
5735
5736 /* Allocate a TYPE_CODE_FLT type structure associated with GDBARCH.
5737    BIT is the type size in bits; if BIT equals -1, the size is
5738    determined by the floatformat.  NAME is the type name.  Set the
5739    TYPE_FLOATFORMAT from FLOATFORMATS.  */
5740
5741 struct type *
5742 arch_float_type (struct gdbarch *gdbarch,
5743                  int bit, const char *name,
5744                  const struct floatformat **floatformats)
5745 {
5746   const struct floatformat *fmt = floatformats[gdbarch_byte_order (gdbarch)];
5747   struct type *t;
5748
5749   bit = verify_floatformat (bit, fmt);
5750   t = arch_type (gdbarch, TYPE_CODE_FLT, bit, name);
5751   TYPE_FLOATFORMAT (t) = fmt;
5752
5753   return t;
5754 }
5755
5756 /* Allocate a TYPE_CODE_DECFLOAT type structure associated with GDBARCH.
5757    BIT is the type size in bits.  NAME is the type name.  */
5758
5759 struct type *
5760 arch_decfloat_type (struct gdbarch *gdbarch, int bit, const char *name)
5761 {
5762   struct type *t;
5763
5764   t = arch_type (gdbarch, TYPE_CODE_DECFLOAT, bit, name);
5765   return t;
5766 }
5767
5768 /* Allocate a TYPE_CODE_PTR type structure associated with GDBARCH.
5769    BIT is the pointer type size in bits.  NAME is the type name.
5770    TARGET_TYPE is the pointer target type.  Always sets the pointer type's
5771    TYPE_UNSIGNED flag.  */
5772
5773 struct type *
5774 arch_pointer_type (struct gdbarch *gdbarch,
5775                    int bit, const char *name, struct type *target_type)
5776 {
5777   struct type *t;
5778
5779   t = arch_type (gdbarch, TYPE_CODE_PTR, bit, name);
5780   TYPE_TARGET_TYPE (t) = target_type;
5781   t->set_is_unsigned (true);
5782   return t;
5783 }
5784
5785 /* Allocate a TYPE_CODE_FLAGS type structure associated with GDBARCH.
5786    NAME is the type name.  BIT is the size of the flag word in bits.  */
5787
5788 struct type *
5789 arch_flags_type (struct gdbarch *gdbarch, const char *name, int bit)
5790 {
5791   struct type *type;
5792
5793   type = arch_type (gdbarch, TYPE_CODE_FLAGS, bit, name);
5794   type->set_is_unsigned (true);
5795   type->set_num_fields (0);
5796   /* Pre-allocate enough space assuming every field is one bit.  */
5797   type->set_fields
5798     ((struct field *) TYPE_ZALLOC (type, bit * sizeof (struct field)));
5799
5800   return type;
5801 }
5802
5803 /* Add field to TYPE_CODE_FLAGS type TYPE to indicate the bit at
5804    position BITPOS is called NAME.  Pass NAME as "" for fields that
5805    should not be printed.  */
5806
5807 void
5808 append_flags_type_field (struct type *type, int start_bitpos, int nr_bits,
5809                          struct type *field_type, const char *name)
5810 {
5811   int type_bitsize = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
5812   int field_nr = type->num_fields ();
5813
5814   gdb_assert (type->code () == TYPE_CODE_FLAGS);
5815   gdb_assert (type->num_fields () + 1 <= type_bitsize);
5816   gdb_assert (start_bitpos >= 0 && start_bitpos < type_bitsize);
5817   gdb_assert (nr_bits >= 1 && (start_bitpos + nr_bits) <= type_bitsize);
5818   gdb_assert (name != NULL);
5819
5820   type->set_num_fields (type->num_fields () + 1);
5821   type->field (field_nr).set_name (xstrdup (name));
5822   type->field (field_nr).set_type (field_type);
5823   type->field (field_nr).set_loc_bitpos (start_bitpos);
5824   TYPE_FIELD_BITSIZE (type, field_nr) = nr_bits;
5825 }
5826
5827 /* Special version of append_flags_type_field to add a flag field.
5828    Add field to TYPE_CODE_FLAGS type TYPE to indicate the bit at
5829    position BITPOS is called NAME.  */
5830
5831 void
5832 append_flags_type_flag (struct type *type, int bitpos, const char *name)
5833 {
5834   append_flags_type_field (type, bitpos, 1,
5835                            builtin_type (type->arch ())->builtin_bool,
5836                            name);
5837 }
5838
5839 /* Allocate a TYPE_CODE_STRUCT or TYPE_CODE_UNION type structure (as
5840    specified by CODE) associated with GDBARCH.  NAME is the type name.  */
5841
5842 struct type *
5843 arch_composite_type (struct gdbarch *gdbarch, const char *name,
5844                      enum type_code code)
5845 {
5846   struct type *t;
5847
5848   gdb_assert (code == TYPE_CODE_STRUCT || code == TYPE_CODE_UNION);
5849   t = arch_type (gdbarch, code, 0, NULL);
5850   t->set_name (name);
5851   INIT_CPLUS_SPECIFIC (t);
5852   return t;
5853 }
5854
5855 /* Add new field with name NAME and type FIELD to composite type T.
5856    Do not set the field's position or adjust the type's length;
5857    the caller should do so.  Return the new field.  */
5858
5859 struct field *
5860 append_composite_type_field_raw (struct type *t, const char *name,
5861                                  struct type *field)
5862 {
5863   struct field *f;
5864
5865   t->set_num_fields (t->num_fields () + 1);
5866   t->set_fields (XRESIZEVEC (struct field, t->fields (),
5867                              t->num_fields ()));
5868   f = &t->field (t->num_fields () - 1);
5869   memset (f, 0, sizeof f[0]);
5870   f[0].set_type (field);
5871   f[0].set_name (name);
5872   return f;
5873 }
5874
5875 /* Add new field with name NAME and type FIELD to composite type T.
5876    ALIGNMENT (if non-zero) specifies the minimum field alignment.  */
5877
5878 void
5879 append_composite_type_field_aligned (struct type *t, const char *name,
5880                                      struct type *field, int alignment)
5881 {
5882   struct field *f = append_composite_type_field_raw (t, name, field);
5883
5884   if (t->code () == TYPE_CODE_UNION)
5885     {
5886       if (TYPE_LENGTH (t) < TYPE_LENGTH (field))
5887         TYPE_LENGTH (t) = TYPE_LENGTH (field);
5888     }
5889   else if (t->code () == TYPE_CODE_STRUCT)
5890     {
5891       TYPE_LENGTH (t) = TYPE_LENGTH (t) + TYPE_LENGTH (field);
5892       if (t->num_fields () > 1)
5893         {
5894           f->set_loc_bitpos
5895             (f[-1].loc_bitpos () + (TYPE_LENGTH (f[-1].type ()) * TARGET_CHAR_BIT));
5896
5897           if (alignment)
5898             {
5899               int left;
5900
5901               alignment *= TARGET_CHAR_BIT;
5902               left = f[0].loc_bitpos () % alignment;
5903
5904               if (left)
5905                 {
5906                   f->set_loc_bitpos (f[0].loc_bitpos () + (alignment - left));
5907                   TYPE_LENGTH (t) += (alignment - left) / TARGET_CHAR_BIT;
5908                 }
5909             }
5910         }
5911     }
5912 }
5913
5914 /* Add new field with name NAME and type FIELD to composite type T.  */
5915
5916 void
5917 append_composite_type_field (struct type *t, const char *name,
5918                              struct type *field)
5919 {
5920   append_composite_type_field_aligned (t, name, field, 0);
5921 }
5922
5923 \f
5924
5925 /* We manage the lifetimes of fixed_point_type_info objects by
5926    attaching them to the objfile.  Currently, these objects are
5927    modified during construction, and GMP does not provide a way to
5928    hash the contents of an mpq_t; so it's a bit of a pain to hash-cons
5929    them.  If we did do this, they could be moved to the per-BFD and
5930    shared across objfiles.  */
5931 typedef std::vector<std::unique_ptr<fixed_point_type_info>>
5932     fixed_point_type_storage;
5933
5934 /* Key used for managing the storage of fixed-point type info.  */
5935 static const struct objfile_key<fixed_point_type_storage>
5936     fixed_point_objfile_key;
5937
5938 /* See gdbtypes.h.  */
5939
5940 void
5941 allocate_fixed_point_type_info (struct type *type)
5942 {
5943   std::unique_ptr<fixed_point_type_info> up (new fixed_point_type_info);
5944   fixed_point_type_info *info;
5945
5946   if (type->is_objfile_owned ())
5947     {
5948       fixed_point_type_storage *storage
5949         = fixed_point_objfile_key.get (type->objfile_owner ());
5950       if (storage == nullptr)
5951         storage = fixed_point_objfile_key.emplace (type->objfile_owner ());
5952       info = up.get ();
5953       storage->push_back (std::move (up));
5954     }
5955   else
5956     {
5957       /* We just leak the memory, because that's what we do generally
5958          for non-objfile-attached types.  */
5959       info = up.release ();
5960     }
5961
5962   type->set_fixed_point_info (info);
5963 }
5964
5965 /* See gdbtypes.h.  */
5966
5967 bool
5968 is_fixed_point_type (struct type *type)
5969 {
5970   while (check_typedef (type)->code () == TYPE_CODE_RANGE)
5971     type = TYPE_TARGET_TYPE (check_typedef (type));
5972   type = check_typedef (type);
5973
5974   return type->code () == TYPE_CODE_FIXED_POINT;
5975 }
5976
5977 /* See gdbtypes.h.  */
5978
5979 struct type *
5980 type::fixed_point_type_base_type ()
5981 {
5982   struct type *type = this;
5983
5984   while (check_typedef (type)->code () == TYPE_CODE_RANGE)
5985     type = TYPE_TARGET_TYPE (check_typedef (type));
5986   type = check_typedef (type);
5987
5988   gdb_assert (type->code () == TYPE_CODE_FIXED_POINT);
5989   return type;
5990 }
5991
5992 /* See gdbtypes.h.  */
5993
5994 const gdb_mpq &
5995 type::fixed_point_scaling_factor ()
5996 {
5997   struct type *type = this->fixed_point_type_base_type ();
5998
5999   return type->fixed_point_info ().scaling_factor;
6000 }
6001
6002 \f
6003
6004 static struct gdbarch_data *gdbtypes_data;
6005
6006 const struct builtin_type *
6007 builtin_type (struct gdbarch *gdbarch)
6008 {
6009   return (const struct builtin_type *) gdbarch_data (gdbarch, gdbtypes_data);
6010 }
6011
6012 static void *
6013 gdbtypes_post_init (struct gdbarch *gdbarch)
6014 {
6015   struct builtin_type *builtin_type
6016     = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct builtin_type);
6017
6018   /* Basic types.  */
6019   builtin_type->builtin_void
6020     = arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT, "void");
6021   builtin_type->builtin_char
6022     = arch_integer_type (gdbarch, TARGET_CHAR_BIT,
6023                          !gdbarch_char_signed (gdbarch), "char");
6024   builtin_type->builtin_char->set_has_no_signedness (true);
6025   builtin_type->builtin_signed_char
6026     = arch_integer_type (gdbarch, TARGET_CHAR_BIT,
6027                          0, "signed char");
6028   builtin_type->builtin_unsigned_char
6029     = arch_integer_type (gdbarch, TARGET_CHAR_BIT,
6030                          1, "unsigned char");
6031   builtin_type->builtin_short
6032     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
6033                          0, "short");
6034   builtin_type->builtin_unsigned_short
6035     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
6036                          1, "unsigned short");
6037   builtin_type->builtin_int
6038     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
6039                          0, "int");
6040   builtin_type->builtin_unsigned_int
6041     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
6042                          1, "unsigned int");
6043   builtin_type->builtin_long
6044     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
6045                          0, "long");
6046   builtin_type->builtin_unsigned_long
6047     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
6048                          1, "unsigned long");
6049   builtin_type->builtin_long_long
6050     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
6051                          0, "long long");
6052   builtin_type->builtin_unsigned_long_long
6053     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
6054                          1, "unsigned long long");
6055   builtin_type->builtin_half
6056     = arch_float_type (gdbarch, gdbarch_half_bit (gdbarch),
6057                        "half", gdbarch_half_format (gdbarch));
6058   builtin_type->builtin_float
6059     = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
6060                        "float", gdbarch_float_format (gdbarch));
6061   builtin_type->builtin_bfloat16
6062     = arch_float_type (gdbarch, gdbarch_bfloat16_bit (gdbarch),
6063                        "bfloat16", gdbarch_bfloat16_format (gdbarch));
6064   builtin_type->builtin_double
6065     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
6066                        "double", gdbarch_double_format (gdbarch));
6067   builtin_type->builtin_long_double
6068     = arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
6069                        "long double", gdbarch_long_double_format (gdbarch));
6070   builtin_type->builtin_complex
6071     = init_complex_type ("complex", builtin_type->builtin_float);
6072   builtin_type->builtin_double_complex
6073     = init_complex_type ("double complex", builtin_type->builtin_double);
6074   builtin_type->builtin_string
6075     = arch_type (gdbarch, TYPE_CODE_STRING, TARGET_CHAR_BIT, "string");
6076   builtin_type->builtin_bool
6077     = arch_boolean_type (gdbarch, TARGET_CHAR_BIT, 1, "bool");
6078
6079   /* The following three are about decimal floating point types, which
6080      are 32-bits, 64-bits and 128-bits respectively.  */
6081   builtin_type->builtin_decfloat
6082     = arch_decfloat_type (gdbarch, 32, "_Decimal32");
6083   builtin_type->builtin_decdouble
6084     = arch_decfloat_type (gdbarch, 64, "_Decimal64");
6085   builtin_type->builtin_declong
6086     = arch_decfloat_type (gdbarch, 128, "_Decimal128");
6087
6088   /* "True" character types.  */
6089   builtin_type->builtin_true_char
6090     = arch_character_type (gdbarch, TARGET_CHAR_BIT, 0, "true character");
6091   builtin_type->builtin_true_unsigned_char
6092     = arch_character_type (gdbarch, TARGET_CHAR_BIT, 1, "true character");
6093
6094   /* Fixed-size integer types.  */
6095   builtin_type->builtin_int0
6096     = arch_integer_type (gdbarch, 0, 0, "int0_t");
6097   builtin_type->builtin_int8
6098     = arch_integer_type (gdbarch, 8, 0, "int8_t");
6099   builtin_type->builtin_uint8
6100     = arch_integer_type (gdbarch, 8, 1, "uint8_t");
6101   builtin_type->builtin_int16
6102     = arch_integer_type (gdbarch, 16, 0, "int16_t");
6103   builtin_type->builtin_uint16
6104     = arch_integer_type (gdbarch, 16, 1, "uint16_t");
6105   builtin_type->builtin_int24
6106     = arch_integer_type (gdbarch, 24, 0, "int24_t");
6107   builtin_type->builtin_uint24
6108     = arch_integer_type (gdbarch, 24, 1, "uint24_t");
6109   builtin_type->builtin_int32
6110     = arch_integer_type (gdbarch, 32, 0, "int32_t");
6111   builtin_type->builtin_uint32
6112     = arch_integer_type (gdbarch, 32, 1, "uint32_t");
6113   builtin_type->builtin_int64
6114     = arch_integer_type (gdbarch, 64, 0, "int64_t");
6115   builtin_type->builtin_uint64
6116     = arch_integer_type (gdbarch, 64, 1, "uint64_t");
6117   builtin_type->builtin_int128
6118     = arch_integer_type (gdbarch, 128, 0, "int128_t");
6119   builtin_type->builtin_uint128
6120     = arch_integer_type (gdbarch, 128, 1, "uint128_t");
6121
6122   builtin_type->builtin_int8->set_instance_flags
6123     (builtin_type->builtin_int8->instance_flags ()
6124      | TYPE_INSTANCE_FLAG_NOTTEXT);
6125
6126   builtin_type->builtin_uint8->set_instance_flags
6127     (builtin_type->builtin_uint8->instance_flags ()
6128      | TYPE_INSTANCE_FLAG_NOTTEXT);
6129
6130   /* Wide character types.  */
6131   builtin_type->builtin_char16
6132     = arch_integer_type (gdbarch, 16, 1, "char16_t");
6133   builtin_type->builtin_char32
6134     = arch_integer_type (gdbarch, 32, 1, "char32_t");
6135   builtin_type->builtin_wchar
6136     = arch_integer_type (gdbarch, gdbarch_wchar_bit (gdbarch),
6137                          !gdbarch_wchar_signed (gdbarch), "wchar_t");
6138
6139   /* Default data/code pointer types.  */
6140   builtin_type->builtin_data_ptr
6141     = lookup_pointer_type (builtin_type->builtin_void);
6142   builtin_type->builtin_func_ptr
6143     = lookup_pointer_type (lookup_function_type (builtin_type->builtin_void));
6144   builtin_type->builtin_func_func
6145     = lookup_function_type (builtin_type->builtin_func_ptr);
6146
6147   /* This type represents a GDB internal function.  */
6148   builtin_type->internal_fn
6149     = arch_type (gdbarch, TYPE_CODE_INTERNAL_FUNCTION, 0,
6150                  "<internal function>");
6151
6152   /* This type represents an xmethod.  */
6153   builtin_type->xmethod
6154     = arch_type (gdbarch, TYPE_CODE_XMETHOD, 0, "<xmethod>");
6155
6156   return builtin_type;
6157 }
6158
6159 /* This set of objfile-based types is intended to be used by symbol
6160    readers as basic types.  */
6161
6162 static const struct objfile_key<struct objfile_type,
6163                                 gdb::noop_deleter<struct objfile_type>>
6164   objfile_type_data;
6165
6166 const struct objfile_type *
6167 objfile_type (struct objfile *objfile)
6168 {
6169   struct gdbarch *gdbarch;
6170   struct objfile_type *objfile_type = objfile_type_data.get (objfile);
6171
6172   if (objfile_type)
6173     return objfile_type;
6174
6175   objfile_type = OBSTACK_CALLOC (&objfile->objfile_obstack,
6176                                  1, struct objfile_type);
6177
6178   /* Use the objfile architecture to determine basic type properties.  */
6179   gdbarch = objfile->arch ();
6180
6181   /* Basic types.  */
6182   objfile_type->builtin_void
6183     = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, "void");
6184   objfile_type->builtin_char
6185     = init_integer_type (objfile, TARGET_CHAR_BIT,
6186                          !gdbarch_char_signed (gdbarch), "char");
6187   objfile_type->builtin_char->set_has_no_signedness (true);
6188   objfile_type->builtin_signed_char
6189     = init_integer_type (objfile, TARGET_CHAR_BIT,
6190                          0, "signed char");
6191   objfile_type->builtin_unsigned_char
6192     = init_integer_type (objfile, TARGET_CHAR_BIT,
6193                          1, "unsigned char");
6194   objfile_type->builtin_short
6195     = init_integer_type (objfile, gdbarch_short_bit (gdbarch),
6196                          0, "short");
6197   objfile_type->builtin_unsigned_short
6198     = init_integer_type (objfile, gdbarch_short_bit (gdbarch),
6199                          1, "unsigned short");
6200   objfile_type->builtin_int
6201     = init_integer_type (objfile, gdbarch_int_bit (gdbarch),
6202                          0, "int");
6203   objfile_type->builtin_unsigned_int
6204     = init_integer_type (objfile, gdbarch_int_bit (gdbarch),
6205                          1, "unsigned int");
6206   objfile_type->builtin_long
6207     = init_integer_type (objfile, gdbarch_long_bit (gdbarch),
6208                          0, "long");
6209   objfile_type->builtin_unsigned_long
6210     = init_integer_type (objfile, gdbarch_long_bit (gdbarch),
6211                          1, "unsigned long");
6212   objfile_type->builtin_long_long
6213     = init_integer_type (objfile, gdbarch_long_long_bit (gdbarch),
6214                          0, "long long");
6215   objfile_type->builtin_unsigned_long_long
6216     = init_integer_type (objfile, gdbarch_long_long_bit (gdbarch),
6217                          1, "unsigned long long");
6218   objfile_type->builtin_float
6219     = init_float_type (objfile, gdbarch_float_bit (gdbarch),
6220                        "float", gdbarch_float_format (gdbarch));
6221   objfile_type->builtin_double
6222     = init_float_type (objfile, gdbarch_double_bit (gdbarch),
6223                        "double", gdbarch_double_format (gdbarch));
6224   objfile_type->builtin_long_double
6225     = init_float_type (objfile, gdbarch_long_double_bit (gdbarch),
6226                        "long double", gdbarch_long_double_format (gdbarch));
6227
6228   /* This type represents a type that was unrecognized in symbol read-in.  */
6229   objfile_type->builtin_error
6230     = init_type (objfile, TYPE_CODE_ERROR, 0, "<unknown type>");
6231
6232   /* The following set of types is used for symbols with no
6233      debug information.  */
6234   objfile_type->nodebug_text_symbol
6235     = init_type (objfile, TYPE_CODE_FUNC, TARGET_CHAR_BIT,
6236                  "<text variable, no debug info>");
6237
6238   objfile_type->nodebug_text_gnu_ifunc_symbol
6239     = init_type (objfile, TYPE_CODE_FUNC, TARGET_CHAR_BIT,
6240                  "<text gnu-indirect-function variable, no debug info>");
6241   objfile_type->nodebug_text_gnu_ifunc_symbol->set_is_gnu_ifunc (true);
6242
6243   objfile_type->nodebug_got_plt_symbol
6244     = init_pointer_type (objfile, gdbarch_addr_bit (gdbarch),
6245                          "<text from jump slot in .got.plt, no debug info>",
6246                          objfile_type->nodebug_text_symbol);
6247   objfile_type->nodebug_data_symbol
6248     = init_nodebug_var_type (objfile, "<data variable, no debug info>");
6249   objfile_type->nodebug_unknown_symbol
6250     = init_nodebug_var_type (objfile, "<variable (not text or data), no debug info>");
6251   objfile_type->nodebug_tls_symbol
6252     = init_nodebug_var_type (objfile, "<thread local variable, no debug info>");
6253
6254   /* NOTE: on some targets, addresses and pointers are not necessarily
6255      the same.
6256
6257      The upshot is:
6258      - gdb's `struct type' always describes the target's
6259        representation.
6260      - gdb's `struct value' objects should always hold values in
6261        target form.
6262      - gdb's CORE_ADDR values are addresses in the unified virtual
6263        address space that the assembler and linker work with.  Thus,
6264        since target_read_memory takes a CORE_ADDR as an argument, it
6265        can access any memory on the target, even if the processor has
6266        separate code and data address spaces.
6267
6268      In this context, objfile_type->builtin_core_addr is a bit odd:
6269      it's a target type for a value the target will never see.  It's
6270      only used to hold the values of (typeless) linker symbols, which
6271      are indeed in the unified virtual address space.  */
6272
6273   objfile_type->builtin_core_addr
6274     = init_integer_type (objfile, gdbarch_addr_bit (gdbarch), 1,
6275                          "__CORE_ADDR");
6276
6277   objfile_type_data.set (objfile, objfile_type);
6278   return objfile_type;
6279 }
6280
6281 /* See gdbtypes.h.  */
6282
6283 CORE_ADDR
6284 call_site::pc () const
6285 {
6286   compunit_symtab *cust = this->per_objfile->get_symtab (this->per_cu);
6287   CORE_ADDR delta
6288         = this->per_objfile->objfile->section_offsets[COMPUNIT_BLOCK_LINE_SECTION (cust)];
6289   return m_unrelocated_pc + delta;
6290 }
6291
6292 void _initialize_gdbtypes ();
6293 void
6294 _initialize_gdbtypes ()
6295 {
6296   gdbtypes_data = gdbarch_data_register_post_init (gdbtypes_post_init);
6297
6298   add_setshow_zuinteger_cmd ("overload", no_class, &overload_debug,
6299                              _("Set debugging of C++ overloading."),
6300                              _("Show debugging of C++ overloading."),
6301                              _("When enabled, ranking of the "
6302                                "functions is displayed."),
6303                              NULL,
6304                              show_overload_debug,
6305                              &setdebuglist, &showdebuglist);
6306
6307   /* Add user knob for controlling resolution of opaque types.  */
6308   add_setshow_boolean_cmd ("opaque-type-resolution", class_support,
6309                            &opaque_type_resolution,
6310                            _("Set resolution of opaque struct/class/union"
6311                              " types (if set before loading symbols)."),
6312                            _("Show resolution of opaque struct/class/union"
6313                              " types (if set before loading symbols)."),
6314                            NULL, NULL,
6315                            show_opaque_type_resolution,
6316                            &setlist, &showlist);
6317
6318   /* Add an option to permit non-strict type checking.  */
6319   add_setshow_boolean_cmd ("type", class_support,
6320                            &strict_type_checking,
6321                            _("Set strict type checking."),
6322                            _("Show strict type checking."),
6323                            NULL, NULL,
6324                            show_strict_type_checking,
6325                            &setchecklist, &showchecklist);
6326 }
This page took 0.379591 seconds and 4 git commands to generate.