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