Use skip_spaces and skip_to_space in ada-lang.c
[external/binutils.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3    Copyright (C) 1992-1994, 1997-2000, 2003-2005, 2007-2012 Free
4    Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21
22 #include "defs.h"
23 #include <stdio.h>
24 #include "gdb_string.h"
25 #include <ctype.h>
26 #include <stdarg.h>
27 #include "demangle.h"
28 #include "gdb_regex.h"
29 #include "frame.h"
30 #include "symtab.h"
31 #include "gdbtypes.h"
32 #include "gdbcmd.h"
33 #include "expression.h"
34 #include "parser-defs.h"
35 #include "language.h"
36 #include "c-lang.h"
37 #include "inferior.h"
38 #include "symfile.h"
39 #include "objfiles.h"
40 #include "breakpoint.h"
41 #include "gdbcore.h"
42 #include "hashtab.h"
43 #include "gdb_obstack.h"
44 #include "ada-lang.h"
45 #include "completer.h"
46 #include "gdb_stat.h"
47 #ifdef UI_OUT
48 #include "ui-out.h"
49 #endif
50 #include "block.h"
51 #include "infcall.h"
52 #include "dictionary.h"
53 #include "exceptions.h"
54 #include "annotate.h"
55 #include "valprint.h"
56 #include "source.h"
57 #include "observer.h"
58 #include "vec.h"
59 #include "stack.h"
60
61 #include "psymtab.h"
62 #include "value.h"
63 #include "mi/mi-common.h"
64 #include "arch-utils.h"
65 #include "exceptions.h"
66 #include "cli/cli-utils.h"
67
68 /* Define whether or not the C operator '/' truncates towards zero for
69    differently signed operands (truncation direction is undefined in C).
70    Copied from valarith.c.  */
71
72 #ifndef TRUNCATION_TOWARDS_ZERO
73 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
74 #endif
75
76 static struct type *desc_base_type (struct type *);
77
78 static struct type *desc_bounds_type (struct type *);
79
80 static struct value *desc_bounds (struct value *);
81
82 static int fat_pntr_bounds_bitpos (struct type *);
83
84 static int fat_pntr_bounds_bitsize (struct type *);
85
86 static struct type *desc_data_target_type (struct type *);
87
88 static struct value *desc_data (struct value *);
89
90 static int fat_pntr_data_bitpos (struct type *);
91
92 static int fat_pntr_data_bitsize (struct type *);
93
94 static struct value *desc_one_bound (struct value *, int, int);
95
96 static int desc_bound_bitpos (struct type *, int, int);
97
98 static int desc_bound_bitsize (struct type *, int, int);
99
100 static struct type *desc_index_type (struct type *, int);
101
102 static int desc_arity (struct type *);
103
104 static int ada_type_match (struct type *, struct type *, int);
105
106 static int ada_args_match (struct symbol *, struct value **, int);
107
108 static int full_match (const char *, const char *);
109
110 static struct value *make_array_descriptor (struct type *, struct value *);
111
112 static void ada_add_block_symbols (struct obstack *,
113                                    struct block *, const char *,
114                                    domain_enum, struct objfile *, int);
115
116 static int is_nonfunction (struct ada_symbol_info *, int);
117
118 static void add_defn_to_vec (struct obstack *, struct symbol *,
119                              struct block *);
120
121 static int num_defns_collected (struct obstack *);
122
123 static struct ada_symbol_info *defns_collected (struct obstack *, int);
124
125 static struct value *resolve_subexp (struct expression **, int *, int,
126                                      struct type *);
127
128 static void replace_operator_with_call (struct expression **, int, int, int,
129                                         struct symbol *, struct block *);
130
131 static int possible_user_operator_p (enum exp_opcode, struct value **);
132
133 static char *ada_op_name (enum exp_opcode);
134
135 static const char *ada_decoded_op_name (enum exp_opcode);
136
137 static int numeric_type_p (struct type *);
138
139 static int integer_type_p (struct type *);
140
141 static int scalar_type_p (struct type *);
142
143 static int discrete_type_p (struct type *);
144
145 static enum ada_renaming_category parse_old_style_renaming (struct type *,
146                                                             const char **,
147                                                             int *,
148                                                             const char **);
149
150 static struct symbol *find_old_style_renaming_symbol (const char *,
151                                                       struct block *);
152
153 static struct type *ada_lookup_struct_elt_type (struct type *, char *,
154                                                 int, int, int *);
155
156 static struct value *evaluate_subexp_type (struct expression *, int *);
157
158 static struct type *ada_find_parallel_type_with_name (struct type *,
159                                                       const char *);
160
161 static int is_dynamic_field (struct type *, int);
162
163 static struct type *to_fixed_variant_branch_type (struct type *,
164                                                   const gdb_byte *,
165                                                   CORE_ADDR, struct value *);
166
167 static struct type *to_fixed_array_type (struct type *, struct value *, int);
168
169 static struct type *to_fixed_range_type (struct type *, struct value *);
170
171 static struct type *to_static_fixed_type (struct type *);
172 static struct type *static_unwrap_type (struct type *type);
173
174 static struct value *unwrap_value (struct value *);
175
176 static struct type *constrained_packed_array_type (struct type *, long *);
177
178 static struct type *decode_constrained_packed_array_type (struct type *);
179
180 static long decode_packed_array_bitsize (struct type *);
181
182 static struct value *decode_constrained_packed_array (struct value *);
183
184 static int ada_is_packed_array_type  (struct type *);
185
186 static int ada_is_unconstrained_packed_array_type (struct type *);
187
188 static struct value *value_subscript_packed (struct value *, int,
189                                              struct value **);
190
191 static void move_bits (gdb_byte *, int, const gdb_byte *, int, int, int);
192
193 static struct value *coerce_unspec_val_to_type (struct value *,
194                                                 struct type *);
195
196 static struct value *get_var_value (char *, char *);
197
198 static int lesseq_defined_than (struct symbol *, struct symbol *);
199
200 static int equiv_types (struct type *, struct type *);
201
202 static int is_name_suffix (const char *);
203
204 static int advance_wild_match (const char **, const char *, int);
205
206 static int wild_match (const char *, const char *);
207
208 static struct value *ada_coerce_ref (struct value *);
209
210 static LONGEST pos_atr (struct value *);
211
212 static struct value *value_pos_atr (struct type *, struct value *);
213
214 static struct value *value_val_atr (struct type *, struct value *);
215
216 static struct symbol *standard_lookup (const char *, const struct block *,
217                                        domain_enum);
218
219 static struct value *ada_search_struct_field (char *, struct value *, int,
220                                               struct type *);
221
222 static struct value *ada_value_primitive_field (struct value *, int, int,
223                                                 struct type *);
224
225 static int find_struct_field (char *, struct type *, int,
226                               struct type **, int *, int *, int *, int *);
227
228 static struct value *ada_to_fixed_value_create (struct type *, CORE_ADDR,
229                                                 struct value *);
230
231 static int ada_resolve_function (struct ada_symbol_info *, int,
232                                  struct value **, int, const char *,
233                                  struct type *);
234
235 static int ada_is_direct_array_type (struct type *);
236
237 static void ada_language_arch_info (struct gdbarch *,
238                                     struct language_arch_info *);
239
240 static void check_size (const struct type *);
241
242 static struct value *ada_index_struct_field (int, struct value *, int,
243                                              struct type *);
244
245 static struct value *assign_aggregate (struct value *, struct value *, 
246                                        struct expression *,
247                                        int *, enum noside);
248
249 static void aggregate_assign_from_choices (struct value *, struct value *, 
250                                            struct expression *,
251                                            int *, LONGEST *, int *,
252                                            int, LONGEST, LONGEST);
253
254 static void aggregate_assign_positional (struct value *, struct value *,
255                                          struct expression *,
256                                          int *, LONGEST *, int *, int,
257                                          LONGEST, LONGEST);
258
259
260 static void aggregate_assign_others (struct value *, struct value *,
261                                      struct expression *,
262                                      int *, LONGEST *, int, LONGEST, LONGEST);
263
264
265 static void add_component_interval (LONGEST, LONGEST, LONGEST *, int *, int);
266
267
268 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
269                                           int *, enum noside);
270
271 static void ada_forward_operator_length (struct expression *, int, int *,
272                                          int *);
273 \f
274
275
276 /* Maximum-sized dynamic type.  */
277 static unsigned int varsize_limit;
278
279 /* FIXME: brobecker/2003-09-17: No longer a const because it is
280    returned by a function that does not return a const char *.  */
281 static char *ada_completer_word_break_characters =
282 #ifdef VMS
283   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
284 #else
285   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
286 #endif
287
288 /* The name of the symbol to use to get the name of the main subprogram.  */
289 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
290   = "__gnat_ada_main_program_name";
291
292 /* Limit on the number of warnings to raise per expression evaluation.  */
293 static int warning_limit = 2;
294
295 /* Number of warning messages issued; reset to 0 by cleanups after
296    expression evaluation.  */
297 static int warnings_issued = 0;
298
299 static const char *known_runtime_file_name_patterns[] = {
300   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
301 };
302
303 static const char *known_auxiliary_function_name_patterns[] = {
304   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
305 };
306
307 /* Space for allocating results of ada_lookup_symbol_list.  */
308 static struct obstack symbol_list_obstack;
309
310                         /* Inferior-specific data.  */
311
312 /* Per-inferior data for this module.  */
313
314 struct ada_inferior_data
315 {
316   /* The ada__tags__type_specific_data type, which is used when decoding
317      tagged types.  With older versions of GNAT, this type was directly
318      accessible through a component ("tsd") in the object tag.  But this
319      is no longer the case, so we cache it for each inferior.  */
320   struct type *tsd_type;
321
322   /* The exception_support_info data.  This data is used to determine
323      how to implement support for Ada exception catchpoints in a given
324      inferior.  */
325   const struct exception_support_info *exception_info;
326 };
327
328 /* Our key to this module's inferior data.  */
329 static const struct inferior_data *ada_inferior_data;
330
331 /* A cleanup routine for our inferior data.  */
332 static void
333 ada_inferior_data_cleanup (struct inferior *inf, void *arg)
334 {
335   struct ada_inferior_data *data;
336
337   data = inferior_data (inf, ada_inferior_data);
338   if (data != NULL)
339     xfree (data);
340 }
341
342 /* Return our inferior data for the given inferior (INF).
343
344    This function always returns a valid pointer to an allocated
345    ada_inferior_data structure.  If INF's inferior data has not
346    been previously set, this functions creates a new one with all
347    fields set to zero, sets INF's inferior to it, and then returns
348    a pointer to that newly allocated ada_inferior_data.  */
349
350 static struct ada_inferior_data *
351 get_ada_inferior_data (struct inferior *inf)
352 {
353   struct ada_inferior_data *data;
354
355   data = inferior_data (inf, ada_inferior_data);
356   if (data == NULL)
357     {
358       data = XZALLOC (struct ada_inferior_data);
359       set_inferior_data (inf, ada_inferior_data, data);
360     }
361
362   return data;
363 }
364
365 /* Perform all necessary cleanups regarding our module's inferior data
366    that is required after the inferior INF just exited.  */
367
368 static void
369 ada_inferior_exit (struct inferior *inf)
370 {
371   ada_inferior_data_cleanup (inf, NULL);
372   set_inferior_data (inf, ada_inferior_data, NULL);
373 }
374
375                         /* Utilities */
376
377 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
378    all typedef layers have been peeled.  Otherwise, return TYPE.
379
380    Normally, we really expect a typedef type to only have 1 typedef layer.
381    In other words, we really expect the target type of a typedef type to be
382    a non-typedef type.  This is particularly true for Ada units, because
383    the language does not have a typedef vs not-typedef distinction.
384    In that respect, the Ada compiler has been trying to eliminate as many
385    typedef definitions in the debugging information, since they generally
386    do not bring any extra information (we still use typedef under certain
387    circumstances related mostly to the GNAT encoding).
388
389    Unfortunately, we have seen situations where the debugging information
390    generated by the compiler leads to such multiple typedef layers.  For
391    instance, consider the following example with stabs:
392
393      .stabs  "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
394      .stabs  "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
395
396    This is an error in the debugging information which causes type
397    pck__float_array___XUP to be defined twice, and the second time,
398    it is defined as a typedef of a typedef.
399
400    This is on the fringe of legality as far as debugging information is
401    concerned, and certainly unexpected.  But it is easy to handle these
402    situations correctly, so we can afford to be lenient in this case.  */
403
404 static struct type *
405 ada_typedef_target_type (struct type *type)
406 {
407   while (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
408     type = TYPE_TARGET_TYPE (type);
409   return type;
410 }
411
412 /* Given DECODED_NAME a string holding a symbol name in its
413    decoded form (ie using the Ada dotted notation), returns
414    its unqualified name.  */
415
416 static const char *
417 ada_unqualified_name (const char *decoded_name)
418 {
419   const char *result = strrchr (decoded_name, '.');
420
421   if (result != NULL)
422     result++;                   /* Skip the dot...  */
423   else
424     result = decoded_name;
425
426   return result;
427 }
428
429 /* Return a string starting with '<', followed by STR, and '>'.
430    The result is good until the next call.  */
431
432 static char *
433 add_angle_brackets (const char *str)
434 {
435   static char *result = NULL;
436
437   xfree (result);
438   result = xstrprintf ("<%s>", str);
439   return result;
440 }
441
442 static char *
443 ada_get_gdb_completer_word_break_characters (void)
444 {
445   return ada_completer_word_break_characters;
446 }
447
448 /* Print an array element index using the Ada syntax.  */
449
450 static void
451 ada_print_array_index (struct value *index_value, struct ui_file *stream,
452                        const struct value_print_options *options)
453 {
454   LA_VALUE_PRINT (index_value, stream, options);
455   fprintf_filtered (stream, " => ");
456 }
457
458 /* Assuming VECT points to an array of *SIZE objects of size
459    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
460    updating *SIZE as necessary and returning the (new) array.  */
461
462 void *
463 grow_vect (void *vect, size_t *size, size_t min_size, int element_size)
464 {
465   if (*size < min_size)
466     {
467       *size *= 2;
468       if (*size < min_size)
469         *size = min_size;
470       vect = xrealloc (vect, *size * element_size);
471     }
472   return vect;
473 }
474
475 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
476    suffix of FIELD_NAME beginning "___".  */
477
478 static int
479 field_name_match (const char *field_name, const char *target)
480 {
481   int len = strlen (target);
482
483   return
484     (strncmp (field_name, target, len) == 0
485      && (field_name[len] == '\0'
486          || (strncmp (field_name + len, "___", 3) == 0
487              && strcmp (field_name + strlen (field_name) - 6,
488                         "___XVN") != 0)));
489 }
490
491
492 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
493    a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
494    and return its index.  This function also handles fields whose name
495    have ___ suffixes because the compiler sometimes alters their name
496    by adding such a suffix to represent fields with certain constraints.
497    If the field could not be found, return a negative number if
498    MAYBE_MISSING is set.  Otherwise raise an error.  */
499
500 int
501 ada_get_field_index (const struct type *type, const char *field_name,
502                      int maybe_missing)
503 {
504   int fieldno;
505   struct type *struct_type = check_typedef ((struct type *) type);
506
507   for (fieldno = 0; fieldno < TYPE_NFIELDS (struct_type); fieldno++)
508     if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
509       return fieldno;
510
511   if (!maybe_missing)
512     error (_("Unable to find field %s in struct %s.  Aborting"),
513            field_name, TYPE_NAME (struct_type));
514
515   return -1;
516 }
517
518 /* The length of the prefix of NAME prior to any "___" suffix.  */
519
520 int
521 ada_name_prefix_len (const char *name)
522 {
523   if (name == NULL)
524     return 0;
525   else
526     {
527       const char *p = strstr (name, "___");
528
529       if (p == NULL)
530         return strlen (name);
531       else
532         return p - name;
533     }
534 }
535
536 /* Return non-zero if SUFFIX is a suffix of STR.
537    Return zero if STR is null.  */
538
539 static int
540 is_suffix (const char *str, const char *suffix)
541 {
542   int len1, len2;
543
544   if (str == NULL)
545     return 0;
546   len1 = strlen (str);
547   len2 = strlen (suffix);
548   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
549 }
550
551 /* The contents of value VAL, treated as a value of type TYPE.  The
552    result is an lval in memory if VAL is.  */
553
554 static struct value *
555 coerce_unspec_val_to_type (struct value *val, struct type *type)
556 {
557   type = ada_check_typedef (type);
558   if (value_type (val) == type)
559     return val;
560   else
561     {
562       struct value *result;
563
564       /* Make sure that the object size is not unreasonable before
565          trying to allocate some memory for it.  */
566       check_size (type);
567
568       if (value_lazy (val)
569           || TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val)))
570         result = allocate_value_lazy (type);
571       else
572         {
573           result = allocate_value (type);
574           memcpy (value_contents_raw (result), value_contents (val),
575                   TYPE_LENGTH (type));
576         }
577       set_value_component_location (result, val);
578       set_value_bitsize (result, value_bitsize (val));
579       set_value_bitpos (result, value_bitpos (val));
580       set_value_address (result, value_address (val));
581       return result;
582     }
583 }
584
585 static const gdb_byte *
586 cond_offset_host (const gdb_byte *valaddr, long offset)
587 {
588   if (valaddr == NULL)
589     return NULL;
590   else
591     return valaddr + offset;
592 }
593
594 static CORE_ADDR
595 cond_offset_target (CORE_ADDR address, long offset)
596 {
597   if (address == 0)
598     return 0;
599   else
600     return address + offset;
601 }
602
603 /* Issue a warning (as for the definition of warning in utils.c, but
604    with exactly one argument rather than ...), unless the limit on the
605    number of warnings has passed during the evaluation of the current
606    expression.  */
607
608 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
609    provided by "complaint".  */
610 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
611
612 static void
613 lim_warning (const char *format, ...)
614 {
615   va_list args;
616
617   va_start (args, format);
618   warnings_issued += 1;
619   if (warnings_issued <= warning_limit)
620     vwarning (format, args);
621
622   va_end (args);
623 }
624
625 /* Issue an error if the size of an object of type T is unreasonable,
626    i.e. if it would be a bad idea to allocate a value of this type in
627    GDB.  */
628
629 static void
630 check_size (const struct type *type)
631 {
632   if (TYPE_LENGTH (type) > varsize_limit)
633     error (_("object size is larger than varsize-limit"));
634 }
635
636 /* Maximum value of a SIZE-byte signed integer type.  */
637 static LONGEST
638 max_of_size (int size)
639 {
640   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
641
642   return top_bit | (top_bit - 1);
643 }
644
645 /* Minimum value of a SIZE-byte signed integer type.  */
646 static LONGEST
647 min_of_size (int size)
648 {
649   return -max_of_size (size) - 1;
650 }
651
652 /* Maximum value of a SIZE-byte unsigned integer type.  */
653 static ULONGEST
654 umax_of_size (int size)
655 {
656   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
657
658   return top_bit | (top_bit - 1);
659 }
660
661 /* Maximum value of integral type T, as a signed quantity.  */
662 static LONGEST
663 max_of_type (struct type *t)
664 {
665   if (TYPE_UNSIGNED (t))
666     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
667   else
668     return max_of_size (TYPE_LENGTH (t));
669 }
670
671 /* Minimum value of integral type T, as a signed quantity.  */
672 static LONGEST
673 min_of_type (struct type *t)
674 {
675   if (TYPE_UNSIGNED (t)) 
676     return 0;
677   else
678     return min_of_size (TYPE_LENGTH (t));
679 }
680
681 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
682 LONGEST
683 ada_discrete_type_high_bound (struct type *type)
684 {
685   switch (TYPE_CODE (type))
686     {
687     case TYPE_CODE_RANGE:
688       return TYPE_HIGH_BOUND (type);
689     case TYPE_CODE_ENUM:
690       return TYPE_FIELD_BITPOS (type, TYPE_NFIELDS (type) - 1);
691     case TYPE_CODE_BOOL:
692       return 1;
693     case TYPE_CODE_CHAR:
694     case TYPE_CODE_INT:
695       return max_of_type (type);
696     default:
697       error (_("Unexpected type in ada_discrete_type_high_bound."));
698     }
699 }
700
701 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
702 LONGEST
703 ada_discrete_type_low_bound (struct type *type)
704 {
705   switch (TYPE_CODE (type))
706     {
707     case TYPE_CODE_RANGE:
708       return TYPE_LOW_BOUND (type);
709     case TYPE_CODE_ENUM:
710       return TYPE_FIELD_BITPOS (type, 0);
711     case TYPE_CODE_BOOL:
712       return 0;
713     case TYPE_CODE_CHAR:
714     case TYPE_CODE_INT:
715       return min_of_type (type);
716     default:
717       error (_("Unexpected type in ada_discrete_type_low_bound."));
718     }
719 }
720
721 /* The identity on non-range types.  For range types, the underlying
722    non-range scalar type.  */
723
724 static struct type *
725 get_base_type (struct type *type)
726 {
727   while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
728     {
729       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
730         return type;
731       type = TYPE_TARGET_TYPE (type);
732     }
733   return type;
734 }
735 \f
736
737                                 /* Language Selection */
738
739 /* If the main program is in Ada, return language_ada, otherwise return LANG
740    (the main program is in Ada iif the adainit symbol is found).  */
741
742 enum language
743 ada_update_initial_language (enum language lang)
744 {
745   if (lookup_minimal_symbol ("adainit", (const char *) NULL,
746                              (struct objfile *) NULL) != NULL)
747     return language_ada;
748
749   return lang;
750 }
751
752 /* If the main procedure is written in Ada, then return its name.
753    The result is good until the next call.  Return NULL if the main
754    procedure doesn't appear to be in Ada.  */
755
756 char *
757 ada_main_name (void)
758 {
759   struct minimal_symbol *msym;
760   static char *main_program_name = NULL;
761
762   /* For Ada, the name of the main procedure is stored in a specific
763      string constant, generated by the binder.  Look for that symbol,
764      extract its address, and then read that string.  If we didn't find
765      that string, then most probably the main procedure is not written
766      in Ada.  */
767   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
768
769   if (msym != NULL)
770     {
771       CORE_ADDR main_program_name_addr;
772       int err_code;
773
774       main_program_name_addr = SYMBOL_VALUE_ADDRESS (msym);
775       if (main_program_name_addr == 0)
776         error (_("Invalid address for Ada main program name."));
777
778       xfree (main_program_name);
779       target_read_string (main_program_name_addr, &main_program_name,
780                           1024, &err_code);
781
782       if (err_code != 0)
783         return NULL;
784       return main_program_name;
785     }
786
787   /* The main procedure doesn't seem to be in Ada.  */
788   return NULL;
789 }
790 \f
791                                 /* Symbols */
792
793 /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
794    of NULLs.  */
795
796 const struct ada_opname_map ada_opname_table[] = {
797   {"Oadd", "\"+\"", BINOP_ADD},
798   {"Osubtract", "\"-\"", BINOP_SUB},
799   {"Omultiply", "\"*\"", BINOP_MUL},
800   {"Odivide", "\"/\"", BINOP_DIV},
801   {"Omod", "\"mod\"", BINOP_MOD},
802   {"Orem", "\"rem\"", BINOP_REM},
803   {"Oexpon", "\"**\"", BINOP_EXP},
804   {"Olt", "\"<\"", BINOP_LESS},
805   {"Ole", "\"<=\"", BINOP_LEQ},
806   {"Ogt", "\">\"", BINOP_GTR},
807   {"Oge", "\">=\"", BINOP_GEQ},
808   {"Oeq", "\"=\"", BINOP_EQUAL},
809   {"One", "\"/=\"", BINOP_NOTEQUAL},
810   {"Oand", "\"and\"", BINOP_BITWISE_AND},
811   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
812   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
813   {"Oconcat", "\"&\"", BINOP_CONCAT},
814   {"Oabs", "\"abs\"", UNOP_ABS},
815   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
816   {"Oadd", "\"+\"", UNOP_PLUS},
817   {"Osubtract", "\"-\"", UNOP_NEG},
818   {NULL, NULL}
819 };
820
821 /* The "encoded" form of DECODED, according to GNAT conventions.
822    The result is valid until the next call to ada_encode.  */
823
824 char *
825 ada_encode (const char *decoded)
826 {
827   static char *encoding_buffer = NULL;
828   static size_t encoding_buffer_size = 0;
829   const char *p;
830   int k;
831
832   if (decoded == NULL)
833     return NULL;
834
835   GROW_VECT (encoding_buffer, encoding_buffer_size,
836              2 * strlen (decoded) + 10);
837
838   k = 0;
839   for (p = decoded; *p != '\0'; p += 1)
840     {
841       if (*p == '.')
842         {
843           encoding_buffer[k] = encoding_buffer[k + 1] = '_';
844           k += 2;
845         }
846       else if (*p == '"')
847         {
848           const struct ada_opname_map *mapping;
849
850           for (mapping = ada_opname_table;
851                mapping->encoded != NULL
852                && strncmp (mapping->decoded, p,
853                            strlen (mapping->decoded)) != 0; mapping += 1)
854             ;
855           if (mapping->encoded == NULL)
856             error (_("invalid Ada operator name: %s"), p);
857           strcpy (encoding_buffer + k, mapping->encoded);
858           k += strlen (mapping->encoded);
859           break;
860         }
861       else
862         {
863           encoding_buffer[k] = *p;
864           k += 1;
865         }
866     }
867
868   encoding_buffer[k] = '\0';
869   return encoding_buffer;
870 }
871
872 /* Return NAME folded to lower case, or, if surrounded by single
873    quotes, unfolded, but with the quotes stripped away.  Result good
874    to next call.  */
875
876 char *
877 ada_fold_name (const char *name)
878 {
879   static char *fold_buffer = NULL;
880   static size_t fold_buffer_size = 0;
881
882   int len = strlen (name);
883   GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
884
885   if (name[0] == '\'')
886     {
887       strncpy (fold_buffer, name + 1, len - 2);
888       fold_buffer[len - 2] = '\000';
889     }
890   else
891     {
892       int i;
893
894       for (i = 0; i <= len; i += 1)
895         fold_buffer[i] = tolower (name[i]);
896     }
897
898   return fold_buffer;
899 }
900
901 /* Return nonzero if C is either a digit or a lowercase alphabet character.  */
902
903 static int
904 is_lower_alphanum (const char c)
905 {
906   return (isdigit (c) || (isalpha (c) && islower (c)));
907 }
908
909 /* ENCODED is the linkage name of a symbol and LEN contains its length.
910    This function saves in LEN the length of that same symbol name but
911    without either of these suffixes:
912      . .{DIGIT}+
913      . ${DIGIT}+
914      . ___{DIGIT}+
915      . __{DIGIT}+.
916
917    These are suffixes introduced by the compiler for entities such as
918    nested subprogram for instance, in order to avoid name clashes.
919    They do not serve any purpose for the debugger.  */
920
921 static void
922 ada_remove_trailing_digits (const char *encoded, int *len)
923 {
924   if (*len > 1 && isdigit (encoded[*len - 1]))
925     {
926       int i = *len - 2;
927
928       while (i > 0 && isdigit (encoded[i]))
929         i--;
930       if (i >= 0 && encoded[i] == '.')
931         *len = i;
932       else if (i >= 0 && encoded[i] == '$')
933         *len = i;
934       else if (i >= 2 && strncmp (encoded + i - 2, "___", 3) == 0)
935         *len = i - 2;
936       else if (i >= 1 && strncmp (encoded + i - 1, "__", 2) == 0)
937         *len = i - 1;
938     }
939 }
940
941 /* Remove the suffix introduced by the compiler for protected object
942    subprograms.  */
943
944 static void
945 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
946 {
947   /* Remove trailing N.  */
948
949   /* Protected entry subprograms are broken into two
950      separate subprograms: The first one is unprotected, and has
951      a 'N' suffix; the second is the protected version, and has
952      the 'P' suffix.  The second calls the first one after handling
953      the protection.  Since the P subprograms are internally generated,
954      we leave these names undecoded, giving the user a clue that this
955      entity is internal.  */
956
957   if (*len > 1
958       && encoded[*len - 1] == 'N'
959       && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
960     *len = *len - 1;
961 }
962
963 /* Remove trailing X[bn]* suffixes (indicating names in package bodies).  */
964
965 static void
966 ada_remove_Xbn_suffix (const char *encoded, int *len)
967 {
968   int i = *len - 1;
969
970   while (i > 0 && (encoded[i] == 'b' || encoded[i] == 'n'))
971     i--;
972
973   if (encoded[i] != 'X')
974     return;
975
976   if (i == 0)
977     return;
978
979   if (isalnum (encoded[i-1]))
980     *len = i;
981 }
982
983 /* If ENCODED follows the GNAT entity encoding conventions, then return
984    the decoded form of ENCODED.  Otherwise, return "<%s>" where "%s" is
985    replaced by ENCODED.
986
987    The resulting string is valid until the next call of ada_decode.
988    If the string is unchanged by decoding, the original string pointer
989    is returned.  */
990
991 const char *
992 ada_decode (const char *encoded)
993 {
994   int i, j;
995   int len0;
996   const char *p;
997   char *decoded;
998   int at_start_name;
999   static char *decoding_buffer = NULL;
1000   static size_t decoding_buffer_size = 0;
1001
1002   /* The name of the Ada main procedure starts with "_ada_".
1003      This prefix is not part of the decoded name, so skip this part
1004      if we see this prefix.  */
1005   if (strncmp (encoded, "_ada_", 5) == 0)
1006     encoded += 5;
1007
1008   /* If the name starts with '_', then it is not a properly encoded
1009      name, so do not attempt to decode it.  Similarly, if the name
1010      starts with '<', the name should not be decoded.  */
1011   if (encoded[0] == '_' || encoded[0] == '<')
1012     goto Suppress;
1013
1014   len0 = strlen (encoded);
1015
1016   ada_remove_trailing_digits (encoded, &len0);
1017   ada_remove_po_subprogram_suffix (encoded, &len0);
1018
1019   /* Remove the ___X.* suffix if present.  Do not forget to verify that
1020      the suffix is located before the current "end" of ENCODED.  We want
1021      to avoid re-matching parts of ENCODED that have previously been
1022      marked as discarded (by decrementing LEN0).  */
1023   p = strstr (encoded, "___");
1024   if (p != NULL && p - encoded < len0 - 3)
1025     {
1026       if (p[3] == 'X')
1027         len0 = p - encoded;
1028       else
1029         goto Suppress;
1030     }
1031
1032   /* Remove any trailing TKB suffix.  It tells us that this symbol
1033      is for the body of a task, but that information does not actually
1034      appear in the decoded name.  */
1035
1036   if (len0 > 3 && strncmp (encoded + len0 - 3, "TKB", 3) == 0)
1037     len0 -= 3;
1038
1039   /* Remove any trailing TB suffix.  The TB suffix is slightly different
1040      from the TKB suffix because it is used for non-anonymous task
1041      bodies.  */
1042
1043   if (len0 > 2 && strncmp (encoded + len0 - 2, "TB", 2) == 0)
1044     len0 -= 2;
1045
1046   /* Remove trailing "B" suffixes.  */
1047   /* FIXME: brobecker/2006-04-19: Not sure what this are used for...  */
1048
1049   if (len0 > 1 && strncmp (encoded + len0 - 1, "B", 1) == 0)
1050     len0 -= 1;
1051
1052   /* Make decoded big enough for possible expansion by operator name.  */
1053
1054   GROW_VECT (decoding_buffer, decoding_buffer_size, 2 * len0 + 1);
1055   decoded = decoding_buffer;
1056
1057   /* Remove trailing __{digit}+ or trailing ${digit}+.  */
1058
1059   if (len0 > 1 && isdigit (encoded[len0 - 1]))
1060     {
1061       i = len0 - 2;
1062       while ((i >= 0 && isdigit (encoded[i]))
1063              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1064         i -= 1;
1065       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1066         len0 = i - 1;
1067       else if (encoded[i] == '$')
1068         len0 = i;
1069     }
1070
1071   /* The first few characters that are not alphabetic are not part
1072      of any encoding we use, so we can copy them over verbatim.  */
1073
1074   for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1075     decoded[j] = encoded[i];
1076
1077   at_start_name = 1;
1078   while (i < len0)
1079     {
1080       /* Is this a symbol function?  */
1081       if (at_start_name && encoded[i] == 'O')
1082         {
1083           int k;
1084
1085           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1086             {
1087               int op_len = strlen (ada_opname_table[k].encoded);
1088               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1089                             op_len - 1) == 0)
1090                   && !isalnum (encoded[i + op_len]))
1091                 {
1092                   strcpy (decoded + j, ada_opname_table[k].decoded);
1093                   at_start_name = 0;
1094                   i += op_len;
1095                   j += strlen (ada_opname_table[k].decoded);
1096                   break;
1097                 }
1098             }
1099           if (ada_opname_table[k].encoded != NULL)
1100             continue;
1101         }
1102       at_start_name = 0;
1103
1104       /* Replace "TK__" with "__", which will eventually be translated
1105          into "." (just below).  */
1106
1107       if (i < len0 - 4 && strncmp (encoded + i, "TK__", 4) == 0)
1108         i += 2;
1109
1110       /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1111          be translated into "." (just below).  These are internal names
1112          generated for anonymous blocks inside which our symbol is nested.  */
1113
1114       if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1115           && encoded [i+2] == 'B' && encoded [i+3] == '_'
1116           && isdigit (encoded [i+4]))
1117         {
1118           int k = i + 5;
1119           
1120           while (k < len0 && isdigit (encoded[k]))
1121             k++;  /* Skip any extra digit.  */
1122
1123           /* Double-check that the "__B_{DIGITS}+" sequence we found
1124              is indeed followed by "__".  */
1125           if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1126             i = k;
1127         }
1128
1129       /* Remove _E{DIGITS}+[sb] */
1130
1131       /* Just as for protected object subprograms, there are 2 categories
1132          of subprograms created by the compiler for each entry.  The first
1133          one implements the actual entry code, and has a suffix following
1134          the convention above; the second one implements the barrier and
1135          uses the same convention as above, except that the 'E' is replaced
1136          by a 'B'.
1137
1138          Just as above, we do not decode the name of barrier functions
1139          to give the user a clue that the code he is debugging has been
1140          internally generated.  */
1141
1142       if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1143           && isdigit (encoded[i+2]))
1144         {
1145           int k = i + 3;
1146
1147           while (k < len0 && isdigit (encoded[k]))
1148             k++;
1149
1150           if (k < len0
1151               && (encoded[k] == 'b' || encoded[k] == 's'))
1152             {
1153               k++;
1154               /* Just as an extra precaution, make sure that if this
1155                  suffix is followed by anything else, it is a '_'.
1156                  Otherwise, we matched this sequence by accident.  */
1157               if (k == len0
1158                   || (k < len0 && encoded[k] == '_'))
1159                 i = k;
1160             }
1161         }
1162
1163       /* Remove trailing "N" in [a-z0-9]+N__.  The N is added by
1164          the GNAT front-end in protected object subprograms.  */
1165
1166       if (i < len0 + 3
1167           && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1168         {
1169           /* Backtrack a bit up until we reach either the begining of
1170              the encoded name, or "__".  Make sure that we only find
1171              digits or lowercase characters.  */
1172           const char *ptr = encoded + i - 1;
1173
1174           while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1175             ptr--;
1176           if (ptr < encoded
1177               || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1178             i++;
1179         }
1180
1181       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1182         {
1183           /* This is a X[bn]* sequence not separated from the previous
1184              part of the name with a non-alpha-numeric character (in other
1185              words, immediately following an alpha-numeric character), then
1186              verify that it is placed at the end of the encoded name.  If
1187              not, then the encoding is not valid and we should abort the
1188              decoding.  Otherwise, just skip it, it is used in body-nested
1189              package names.  */
1190           do
1191             i += 1;
1192           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1193           if (i < len0)
1194             goto Suppress;
1195         }
1196       else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1197         {
1198          /* Replace '__' by '.'.  */
1199           decoded[j] = '.';
1200           at_start_name = 1;
1201           i += 2;
1202           j += 1;
1203         }
1204       else
1205         {
1206           /* It's a character part of the decoded name, so just copy it
1207              over.  */
1208           decoded[j] = encoded[i];
1209           i += 1;
1210           j += 1;
1211         }
1212     }
1213   decoded[j] = '\000';
1214
1215   /* Decoded names should never contain any uppercase character.
1216      Double-check this, and abort the decoding if we find one.  */
1217
1218   for (i = 0; decoded[i] != '\0'; i += 1)
1219     if (isupper (decoded[i]) || decoded[i] == ' ')
1220       goto Suppress;
1221
1222   if (strcmp (decoded, encoded) == 0)
1223     return encoded;
1224   else
1225     return decoded;
1226
1227 Suppress:
1228   GROW_VECT (decoding_buffer, decoding_buffer_size, strlen (encoded) + 3);
1229   decoded = decoding_buffer;
1230   if (encoded[0] == '<')
1231     strcpy (decoded, encoded);
1232   else
1233     xsnprintf (decoded, decoding_buffer_size, "<%s>", encoded);
1234   return decoded;
1235
1236 }
1237
1238 /* Table for keeping permanent unique copies of decoded names.  Once
1239    allocated, names in this table are never released.  While this is a
1240    storage leak, it should not be significant unless there are massive
1241    changes in the set of decoded names in successive versions of a 
1242    symbol table loaded during a single session.  */
1243 static struct htab *decoded_names_store;
1244
1245 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1246    in the language-specific part of GSYMBOL, if it has not been
1247    previously computed.  Tries to save the decoded name in the same
1248    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1249    in any case, the decoded symbol has a lifetime at least that of
1250    GSYMBOL).
1251    The GSYMBOL parameter is "mutable" in the C++ sense: logically
1252    const, but nevertheless modified to a semantically equivalent form
1253    when a decoded name is cached in it.  */
1254
1255 char *
1256 ada_decode_symbol (const struct general_symbol_info *gsymbol)
1257 {
1258   char **resultp =
1259     (char **) &gsymbol->language_specific.mangled_lang.demangled_name;
1260
1261   if (*resultp == NULL)
1262     {
1263       const char *decoded = ada_decode (gsymbol->name);
1264
1265       if (gsymbol->obj_section != NULL)
1266         {
1267           struct objfile *objf = gsymbol->obj_section->objfile;
1268
1269           *resultp = obsavestring (decoded, strlen (decoded),
1270                                    &objf->objfile_obstack);
1271         }
1272       /* Sometimes, we can't find a corresponding objfile, in which
1273          case, we put the result on the heap.  Since we only decode
1274          when needed, we hope this usually does not cause a
1275          significant memory leak (FIXME).  */
1276       if (*resultp == NULL)
1277         {
1278           char **slot = (char **) htab_find_slot (decoded_names_store,
1279                                                   decoded, INSERT);
1280
1281           if (*slot == NULL)
1282             *slot = xstrdup (decoded);
1283           *resultp = *slot;
1284         }
1285     }
1286
1287   return *resultp;
1288 }
1289
1290 static char *
1291 ada_la_decode (const char *encoded, int options)
1292 {
1293   return xstrdup (ada_decode (encoded));
1294 }
1295
1296 /* Returns non-zero iff SYM_NAME matches NAME, ignoring any trailing
1297    suffixes that encode debugging information or leading _ada_ on
1298    SYM_NAME (see is_name_suffix commentary for the debugging
1299    information that is ignored).  If WILD, then NAME need only match a
1300    suffix of SYM_NAME minus the same suffixes.  Also returns 0 if
1301    either argument is NULL.  */
1302
1303 static int
1304 match_name (const char *sym_name, const char *name, int wild)
1305 {
1306   if (sym_name == NULL || name == NULL)
1307     return 0;
1308   else if (wild)
1309     return wild_match (sym_name, name) == 0;
1310   else
1311     {
1312       int len_name = strlen (name);
1313
1314       return (strncmp (sym_name, name, len_name) == 0
1315               && is_name_suffix (sym_name + len_name))
1316         || (strncmp (sym_name, "_ada_", 5) == 0
1317             && strncmp (sym_name + 5, name, len_name) == 0
1318             && is_name_suffix (sym_name + len_name + 5));
1319     }
1320 }
1321 \f
1322
1323                                 /* Arrays */
1324
1325 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1326    generated by the GNAT compiler to describe the index type used
1327    for each dimension of an array, check whether it follows the latest
1328    known encoding.  If not, fix it up to conform to the latest encoding.
1329    Otherwise, do nothing.  This function also does nothing if
1330    INDEX_DESC_TYPE is NULL.
1331
1332    The GNAT encoding used to describle the array index type evolved a bit.
1333    Initially, the information would be provided through the name of each
1334    field of the structure type only, while the type of these fields was
1335    described as unspecified and irrelevant.  The debugger was then expected
1336    to perform a global type lookup using the name of that field in order
1337    to get access to the full index type description.  Because these global
1338    lookups can be very expensive, the encoding was later enhanced to make
1339    the global lookup unnecessary by defining the field type as being
1340    the full index type description.
1341
1342    The purpose of this routine is to allow us to support older versions
1343    of the compiler by detecting the use of the older encoding, and by
1344    fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1345    we essentially replace each field's meaningless type by the associated
1346    index subtype).  */
1347
1348 void
1349 ada_fixup_array_indexes_type (struct type *index_desc_type)
1350 {
1351   int i;
1352
1353   if (index_desc_type == NULL)
1354     return;
1355   gdb_assert (TYPE_NFIELDS (index_desc_type) > 0);
1356
1357   /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1358      to check one field only, no need to check them all).  If not, return
1359      now.
1360
1361      If our INDEX_DESC_TYPE was generated using the older encoding,
1362      the field type should be a meaningless integer type whose name
1363      is not equal to the field name.  */
1364   if (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)) != NULL
1365       && strcmp (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)),
1366                  TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
1367     return;
1368
1369   /* Fixup each field of INDEX_DESC_TYPE.  */
1370   for (i = 0; i < TYPE_NFIELDS (index_desc_type); i++)
1371    {
1372      char *name = TYPE_FIELD_NAME (index_desc_type, i);
1373      struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1374
1375      if (raw_type)
1376        TYPE_FIELD_TYPE (index_desc_type, i) = raw_type;
1377    }
1378 }
1379
1380 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors.  */
1381
1382 static char *bound_name[] = {
1383   "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
1384   "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
1385 };
1386
1387 /* Maximum number of array dimensions we are prepared to handle.  */
1388
1389 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))
1390
1391
1392 /* The desc_* routines return primitive portions of array descriptors
1393    (fat pointers).  */
1394
1395 /* The descriptor or array type, if any, indicated by TYPE; removes
1396    level of indirection, if needed.  */
1397
1398 static struct type *
1399 desc_base_type (struct type *type)
1400 {
1401   if (type == NULL)
1402     return NULL;
1403   type = ada_check_typedef (type);
1404   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
1405     type = ada_typedef_target_type (type);
1406
1407   if (type != NULL
1408       && (TYPE_CODE (type) == TYPE_CODE_PTR
1409           || TYPE_CODE (type) == TYPE_CODE_REF))
1410     return ada_check_typedef (TYPE_TARGET_TYPE (type));
1411   else
1412     return type;
1413 }
1414
1415 /* True iff TYPE indicates a "thin" array pointer type.  */
1416
1417 static int
1418 is_thin_pntr (struct type *type)
1419 {
1420   return
1421     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1422     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1423 }
1424
1425 /* The descriptor type for thin pointer type TYPE.  */
1426
1427 static struct type *
1428 thin_descriptor_type (struct type *type)
1429 {
1430   struct type *base_type = desc_base_type (type);
1431
1432   if (base_type == NULL)
1433     return NULL;
1434   if (is_suffix (ada_type_name (base_type), "___XVE"))
1435     return base_type;
1436   else
1437     {
1438       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1439
1440       if (alt_type == NULL)
1441         return base_type;
1442       else
1443         return alt_type;
1444     }
1445 }
1446
1447 /* A pointer to the array data for thin-pointer value VAL.  */
1448
1449 static struct value *
1450 thin_data_pntr (struct value *val)
1451 {
1452   struct type *type = ada_check_typedef (value_type (val));
1453   struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1454
1455   data_type = lookup_pointer_type (data_type);
1456
1457   if (TYPE_CODE (type) == TYPE_CODE_PTR)
1458     return value_cast (data_type, value_copy (val));
1459   else
1460     return value_from_longest (data_type, value_address (val));
1461 }
1462
1463 /* True iff TYPE indicates a "thick" array pointer type.  */
1464
1465 static int
1466 is_thick_pntr (struct type *type)
1467 {
1468   type = desc_base_type (type);
1469   return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
1470           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1471 }
1472
1473 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1474    pointer to one, the type of its bounds data; otherwise, NULL.  */
1475
1476 static struct type *
1477 desc_bounds_type (struct type *type)
1478 {
1479   struct type *r;
1480
1481   type = desc_base_type (type);
1482
1483   if (type == NULL)
1484     return NULL;
1485   else if (is_thin_pntr (type))
1486     {
1487       type = thin_descriptor_type (type);
1488       if (type == NULL)
1489         return NULL;
1490       r = lookup_struct_elt_type (type, "BOUNDS", 1);
1491       if (r != NULL)
1492         return ada_check_typedef (r);
1493     }
1494   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1495     {
1496       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1497       if (r != NULL)
1498         return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1499     }
1500   return NULL;
1501 }
1502
1503 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1504    one, a pointer to its bounds data.   Otherwise NULL.  */
1505
1506 static struct value *
1507 desc_bounds (struct value *arr)
1508 {
1509   struct type *type = ada_check_typedef (value_type (arr));
1510
1511   if (is_thin_pntr (type))
1512     {
1513       struct type *bounds_type =
1514         desc_bounds_type (thin_descriptor_type (type));
1515       LONGEST addr;
1516
1517       if (bounds_type == NULL)
1518         error (_("Bad GNAT array descriptor"));
1519
1520       /* NOTE: The following calculation is not really kosher, but
1521          since desc_type is an XVE-encoded type (and shouldn't be),
1522          the correct calculation is a real pain.  FIXME (and fix GCC).  */
1523       if (TYPE_CODE (type) == TYPE_CODE_PTR)
1524         addr = value_as_long (arr);
1525       else
1526         addr = value_address (arr);
1527
1528       return
1529         value_from_longest (lookup_pointer_type (bounds_type),
1530                             addr - TYPE_LENGTH (bounds_type));
1531     }
1532
1533   else if (is_thick_pntr (type))
1534     {
1535       struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1536                                                _("Bad GNAT array descriptor"));
1537       struct type *p_bounds_type = value_type (p_bounds);
1538
1539       if (p_bounds_type
1540           && TYPE_CODE (p_bounds_type) == TYPE_CODE_PTR)
1541         {
1542           struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1543
1544           if (TYPE_STUB (target_type))
1545             p_bounds = value_cast (lookup_pointer_type
1546                                    (ada_check_typedef (target_type)),
1547                                    p_bounds);
1548         }
1549       else
1550         error (_("Bad GNAT array descriptor"));
1551
1552       return p_bounds;
1553     }
1554   else
1555     return NULL;
1556 }
1557
1558 /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
1559    position of the field containing the address of the bounds data.  */
1560
1561 static int
1562 fat_pntr_bounds_bitpos (struct type *type)
1563 {
1564   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1565 }
1566
1567 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1568    size of the field containing the address of the bounds data.  */
1569
1570 static int
1571 fat_pntr_bounds_bitsize (struct type *type)
1572 {
1573   type = desc_base_type (type);
1574
1575   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1576     return TYPE_FIELD_BITSIZE (type, 1);
1577   else
1578     return 8 * TYPE_LENGTH (ada_check_typedef (TYPE_FIELD_TYPE (type, 1)));
1579 }
1580
1581 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1582    pointer to one, the type of its array data (a array-with-no-bounds type);
1583    otherwise, NULL.  Use ada_type_of_array to get an array type with bounds
1584    data.  */
1585
1586 static struct type *
1587 desc_data_target_type (struct type *type)
1588 {
1589   type = desc_base_type (type);
1590
1591   /* NOTE: The following is bogus; see comment in desc_bounds.  */
1592   if (is_thin_pntr (type))
1593     return desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1));
1594   else if (is_thick_pntr (type))
1595     {
1596       struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1597
1598       if (data_type
1599           && TYPE_CODE (ada_check_typedef (data_type)) == TYPE_CODE_PTR)
1600         return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1601     }
1602
1603   return NULL;
1604 }
1605
1606 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1607    its array data.  */
1608
1609 static struct value *
1610 desc_data (struct value *arr)
1611 {
1612   struct type *type = value_type (arr);
1613
1614   if (is_thin_pntr (type))
1615     return thin_data_pntr (arr);
1616   else if (is_thick_pntr (type))
1617     return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1618                              _("Bad GNAT array descriptor"));
1619   else
1620     return NULL;
1621 }
1622
1623
1624 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1625    position of the field containing the address of the data.  */
1626
1627 static int
1628 fat_pntr_data_bitpos (struct type *type)
1629 {
1630   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1631 }
1632
1633 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1634    size of the field containing the address of the data.  */
1635
1636 static int
1637 fat_pntr_data_bitsize (struct type *type)
1638 {
1639   type = desc_base_type (type);
1640
1641   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1642     return TYPE_FIELD_BITSIZE (type, 0);
1643   else
1644     return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
1645 }
1646
1647 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1648    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1649    bound, if WHICH is 1.  The first bound is I=1.  */
1650
1651 static struct value *
1652 desc_one_bound (struct value *bounds, int i, int which)
1653 {
1654   return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
1655                            _("Bad GNAT array descriptor bounds"));
1656 }
1657
1658 /* If BOUNDS is an array-bounds structure type, return the bit position
1659    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1660    bound, if WHICH is 1.  The first bound is I=1.  */
1661
1662 static int
1663 desc_bound_bitpos (struct type *type, int i, int which)
1664 {
1665   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1666 }
1667
1668 /* If BOUNDS is an array-bounds structure type, return the bit field size
1669    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1670    bound, if WHICH is 1.  The first bound is I=1.  */
1671
1672 static int
1673 desc_bound_bitsize (struct type *type, int i, int which)
1674 {
1675   type = desc_base_type (type);
1676
1677   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1678     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1679   else
1680     return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
1681 }
1682
1683 /* If TYPE is the type of an array-bounds structure, the type of its
1684    Ith bound (numbering from 1).  Otherwise, NULL.  */
1685
1686 static struct type *
1687 desc_index_type (struct type *type, int i)
1688 {
1689   type = desc_base_type (type);
1690
1691   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1692     return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
1693   else
1694     return NULL;
1695 }
1696
1697 /* The number of index positions in the array-bounds type TYPE.
1698    Return 0 if TYPE is NULL.  */
1699
1700 static int
1701 desc_arity (struct type *type)
1702 {
1703   type = desc_base_type (type);
1704
1705   if (type != NULL)
1706     return TYPE_NFIELDS (type) / 2;
1707   return 0;
1708 }
1709
1710 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or 
1711    an array descriptor type (representing an unconstrained array
1712    type).  */
1713
1714 static int
1715 ada_is_direct_array_type (struct type *type)
1716 {
1717   if (type == NULL)
1718     return 0;
1719   type = ada_check_typedef (type);
1720   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1721           || ada_is_array_descriptor_type (type));
1722 }
1723
1724 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1725  * to one.  */
1726
1727 static int
1728 ada_is_array_type (struct type *type)
1729 {
1730   while (type != NULL 
1731          && (TYPE_CODE (type) == TYPE_CODE_PTR 
1732              || TYPE_CODE (type) == TYPE_CODE_REF))
1733     type = TYPE_TARGET_TYPE (type);
1734   return ada_is_direct_array_type (type);
1735 }
1736
1737 /* Non-zero iff TYPE is a simple array type or pointer to one.  */
1738
1739 int
1740 ada_is_simple_array_type (struct type *type)
1741 {
1742   if (type == NULL)
1743     return 0;
1744   type = ada_check_typedef (type);
1745   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1746           || (TYPE_CODE (type) == TYPE_CODE_PTR
1747               && TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type)))
1748                  == TYPE_CODE_ARRAY));
1749 }
1750
1751 /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */
1752
1753 int
1754 ada_is_array_descriptor_type (struct type *type)
1755 {
1756   struct type *data_type = desc_data_target_type (type);
1757
1758   if (type == NULL)
1759     return 0;
1760   type = ada_check_typedef (type);
1761   return (data_type != NULL
1762           && TYPE_CODE (data_type) == TYPE_CODE_ARRAY
1763           && desc_arity (desc_bounds_type (type)) > 0);
1764 }
1765
1766 /* Non-zero iff type is a partially mal-formed GNAT array
1767    descriptor.  FIXME: This is to compensate for some problems with
1768    debugging output from GNAT.  Re-examine periodically to see if it
1769    is still needed.  */
1770
1771 int
1772 ada_is_bogus_array_descriptor (struct type *type)
1773 {
1774   return
1775     type != NULL
1776     && TYPE_CODE (type) == TYPE_CODE_STRUCT
1777     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1778         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1779     && !ada_is_array_descriptor_type (type);
1780 }
1781
1782
1783 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1784    (fat pointer) returns the type of the array data described---specifically,
1785    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
1786    in from the descriptor; otherwise, they are left unspecified.  If
1787    the ARR denotes a null array descriptor and BOUNDS is non-zero,
1788    returns NULL.  The result is simply the type of ARR if ARR is not
1789    a descriptor.  */
1790 struct type *
1791 ada_type_of_array (struct value *arr, int bounds)
1792 {
1793   if (ada_is_constrained_packed_array_type (value_type (arr)))
1794     return decode_constrained_packed_array_type (value_type (arr));
1795
1796   if (!ada_is_array_descriptor_type (value_type (arr)))
1797     return value_type (arr);
1798
1799   if (!bounds)
1800     {
1801       struct type *array_type =
1802         ada_check_typedef (desc_data_target_type (value_type (arr)));
1803
1804       if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1805         TYPE_FIELD_BITSIZE (array_type, 0) =
1806           decode_packed_array_bitsize (value_type (arr));
1807       
1808       return array_type;
1809     }
1810   else
1811     {
1812       struct type *elt_type;
1813       int arity;
1814       struct value *descriptor;
1815
1816       elt_type = ada_array_element_type (value_type (arr), -1);
1817       arity = ada_array_arity (value_type (arr));
1818
1819       if (elt_type == NULL || arity == 0)
1820         return ada_check_typedef (value_type (arr));
1821
1822       descriptor = desc_bounds (arr);
1823       if (value_as_long (descriptor) == 0)
1824         return NULL;
1825       while (arity > 0)
1826         {
1827           struct type *range_type = alloc_type_copy (value_type (arr));
1828           struct type *array_type = alloc_type_copy (value_type (arr));
1829           struct value *low = desc_one_bound (descriptor, arity, 0);
1830           struct value *high = desc_one_bound (descriptor, arity, 1);
1831
1832           arity -= 1;
1833           create_range_type (range_type, value_type (low),
1834                              longest_to_int (value_as_long (low)),
1835                              longest_to_int (value_as_long (high)));
1836           elt_type = create_array_type (array_type, elt_type, range_type);
1837
1838           if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1839             {
1840               /* We need to store the element packed bitsize, as well as
1841                  recompute the array size, because it was previously
1842                  computed based on the unpacked element size.  */
1843               LONGEST lo = value_as_long (low);
1844               LONGEST hi = value_as_long (high);
1845
1846               TYPE_FIELD_BITSIZE (elt_type, 0) =
1847                 decode_packed_array_bitsize (value_type (arr));
1848               /* If the array has no element, then the size is already
1849                  zero, and does not need to be recomputed.  */
1850               if (lo < hi)
1851                 {
1852                   int array_bitsize =
1853                         (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
1854
1855                   TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
1856                 }
1857             }
1858         }
1859
1860       return lookup_pointer_type (elt_type);
1861     }
1862 }
1863
1864 /* If ARR does not represent an array, returns ARR unchanged.
1865    Otherwise, returns either a standard GDB array with bounds set
1866    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1867    GDB array.  Returns NULL if ARR is a null fat pointer.  */
1868
1869 struct value *
1870 ada_coerce_to_simple_array_ptr (struct value *arr)
1871 {
1872   if (ada_is_array_descriptor_type (value_type (arr)))
1873     {
1874       struct type *arrType = ada_type_of_array (arr, 1);
1875
1876       if (arrType == NULL)
1877         return NULL;
1878       return value_cast (arrType, value_copy (desc_data (arr)));
1879     }
1880   else if (ada_is_constrained_packed_array_type (value_type (arr)))
1881     return decode_constrained_packed_array (arr);
1882   else
1883     return arr;
1884 }
1885
1886 /* If ARR does not represent an array, returns ARR unchanged.
1887    Otherwise, returns a standard GDB array describing ARR (which may
1888    be ARR itself if it already is in the proper form).  */
1889
1890 struct value *
1891 ada_coerce_to_simple_array (struct value *arr)
1892 {
1893   if (ada_is_array_descriptor_type (value_type (arr)))
1894     {
1895       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1896
1897       if (arrVal == NULL)
1898         error (_("Bounds unavailable for null array pointer."));
1899       check_size (TYPE_TARGET_TYPE (value_type (arrVal)));
1900       return value_ind (arrVal);
1901     }
1902   else if (ada_is_constrained_packed_array_type (value_type (arr)))
1903     return decode_constrained_packed_array (arr);
1904   else
1905     return arr;
1906 }
1907
1908 /* If TYPE represents a GNAT array type, return it translated to an
1909    ordinary GDB array type (possibly with BITSIZE fields indicating
1910    packing).  For other types, is the identity.  */
1911
1912 struct type *
1913 ada_coerce_to_simple_array_type (struct type *type)
1914 {
1915   if (ada_is_constrained_packed_array_type (type))
1916     return decode_constrained_packed_array_type (type);
1917
1918   if (ada_is_array_descriptor_type (type))
1919     return ada_check_typedef (desc_data_target_type (type));
1920
1921   return type;
1922 }
1923
1924 /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */
1925
1926 static int
1927 ada_is_packed_array_type  (struct type *type)
1928 {
1929   if (type == NULL)
1930     return 0;
1931   type = desc_base_type (type);
1932   type = ada_check_typedef (type);
1933   return
1934     ada_type_name (type) != NULL
1935     && strstr (ada_type_name (type), "___XP") != NULL;
1936 }
1937
1938 /* Non-zero iff TYPE represents a standard GNAT constrained
1939    packed-array type.  */
1940
1941 int
1942 ada_is_constrained_packed_array_type (struct type *type)
1943 {
1944   return ada_is_packed_array_type (type)
1945     && !ada_is_array_descriptor_type (type);
1946 }
1947
1948 /* Non-zero iff TYPE represents an array descriptor for a
1949    unconstrained packed-array type.  */
1950
1951 static int
1952 ada_is_unconstrained_packed_array_type (struct type *type)
1953 {
1954   return ada_is_packed_array_type (type)
1955     && ada_is_array_descriptor_type (type);
1956 }
1957
1958 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
1959    return the size of its elements in bits.  */
1960
1961 static long
1962 decode_packed_array_bitsize (struct type *type)
1963 {
1964   char *raw_name;
1965   char *tail;
1966   long bits;
1967
1968   /* Access to arrays implemented as fat pointers are encoded as a typedef
1969      of the fat pointer type.  We need the name of the fat pointer type
1970      to do the decoding, so strip the typedef layer.  */
1971   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
1972     type = ada_typedef_target_type (type);
1973
1974   raw_name = ada_type_name (ada_check_typedef (type));
1975   if (!raw_name)
1976     raw_name = ada_type_name (desc_base_type (type));
1977
1978   if (!raw_name)
1979     return 0;
1980
1981   tail = strstr (raw_name, "___XP");
1982   gdb_assert (tail != NULL);
1983
1984   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
1985     {
1986       lim_warning
1987         (_("could not understand bit size information on packed array"));
1988       return 0;
1989     }
1990
1991   return bits;
1992 }
1993
1994 /* Given that TYPE is a standard GDB array type with all bounds filled
1995    in, and that the element size of its ultimate scalar constituents
1996    (that is, either its elements, or, if it is an array of arrays, its
1997    elements' elements, etc.) is *ELT_BITS, return an identical type,
1998    but with the bit sizes of its elements (and those of any
1999    constituent arrays) recorded in the BITSIZE components of its
2000    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2001    in bits.  */
2002
2003 static struct type *
2004 constrained_packed_array_type (struct type *type, long *elt_bits)
2005 {
2006   struct type *new_elt_type;
2007   struct type *new_type;
2008   LONGEST low_bound, high_bound;
2009
2010   type = ada_check_typedef (type);
2011   if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2012     return type;
2013
2014   new_type = alloc_type_copy (type);
2015   new_elt_type =
2016     constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2017                                    elt_bits);
2018   create_array_type (new_type, new_elt_type, TYPE_INDEX_TYPE (type));
2019   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2020   TYPE_NAME (new_type) = ada_type_name (type);
2021
2022   if (get_discrete_bounds (TYPE_INDEX_TYPE (type),
2023                            &low_bound, &high_bound) < 0)
2024     low_bound = high_bound = 0;
2025   if (high_bound < low_bound)
2026     *elt_bits = TYPE_LENGTH (new_type) = 0;
2027   else
2028     {
2029       *elt_bits *= (high_bound - low_bound + 1);
2030       TYPE_LENGTH (new_type) =
2031         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2032     }
2033
2034   TYPE_FIXED_INSTANCE (new_type) = 1;
2035   return new_type;
2036 }
2037
2038 /* The array type encoded by TYPE, where
2039    ada_is_constrained_packed_array_type (TYPE).  */
2040
2041 static struct type *
2042 decode_constrained_packed_array_type (struct type *type)
2043 {
2044   char *raw_name = ada_type_name (ada_check_typedef (type));
2045   char *name;
2046   char *tail;
2047   struct type *shadow_type;
2048   long bits;
2049
2050   if (!raw_name)
2051     raw_name = ada_type_name (desc_base_type (type));
2052
2053   if (!raw_name)
2054     return NULL;
2055
2056   name = (char *) alloca (strlen (raw_name) + 1);
2057   tail = strstr (raw_name, "___XP");
2058   type = desc_base_type (type);
2059
2060   memcpy (name, raw_name, tail - raw_name);
2061   name[tail - raw_name] = '\000';
2062
2063   shadow_type = ada_find_parallel_type_with_name (type, name);
2064
2065   if (shadow_type == NULL)
2066     {
2067       lim_warning (_("could not find bounds information on packed array"));
2068       return NULL;
2069     }
2070   CHECK_TYPEDEF (shadow_type);
2071
2072   if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
2073     {
2074       lim_warning (_("could not understand bounds "
2075                      "information on packed array"));
2076       return NULL;
2077     }
2078
2079   bits = decode_packed_array_bitsize (type);
2080   return constrained_packed_array_type (shadow_type, &bits);
2081 }
2082
2083 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2084    array, returns a simple array that denotes that array.  Its type is a
2085    standard GDB array type except that the BITSIZEs of the array
2086    target types are set to the number of bits in each element, and the
2087    type length is set appropriately.  */
2088
2089 static struct value *
2090 decode_constrained_packed_array (struct value *arr)
2091 {
2092   struct type *type;
2093
2094   arr = ada_coerce_ref (arr);
2095
2096   /* If our value is a pointer, then dererence it.  Make sure that
2097      this operation does not cause the target type to be fixed, as
2098      this would indirectly cause this array to be decoded.  The rest
2099      of the routine assumes that the array hasn't been decoded yet,
2100      so we use the basic "value_ind" routine to perform the dereferencing,
2101      as opposed to using "ada_value_ind".  */
2102   if (TYPE_CODE (ada_check_typedef (value_type (arr))) == TYPE_CODE_PTR)
2103     arr = value_ind (arr);
2104
2105   type = decode_constrained_packed_array_type (value_type (arr));
2106   if (type == NULL)
2107     {
2108       error (_("can't unpack array"));
2109       return NULL;
2110     }
2111
2112   if (gdbarch_bits_big_endian (get_type_arch (value_type (arr)))
2113       && ada_is_modular_type (value_type (arr)))
2114     {
2115        /* This is a (right-justified) modular type representing a packed
2116          array with no wrapper.  In order to interpret the value through
2117          the (left-justified) packed array type we just built, we must
2118          first left-justify it.  */
2119       int bit_size, bit_pos;
2120       ULONGEST mod;
2121
2122       mod = ada_modulus (value_type (arr)) - 1;
2123       bit_size = 0;
2124       while (mod > 0)
2125         {
2126           bit_size += 1;
2127           mod >>= 1;
2128         }
2129       bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2130       arr = ada_value_primitive_packed_val (arr, NULL,
2131                                             bit_pos / HOST_CHAR_BIT,
2132                                             bit_pos % HOST_CHAR_BIT,
2133                                             bit_size,
2134                                             type);
2135     }
2136
2137   return coerce_unspec_val_to_type (arr, type);
2138 }
2139
2140
2141 /* The value of the element of packed array ARR at the ARITY indices
2142    given in IND.   ARR must be a simple array.  */
2143
2144 static struct value *
2145 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2146 {
2147   int i;
2148   int bits, elt_off, bit_off;
2149   long elt_total_bit_offset;
2150   struct type *elt_type;
2151   struct value *v;
2152
2153   bits = 0;
2154   elt_total_bit_offset = 0;
2155   elt_type = ada_check_typedef (value_type (arr));
2156   for (i = 0; i < arity; i += 1)
2157     {
2158       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
2159           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2160         error
2161           (_("attempt to do packed indexing of "
2162              "something other than a packed array"));
2163       else
2164         {
2165           struct type *range_type = TYPE_INDEX_TYPE (elt_type);
2166           LONGEST lowerbound, upperbound;
2167           LONGEST idx;
2168
2169           if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
2170             {
2171               lim_warning (_("don't know bounds of array"));
2172               lowerbound = upperbound = 0;
2173             }
2174
2175           idx = pos_atr (ind[i]);
2176           if (idx < lowerbound || idx > upperbound)
2177             lim_warning (_("packed array index %ld out of bounds"),
2178                          (long) idx);
2179           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2180           elt_total_bit_offset += (idx - lowerbound) * bits;
2181           elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2182         }
2183     }
2184   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2185   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2186
2187   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2188                                       bits, elt_type);
2189   return v;
2190 }
2191
2192 /* Non-zero iff TYPE includes negative integer values.  */
2193
2194 static int
2195 has_negatives (struct type *type)
2196 {
2197   switch (TYPE_CODE (type))
2198     {
2199     default:
2200       return 0;
2201     case TYPE_CODE_INT:
2202       return !TYPE_UNSIGNED (type);
2203     case TYPE_CODE_RANGE:
2204       return TYPE_LOW_BOUND (type) < 0;
2205     }
2206 }
2207
2208
2209 /* Create a new value of type TYPE from the contents of OBJ starting
2210    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2211    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
2212    assigning through the result will set the field fetched from.
2213    VALADDR is ignored unless OBJ is NULL, in which case,
2214    VALADDR+OFFSET must address the start of storage containing the 
2215    packed value.  The value returned  in this case is never an lval.
2216    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */
2217
2218 struct value *
2219 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2220                                 long offset, int bit_offset, int bit_size,
2221                                 struct type *type)
2222 {
2223   struct value *v;
2224   int src,                      /* Index into the source area */
2225     targ,                       /* Index into the target area */
2226     srcBitsLeft,                /* Number of source bits left to move */
2227     nsrc, ntarg,                /* Number of source and target bytes */
2228     unusedLS,                   /* Number of bits in next significant
2229                                    byte of source that are unused */
2230     accumSize;                  /* Number of meaningful bits in accum */
2231   unsigned char *bytes;         /* First byte containing data to unpack */
2232   unsigned char *unpacked;
2233   unsigned long accum;          /* Staging area for bits being transferred */
2234   unsigned char sign;
2235   int len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2236   /* Transmit bytes from least to most significant; delta is the direction
2237      the indices move.  */
2238   int delta = gdbarch_bits_big_endian (get_type_arch (type)) ? -1 : 1;
2239
2240   type = ada_check_typedef (type);
2241
2242   if (obj == NULL)
2243     {
2244       v = allocate_value (type);
2245       bytes = (unsigned char *) (valaddr + offset);
2246     }
2247   else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2248     {
2249       v = value_at (type,
2250                     value_address (obj) + offset);
2251       bytes = (unsigned char *) alloca (len);
2252       read_memory (value_address (v), bytes, len);
2253     }
2254   else
2255     {
2256       v = allocate_value (type);
2257       bytes = (unsigned char *) value_contents (obj) + offset;
2258     }
2259
2260   if (obj != NULL)
2261     {
2262       CORE_ADDR new_addr;
2263
2264       set_value_component_location (v, obj);
2265       new_addr = value_address (obj) + offset;
2266       set_value_bitpos (v, bit_offset + value_bitpos (obj));
2267       set_value_bitsize (v, bit_size);
2268       if (value_bitpos (v) >= HOST_CHAR_BIT)
2269         {
2270           ++new_addr;
2271           set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2272         }
2273       set_value_address (v, new_addr);
2274     }
2275   else
2276     set_value_bitsize (v, bit_size);
2277   unpacked = (unsigned char *) value_contents (v);
2278
2279   srcBitsLeft = bit_size;
2280   nsrc = len;
2281   ntarg = TYPE_LENGTH (type);
2282   sign = 0;
2283   if (bit_size == 0)
2284     {
2285       memset (unpacked, 0, TYPE_LENGTH (type));
2286       return v;
2287     }
2288   else if (gdbarch_bits_big_endian (get_type_arch (type)))
2289     {
2290       src = len - 1;
2291       if (has_negatives (type)
2292           && ((bytes[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2293         sign = ~0;
2294
2295       unusedLS =
2296         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2297         % HOST_CHAR_BIT;
2298
2299       switch (TYPE_CODE (type))
2300         {
2301         case TYPE_CODE_ARRAY:
2302         case TYPE_CODE_UNION:
2303         case TYPE_CODE_STRUCT:
2304           /* Non-scalar values must be aligned at a byte boundary...  */
2305           accumSize =
2306             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2307           /* ... And are placed at the beginning (most-significant) bytes
2308              of the target.  */
2309           targ = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2310           ntarg = targ + 1;
2311           break;
2312         default:
2313           accumSize = 0;
2314           targ = TYPE_LENGTH (type) - 1;
2315           break;
2316         }
2317     }
2318   else
2319     {
2320       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2321
2322       src = targ = 0;
2323       unusedLS = bit_offset;
2324       accumSize = 0;
2325
2326       if (has_negatives (type) && (bytes[len - 1] & (1 << sign_bit_offset)))
2327         sign = ~0;
2328     }
2329
2330   accum = 0;
2331   while (nsrc > 0)
2332     {
2333       /* Mask for removing bits of the next source byte that are not
2334          part of the value.  */
2335       unsigned int unusedMSMask =
2336         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2337         1;
2338       /* Sign-extend bits for this byte.  */
2339       unsigned int signMask = sign & ~unusedMSMask;
2340
2341       accum |=
2342         (((bytes[src] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2343       accumSize += HOST_CHAR_BIT - unusedLS;
2344       if (accumSize >= HOST_CHAR_BIT)
2345         {
2346           unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
2347           accumSize -= HOST_CHAR_BIT;
2348           accum >>= HOST_CHAR_BIT;
2349           ntarg -= 1;
2350           targ += delta;
2351         }
2352       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2353       unusedLS = 0;
2354       nsrc -= 1;
2355       src += delta;
2356     }
2357   while (ntarg > 0)
2358     {
2359       accum |= sign << accumSize;
2360       unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
2361       accumSize -= HOST_CHAR_BIT;
2362       accum >>= HOST_CHAR_BIT;
2363       ntarg -= 1;
2364       targ += delta;
2365     }
2366
2367   return v;
2368 }
2369
2370 /* Move N bits from SOURCE, starting at bit offset SRC_OFFSET to
2371    TARGET, starting at bit offset TARG_OFFSET.  SOURCE and TARGET must
2372    not overlap.  */
2373 static void
2374 move_bits (gdb_byte *target, int targ_offset, const gdb_byte *source,
2375            int src_offset, int n, int bits_big_endian_p)
2376 {
2377   unsigned int accum, mask;
2378   int accum_bits, chunk_size;
2379
2380   target += targ_offset / HOST_CHAR_BIT;
2381   targ_offset %= HOST_CHAR_BIT;
2382   source += src_offset / HOST_CHAR_BIT;
2383   src_offset %= HOST_CHAR_BIT;
2384   if (bits_big_endian_p)
2385     {
2386       accum = (unsigned char) *source;
2387       source += 1;
2388       accum_bits = HOST_CHAR_BIT - src_offset;
2389
2390       while (n > 0)
2391         {
2392           int unused_right;
2393
2394           accum = (accum << HOST_CHAR_BIT) + (unsigned char) *source;
2395           accum_bits += HOST_CHAR_BIT;
2396           source += 1;
2397           chunk_size = HOST_CHAR_BIT - targ_offset;
2398           if (chunk_size > n)
2399             chunk_size = n;
2400           unused_right = HOST_CHAR_BIT - (chunk_size + targ_offset);
2401           mask = ((1 << chunk_size) - 1) << unused_right;
2402           *target =
2403             (*target & ~mask)
2404             | ((accum >> (accum_bits - chunk_size - unused_right)) & mask);
2405           n -= chunk_size;
2406           accum_bits -= chunk_size;
2407           target += 1;
2408           targ_offset = 0;
2409         }
2410     }
2411   else
2412     {
2413       accum = (unsigned char) *source >> src_offset;
2414       source += 1;
2415       accum_bits = HOST_CHAR_BIT - src_offset;
2416
2417       while (n > 0)
2418         {
2419           accum = accum + ((unsigned char) *source << accum_bits);
2420           accum_bits += HOST_CHAR_BIT;
2421           source += 1;
2422           chunk_size = HOST_CHAR_BIT - targ_offset;
2423           if (chunk_size > n)
2424             chunk_size = n;
2425           mask = ((1 << chunk_size) - 1) << targ_offset;
2426           *target = (*target & ~mask) | ((accum << targ_offset) & mask);
2427           n -= chunk_size;
2428           accum_bits -= chunk_size;
2429           accum >>= chunk_size;
2430           target += 1;
2431           targ_offset = 0;
2432         }
2433     }
2434 }
2435
2436 /* Store the contents of FROMVAL into the location of TOVAL.
2437    Return a new value with the location of TOVAL and contents of
2438    FROMVAL.   Handles assignment into packed fields that have
2439    floating-point or non-scalar types.  */
2440
2441 static struct value *
2442 ada_value_assign (struct value *toval, struct value *fromval)
2443 {
2444   struct type *type = value_type (toval);
2445   int bits = value_bitsize (toval);
2446
2447   toval = ada_coerce_ref (toval);
2448   fromval = ada_coerce_ref (fromval);
2449
2450   if (ada_is_direct_array_type (value_type (toval)))
2451     toval = ada_coerce_to_simple_array (toval);
2452   if (ada_is_direct_array_type (value_type (fromval)))
2453     fromval = ada_coerce_to_simple_array (fromval);
2454
2455   if (!deprecated_value_modifiable (toval))
2456     error (_("Left operand of assignment is not a modifiable lvalue."));
2457
2458   if (VALUE_LVAL (toval) == lval_memory
2459       && bits > 0
2460       && (TYPE_CODE (type) == TYPE_CODE_FLT
2461           || TYPE_CODE (type) == TYPE_CODE_STRUCT))
2462     {
2463       int len = (value_bitpos (toval)
2464                  + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2465       int from_size;
2466       char *buffer = (char *) alloca (len);
2467       struct value *val;
2468       CORE_ADDR to_addr = value_address (toval);
2469
2470       if (TYPE_CODE (type) == TYPE_CODE_FLT)
2471         fromval = value_cast (type, fromval);
2472
2473       read_memory (to_addr, buffer, len);
2474       from_size = value_bitsize (fromval);
2475       if (from_size == 0)
2476         from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2477       if (gdbarch_bits_big_endian (get_type_arch (type)))
2478         move_bits (buffer, value_bitpos (toval),
2479                    value_contents (fromval), from_size - bits, bits, 1);
2480       else
2481         move_bits (buffer, value_bitpos (toval),
2482                    value_contents (fromval), 0, bits, 0);
2483       write_memory (to_addr, buffer, len);
2484       observer_notify_memory_changed (to_addr, len, buffer);
2485
2486       val = value_copy (toval);
2487       memcpy (value_contents_raw (val), value_contents (fromval),
2488               TYPE_LENGTH (type));
2489       deprecated_set_value_type (val, type);
2490
2491       return val;
2492     }
2493
2494   return value_assign (toval, fromval);
2495 }
2496
2497
2498 /* Given that COMPONENT is a memory lvalue that is part of the lvalue 
2499  * CONTAINER, assign the contents of VAL to COMPONENTS's place in 
2500  * CONTAINER.  Modifies the VALUE_CONTENTS of CONTAINER only, not 
2501  * COMPONENT, and not the inferior's memory.  The current contents 
2502  * of COMPONENT are ignored.  */
2503 static void
2504 value_assign_to_component (struct value *container, struct value *component,
2505                            struct value *val)
2506 {
2507   LONGEST offset_in_container =
2508     (LONGEST)  (value_address (component) - value_address (container));
2509   int bit_offset_in_container = 
2510     value_bitpos (component) - value_bitpos (container);
2511   int bits;
2512   
2513   val = value_cast (value_type (component), val);
2514
2515   if (value_bitsize (component) == 0)
2516     bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2517   else
2518     bits = value_bitsize (component);
2519
2520   if (gdbarch_bits_big_endian (get_type_arch (value_type (container))))
2521     move_bits (value_contents_writeable (container) + offset_in_container, 
2522                value_bitpos (container) + bit_offset_in_container,
2523                value_contents (val),
2524                TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits,
2525                bits, 1);
2526   else
2527     move_bits (value_contents_writeable (container) + offset_in_container, 
2528                value_bitpos (container) + bit_offset_in_container,
2529                value_contents (val), 0, bits, 0);
2530 }              
2531                         
2532 /* The value of the element of array ARR at the ARITY indices given in IND.
2533    ARR may be either a simple array, GNAT array descriptor, or pointer
2534    thereto.  */
2535
2536 struct value *
2537 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2538 {
2539   int k;
2540   struct value *elt;
2541   struct type *elt_type;
2542
2543   elt = ada_coerce_to_simple_array (arr);
2544
2545   elt_type = ada_check_typedef (value_type (elt));
2546   if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
2547       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2548     return value_subscript_packed (elt, arity, ind);
2549
2550   for (k = 0; k < arity; k += 1)
2551     {
2552       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
2553         error (_("too many subscripts (%d expected)"), k);
2554       elt = value_subscript (elt, pos_atr (ind[k]));
2555     }
2556   return elt;
2557 }
2558
2559 /* Assuming ARR is a pointer to a standard GDB array of type TYPE, the
2560    value of the element of *ARR at the ARITY indices given in
2561    IND.  Does not read the entire array into memory.  */
2562
2563 static struct value *
2564 ada_value_ptr_subscript (struct value *arr, struct type *type, int arity,
2565                          struct value **ind)
2566 {
2567   int k;
2568
2569   for (k = 0; k < arity; k += 1)
2570     {
2571       LONGEST lwb, upb;
2572
2573       if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2574         error (_("too many subscripts (%d expected)"), k);
2575       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2576                         value_copy (arr));
2577       get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
2578       arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
2579       type = TYPE_TARGET_TYPE (type);
2580     }
2581
2582   return value_ind (arr);
2583 }
2584
2585 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2586    actual type of ARRAY_PTR is ignored), returns the Ada slice of HIGH-LOW+1
2587    elements starting at index LOW.  The lower bound of this array is LOW, as
2588    per Ada rules.  */
2589 static struct value *
2590 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2591                           int low, int high)
2592 {
2593   struct type *type0 = ada_check_typedef (type);
2594   CORE_ADDR base = value_as_address (array_ptr)
2595     + ((low - ada_discrete_type_low_bound (TYPE_INDEX_TYPE (type0)))
2596        * TYPE_LENGTH (TYPE_TARGET_TYPE (type0)));
2597   struct type *index_type =
2598     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type0)),
2599                        low, high);
2600   struct type *slice_type =
2601     create_array_type (NULL, TYPE_TARGET_TYPE (type0), index_type);
2602
2603   return value_at_lazy (slice_type, base);
2604 }
2605
2606
2607 static struct value *
2608 ada_value_slice (struct value *array, int low, int high)
2609 {
2610   struct type *type = ada_check_typedef (value_type (array));
2611   struct type *index_type =
2612     create_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
2613   struct type *slice_type =
2614     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);
2615
2616   return value_cast (slice_type, value_slice (array, low, high - low + 1));
2617 }
2618
2619 /* If type is a record type in the form of a standard GNAT array
2620    descriptor, returns the number of dimensions for type.  If arr is a
2621    simple array, returns the number of "array of"s that prefix its
2622    type designation.  Otherwise, returns 0.  */
2623
2624 int
2625 ada_array_arity (struct type *type)
2626 {
2627   int arity;
2628
2629   if (type == NULL)
2630     return 0;
2631
2632   type = desc_base_type (type);
2633
2634   arity = 0;
2635   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2636     return desc_arity (desc_bounds_type (type));
2637   else
2638     while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2639       {
2640         arity += 1;
2641         type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2642       }
2643
2644   return arity;
2645 }
2646
2647 /* If TYPE is a record type in the form of a standard GNAT array
2648    descriptor or a simple array type, returns the element type for
2649    TYPE after indexing by NINDICES indices, or by all indices if
2650    NINDICES is -1.  Otherwise, returns NULL.  */
2651
2652 struct type *
2653 ada_array_element_type (struct type *type, int nindices)
2654 {
2655   type = desc_base_type (type);
2656
2657   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2658     {
2659       int k;
2660       struct type *p_array_type;
2661
2662       p_array_type = desc_data_target_type (type);
2663
2664       k = ada_array_arity (type);
2665       if (k == 0)
2666         return NULL;
2667
2668       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
2669       if (nindices >= 0 && k > nindices)
2670         k = nindices;
2671       while (k > 0 && p_array_type != NULL)
2672         {
2673           p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2674           k -= 1;
2675         }
2676       return p_array_type;
2677     }
2678   else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2679     {
2680       while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
2681         {
2682           type = TYPE_TARGET_TYPE (type);
2683           nindices -= 1;
2684         }
2685       return type;
2686     }
2687
2688   return NULL;
2689 }
2690
2691 /* The type of nth index in arrays of given type (n numbering from 1).
2692    Does not examine memory.  Throws an error if N is invalid or TYPE
2693    is not an array type.  NAME is the name of the Ada attribute being
2694    evaluated ('range, 'first, 'last, or 'length); it is used in building
2695    the error message.  */
2696
2697 static struct type *
2698 ada_index_type (struct type *type, int n, const char *name)
2699 {
2700   struct type *result_type;
2701
2702   type = desc_base_type (type);
2703
2704   if (n < 0 || n > ada_array_arity (type))
2705     error (_("invalid dimension number to '%s"), name);
2706
2707   if (ada_is_simple_array_type (type))
2708     {
2709       int i;
2710
2711       for (i = 1; i < n; i += 1)
2712         type = TYPE_TARGET_TYPE (type);
2713       result_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
2714       /* FIXME: The stabs type r(0,0);bound;bound in an array type
2715          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
2716          perhaps stabsread.c would make more sense.  */
2717       if (result_type && TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
2718         result_type = NULL;
2719     }
2720   else
2721     {
2722       result_type = desc_index_type (desc_bounds_type (type), n);
2723       if (result_type == NULL)
2724         error (_("attempt to take bound of something that is not an array"));
2725     }
2726
2727   return result_type;
2728 }
2729
2730 /* Given that arr is an array type, returns the lower bound of the
2731    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2732    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
2733    array-descriptor type.  It works for other arrays with bounds supplied
2734    by run-time quantities other than discriminants.  */
2735
2736 static LONGEST
2737 ada_array_bound_from_type (struct type * arr_type, int n, int which)
2738 {
2739   struct type *type, *elt_type, *index_type_desc, *index_type;
2740   int i;
2741
2742   gdb_assert (which == 0 || which == 1);
2743
2744   if (ada_is_constrained_packed_array_type (arr_type))
2745     arr_type = decode_constrained_packed_array_type (arr_type);
2746
2747   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2748     return (LONGEST) - which;
2749
2750   if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
2751     type = TYPE_TARGET_TYPE (arr_type);
2752   else
2753     type = arr_type;
2754
2755   elt_type = type;
2756   for (i = n; i > 1; i--)
2757     elt_type = TYPE_TARGET_TYPE (type);
2758
2759   index_type_desc = ada_find_parallel_type (type, "___XA");
2760   ada_fixup_array_indexes_type (index_type_desc);
2761   if (index_type_desc != NULL)
2762     index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, n - 1),
2763                                       NULL);
2764   else
2765     index_type = TYPE_INDEX_TYPE (elt_type);
2766
2767   return
2768     (LONGEST) (which == 0
2769                ? ada_discrete_type_low_bound (index_type)
2770                : ada_discrete_type_high_bound (index_type));
2771 }
2772
2773 /* Given that arr is an array value, returns the lower bound of the
2774    nth index (numbering from 1) if WHICH is 0, and the upper bound if
2775    WHICH is 1.  This routine will also work for arrays with bounds
2776    supplied by run-time quantities other than discriminants.  */
2777
2778 static LONGEST
2779 ada_array_bound (struct value *arr, int n, int which)
2780 {
2781   struct type *arr_type = value_type (arr);
2782
2783   if (ada_is_constrained_packed_array_type (arr_type))
2784     return ada_array_bound (decode_constrained_packed_array (arr), n, which);
2785   else if (ada_is_simple_array_type (arr_type))
2786     return ada_array_bound_from_type (arr_type, n, which);
2787   else
2788     return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
2789 }
2790
2791 /* Given that arr is an array value, returns the length of the
2792    nth index.  This routine will also work for arrays with bounds
2793    supplied by run-time quantities other than discriminants.
2794    Does not work for arrays indexed by enumeration types with representation
2795    clauses at the moment.  */
2796
2797 static LONGEST
2798 ada_array_length (struct value *arr, int n)
2799 {
2800   struct type *arr_type = ada_check_typedef (value_type (arr));
2801
2802   if (ada_is_constrained_packed_array_type (arr_type))
2803     return ada_array_length (decode_constrained_packed_array (arr), n);
2804
2805   if (ada_is_simple_array_type (arr_type))
2806     return (ada_array_bound_from_type (arr_type, n, 1)
2807             - ada_array_bound_from_type (arr_type, n, 0) + 1);
2808   else
2809     return (value_as_long (desc_one_bound (desc_bounds (arr), n, 1))
2810             - value_as_long (desc_one_bound (desc_bounds (arr), n, 0)) + 1);
2811 }
2812
2813 /* An empty array whose type is that of ARR_TYPE (an array type),
2814    with bounds LOW to LOW-1.  */
2815
2816 static struct value *
2817 empty_array (struct type *arr_type, int low)
2818 {
2819   struct type *arr_type0 = ada_check_typedef (arr_type);
2820   struct type *index_type =
2821     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type0)),
2822                        low, low - 1);
2823   struct type *elt_type = ada_array_element_type (arr_type0, 1);
2824
2825   return allocate_value (create_array_type (NULL, elt_type, index_type));
2826 }
2827 \f
2828
2829                                 /* Name resolution */
2830
2831 /* The "decoded" name for the user-definable Ada operator corresponding
2832    to OP.  */
2833
2834 static const char *
2835 ada_decoded_op_name (enum exp_opcode op)
2836 {
2837   int i;
2838
2839   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
2840     {
2841       if (ada_opname_table[i].op == op)
2842         return ada_opname_table[i].decoded;
2843     }
2844   error (_("Could not find operator name for opcode"));
2845 }
2846
2847
2848 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
2849    references (marked by OP_VAR_VALUE nodes in which the symbol has an
2850    undefined namespace) and converts operators that are
2851    user-defined into appropriate function calls.  If CONTEXT_TYPE is
2852    non-null, it provides a preferred result type [at the moment, only
2853    type void has any effect---causing procedures to be preferred over
2854    functions in calls].  A null CONTEXT_TYPE indicates that a non-void
2855    return type is preferred.  May change (expand) *EXP.  */
2856
2857 static void
2858 resolve (struct expression **expp, int void_context_p)
2859 {
2860   struct type *context_type = NULL;
2861   int pc = 0;
2862
2863   if (void_context_p)
2864     context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
2865
2866   resolve_subexp (expp, &pc, 1, context_type);
2867 }
2868
2869 /* Resolve the operator of the subexpression beginning at
2870    position *POS of *EXPP.  "Resolving" consists of replacing
2871    the symbols that have undefined namespaces in OP_VAR_VALUE nodes
2872    with their resolutions, replacing built-in operators with
2873    function calls to user-defined operators, where appropriate, and,
2874    when DEPROCEDURE_P is non-zero, converting function-valued variables
2875    into parameterless calls.  May expand *EXPP.  The CONTEXT_TYPE functions
2876    are as in ada_resolve, above.  */
2877
2878 static struct value *
2879 resolve_subexp (struct expression **expp, int *pos, int deprocedure_p,
2880                 struct type *context_type)
2881 {
2882   int pc = *pos;
2883   int i;
2884   struct expression *exp;       /* Convenience: == *expp.  */
2885   enum exp_opcode op = (*expp)->elts[pc].opcode;
2886   struct value **argvec;        /* Vector of operand types (alloca'ed).  */
2887   int nargs;                    /* Number of operands.  */
2888   int oplen;
2889
2890   argvec = NULL;
2891   nargs = 0;
2892   exp = *expp;
2893
2894   /* Pass one: resolve operands, saving their types and updating *pos,
2895      if needed.  */
2896   switch (op)
2897     {
2898     case OP_FUNCALL:
2899       if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
2900           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
2901         *pos += 7;
2902       else
2903         {
2904           *pos += 3;
2905           resolve_subexp (expp, pos, 0, NULL);
2906         }
2907       nargs = longest_to_int (exp->elts[pc + 1].longconst);
2908       break;
2909
2910     case UNOP_ADDR:
2911       *pos += 1;
2912       resolve_subexp (expp, pos, 0, NULL);
2913       break;
2914
2915     case UNOP_QUAL:
2916       *pos += 3;
2917       resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type));
2918       break;
2919
2920     case OP_ATR_MODULUS:
2921     case OP_ATR_SIZE:
2922     case OP_ATR_TAG:
2923     case OP_ATR_FIRST:
2924     case OP_ATR_LAST:
2925     case OP_ATR_LENGTH:
2926     case OP_ATR_POS:
2927     case OP_ATR_VAL:
2928     case OP_ATR_MIN:
2929     case OP_ATR_MAX:
2930     case TERNOP_IN_RANGE:
2931     case BINOP_IN_BOUNDS:
2932     case UNOP_IN_RANGE:
2933     case OP_AGGREGATE:
2934     case OP_OTHERS:
2935     case OP_CHOICES:
2936     case OP_POSITIONAL:
2937     case OP_DISCRETE_RANGE:
2938     case OP_NAME:
2939       ada_forward_operator_length (exp, pc, &oplen, &nargs);
2940       *pos += oplen;
2941       break;
2942
2943     case BINOP_ASSIGN:
2944       {
2945         struct value *arg1;
2946
2947         *pos += 1;
2948         arg1 = resolve_subexp (expp, pos, 0, NULL);
2949         if (arg1 == NULL)
2950           resolve_subexp (expp, pos, 1, NULL);
2951         else
2952           resolve_subexp (expp, pos, 1, value_type (arg1));
2953         break;
2954       }
2955
2956     case UNOP_CAST:
2957       *pos += 3;
2958       nargs = 1;
2959       break;
2960
2961     case BINOP_ADD:
2962     case BINOP_SUB:
2963     case BINOP_MUL:
2964     case BINOP_DIV:
2965     case BINOP_REM:
2966     case BINOP_MOD:
2967     case BINOP_EXP:
2968     case BINOP_CONCAT:
2969     case BINOP_LOGICAL_AND:
2970     case BINOP_LOGICAL_OR:
2971     case BINOP_BITWISE_AND:
2972     case BINOP_BITWISE_IOR:
2973     case BINOP_BITWISE_XOR:
2974
2975     case BINOP_EQUAL:
2976     case BINOP_NOTEQUAL:
2977     case BINOP_LESS:
2978     case BINOP_GTR:
2979     case BINOP_LEQ:
2980     case BINOP_GEQ:
2981
2982     case BINOP_REPEAT:
2983     case BINOP_SUBSCRIPT:
2984     case BINOP_COMMA:
2985       *pos += 1;
2986       nargs = 2;
2987       break;
2988
2989     case UNOP_NEG:
2990     case UNOP_PLUS:
2991     case UNOP_LOGICAL_NOT:
2992     case UNOP_ABS:
2993     case UNOP_IND:
2994       *pos += 1;
2995       nargs = 1;
2996       break;
2997
2998     case OP_LONG:
2999     case OP_DOUBLE:
3000     case OP_VAR_VALUE:
3001       *pos += 4;
3002       break;
3003
3004     case OP_TYPE:
3005     case OP_BOOL:
3006     case OP_LAST:
3007     case OP_INTERNALVAR:
3008       *pos += 3;
3009       break;
3010
3011     case UNOP_MEMVAL:
3012       *pos += 3;
3013       nargs = 1;
3014       break;
3015
3016     case OP_REGISTER:
3017       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3018       break;
3019
3020     case STRUCTOP_STRUCT:
3021       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3022       nargs = 1;
3023       break;
3024
3025     case TERNOP_SLICE:
3026       *pos += 1;
3027       nargs = 3;
3028       break;
3029
3030     case OP_STRING:
3031       break;
3032
3033     default:
3034       error (_("Unexpected operator during name resolution"));
3035     }
3036
3037   argvec = (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
3038   for (i = 0; i < nargs; i += 1)
3039     argvec[i] = resolve_subexp (expp, pos, 1, NULL);
3040   argvec[i] = NULL;
3041   exp = *expp;
3042
3043   /* Pass two: perform any resolution on principal operator.  */
3044   switch (op)
3045     {
3046     default:
3047       break;
3048
3049     case OP_VAR_VALUE:
3050       if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
3051         {
3052           struct ada_symbol_info *candidates;
3053           int n_candidates;
3054
3055           n_candidates =
3056             ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
3057                                     (exp->elts[pc + 2].symbol),
3058                                     exp->elts[pc + 1].block, VAR_DOMAIN,
3059                                     &candidates);
3060
3061           if (n_candidates > 1)
3062             {
3063               /* Types tend to get re-introduced locally, so if there
3064                  are any local symbols that are not types, first filter
3065                  out all types.  */
3066               int j;
3067               for (j = 0; j < n_candidates; j += 1)
3068                 switch (SYMBOL_CLASS (candidates[j].sym))
3069                   {
3070                   case LOC_REGISTER:
3071                   case LOC_ARG:
3072                   case LOC_REF_ARG:
3073                   case LOC_REGPARM_ADDR:
3074                   case LOC_LOCAL:
3075                   case LOC_COMPUTED:
3076                     goto FoundNonType;
3077                   default:
3078                     break;
3079                   }
3080             FoundNonType:
3081               if (j < n_candidates)
3082                 {
3083                   j = 0;
3084                   while (j < n_candidates)
3085                     {
3086                       if (SYMBOL_CLASS (candidates[j].sym) == LOC_TYPEDEF)
3087                         {
3088                           candidates[j] = candidates[n_candidates - 1];
3089                           n_candidates -= 1;
3090                         }
3091                       else
3092                         j += 1;
3093                     }
3094                 }
3095             }
3096
3097           if (n_candidates == 0)
3098             error (_("No definition found for %s"),
3099                    SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
3100           else if (n_candidates == 1)
3101             i = 0;
3102           else if (deprocedure_p
3103                    && !is_nonfunction (candidates, n_candidates))
3104             {
3105               i = ada_resolve_function
3106                 (candidates, n_candidates, NULL, 0,
3107                  SYMBOL_LINKAGE_NAME (exp->elts[pc + 2].symbol),
3108                  context_type);
3109               if (i < 0)
3110                 error (_("Could not find a match for %s"),
3111                        SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
3112             }
3113           else
3114             {
3115               printf_filtered (_("Multiple matches for %s\n"),
3116                                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
3117               user_select_syms (candidates, n_candidates, 1);
3118               i = 0;
3119             }
3120
3121           exp->elts[pc + 1].block = candidates[i].block;
3122           exp->elts[pc + 2].symbol = candidates[i].sym;
3123           if (innermost_block == NULL
3124               || contained_in (candidates[i].block, innermost_block))
3125             innermost_block = candidates[i].block;
3126         }
3127
3128       if (deprocedure_p
3129           && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
3130               == TYPE_CODE_FUNC))
3131         {
3132           replace_operator_with_call (expp, pc, 0, 0,
3133                                       exp->elts[pc + 2].symbol,
3134                                       exp->elts[pc + 1].block);
3135           exp = *expp;
3136         }
3137       break;
3138
3139     case OP_FUNCALL:
3140       {
3141         if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3142             && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3143           {
3144             struct ada_symbol_info *candidates;
3145             int n_candidates;
3146
3147             n_candidates =
3148               ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
3149                                       (exp->elts[pc + 5].symbol),
3150                                       exp->elts[pc + 4].block, VAR_DOMAIN,
3151                                       &candidates);
3152             if (n_candidates == 1)
3153               i = 0;
3154             else
3155               {
3156                 i = ada_resolve_function
3157                   (candidates, n_candidates,
3158                    argvec, nargs,
3159                    SYMBOL_LINKAGE_NAME (exp->elts[pc + 5].symbol),
3160                    context_type);
3161                 if (i < 0)
3162                   error (_("Could not find a match for %s"),
3163                          SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
3164               }
3165
3166             exp->elts[pc + 4].block = candidates[i].block;
3167             exp->elts[pc + 5].symbol = candidates[i].sym;
3168             if (innermost_block == NULL
3169                 || contained_in (candidates[i].block, innermost_block))
3170               innermost_block = candidates[i].block;
3171           }
3172       }
3173       break;
3174     case BINOP_ADD:
3175     case BINOP_SUB:
3176     case BINOP_MUL:
3177     case BINOP_DIV:
3178     case BINOP_REM:
3179     case BINOP_MOD:
3180     case BINOP_CONCAT:
3181     case BINOP_BITWISE_AND:
3182     case BINOP_BITWISE_IOR:
3183     case BINOP_BITWISE_XOR:
3184     case BINOP_EQUAL:
3185     case BINOP_NOTEQUAL:
3186     case BINOP_LESS:
3187     case BINOP_GTR:
3188     case BINOP_LEQ:
3189     case BINOP_GEQ:
3190     case BINOP_EXP:
3191     case UNOP_NEG:
3192     case UNOP_PLUS:
3193     case UNOP_LOGICAL_NOT:
3194     case UNOP_ABS:
3195       if (possible_user_operator_p (op, argvec))
3196         {
3197           struct ada_symbol_info *candidates;
3198           int n_candidates;
3199
3200           n_candidates =
3201             ada_lookup_symbol_list (ada_encode (ada_decoded_op_name (op)),
3202                                     (struct block *) NULL, VAR_DOMAIN,
3203                                     &candidates);
3204           i = ada_resolve_function (candidates, n_candidates, argvec, nargs,
3205                                     ada_decoded_op_name (op), NULL);
3206           if (i < 0)
3207             break;
3208
3209           replace_operator_with_call (expp, pc, nargs, 1,
3210                                       candidates[i].sym, candidates[i].block);
3211           exp = *expp;
3212         }
3213       break;
3214
3215     case OP_TYPE:
3216     case OP_REGISTER:
3217       return NULL;
3218     }
3219
3220   *pos = pc;
3221   return evaluate_subexp_type (exp, pos);
3222 }
3223
3224 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  If
3225    MAY_DEREF is non-zero, the formal may be a pointer and the actual
3226    a non-pointer.  */
3227 /* The term "match" here is rather loose.  The match is heuristic and
3228    liberal.  */
3229
3230 static int
3231 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
3232 {
3233   ftype = ada_check_typedef (ftype);
3234   atype = ada_check_typedef (atype);
3235
3236   if (TYPE_CODE (ftype) == TYPE_CODE_REF)
3237     ftype = TYPE_TARGET_TYPE (ftype);
3238   if (TYPE_CODE (atype) == TYPE_CODE_REF)
3239     atype = TYPE_TARGET_TYPE (atype);
3240
3241   switch (TYPE_CODE (ftype))
3242     {
3243     default:
3244       return TYPE_CODE (ftype) == TYPE_CODE (atype);
3245     case TYPE_CODE_PTR:
3246       if (TYPE_CODE (atype) == TYPE_CODE_PTR)
3247         return ada_type_match (TYPE_TARGET_TYPE (ftype),
3248                                TYPE_TARGET_TYPE (atype), 0);
3249       else
3250         return (may_deref
3251                 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
3252     case TYPE_CODE_INT:
3253     case TYPE_CODE_ENUM:
3254     case TYPE_CODE_RANGE:
3255       switch (TYPE_CODE (atype))
3256         {
3257         case TYPE_CODE_INT:
3258         case TYPE_CODE_ENUM:
3259         case TYPE_CODE_RANGE:
3260           return 1;
3261         default:
3262           return 0;
3263         }
3264
3265     case TYPE_CODE_ARRAY:
3266       return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3267               || ada_is_array_descriptor_type (atype));
3268
3269     case TYPE_CODE_STRUCT:
3270       if (ada_is_array_descriptor_type (ftype))
3271         return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3272                 || ada_is_array_descriptor_type (atype));
3273       else
3274         return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
3275                 && !ada_is_array_descriptor_type (atype));
3276
3277     case TYPE_CODE_UNION:
3278     case TYPE_CODE_FLT:
3279       return (TYPE_CODE (atype) == TYPE_CODE (ftype));
3280     }
3281 }
3282
3283 /* Return non-zero if the formals of FUNC "sufficiently match" the
3284    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
3285    may also be an enumeral, in which case it is treated as a 0-
3286    argument function.  */
3287
3288 static int
3289 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3290 {
3291   int i;
3292   struct type *func_type = SYMBOL_TYPE (func);
3293
3294   if (SYMBOL_CLASS (func) == LOC_CONST
3295       && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
3296     return (n_actuals == 0);
3297   else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
3298     return 0;
3299
3300   if (TYPE_NFIELDS (func_type) != n_actuals)
3301     return 0;
3302
3303   for (i = 0; i < n_actuals; i += 1)
3304     {
3305       if (actuals[i] == NULL)
3306         return 0;
3307       else
3308         {
3309           struct type *ftype = ada_check_typedef (TYPE_FIELD_TYPE (func_type,
3310                                                                    i));
3311           struct type *atype = ada_check_typedef (value_type (actuals[i]));
3312
3313           if (!ada_type_match (ftype, atype, 1))
3314             return 0;
3315         }
3316     }
3317   return 1;
3318 }
3319
3320 /* False iff function type FUNC_TYPE definitely does not produce a value
3321    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
3322    FUNC_TYPE is not a valid function type with a non-null return type
3323    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
3324
3325 static int
3326 return_match (struct type *func_type, struct type *context_type)
3327 {
3328   struct type *return_type;
3329
3330   if (func_type == NULL)
3331     return 1;
3332
3333   if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
3334     return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3335   else
3336     return_type = get_base_type (func_type);
3337   if (return_type == NULL)
3338     return 1;
3339
3340   context_type = get_base_type (context_type);
3341
3342   if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
3343     return context_type == NULL || return_type == context_type;
3344   else if (context_type == NULL)
3345     return TYPE_CODE (return_type) != TYPE_CODE_VOID;
3346   else
3347     return TYPE_CODE (return_type) == TYPE_CODE (context_type);
3348 }
3349
3350
3351 /* Returns the index in SYMS[0..NSYMS-1] that contains  the symbol for the
3352    function (if any) that matches the types of the NARGS arguments in
3353    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
3354    that returns that type, then eliminate matches that don't.  If
3355    CONTEXT_TYPE is void and there is at least one match that does not
3356    return void, eliminate all matches that do.
3357
3358    Asks the user if there is more than one match remaining.  Returns -1
3359    if there is no such symbol or none is selected.  NAME is used
3360    solely for messages.  May re-arrange and modify SYMS in
3361    the process; the index returned is for the modified vector.  */
3362
3363 static int
3364 ada_resolve_function (struct ada_symbol_info syms[],
3365                       int nsyms, struct value **args, int nargs,
3366                       const char *name, struct type *context_type)
3367 {
3368   int fallback;
3369   int k;
3370   int m;                        /* Number of hits */
3371
3372   m = 0;
3373   /* In the first pass of the loop, we only accept functions matching
3374      context_type.  If none are found, we add a second pass of the loop
3375      where every function is accepted.  */
3376   for (fallback = 0; m == 0 && fallback < 2; fallback++)
3377     {
3378       for (k = 0; k < nsyms; k += 1)
3379         {
3380           struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].sym));
3381
3382           if (ada_args_match (syms[k].sym, args, nargs)
3383               && (fallback || return_match (type, context_type)))
3384             {
3385               syms[m] = syms[k];
3386               m += 1;
3387             }
3388         }
3389     }
3390
3391   if (m == 0)
3392     return -1;
3393   else if (m > 1)
3394     {
3395       printf_filtered (_("Multiple matches for %s\n"), name);
3396       user_select_syms (syms, m, 1);
3397       return 0;
3398     }
3399   return 0;
3400 }
3401
3402 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3403    in a listing of choices during disambiguation (see sort_choices, below).
3404    The idea is that overloadings of a subprogram name from the
3405    same package should sort in their source order.  We settle for ordering
3406    such symbols by their trailing number (__N  or $N).  */
3407
3408 static int
3409 encoded_ordered_before (char *N0, char *N1)
3410 {
3411   if (N1 == NULL)
3412     return 0;
3413   else if (N0 == NULL)
3414     return 1;
3415   else
3416     {
3417       int k0, k1;
3418
3419       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3420         ;
3421       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3422         ;
3423       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3424           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3425         {
3426           int n0, n1;
3427
3428           n0 = k0;
3429           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3430             n0 -= 1;
3431           n1 = k1;
3432           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3433             n1 -= 1;
3434           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3435             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3436         }
3437       return (strcmp (N0, N1) < 0);
3438     }
3439 }
3440
3441 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3442    encoded names.  */
3443
3444 static void
3445 sort_choices (struct ada_symbol_info syms[], int nsyms)
3446 {
3447   int i;
3448
3449   for (i = 1; i < nsyms; i += 1)
3450     {
3451       struct ada_symbol_info sym = syms[i];
3452       int j;
3453
3454       for (j = i - 1; j >= 0; j -= 1)
3455         {
3456           if (encoded_ordered_before (SYMBOL_LINKAGE_NAME (syms[j].sym),
3457                                       SYMBOL_LINKAGE_NAME (sym.sym)))
3458             break;
3459           syms[j + 1] = syms[j];
3460         }
3461       syms[j + 1] = sym;
3462     }
3463 }
3464
3465 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0 
3466    by asking the user (if necessary), returning the number selected, 
3467    and setting the first elements of SYMS items.  Error if no symbols
3468    selected.  */
3469
3470 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3471    to be re-integrated one of these days.  */
3472
3473 int
3474 user_select_syms (struct ada_symbol_info *syms, int nsyms, int max_results)
3475 {
3476   int i;
3477   int *chosen = (int *) alloca (sizeof (int) * nsyms);
3478   int n_chosen;
3479   int first_choice = (max_results == 1) ? 1 : 2;
3480   const char *select_mode = multiple_symbols_select_mode ();
3481
3482   if (max_results < 1)
3483     error (_("Request to select 0 symbols!"));
3484   if (nsyms <= 1)
3485     return nsyms;
3486
3487   if (select_mode == multiple_symbols_cancel)
3488     error (_("\
3489 canceled because the command is ambiguous\n\
3490 See set/show multiple-symbol."));
3491   
3492   /* If select_mode is "all", then return all possible symbols.
3493      Only do that if more than one symbol can be selected, of course.
3494      Otherwise, display the menu as usual.  */
3495   if (select_mode == multiple_symbols_all && max_results > 1)
3496     return nsyms;
3497
3498   printf_unfiltered (_("[0] cancel\n"));
3499   if (max_results > 1)
3500     printf_unfiltered (_("[1] all\n"));
3501
3502   sort_choices (syms, nsyms);
3503
3504   for (i = 0; i < nsyms; i += 1)
3505     {
3506       if (syms[i].sym == NULL)
3507         continue;
3508
3509       if (SYMBOL_CLASS (syms[i].sym) == LOC_BLOCK)
3510         {
3511           struct symtab_and_line sal =
3512             find_function_start_sal (syms[i].sym, 1);
3513
3514           if (sal.symtab == NULL)
3515             printf_unfiltered (_("[%d] %s at <no source file available>:%d\n"),
3516                                i + first_choice,
3517                                SYMBOL_PRINT_NAME (syms[i].sym),
3518                                sal.line);
3519           else
3520             printf_unfiltered (_("[%d] %s at %s:%d\n"), i + first_choice,
3521                                SYMBOL_PRINT_NAME (syms[i].sym),
3522                                sal.symtab->filename, sal.line);
3523           continue;
3524         }
3525       else
3526         {
3527           int is_enumeral =
3528             (SYMBOL_CLASS (syms[i].sym) == LOC_CONST
3529              && SYMBOL_TYPE (syms[i].sym) != NULL
3530              && TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) == TYPE_CODE_ENUM);
3531           struct symtab *symtab = syms[i].sym->symtab;
3532
3533           if (SYMBOL_LINE (syms[i].sym) != 0 && symtab != NULL)
3534             printf_unfiltered (_("[%d] %s at %s:%d\n"),
3535                                i + first_choice,
3536                                SYMBOL_PRINT_NAME (syms[i].sym),
3537                                symtab->filename, SYMBOL_LINE (syms[i].sym));
3538           else if (is_enumeral
3539                    && TYPE_NAME (SYMBOL_TYPE (syms[i].sym)) != NULL)
3540             {
3541               printf_unfiltered (("[%d] "), i + first_choice);
3542               ada_print_type (SYMBOL_TYPE (syms[i].sym), NULL,
3543                               gdb_stdout, -1, 0);
3544               printf_unfiltered (_("'(%s) (enumeral)\n"),
3545                                  SYMBOL_PRINT_NAME (syms[i].sym));
3546             }
3547           else if (symtab != NULL)
3548             printf_unfiltered (is_enumeral
3549                                ? _("[%d] %s in %s (enumeral)\n")
3550                                : _("[%d] %s at %s:?\n"),
3551                                i + first_choice,
3552                                SYMBOL_PRINT_NAME (syms[i].sym),
3553                                symtab->filename);
3554           else
3555             printf_unfiltered (is_enumeral
3556                                ? _("[%d] %s (enumeral)\n")
3557                                : _("[%d] %s at ?\n"),
3558                                i + first_choice,
3559                                SYMBOL_PRINT_NAME (syms[i].sym));
3560         }
3561     }
3562
3563   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3564                              "overload-choice");
3565
3566   for (i = 0; i < n_chosen; i += 1)
3567     syms[i] = syms[chosen[i]];
3568
3569   return n_chosen;
3570 }
3571
3572 /* Read and validate a set of numeric choices from the user in the
3573    range 0 .. N_CHOICES-1.  Place the results in increasing
3574    order in CHOICES[0 .. N-1], and return N.
3575
3576    The user types choices as a sequence of numbers on one line
3577    separated by blanks, encoding them as follows:
3578
3579      + A choice of 0 means to cancel the selection, throwing an error.
3580      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3581      + The user chooses k by typing k+IS_ALL_CHOICE+1.
3582
3583    The user is not allowed to choose more than MAX_RESULTS values.
3584
3585    ANNOTATION_SUFFIX, if present, is used to annotate the input
3586    prompts (for use with the -f switch).  */
3587
3588 int
3589 get_selections (int *choices, int n_choices, int max_results,
3590                 int is_all_choice, char *annotation_suffix)
3591 {
3592   char *args;
3593   char *prompt;
3594   int n_chosen;
3595   int first_choice = is_all_choice ? 2 : 1;
3596
3597   prompt = getenv ("PS2");
3598   if (prompt == NULL)
3599     prompt = "> ";
3600
3601   args = command_line_input (prompt, 0, annotation_suffix);
3602
3603   if (args == NULL)
3604     error_no_arg (_("one or more choice numbers"));
3605
3606   n_chosen = 0;
3607
3608   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3609      order, as given in args.  Choices are validated.  */
3610   while (1)
3611     {
3612       char *args2;
3613       int choice, j;
3614
3615       args = skip_spaces (args);
3616       if (*args == '\0' && n_chosen == 0)
3617         error_no_arg (_("one or more choice numbers"));
3618       else if (*args == '\0')
3619         break;
3620
3621       choice = strtol (args, &args2, 10);
3622       if (args == args2 || choice < 0
3623           || choice > n_choices + first_choice - 1)
3624         error (_("Argument must be choice number"));
3625       args = args2;
3626
3627       if (choice == 0)
3628         error (_("cancelled"));
3629
3630       if (choice < first_choice)
3631         {
3632           n_chosen = n_choices;
3633           for (j = 0; j < n_choices; j += 1)
3634             choices[j] = j;
3635           break;
3636         }
3637       choice -= first_choice;
3638
3639       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3640         {
3641         }
3642
3643       if (j < 0 || choice != choices[j])
3644         {
3645           int k;
3646
3647           for (k = n_chosen - 1; k > j; k -= 1)
3648             choices[k + 1] = choices[k];
3649           choices[j + 1] = choice;
3650           n_chosen += 1;
3651         }
3652     }
3653
3654   if (n_chosen > max_results)
3655     error (_("Select no more than %d of the above"), max_results);
3656
3657   return n_chosen;
3658 }
3659
3660 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
3661    on the function identified by SYM and BLOCK, and taking NARGS
3662    arguments.  Update *EXPP as needed to hold more space.  */
3663
3664 static void
3665 replace_operator_with_call (struct expression **expp, int pc, int nargs,
3666                             int oplen, struct symbol *sym,
3667                             struct block *block)
3668 {
3669   /* A new expression, with 6 more elements (3 for funcall, 4 for function
3670      symbol, -oplen for operator being replaced).  */
3671   struct expression *newexp = (struct expression *)
3672     xzalloc (sizeof (struct expression)
3673              + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
3674   struct expression *exp = *expp;
3675
3676   newexp->nelts = exp->nelts + 7 - oplen;
3677   newexp->language_defn = exp->language_defn;
3678   newexp->gdbarch = exp->gdbarch;
3679   memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
3680   memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
3681           EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
3682
3683   newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
3684   newexp->elts[pc + 1].longconst = (LONGEST) nargs;
3685
3686   newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
3687   newexp->elts[pc + 4].block = block;
3688   newexp->elts[pc + 5].symbol = sym;
3689
3690   *expp = newexp;
3691   xfree (exp);
3692 }
3693
3694 /* Type-class predicates */
3695
3696 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
3697    or FLOAT).  */
3698
3699 static int
3700 numeric_type_p (struct type *type)
3701 {
3702   if (type == NULL)
3703     return 0;
3704   else
3705     {
3706       switch (TYPE_CODE (type))
3707         {
3708         case TYPE_CODE_INT:
3709         case TYPE_CODE_FLT:
3710           return 1;
3711         case TYPE_CODE_RANGE:
3712           return (type == TYPE_TARGET_TYPE (type)
3713                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
3714         default:
3715           return 0;
3716         }
3717     }
3718 }
3719
3720 /* True iff TYPE is integral (an INT or RANGE of INTs).  */
3721
3722 static int
3723 integer_type_p (struct type *type)
3724 {
3725   if (type == NULL)
3726     return 0;
3727   else
3728     {
3729       switch (TYPE_CODE (type))
3730         {
3731         case TYPE_CODE_INT:
3732           return 1;
3733         case TYPE_CODE_RANGE:
3734           return (type == TYPE_TARGET_TYPE (type)
3735                   || integer_type_p (TYPE_TARGET_TYPE (type)));
3736         default:
3737           return 0;
3738         }
3739     }
3740 }
3741
3742 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */
3743
3744 static int
3745 scalar_type_p (struct type *type)
3746 {
3747   if (type == NULL)
3748     return 0;
3749   else
3750     {
3751       switch (TYPE_CODE (type))
3752         {
3753         case TYPE_CODE_INT:
3754         case TYPE_CODE_RANGE:
3755         case TYPE_CODE_ENUM:
3756         case TYPE_CODE_FLT:
3757           return 1;
3758         default:
3759           return 0;
3760         }
3761     }
3762 }
3763
3764 /* True iff TYPE is discrete (INT, RANGE, ENUM).  */
3765
3766 static int
3767 discrete_type_p (struct type *type)
3768 {
3769   if (type == NULL)
3770     return 0;
3771   else
3772     {
3773       switch (TYPE_CODE (type))
3774         {
3775         case TYPE_CODE_INT:
3776         case TYPE_CODE_RANGE:
3777         case TYPE_CODE_ENUM:
3778         case TYPE_CODE_BOOL:
3779           return 1;
3780         default:
3781           return 0;
3782         }
3783     }
3784 }
3785
3786 /* Returns non-zero if OP with operands in the vector ARGS could be
3787    a user-defined function.  Errs on the side of pre-defined operators
3788    (i.e., result 0).  */
3789
3790 static int
3791 possible_user_operator_p (enum exp_opcode op, struct value *args[])
3792 {
3793   struct type *type0 =
3794     (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
3795   struct type *type1 =
3796     (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
3797
3798   if (type0 == NULL)
3799     return 0;
3800
3801   switch (op)
3802     {
3803     default:
3804       return 0;
3805
3806     case BINOP_ADD:
3807     case BINOP_SUB:
3808     case BINOP_MUL:
3809     case BINOP_DIV:
3810       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
3811
3812     case BINOP_REM:
3813     case BINOP_MOD:
3814     case BINOP_BITWISE_AND:
3815     case BINOP_BITWISE_IOR:
3816     case BINOP_BITWISE_XOR:
3817       return (!(integer_type_p (type0) && integer_type_p (type1)));
3818
3819     case BINOP_EQUAL:
3820     case BINOP_NOTEQUAL:
3821     case BINOP_LESS:
3822     case BINOP_GTR:
3823     case BINOP_LEQ:
3824     case BINOP_GEQ:
3825       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
3826
3827     case BINOP_CONCAT:
3828       return !ada_is_array_type (type0) || !ada_is_array_type (type1);
3829
3830     case BINOP_EXP:
3831       return (!(numeric_type_p (type0) && integer_type_p (type1)));
3832
3833     case UNOP_NEG:
3834     case UNOP_PLUS:
3835     case UNOP_LOGICAL_NOT:
3836     case UNOP_ABS:
3837       return (!numeric_type_p (type0));
3838
3839     }
3840 }
3841 \f
3842                                 /* Renaming */
3843
3844 /* NOTES: 
3845
3846    1. In the following, we assume that a renaming type's name may
3847       have an ___XD suffix.  It would be nice if this went away at some
3848       point.
3849    2. We handle both the (old) purely type-based representation of 
3850       renamings and the (new) variable-based encoding.  At some point,
3851       it is devoutly to be hoped that the former goes away 
3852       (FIXME: hilfinger-2007-07-09).
3853    3. Subprogram renamings are not implemented, although the XRS
3854       suffix is recognized (FIXME: hilfinger-2007-07-09).  */
3855
3856 /* If SYM encodes a renaming, 
3857
3858        <renaming> renames <renamed entity>,
3859
3860    sets *LEN to the length of the renamed entity's name,
3861    *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
3862    the string describing the subcomponent selected from the renamed
3863    entity.  Returns ADA_NOT_RENAMING if SYM does not encode a renaming
3864    (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
3865    are undefined).  Otherwise, returns a value indicating the category
3866    of entity renamed: an object (ADA_OBJECT_RENAMING), exception
3867    (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
3868    subprogram (ADA_SUBPROGRAM_RENAMING).  Does no allocation; the
3869    strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
3870    deallocated.  The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
3871    may be NULL, in which case they are not assigned.
3872
3873    [Currently, however, GCC does not generate subprogram renamings.]  */
3874
3875 enum ada_renaming_category
3876 ada_parse_renaming (struct symbol *sym,
3877                     const char **renamed_entity, int *len, 
3878                     const char **renaming_expr)
3879 {
3880   enum ada_renaming_category kind;
3881   const char *info;
3882   const char *suffix;
3883
3884   if (sym == NULL)
3885     return ADA_NOT_RENAMING;
3886   switch (SYMBOL_CLASS (sym)) 
3887     {
3888     default:
3889       return ADA_NOT_RENAMING;
3890     case LOC_TYPEDEF:
3891       return parse_old_style_renaming (SYMBOL_TYPE (sym), 
3892                                        renamed_entity, len, renaming_expr);
3893     case LOC_LOCAL:
3894     case LOC_STATIC:
3895     case LOC_COMPUTED:
3896     case LOC_OPTIMIZED_OUT:
3897       info = strstr (SYMBOL_LINKAGE_NAME (sym), "___XR");
3898       if (info == NULL)
3899         return ADA_NOT_RENAMING;
3900       switch (info[5])
3901         {
3902         case '_':
3903           kind = ADA_OBJECT_RENAMING;
3904           info += 6;
3905           break;
3906         case 'E':
3907           kind = ADA_EXCEPTION_RENAMING;
3908           info += 7;
3909           break;
3910         case 'P':
3911           kind = ADA_PACKAGE_RENAMING;
3912           info += 7;
3913           break;
3914         case 'S':
3915           kind = ADA_SUBPROGRAM_RENAMING;
3916           info += 7;
3917           break;
3918         default:
3919           return ADA_NOT_RENAMING;
3920         }
3921     }
3922
3923   if (renamed_entity != NULL)
3924     *renamed_entity = info;
3925   suffix = strstr (info, "___XE");
3926   if (suffix == NULL || suffix == info)
3927     return ADA_NOT_RENAMING;
3928   if (len != NULL)
3929     *len = strlen (info) - strlen (suffix);
3930   suffix += 5;
3931   if (renaming_expr != NULL)
3932     *renaming_expr = suffix;
3933   return kind;
3934 }
3935
3936 /* Assuming TYPE encodes a renaming according to the old encoding in
3937    exp_dbug.ads, returns details of that renaming in *RENAMED_ENTITY,
3938    *LEN, and *RENAMING_EXPR, as for ada_parse_renaming, above.  Returns
3939    ADA_NOT_RENAMING otherwise.  */
3940 static enum ada_renaming_category
3941 parse_old_style_renaming (struct type *type,
3942                           const char **renamed_entity, int *len, 
3943                           const char **renaming_expr)
3944 {
3945   enum ada_renaming_category kind;
3946   const char *name;
3947   const char *info;
3948   const char *suffix;
3949
3950   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM 
3951       || TYPE_NFIELDS (type) != 1)
3952     return ADA_NOT_RENAMING;
3953
3954   name = type_name_no_tag (type);
3955   if (name == NULL)
3956     return ADA_NOT_RENAMING;
3957   
3958   name = strstr (name, "___XR");
3959   if (name == NULL)
3960     return ADA_NOT_RENAMING;
3961   switch (name[5])
3962     {
3963     case '\0':
3964     case '_':
3965       kind = ADA_OBJECT_RENAMING;
3966       break;
3967     case 'E':
3968       kind = ADA_EXCEPTION_RENAMING;
3969       break;
3970     case 'P':
3971       kind = ADA_PACKAGE_RENAMING;
3972       break;
3973     case 'S':
3974       kind = ADA_SUBPROGRAM_RENAMING;
3975       break;
3976     default:
3977       return ADA_NOT_RENAMING;
3978     }
3979
3980   info = TYPE_FIELD_NAME (type, 0);
3981   if (info == NULL)
3982     return ADA_NOT_RENAMING;
3983   if (renamed_entity != NULL)
3984     *renamed_entity = info;
3985   suffix = strstr (info, "___XE");
3986   if (renaming_expr != NULL)
3987     *renaming_expr = suffix + 5;
3988   if (suffix == NULL || suffix == info)
3989     return ADA_NOT_RENAMING;
3990   if (len != NULL)
3991     *len = suffix - info;
3992   return kind;
3993 }  
3994
3995 \f
3996
3997                                 /* Evaluation: Function Calls */
3998
3999 /* Return an lvalue containing the value VAL.  This is the identity on
4000    lvalues, and otherwise has the side-effect of allocating memory
4001    in the inferior where a copy of the value contents is copied.  */
4002
4003 static struct value *
4004 ensure_lval (struct value *val)
4005 {
4006   if (VALUE_LVAL (val) == not_lval
4007       || VALUE_LVAL (val) == lval_internalvar)
4008     {
4009       int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4010       const CORE_ADDR addr =
4011         value_as_long (value_allocate_space_in_inferior (len));
4012
4013       set_value_address (val, addr);
4014       VALUE_LVAL (val) = lval_memory;
4015       write_memory (addr, value_contents (val), len);
4016     }
4017
4018   return val;
4019 }
4020
4021 /* Return the value ACTUAL, converted to be an appropriate value for a
4022    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
4023    allocating any necessary descriptors (fat pointers), or copies of
4024    values not residing in memory, updating it as needed.  */
4025
4026 struct value *
4027 ada_convert_actual (struct value *actual, struct type *formal_type0)
4028 {
4029   struct type *actual_type = ada_check_typedef (value_type (actual));
4030   struct type *formal_type = ada_check_typedef (formal_type0);
4031   struct type *formal_target =
4032     TYPE_CODE (formal_type) == TYPE_CODE_PTR
4033     ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4034   struct type *actual_target =
4035     TYPE_CODE (actual_type) == TYPE_CODE_PTR
4036     ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4037
4038   if (ada_is_array_descriptor_type (formal_target)
4039       && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
4040     return make_array_descriptor (formal_type, actual);
4041   else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR
4042            || TYPE_CODE (formal_type) == TYPE_CODE_REF)
4043     {
4044       struct value *result;
4045
4046       if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
4047           && ada_is_array_descriptor_type (actual_target))
4048         result = desc_data (actual);
4049       else if (TYPE_CODE (actual_type) != TYPE_CODE_PTR)
4050         {
4051           if (VALUE_LVAL (actual) != lval_memory)
4052             {
4053               struct value *val;
4054
4055               actual_type = ada_check_typedef (value_type (actual));
4056               val = allocate_value (actual_type);
4057               memcpy ((char *) value_contents_raw (val),
4058                       (char *) value_contents (actual),
4059                       TYPE_LENGTH (actual_type));
4060               actual = ensure_lval (val);
4061             }
4062           result = value_addr (actual);
4063         }
4064       else
4065         return actual;
4066       return value_cast_pointers (formal_type, result);
4067     }
4068   else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
4069     return ada_value_ind (actual);
4070
4071   return actual;
4072 }
4073
4074 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4075    type TYPE.  This is usually an inefficient no-op except on some targets
4076    (such as AVR) where the representation of a pointer and an address
4077    differs.  */
4078
4079 static CORE_ADDR
4080 value_pointer (struct value *value, struct type *type)
4081 {
4082   struct gdbarch *gdbarch = get_type_arch (type);
4083   unsigned len = TYPE_LENGTH (type);
4084   gdb_byte *buf = alloca (len);
4085   CORE_ADDR addr;
4086
4087   addr = value_address (value);
4088   gdbarch_address_to_pointer (gdbarch, type, buf, addr);
4089   addr = extract_unsigned_integer (buf, len, gdbarch_byte_order (gdbarch));
4090   return addr;
4091 }
4092
4093
4094 /* Push a descriptor of type TYPE for array value ARR on the stack at
4095    *SP, updating *SP to reflect the new descriptor.  Return either
4096    an lvalue representing the new descriptor, or (if TYPE is a pointer-
4097    to-descriptor type rather than a descriptor type), a struct value *
4098    representing a pointer to this descriptor.  */
4099
4100 static struct value *
4101 make_array_descriptor (struct type *type, struct value *arr)
4102 {
4103   struct type *bounds_type = desc_bounds_type (type);
4104   struct type *desc_type = desc_base_type (type);
4105   struct value *descriptor = allocate_value (desc_type);
4106   struct value *bounds = allocate_value (bounds_type);
4107   int i;
4108
4109   for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4110        i > 0; i -= 1)
4111     {
4112       modify_field (value_type (bounds), value_contents_writeable (bounds),
4113                     ada_array_bound (arr, i, 0),
4114                     desc_bound_bitpos (bounds_type, i, 0),
4115                     desc_bound_bitsize (bounds_type, i, 0));
4116       modify_field (value_type (bounds), value_contents_writeable (bounds),
4117                     ada_array_bound (arr, i, 1),
4118                     desc_bound_bitpos (bounds_type, i, 1),
4119                     desc_bound_bitsize (bounds_type, i, 1));
4120     }
4121
4122   bounds = ensure_lval (bounds);
4123
4124   modify_field (value_type (descriptor),
4125                 value_contents_writeable (descriptor),
4126                 value_pointer (ensure_lval (arr),
4127                                TYPE_FIELD_TYPE (desc_type, 0)),
4128                 fat_pntr_data_bitpos (desc_type),
4129                 fat_pntr_data_bitsize (desc_type));
4130
4131   modify_field (value_type (descriptor),
4132                 value_contents_writeable (descriptor),
4133                 value_pointer (bounds,
4134                                TYPE_FIELD_TYPE (desc_type, 1)),
4135                 fat_pntr_bounds_bitpos (desc_type),
4136                 fat_pntr_bounds_bitsize (desc_type));
4137
4138   descriptor = ensure_lval (descriptor);
4139
4140   if (TYPE_CODE (type) == TYPE_CODE_PTR)
4141     return value_addr (descriptor);
4142   else
4143     return descriptor;
4144 }
4145 \f
4146 /* Dummy definitions for an experimental caching module that is not
4147  * used in the public sources.  */
4148
4149 static int
4150 lookup_cached_symbol (const char *name, domain_enum namespace,
4151                       struct symbol **sym, struct block **block)
4152 {
4153   return 0;
4154 }
4155
4156 static void
4157 cache_symbol (const char *name, domain_enum namespace, struct symbol *sym,
4158               struct block *block)
4159 {
4160 }
4161 \f
4162                                 /* Symbol Lookup */
4163
4164 /* Return nonzero if wild matching should be used when searching for
4165    all symbols matching LOOKUP_NAME.
4166
4167    LOOKUP_NAME is expected to be a symbol name after transformation
4168    for Ada lookups (see ada_name_for_lookup).  */
4169
4170 static int
4171 should_use_wild_match (const char *lookup_name)
4172 {
4173   return (strstr (lookup_name, "__") == NULL);
4174 }
4175
4176 /* Return the result of a standard (literal, C-like) lookup of NAME in
4177    given DOMAIN, visible from lexical block BLOCK.  */
4178
4179 static struct symbol *
4180 standard_lookup (const char *name, const struct block *block,
4181                  domain_enum domain)
4182 {
4183   struct symbol *sym;
4184
4185   if (lookup_cached_symbol (name, domain, &sym, NULL))
4186     return sym;
4187   sym = lookup_symbol_in_language (name, block, domain, language_c, 0);
4188   cache_symbol (name, domain, sym, block_found);
4189   return sym;
4190 }
4191
4192
4193 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4194    in the symbol fields of SYMS[0..N-1].  We treat enumerals as functions, 
4195    since they contend in overloading in the same way.  */
4196 static int
4197 is_nonfunction (struct ada_symbol_info syms[], int n)
4198 {
4199   int i;
4200
4201   for (i = 0; i < n; i += 1)
4202     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_FUNC
4203         && (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM
4204             || SYMBOL_CLASS (syms[i].sym) != LOC_CONST))
4205       return 1;
4206
4207   return 0;
4208 }
4209
4210 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4211    struct types.  Otherwise, they may not.  */
4212
4213 static int
4214 equiv_types (struct type *type0, struct type *type1)
4215 {
4216   if (type0 == type1)
4217     return 1;
4218   if (type0 == NULL || type1 == NULL
4219       || TYPE_CODE (type0) != TYPE_CODE (type1))
4220     return 0;
4221   if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
4222        || TYPE_CODE (type0) == TYPE_CODE_ENUM)
4223       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4224       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4225     return 1;
4226
4227   return 0;
4228 }
4229
4230 /* True iff SYM0 represents the same entity as SYM1, or one that is
4231    no more defined than that of SYM1.  */
4232
4233 static int
4234 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4235 {
4236   if (sym0 == sym1)
4237     return 1;
4238   if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
4239       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
4240     return 0;
4241
4242   switch (SYMBOL_CLASS (sym0))
4243     {
4244     case LOC_UNDEF:
4245       return 1;
4246     case LOC_TYPEDEF:
4247       {
4248         struct type *type0 = SYMBOL_TYPE (sym0);
4249         struct type *type1 = SYMBOL_TYPE (sym1);
4250         char *name0 = SYMBOL_LINKAGE_NAME (sym0);
4251         char *name1 = SYMBOL_LINKAGE_NAME (sym1);
4252         int len0 = strlen (name0);
4253
4254         return
4255           TYPE_CODE (type0) == TYPE_CODE (type1)
4256           && (equiv_types (type0, type1)
4257               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4258                   && strncmp (name1 + len0, "___XV", 5) == 0));
4259       }
4260     case LOC_CONST:
4261       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4262         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
4263     default:
4264       return 0;
4265     }
4266 }
4267
4268 /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct ada_symbol_info
4269    records in OBSTACKP.  Do nothing if SYM is a duplicate.  */
4270
4271 static void
4272 add_defn_to_vec (struct obstack *obstackp,
4273                  struct symbol *sym,
4274                  struct block *block)
4275 {
4276   int i;
4277   struct ada_symbol_info *prevDefns = defns_collected (obstackp, 0);
4278
4279   /* Do not try to complete stub types, as the debugger is probably
4280      already scanning all symbols matching a certain name at the
4281      time when this function is called.  Trying to replace the stub
4282      type by its associated full type will cause us to restart a scan
4283      which may lead to an infinite recursion.  Instead, the client
4284      collecting the matching symbols will end up collecting several
4285      matches, with at least one of them complete.  It can then filter
4286      out the stub ones if needed.  */
4287
4288   for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
4289     {
4290       if (lesseq_defined_than (sym, prevDefns[i].sym))
4291         return;
4292       else if (lesseq_defined_than (prevDefns[i].sym, sym))
4293         {
4294           prevDefns[i].sym = sym;
4295           prevDefns[i].block = block;
4296           return;
4297         }
4298     }
4299
4300   {
4301     struct ada_symbol_info info;
4302
4303     info.sym = sym;
4304     info.block = block;
4305     obstack_grow (obstackp, &info, sizeof (struct ada_symbol_info));
4306   }
4307 }
4308
4309 /* Number of ada_symbol_info structures currently collected in 
4310    current vector in *OBSTACKP.  */
4311
4312 static int
4313 num_defns_collected (struct obstack *obstackp)
4314 {
4315   return obstack_object_size (obstackp) / sizeof (struct ada_symbol_info);
4316 }
4317
4318 /* Vector of ada_symbol_info structures currently collected in current 
4319    vector in *OBSTACKP.  If FINISH, close off the vector and return
4320    its final address.  */
4321
4322 static struct ada_symbol_info *
4323 defns_collected (struct obstack *obstackp, int finish)
4324 {
4325   if (finish)
4326     return obstack_finish (obstackp);
4327   else
4328     return (struct ada_symbol_info *) obstack_base (obstackp);
4329 }
4330
4331 /* Return a minimal symbol matching NAME according to Ada decoding
4332    rules.  Returns NULL if there is no such minimal symbol.  Names 
4333    prefixed with "standard__" are handled specially: "standard__" is 
4334    first stripped off, and only static and global symbols are searched.  */
4335
4336 struct minimal_symbol *
4337 ada_lookup_simple_minsym (const char *name)
4338 {
4339   struct objfile *objfile;
4340   struct minimal_symbol *msymbol;
4341   const int wild_match = should_use_wild_match (name);
4342
4343   /* Special case: If the user specifies a symbol name inside package
4344      Standard, do a non-wild matching of the symbol name without
4345      the "standard__" prefix.  This was primarily introduced in order
4346      to allow the user to specifically access the standard exceptions
4347      using, for instance, Standard.Constraint_Error when Constraint_Error
4348      is ambiguous (due to the user defining its own Constraint_Error
4349      entity inside its program).  */
4350   if (strncmp (name, "standard__", sizeof ("standard__") - 1) == 0)
4351     name += sizeof ("standard__") - 1;
4352
4353   ALL_MSYMBOLS (objfile, msymbol)
4354   {
4355     if (match_name (SYMBOL_LINKAGE_NAME (msymbol), name, wild_match)
4356         && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4357       return msymbol;
4358   }
4359
4360   return NULL;
4361 }
4362
4363 /* For all subprograms that statically enclose the subprogram of the
4364    selected frame, add symbols matching identifier NAME in DOMAIN
4365    and their blocks to the list of data in OBSTACKP, as for
4366    ada_add_block_symbols (q.v.).   If WILD, treat as NAME with a
4367    wildcard prefix.  */
4368
4369 static void
4370 add_symbols_from_enclosing_procs (struct obstack *obstackp,
4371                                   const char *name, domain_enum namespace,
4372                                   int wild_match)
4373 {
4374 }
4375
4376 /* True if TYPE is definitely an artificial type supplied to a symbol
4377    for which no debugging information was given in the symbol file.  */
4378
4379 static int
4380 is_nondebugging_type (struct type *type)
4381 {
4382   char *name = ada_type_name (type);
4383
4384   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4385 }
4386
4387 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4388    that are deemed "identical" for practical purposes.
4389
4390    This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4391    types and that their number of enumerals is identical (in other
4392    words, TYPE_NFIELDS (type1) == TYPE_NFIELDS (type2)).  */
4393
4394 static int
4395 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4396 {
4397   int i;
4398
4399   /* The heuristic we use here is fairly conservative.  We consider
4400      that 2 enumerate types are identical if they have the same
4401      number of enumerals and that all enumerals have the same
4402      underlying value and name.  */
4403
4404   /* All enums in the type should have an identical underlying value.  */
4405   for (i = 0; i < TYPE_NFIELDS (type1); i++)
4406     if (TYPE_FIELD_BITPOS (type1, i) != TYPE_FIELD_BITPOS (type2, i))
4407       return 0;
4408
4409   /* All enumerals should also have the same name (modulo any numerical
4410      suffix).  */
4411   for (i = 0; i < TYPE_NFIELDS (type1); i++)
4412     {
4413       char *name_1 = TYPE_FIELD_NAME (type1, i);
4414       char *name_2 = TYPE_FIELD_NAME (type2, i);
4415       int len_1 = strlen (name_1);
4416       int len_2 = strlen (name_2);
4417
4418       ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
4419       ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
4420       if (len_1 != len_2
4421           || strncmp (TYPE_FIELD_NAME (type1, i),
4422                       TYPE_FIELD_NAME (type2, i),
4423                       len_1) != 0)
4424         return 0;
4425     }
4426
4427   return 1;
4428 }
4429
4430 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4431    that are deemed "identical" for practical purposes.  Sometimes,
4432    enumerals are not strictly identical, but their types are so similar
4433    that they can be considered identical.
4434
4435    For instance, consider the following code:
4436
4437       type Color is (Black, Red, Green, Blue, White);
4438       type RGB_Color is new Color range Red .. Blue;
4439
4440    Type RGB_Color is a subrange of an implicit type which is a copy
4441    of type Color. If we call that implicit type RGB_ColorB ("B" is
4442    for "Base Type"), then type RGB_ColorB is a copy of type Color.
4443    As a result, when an expression references any of the enumeral
4444    by name (Eg. "print green"), the expression is technically
4445    ambiguous and the user should be asked to disambiguate. But
4446    doing so would only hinder the user, since it wouldn't matter
4447    what choice he makes, the outcome would always be the same.
4448    So, for practical purposes, we consider them as the same.  */
4449
4450 static int
4451 symbols_are_identical_enums (struct ada_symbol_info *syms, int nsyms)
4452 {
4453   int i;
4454
4455   /* Before performing a thorough comparison check of each type,
4456      we perform a series of inexpensive checks.  We expect that these
4457      checks will quickly fail in the vast majority of cases, and thus
4458      help prevent the unnecessary use of a more expensive comparison.
4459      Said comparison also expects us to make some of these checks
4460      (see ada_identical_enum_types_p).  */
4461
4462   /* Quick check: All symbols should have an enum type.  */
4463   for (i = 0; i < nsyms; i++)
4464     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM)
4465       return 0;
4466
4467   /* Quick check: They should all have the same value.  */
4468   for (i = 1; i < nsyms; i++)
4469     if (SYMBOL_VALUE (syms[i].sym) != SYMBOL_VALUE (syms[0].sym))
4470       return 0;
4471
4472   /* Quick check: They should all have the same number of enumerals.  */
4473   for (i = 1; i < nsyms; i++)
4474     if (TYPE_NFIELDS (SYMBOL_TYPE (syms[i].sym))
4475         != TYPE_NFIELDS (SYMBOL_TYPE (syms[0].sym)))
4476       return 0;
4477
4478   /* All the sanity checks passed, so we might have a set of
4479      identical enumeration types.  Perform a more complete
4480      comparison of the type of each symbol.  */
4481   for (i = 1; i < nsyms; i++)
4482     if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].sym),
4483                                      SYMBOL_TYPE (syms[0].sym)))
4484       return 0;
4485
4486   return 1;
4487 }
4488
4489 /* Remove any non-debugging symbols in SYMS[0 .. NSYMS-1] that definitely
4490    duplicate other symbols in the list (The only case I know of where
4491    this happens is when object files containing stabs-in-ecoff are
4492    linked with files containing ordinary ecoff debugging symbols (or no
4493    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.
4494    Returns the number of items in the modified list.  */
4495
4496 static int
4497 remove_extra_symbols (struct ada_symbol_info *syms, int nsyms)
4498 {
4499   int i, j;
4500
4501   /* We should never be called with less than 2 symbols, as there
4502      cannot be any extra symbol in that case.  But it's easy to
4503      handle, since we have nothing to do in that case.  */
4504   if (nsyms < 2)
4505     return nsyms;
4506
4507   i = 0;
4508   while (i < nsyms)
4509     {
4510       int remove_p = 0;
4511
4512       /* If two symbols have the same name and one of them is a stub type,
4513          the get rid of the stub.  */
4514
4515       if (TYPE_STUB (SYMBOL_TYPE (syms[i].sym))
4516           && SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL)
4517         {
4518           for (j = 0; j < nsyms; j++)
4519             {
4520               if (j != i
4521                   && !TYPE_STUB (SYMBOL_TYPE (syms[j].sym))
4522                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
4523                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
4524                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0)
4525                 remove_p = 1;
4526             }
4527         }
4528
4529       /* Two symbols with the same name, same class and same address
4530          should be identical.  */
4531
4532       else if (SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL
4533           && SYMBOL_CLASS (syms[i].sym) == LOC_STATIC
4534           && is_nondebugging_type (SYMBOL_TYPE (syms[i].sym)))
4535         {
4536           for (j = 0; j < nsyms; j += 1)
4537             {
4538               if (i != j
4539                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
4540                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
4541                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0
4542                   && SYMBOL_CLASS (syms[i].sym) == SYMBOL_CLASS (syms[j].sym)
4543                   && SYMBOL_VALUE_ADDRESS (syms[i].sym)
4544                   == SYMBOL_VALUE_ADDRESS (syms[j].sym))
4545                 remove_p = 1;
4546             }
4547         }
4548       
4549       if (remove_p)
4550         {
4551           for (j = i + 1; j < nsyms; j += 1)
4552             syms[j - 1] = syms[j];
4553           nsyms -= 1;
4554         }
4555
4556       i += 1;
4557     }
4558
4559   /* If all the remaining symbols are identical enumerals, then
4560      just keep the first one and discard the rest.
4561
4562      Unlike what we did previously, we do not discard any entry
4563      unless they are ALL identical.  This is because the symbol
4564      comparison is not a strict comparison, but rather a practical
4565      comparison.  If all symbols are considered identical, then
4566      we can just go ahead and use the first one and discard the rest.
4567      But if we cannot reduce the list to a single element, we have
4568      to ask the user to disambiguate anyways.  And if we have to
4569      present a multiple-choice menu, it's less confusing if the list
4570      isn't missing some choices that were identical and yet distinct.  */
4571   if (symbols_are_identical_enums (syms, nsyms))
4572     nsyms = 1;
4573
4574   return nsyms;
4575 }
4576
4577 /* Given a type that corresponds to a renaming entity, use the type name
4578    to extract the scope (package name or function name, fully qualified,
4579    and following the GNAT encoding convention) where this renaming has been
4580    defined.  The string returned needs to be deallocated after use.  */
4581
4582 static char *
4583 xget_renaming_scope (struct type *renaming_type)
4584 {
4585   /* The renaming types adhere to the following convention:
4586      <scope>__<rename>___<XR extension>.
4587      So, to extract the scope, we search for the "___XR" extension,
4588      and then backtrack until we find the first "__".  */
4589
4590   const char *name = type_name_no_tag (renaming_type);
4591   char *suffix = strstr (name, "___XR");
4592   char *last;
4593   int scope_len;
4594   char *scope;
4595
4596   /* Now, backtrack a bit until we find the first "__".  Start looking
4597      at suffix - 3, as the <rename> part is at least one character long.  */
4598
4599   for (last = suffix - 3; last > name; last--)
4600     if (last[0] == '_' && last[1] == '_')
4601       break;
4602
4603   /* Make a copy of scope and return it.  */
4604
4605   scope_len = last - name;
4606   scope = (char *) xmalloc ((scope_len + 1) * sizeof (char));
4607
4608   strncpy (scope, name, scope_len);
4609   scope[scope_len] = '\0';
4610
4611   return scope;
4612 }
4613
4614 /* Return nonzero if NAME corresponds to a package name.  */
4615
4616 static int
4617 is_package_name (const char *name)
4618 {
4619   /* Here, We take advantage of the fact that no symbols are generated
4620      for packages, while symbols are generated for each function.
4621      So the condition for NAME represent a package becomes equivalent
4622      to NAME not existing in our list of symbols.  There is only one
4623      small complication with library-level functions (see below).  */
4624
4625   char *fun_name;
4626
4627   /* If it is a function that has not been defined at library level,
4628      then we should be able to look it up in the symbols.  */
4629   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
4630     return 0;
4631
4632   /* Library-level function names start with "_ada_".  See if function
4633      "_ada_" followed by NAME can be found.  */
4634
4635   /* Do a quick check that NAME does not contain "__", since library-level
4636      functions names cannot contain "__" in them.  */
4637   if (strstr (name, "__") != NULL)
4638     return 0;
4639
4640   fun_name = xstrprintf ("_ada_%s", name);
4641
4642   return (standard_lookup (fun_name, NULL, VAR_DOMAIN) == NULL);
4643 }
4644
4645 /* Return nonzero if SYM corresponds to a renaming entity that is
4646    not visible from FUNCTION_NAME.  */
4647
4648 static int
4649 old_renaming_is_invisible (const struct symbol *sym, char *function_name)
4650 {
4651   char *scope;
4652
4653   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
4654     return 0;
4655
4656   scope = xget_renaming_scope (SYMBOL_TYPE (sym));
4657
4658   make_cleanup (xfree, scope);
4659
4660   /* If the rename has been defined in a package, then it is visible.  */
4661   if (is_package_name (scope))
4662     return 0;
4663
4664   /* Check that the rename is in the current function scope by checking
4665      that its name starts with SCOPE.  */
4666
4667   /* If the function name starts with "_ada_", it means that it is
4668      a library-level function.  Strip this prefix before doing the
4669      comparison, as the encoding for the renaming does not contain
4670      this prefix.  */
4671   if (strncmp (function_name, "_ada_", 5) == 0)
4672     function_name += 5;
4673
4674   return (strncmp (function_name, scope, strlen (scope)) != 0);
4675 }
4676
4677 /* Remove entries from SYMS that corresponds to a renaming entity that
4678    is not visible from the function associated with CURRENT_BLOCK or
4679    that is superfluous due to the presence of more specific renaming
4680    information.  Places surviving symbols in the initial entries of
4681    SYMS and returns the number of surviving symbols.
4682    
4683    Rationale:
4684    First, in cases where an object renaming is implemented as a
4685    reference variable, GNAT may produce both the actual reference
4686    variable and the renaming encoding.  In this case, we discard the
4687    latter.
4688
4689    Second, GNAT emits a type following a specified encoding for each renaming
4690    entity.  Unfortunately, STABS currently does not support the definition
4691    of types that are local to a given lexical block, so all renamings types
4692    are emitted at library level.  As a consequence, if an application
4693    contains two renaming entities using the same name, and a user tries to
4694    print the value of one of these entities, the result of the ada symbol
4695    lookup will also contain the wrong renaming type.
4696
4697    This function partially covers for this limitation by attempting to
4698    remove from the SYMS list renaming symbols that should be visible
4699    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
4700    method with the current information available.  The implementation
4701    below has a couple of limitations (FIXME: brobecker-2003-05-12):  
4702    
4703       - When the user tries to print a rename in a function while there
4704         is another rename entity defined in a package:  Normally, the
4705         rename in the function has precedence over the rename in the
4706         package, so the latter should be removed from the list.  This is
4707         currently not the case.
4708         
4709       - This function will incorrectly remove valid renames if
4710         the CURRENT_BLOCK corresponds to a function which symbol name
4711         has been changed by an "Export" pragma.  As a consequence,
4712         the user will be unable to print such rename entities.  */
4713
4714 static int
4715 remove_irrelevant_renamings (struct ada_symbol_info *syms,
4716                              int nsyms, const struct block *current_block)
4717 {
4718   struct symbol *current_function;
4719   char *current_function_name;
4720   int i;
4721   int is_new_style_renaming;
4722
4723   /* If there is both a renaming foo___XR... encoded as a variable and
4724      a simple variable foo in the same block, discard the latter.
4725      First, zero out such symbols, then compress.  */
4726   is_new_style_renaming = 0;
4727   for (i = 0; i < nsyms; i += 1)
4728     {
4729       struct symbol *sym = syms[i].sym;
4730       struct block *block = syms[i].block;
4731       const char *name;
4732       const char *suffix;
4733
4734       if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
4735         continue;
4736       name = SYMBOL_LINKAGE_NAME (sym);
4737       suffix = strstr (name, "___XR");
4738
4739       if (suffix != NULL)
4740         {
4741           int name_len = suffix - name;
4742           int j;
4743
4744           is_new_style_renaming = 1;
4745           for (j = 0; j < nsyms; j += 1)
4746             if (i != j && syms[j].sym != NULL
4747                 && strncmp (name, SYMBOL_LINKAGE_NAME (syms[j].sym),
4748                             name_len) == 0
4749                 && block == syms[j].block)
4750               syms[j].sym = NULL;
4751         }
4752     }
4753   if (is_new_style_renaming)
4754     {
4755       int j, k;
4756
4757       for (j = k = 0; j < nsyms; j += 1)
4758         if (syms[j].sym != NULL)
4759             {
4760               syms[k] = syms[j];
4761               k += 1;
4762             }
4763       return k;
4764     }
4765
4766   /* Extract the function name associated to CURRENT_BLOCK.
4767      Abort if unable to do so.  */
4768
4769   if (current_block == NULL)
4770     return nsyms;
4771
4772   current_function = block_linkage_function (current_block);
4773   if (current_function == NULL)
4774     return nsyms;
4775
4776   current_function_name = SYMBOL_LINKAGE_NAME (current_function);
4777   if (current_function_name == NULL)
4778     return nsyms;
4779
4780   /* Check each of the symbols, and remove it from the list if it is
4781      a type corresponding to a renaming that is out of the scope of
4782      the current block.  */
4783
4784   i = 0;
4785   while (i < nsyms)
4786     {
4787       if (ada_parse_renaming (syms[i].sym, NULL, NULL, NULL)
4788           == ADA_OBJECT_RENAMING
4789           && old_renaming_is_invisible (syms[i].sym, current_function_name))
4790         {
4791           int j;
4792
4793           for (j = i + 1; j < nsyms; j += 1)
4794             syms[j - 1] = syms[j];
4795           nsyms -= 1;
4796         }
4797       else
4798         i += 1;
4799     }
4800
4801   return nsyms;
4802 }
4803
4804 /* Add to OBSTACKP all symbols from BLOCK (and its super-blocks)
4805    whose name and domain match NAME and DOMAIN respectively.
4806    If no match was found, then extend the search to "enclosing"
4807    routines (in other words, if we're inside a nested function,
4808    search the symbols defined inside the enclosing functions).
4809
4810    Note: This function assumes that OBSTACKP has 0 (zero) element in it.  */
4811
4812 static void
4813 ada_add_local_symbols (struct obstack *obstackp, const char *name,
4814                        struct block *block, domain_enum domain,
4815                        int wild_match)
4816 {
4817   int block_depth = 0;
4818
4819   while (block != NULL)
4820     {
4821       block_depth += 1;
4822       ada_add_block_symbols (obstackp, block, name, domain, NULL, wild_match);
4823
4824       /* If we found a non-function match, assume that's the one.  */
4825       if (is_nonfunction (defns_collected (obstackp, 0),
4826                           num_defns_collected (obstackp)))
4827         return;
4828
4829       block = BLOCK_SUPERBLOCK (block);
4830     }
4831
4832   /* If no luck so far, try to find NAME as a local symbol in some lexically
4833      enclosing subprogram.  */
4834   if (num_defns_collected (obstackp) == 0 && block_depth > 2)
4835     add_symbols_from_enclosing_procs (obstackp, name, domain, wild_match);
4836 }
4837
4838 /* An object of this type is used as the user_data argument when
4839    calling the map_matching_symbols method.  */
4840
4841 struct match_data
4842 {
4843   struct objfile *objfile;
4844   struct obstack *obstackp;
4845   struct symbol *arg_sym;
4846   int found_sym;
4847 };
4848
4849 /* A callback for add_matching_symbols that adds SYM, found in BLOCK,
4850    to a list of symbols.  DATA0 is a pointer to a struct match_data *
4851    containing the obstack that collects the symbol list, the file that SYM
4852    must come from, a flag indicating whether a non-argument symbol has
4853    been found in the current block, and the last argument symbol
4854    passed in SYM within the current block (if any).  When SYM is null,
4855    marking the end of a block, the argument symbol is added if no
4856    other has been found.  */
4857
4858 static int
4859 aux_add_nonlocal_symbols (struct block *block, struct symbol *sym, void *data0)
4860 {
4861   struct match_data *data = (struct match_data *) data0;
4862   
4863   if (sym == NULL)
4864     {
4865       if (!data->found_sym && data->arg_sym != NULL) 
4866         add_defn_to_vec (data->obstackp,
4867                          fixup_symbol_section (data->arg_sym, data->objfile),
4868                          block);
4869       data->found_sym = 0;
4870       data->arg_sym = NULL;
4871     }
4872   else 
4873     {
4874       if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
4875         return 0;
4876       else if (SYMBOL_IS_ARGUMENT (sym))
4877         data->arg_sym = sym;
4878       else
4879         {
4880           data->found_sym = 1;
4881           add_defn_to_vec (data->obstackp,
4882                            fixup_symbol_section (sym, data->objfile),
4883                            block);
4884         }
4885     }
4886   return 0;
4887 }
4888
4889 /* Compare STRING1 to STRING2, with results as for strcmp.
4890    Compatible with strcmp_iw in that strcmp_iw (STRING1, STRING2) <= 0
4891    implies compare_names (STRING1, STRING2) (they may differ as to
4892    what symbols compare equal).  */
4893
4894 static int
4895 compare_names (const char *string1, const char *string2)
4896 {
4897   while (*string1 != '\0' && *string2 != '\0')
4898     {
4899       if (isspace (*string1) || isspace (*string2))
4900         return strcmp_iw_ordered (string1, string2);
4901       if (*string1 != *string2)
4902         break;
4903       string1 += 1;
4904       string2 += 1;
4905     }
4906   switch (*string1)
4907     {
4908     case '(':
4909       return strcmp_iw_ordered (string1, string2);
4910     case '_':
4911       if (*string2 == '\0')
4912         {
4913           if (is_name_suffix (string1))
4914             return 0;
4915           else
4916             return 1;
4917         }
4918       /* FALLTHROUGH */
4919     default:
4920       if (*string2 == '(')
4921         return strcmp_iw_ordered (string1, string2);
4922       else
4923         return *string1 - *string2;
4924     }
4925 }
4926
4927 /* Add to OBSTACKP all non-local symbols whose name and domain match
4928    NAME and DOMAIN respectively.  The search is performed on GLOBAL_BLOCK
4929    symbols if GLOBAL is non-zero, or on STATIC_BLOCK symbols otherwise.  */
4930
4931 static void
4932 add_nonlocal_symbols (struct obstack *obstackp, const char *name,
4933                       domain_enum domain, int global,
4934                       int is_wild_match)
4935 {
4936   struct objfile *objfile;
4937   struct match_data data;
4938
4939   memset (&data, 0, sizeof data);
4940   data.obstackp = obstackp;
4941
4942   ALL_OBJFILES (objfile)
4943     {
4944       data.objfile = objfile;
4945
4946       if (is_wild_match)
4947         objfile->sf->qf->map_matching_symbols (name, domain, objfile, global,
4948                                                aux_add_nonlocal_symbols, &data,
4949                                                wild_match, NULL);
4950       else
4951         objfile->sf->qf->map_matching_symbols (name, domain, objfile, global,
4952                                                aux_add_nonlocal_symbols, &data,
4953                                                full_match, compare_names);
4954     }
4955
4956   if (num_defns_collected (obstackp) == 0 && global && !is_wild_match)
4957     {
4958       ALL_OBJFILES (objfile)
4959         {
4960           char *name1 = alloca (strlen (name) + sizeof ("_ada_"));
4961           strcpy (name1, "_ada_");
4962           strcpy (name1 + sizeof ("_ada_") - 1, name);
4963           data.objfile = objfile;
4964           objfile->sf->qf->map_matching_symbols (name1, domain,
4965                                                  objfile, global,
4966                                                  aux_add_nonlocal_symbols,
4967                                                  &data,
4968                                                  full_match, compare_names);
4969         }
4970     }           
4971 }
4972
4973 /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and enclosing
4974    scope and in global scopes, returning the number of matches.  Sets
4975    *RESULTS to point to a vector of (SYM,BLOCK) tuples,
4976    indicating the symbols found and the blocks and symbol tables (if
4977    any) in which they were found.  This vector are transient---good only to 
4978    the next call of ada_lookup_symbol_list.  Any non-function/non-enumeral 
4979    symbol match within the nest of blocks whose innermost member is BLOCK0,
4980    is the one match returned (no other matches in that or
4981      enclosing blocks is returned).  If there are any matches in or
4982    surrounding BLOCK0, then these alone are returned.  Otherwise, the
4983    search extends to global and file-scope (static) symbol tables.
4984    Names prefixed with "standard__" are handled specially: "standard__" 
4985    is first stripped off, and only static and global symbols are searched.  */
4986
4987 int
4988 ada_lookup_symbol_list (const char *name0, const struct block *block0,
4989                         domain_enum namespace,
4990                         struct ada_symbol_info **results)
4991 {
4992   struct symbol *sym;
4993   struct block *block;
4994   const char *name;
4995   const int wild_match = should_use_wild_match (name0);
4996   int cacheIfUnique;
4997   int ndefns;
4998
4999   obstack_free (&symbol_list_obstack, NULL);
5000   obstack_init (&symbol_list_obstack);
5001
5002   cacheIfUnique = 0;
5003
5004   /* Search specified block and its superiors.  */
5005
5006   name = name0;
5007   block = (struct block *) block0;      /* FIXME: No cast ought to be
5008                                            needed, but adding const will
5009                                            have a cascade effect.  */
5010
5011   /* Special case: If the user specifies a symbol name inside package
5012      Standard, do a non-wild matching of the symbol name without
5013      the "standard__" prefix.  This was primarily introduced in order
5014      to allow the user to specifically access the standard exceptions
5015      using, for instance, Standard.Constraint_Error when Constraint_Error
5016      is ambiguous (due to the user defining its own Constraint_Error
5017      entity inside its program).  */
5018   if (strncmp (name0, "standard__", sizeof ("standard__") - 1) == 0)
5019     {
5020       block = NULL;
5021       name = name0 + sizeof ("standard__") - 1;
5022     }
5023
5024   /* Check the non-global symbols.  If we have ANY match, then we're done.  */
5025
5026   ada_add_local_symbols (&symbol_list_obstack, name, block, namespace,
5027                          wild_match);
5028   if (num_defns_collected (&symbol_list_obstack) > 0)
5029     goto done;
5030
5031   /* No non-global symbols found.  Check our cache to see if we have
5032      already performed this search before.  If we have, then return
5033      the same result.  */
5034
5035   cacheIfUnique = 1;
5036   if (lookup_cached_symbol (name0, namespace, &sym, &block))
5037     {
5038       if (sym != NULL)
5039         add_defn_to_vec (&symbol_list_obstack, sym, block);
5040       goto done;
5041     }
5042
5043   /* Search symbols from all global blocks.  */
5044  
5045   add_nonlocal_symbols (&symbol_list_obstack, name, namespace, 1,
5046                         wild_match);
5047
5048   /* Now add symbols from all per-file blocks if we've gotten no hits
5049      (not strictly correct, but perhaps better than an error).  */
5050
5051   if (num_defns_collected (&symbol_list_obstack) == 0)
5052     add_nonlocal_symbols (&symbol_list_obstack, name, namespace, 0,
5053                           wild_match);
5054
5055 done:
5056   ndefns = num_defns_collected (&symbol_list_obstack);
5057   *results = defns_collected (&symbol_list_obstack, 1);
5058
5059   ndefns = remove_extra_symbols (*results, ndefns);
5060
5061   if (ndefns == 0)
5062     cache_symbol (name0, namespace, NULL, NULL);
5063
5064   if (ndefns == 1 && cacheIfUnique)
5065     cache_symbol (name0, namespace, (*results)[0].sym, (*results)[0].block);
5066
5067   ndefns = remove_irrelevant_renamings (*results, ndefns, block0);
5068
5069   return ndefns;
5070 }
5071
5072 /* If NAME is the name of an entity, return a string that should
5073    be used to look that entity up in Ada units.  This string should
5074    be deallocated after use using xfree.
5075
5076    NAME can have any form that the "break" or "print" commands might
5077    recognize.  In other words, it does not have to be the "natural"
5078    name, or the "encoded" name.  */
5079
5080 char *
5081 ada_name_for_lookup (const char *name)
5082 {
5083   char *canon;
5084   int nlen = strlen (name);
5085
5086   if (name[0] == '<' && name[nlen - 1] == '>')
5087     {
5088       canon = xmalloc (nlen - 1);
5089       memcpy (canon, name + 1, nlen - 2);
5090       canon[nlen - 2] = '\0';
5091     }
5092   else
5093     canon = xstrdup (ada_encode (ada_fold_name (name)));
5094   return canon;
5095 }
5096
5097 /* Implementation of the la_iterate_over_symbols method.  */
5098
5099 static void
5100 ada_iterate_over_symbols (const struct block *block,
5101                           const char *name, domain_enum domain,
5102                           int (*callback) (struct symbol *, void *),
5103                           void *data)
5104 {
5105   int ndefs, i;
5106   struct ada_symbol_info *results;
5107
5108   ndefs = ada_lookup_symbol_list (name, block, domain, &results);
5109   for (i = 0; i < ndefs; ++i)
5110     {
5111       if (! (*callback) (results[i].sym, data))
5112         break;
5113     }
5114 }
5115
5116 struct symbol *
5117 ada_lookup_encoded_symbol (const char *name, const struct block *block0,
5118                            domain_enum namespace, struct block **block_found)
5119 {
5120   struct ada_symbol_info *candidates;
5121   int n_candidates;
5122
5123   n_candidates = ada_lookup_symbol_list (name, block0, namespace, &candidates);
5124
5125   if (n_candidates == 0)
5126     return NULL;
5127
5128   if (block_found != NULL)
5129     *block_found = candidates[0].block;
5130
5131   return fixup_symbol_section (candidates[0].sym, NULL);
5132 }  
5133
5134 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5135    scope and in global scopes, or NULL if none.  NAME is folded and
5136    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
5137    choosing the first symbol if there are multiple choices.
5138    *IS_A_FIELD_OF_THIS is set to 0 and *SYMTAB is set to the symbol
5139    table in which the symbol was found (in both cases, these
5140    assignments occur only if the pointers are non-null).  */
5141 struct symbol *
5142 ada_lookup_symbol (const char *name, const struct block *block0,
5143                    domain_enum namespace, int *is_a_field_of_this)
5144 {
5145   if (is_a_field_of_this != NULL)
5146     *is_a_field_of_this = 0;
5147
5148   return
5149     ada_lookup_encoded_symbol (ada_encode (ada_fold_name (name)),
5150                                block0, namespace, NULL);
5151 }
5152
5153 static struct symbol *
5154 ada_lookup_symbol_nonlocal (const char *name,
5155                             const struct block *block,
5156                             const domain_enum domain)
5157 {
5158   return ada_lookup_symbol (name, block_static_block (block), domain, NULL);
5159 }
5160
5161
5162 /* True iff STR is a possible encoded suffix of a normal Ada name
5163    that is to be ignored for matching purposes.  Suffixes of parallel
5164    names (e.g., XVE) are not included here.  Currently, the possible suffixes
5165    are given by any of the regular expressions:
5166
5167    [.$][0-9]+       [nested subprogram suffix, on platforms such as GNU/Linux]
5168    ___[0-9]+        [nested subprogram suffix, on platforms such as HP/UX]
5169    TKB              [subprogram suffix for task bodies]
5170    _E[0-9]+[bs]$    [protected object entry suffixes]
5171    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5172
5173    Also, any leading "__[0-9]+" sequence is skipped before the suffix
5174    match is performed.  This sequence is used to differentiate homonyms,
5175    is an optional part of a valid name suffix.  */
5176
5177 static int
5178 is_name_suffix (const char *str)
5179 {
5180   int k;
5181   const char *matching;
5182   const int len = strlen (str);
5183
5184   /* Skip optional leading __[0-9]+.  */
5185
5186   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5187     {
5188       str += 3;
5189       while (isdigit (str[0]))
5190         str += 1;
5191     }
5192   
5193   /* [.$][0-9]+ */
5194
5195   if (str[0] == '.' || str[0] == '$')
5196     {
5197       matching = str + 1;
5198       while (isdigit (matching[0]))
5199         matching += 1;
5200       if (matching[0] == '\0')
5201         return 1;
5202     }
5203
5204   /* ___[0-9]+ */
5205
5206   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5207     {
5208       matching = str + 3;
5209       while (isdigit (matching[0]))
5210         matching += 1;
5211       if (matching[0] == '\0')
5212         return 1;
5213     }
5214
5215   /* "TKB" suffixes are used for subprograms implementing task bodies.  */
5216
5217   if (strcmp (str, "TKB") == 0)
5218     return 1;
5219
5220 #if 0
5221   /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5222      with a N at the end.  Unfortunately, the compiler uses the same
5223      convention for other internal types it creates.  So treating
5224      all entity names that end with an "N" as a name suffix causes
5225      some regressions.  For instance, consider the case of an enumerated
5226      type.  To support the 'Image attribute, it creates an array whose
5227      name ends with N.
5228      Having a single character like this as a suffix carrying some
5229      information is a bit risky.  Perhaps we should change the encoding
5230      to be something like "_N" instead.  In the meantime, do not do
5231      the following check.  */
5232   /* Protected Object Subprograms */
5233   if (len == 1 && str [0] == 'N')
5234     return 1;
5235 #endif
5236
5237   /* _E[0-9]+[bs]$ */
5238   if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5239     {
5240       matching = str + 3;
5241       while (isdigit (matching[0]))
5242         matching += 1;
5243       if ((matching[0] == 'b' || matching[0] == 's')
5244           && matching [1] == '\0')
5245         return 1;
5246     }
5247
5248   /* ??? We should not modify STR directly, as we are doing below.  This
5249      is fine in this case, but may become problematic later if we find
5250      that this alternative did not work, and want to try matching
5251      another one from the begining of STR.  Since we modified it, we
5252      won't be able to find the begining of the string anymore!  */
5253   if (str[0] == 'X')
5254     {
5255       str += 1;
5256       while (str[0] != '_' && str[0] != '\0')
5257         {
5258           if (str[0] != 'n' && str[0] != 'b')
5259             return 0;
5260           str += 1;
5261         }
5262     }
5263
5264   if (str[0] == '\000')
5265     return 1;
5266
5267   if (str[0] == '_')
5268     {
5269       if (str[1] != '_' || str[2] == '\000')
5270         return 0;
5271       if (str[2] == '_')
5272         {
5273           if (strcmp (str + 3, "JM") == 0)
5274             return 1;
5275           /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5276              the LJM suffix in favor of the JM one.  But we will
5277              still accept LJM as a valid suffix for a reasonable
5278              amount of time, just to allow ourselves to debug programs
5279              compiled using an older version of GNAT.  */
5280           if (strcmp (str + 3, "LJM") == 0)
5281             return 1;
5282           if (str[3] != 'X')
5283             return 0;
5284           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5285               || str[4] == 'U' || str[4] == 'P')
5286             return 1;
5287           if (str[4] == 'R' && str[5] != 'T')
5288             return 1;
5289           return 0;
5290         }
5291       if (!isdigit (str[2]))
5292         return 0;
5293       for (k = 3; str[k] != '\0'; k += 1)
5294         if (!isdigit (str[k]) && str[k] != '_')
5295           return 0;
5296       return 1;
5297     }
5298   if (str[0] == '$' && isdigit (str[1]))
5299     {
5300       for (k = 2; str[k] != '\0'; k += 1)
5301         if (!isdigit (str[k]) && str[k] != '_')
5302           return 0;
5303       return 1;
5304     }
5305   return 0;
5306 }
5307
5308 /* Return non-zero if the string starting at NAME and ending before
5309    NAME_END contains no capital letters.  */
5310
5311 static int
5312 is_valid_name_for_wild_match (const char *name0)
5313 {
5314   const char *decoded_name = ada_decode (name0);
5315   int i;
5316
5317   /* If the decoded name starts with an angle bracket, it means that
5318      NAME0 does not follow the GNAT encoding format.  It should then
5319      not be allowed as a possible wild match.  */
5320   if (decoded_name[0] == '<')
5321     return 0;
5322
5323   for (i=0; decoded_name[i] != '\0'; i++)
5324     if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5325       return 0;
5326
5327   return 1;
5328 }
5329
5330 /* Advance *NAMEP to next occurrence of TARGET0 in the string NAME0
5331    that could start a simple name.  Assumes that *NAMEP points into
5332    the string beginning at NAME0.  */
5333
5334 static int
5335 advance_wild_match (const char **namep, const char *name0, int target0)
5336 {
5337   const char *name = *namep;
5338
5339   while (1)
5340     {
5341       int t0, t1;
5342
5343       t0 = *name;
5344       if (t0 == '_')
5345         {
5346           t1 = name[1];
5347           if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5348             {
5349               name += 1;
5350               if (name == name0 + 5 && strncmp (name0, "_ada", 4) == 0)
5351                 break;
5352               else
5353                 name += 1;
5354             }
5355           else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5356                                  || name[2] == target0))
5357             {
5358               name += 2;
5359               break;
5360             }
5361           else
5362             return 0;
5363         }
5364       else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5365         name += 1;
5366       else
5367         return 0;
5368     }
5369
5370   *namep = name;
5371   return 1;
5372 }
5373
5374 /* Return 0 iff NAME encodes a name of the form prefix.PATN.  Ignores any
5375    informational suffixes of NAME (i.e., for which is_name_suffix is
5376    true).  Assumes that PATN is a lower-cased Ada simple name.  */
5377
5378 static int
5379 wild_match (const char *name, const char *patn)
5380 {
5381   const char *p, *n;
5382   const char *name0 = name;
5383
5384   while (1)
5385     {
5386       const char *match = name;
5387
5388       if (*name == *patn)
5389         {
5390           for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5391             if (*p != *name)
5392               break;
5393           if (*p == '\0' && is_name_suffix (name))
5394             return match != name0 && !is_valid_name_for_wild_match (name0);
5395
5396           if (name[-1] == '_')
5397             name -= 1;
5398         }
5399       if (!advance_wild_match (&name, name0, *patn))
5400         return 1;
5401     }
5402 }
5403
5404 /* Returns 0 iff symbol name SYM_NAME matches SEARCH_NAME, apart from
5405    informational suffix.  */
5406
5407 static int
5408 full_match (const char *sym_name, const char *search_name)
5409 {
5410   return !match_name (sym_name, search_name, 0);
5411 }
5412
5413
5414 /* Add symbols from BLOCK matching identifier NAME in DOMAIN to
5415    vector *defn_symbols, updating the list of symbols in OBSTACKP 
5416    (if necessary).  If WILD, treat as NAME with a wildcard prefix.
5417    OBJFILE is the section containing BLOCK.
5418    SYMTAB is recorded with each symbol added.  */
5419
5420 static void
5421 ada_add_block_symbols (struct obstack *obstackp,
5422                        struct block *block, const char *name,
5423                        domain_enum domain, struct objfile *objfile,
5424                        int wild)
5425 {
5426   struct dict_iterator iter;
5427   int name_len = strlen (name);
5428   /* A matching argument symbol, if any.  */
5429   struct symbol *arg_sym;
5430   /* Set true when we find a matching non-argument symbol.  */
5431   int found_sym;
5432   struct symbol *sym;
5433
5434   arg_sym = NULL;
5435   found_sym = 0;
5436   if (wild)
5437     {
5438       for (sym = dict_iter_match_first (BLOCK_DICT (block), name,
5439                                         wild_match, &iter);
5440            sym != NULL; sym = dict_iter_match_next (name, wild_match, &iter))
5441       {
5442         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
5443                                    SYMBOL_DOMAIN (sym), domain)
5444             && wild_match (SYMBOL_LINKAGE_NAME (sym), name) == 0)
5445           {
5446             if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5447               continue;
5448             else if (SYMBOL_IS_ARGUMENT (sym))
5449               arg_sym = sym;
5450             else
5451               {
5452                 found_sym = 1;
5453                 add_defn_to_vec (obstackp,
5454                                  fixup_symbol_section (sym, objfile),
5455                                  block);
5456               }
5457           }
5458       }
5459     }
5460   else
5461     {
5462      for (sym = dict_iter_match_first (BLOCK_DICT (block), name,
5463                                        full_match, &iter);
5464            sym != NULL; sym = dict_iter_match_next (name, full_match, &iter))
5465       {
5466         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
5467                                    SYMBOL_DOMAIN (sym), domain))
5468           {
5469             if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
5470               {
5471                 if (SYMBOL_IS_ARGUMENT (sym))
5472                   arg_sym = sym;
5473                 else
5474                   {
5475                     found_sym = 1;
5476                     add_defn_to_vec (obstackp,
5477                                      fixup_symbol_section (sym, objfile),
5478                                      block);
5479                   }
5480               }
5481           }
5482       }
5483     }
5484
5485   if (!found_sym && arg_sym != NULL)
5486     {
5487       add_defn_to_vec (obstackp,
5488                        fixup_symbol_section (arg_sym, objfile),
5489                        block);
5490     }
5491
5492   if (!wild)
5493     {
5494       arg_sym = NULL;
5495       found_sym = 0;
5496
5497       ALL_BLOCK_SYMBOLS (block, iter, sym)
5498       {
5499         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
5500                                    SYMBOL_DOMAIN (sym), domain))
5501           {
5502             int cmp;
5503
5504             cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (sym)[0];
5505             if (cmp == 0)
5506               {
5507                 cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (sym), 5);
5508                 if (cmp == 0)
5509                   cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym) + 5,
5510                                  name_len);
5511               }
5512
5513             if (cmp == 0
5514                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len + 5))
5515               {
5516                 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
5517                   {
5518                     if (SYMBOL_IS_ARGUMENT (sym))
5519                       arg_sym = sym;
5520                     else
5521                       {
5522                         found_sym = 1;
5523                         add_defn_to_vec (obstackp,
5524                                          fixup_symbol_section (sym, objfile),
5525                                          block);
5526                       }
5527                   }
5528               }
5529           }
5530       }
5531
5532       /* NOTE: This really shouldn't be needed for _ada_ symbols.
5533          They aren't parameters, right?  */
5534       if (!found_sym && arg_sym != NULL)
5535         {
5536           add_defn_to_vec (obstackp,
5537                            fixup_symbol_section (arg_sym, objfile),
5538                            block);
5539         }
5540     }
5541 }
5542 \f
5543
5544                                 /* Symbol Completion */
5545
5546 /* If SYM_NAME is a completion candidate for TEXT, return this symbol
5547    name in a form that's appropriate for the completion.  The result
5548    does not need to be deallocated, but is only good until the next call.
5549
5550    TEXT_LEN is equal to the length of TEXT.
5551    Perform a wild match if WILD_MATCH is set.
5552    ENCODED should be set if TEXT represents the start of a symbol name
5553    in its encoded form.  */
5554
5555 static const char *
5556 symbol_completion_match (const char *sym_name,
5557                          const char *text, int text_len,
5558                          int wild_match, int encoded)
5559 {
5560   const int verbatim_match = (text[0] == '<');
5561   int match = 0;
5562
5563   if (verbatim_match)
5564     {
5565       /* Strip the leading angle bracket.  */
5566       text = text + 1;
5567       text_len--;
5568     }
5569
5570   /* First, test against the fully qualified name of the symbol.  */
5571
5572   if (strncmp (sym_name, text, text_len) == 0)
5573     match = 1;
5574
5575   if (match && !encoded)
5576     {
5577       /* One needed check before declaring a positive match is to verify
5578          that iff we are doing a verbatim match, the decoded version
5579          of the symbol name starts with '<'.  Otherwise, this symbol name
5580          is not a suitable completion.  */
5581       const char *sym_name_copy = sym_name;
5582       int has_angle_bracket;
5583
5584       sym_name = ada_decode (sym_name);
5585       has_angle_bracket = (sym_name[0] == '<');
5586       match = (has_angle_bracket == verbatim_match);
5587       sym_name = sym_name_copy;
5588     }
5589
5590   if (match && !verbatim_match)
5591     {
5592       /* When doing non-verbatim match, another check that needs to
5593          be done is to verify that the potentially matching symbol name
5594          does not include capital letters, because the ada-mode would
5595          not be able to understand these symbol names without the
5596          angle bracket notation.  */
5597       const char *tmp;
5598
5599       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
5600       if (*tmp != '\0')
5601         match = 0;
5602     }
5603
5604   /* Second: Try wild matching...  */
5605
5606   if (!match && wild_match)
5607     {
5608       /* Since we are doing wild matching, this means that TEXT
5609          may represent an unqualified symbol name.  We therefore must
5610          also compare TEXT against the unqualified name of the symbol.  */
5611       sym_name = ada_unqualified_name (ada_decode (sym_name));
5612
5613       if (strncmp (sym_name, text, text_len) == 0)
5614         match = 1;
5615     }
5616
5617   /* Finally: If we found a mach, prepare the result to return.  */
5618
5619   if (!match)
5620     return NULL;
5621
5622   if (verbatim_match)
5623     sym_name = add_angle_brackets (sym_name);
5624
5625   if (!encoded)
5626     sym_name = ada_decode (sym_name);
5627
5628   return sym_name;
5629 }
5630
5631 DEF_VEC_P (char_ptr);
5632
5633 /* A companion function to ada_make_symbol_completion_list().
5634    Check if SYM_NAME represents a symbol which name would be suitable
5635    to complete TEXT (TEXT_LEN is the length of TEXT), in which case
5636    it is appended at the end of the given string vector SV.
5637
5638    ORIG_TEXT is the string original string from the user command
5639    that needs to be completed.  WORD is the entire command on which
5640    completion should be performed.  These two parameters are used to
5641    determine which part of the symbol name should be added to the
5642    completion vector.
5643    if WILD_MATCH is set, then wild matching is performed.
5644    ENCODED should be set if TEXT represents a symbol name in its
5645    encoded formed (in which case the completion should also be
5646    encoded).  */
5647
5648 static void
5649 symbol_completion_add (VEC(char_ptr) **sv,
5650                        const char *sym_name,
5651                        const char *text, int text_len,
5652                        const char *orig_text, const char *word,
5653                        int wild_match, int encoded)
5654 {
5655   const char *match = symbol_completion_match (sym_name, text, text_len,
5656                                                wild_match, encoded);
5657   char *completion;
5658
5659   if (match == NULL)
5660     return;
5661
5662   /* We found a match, so add the appropriate completion to the given
5663      string vector.  */
5664
5665   if (word == orig_text)
5666     {
5667       completion = xmalloc (strlen (match) + 5);
5668       strcpy (completion, match);
5669     }
5670   else if (word > orig_text)
5671     {
5672       /* Return some portion of sym_name.  */
5673       completion = xmalloc (strlen (match) + 5);
5674       strcpy (completion, match + (word - orig_text));
5675     }
5676   else
5677     {
5678       /* Return some of ORIG_TEXT plus sym_name.  */
5679       completion = xmalloc (strlen (match) + (orig_text - word) + 5);
5680       strncpy (completion, word, orig_text - word);
5681       completion[orig_text - word] = '\0';
5682       strcat (completion, match);
5683     }
5684
5685   VEC_safe_push (char_ptr, *sv, completion);
5686 }
5687
5688 /* An object of this type is passed as the user_data argument to the
5689    expand_partial_symbol_names method.  */
5690 struct add_partial_datum
5691 {
5692   VEC(char_ptr) **completions;
5693   char *text;
5694   int text_len;
5695   char *text0;
5696   char *word;
5697   int wild_match;
5698   int encoded;
5699 };
5700
5701 /* A callback for expand_partial_symbol_names.  */
5702 static int
5703 ada_expand_partial_symbol_name (const struct language_defn *language,
5704                                 const char *name, void *user_data)
5705 {
5706   struct add_partial_datum *data = user_data;
5707   
5708   return symbol_completion_match (name, data->text, data->text_len,
5709                                   data->wild_match, data->encoded) != NULL;
5710 }
5711
5712 /* Return a list of possible symbol names completing TEXT0.  The list
5713    is NULL terminated.  WORD is the entire command on which completion
5714    is made.  */
5715
5716 static char **
5717 ada_make_symbol_completion_list (char *text0, char *word)
5718 {
5719   char *text;
5720   int text_len;
5721   int wild_match;
5722   int encoded;
5723   VEC(char_ptr) *completions = VEC_alloc (char_ptr, 128);
5724   struct symbol *sym;
5725   struct symtab *s;
5726   struct minimal_symbol *msymbol;
5727   struct objfile *objfile;
5728   struct block *b, *surrounding_static_block = 0;
5729   int i;
5730   struct dict_iterator iter;
5731
5732   if (text0[0] == '<')
5733     {
5734       text = xstrdup (text0);
5735       make_cleanup (xfree, text);
5736       text_len = strlen (text);
5737       wild_match = 0;
5738       encoded = 1;
5739     }
5740   else
5741     {
5742       text = xstrdup (ada_encode (text0));
5743       make_cleanup (xfree, text);
5744       text_len = strlen (text);
5745       for (i = 0; i < text_len; i++)
5746         text[i] = tolower (text[i]);
5747
5748       encoded = (strstr (text0, "__") != NULL);
5749       /* If the name contains a ".", then the user is entering a fully
5750          qualified entity name, and the match must not be done in wild
5751          mode.  Similarly, if the user wants to complete what looks like
5752          an encoded name, the match must not be done in wild mode.  */
5753       wild_match = (strchr (text0, '.') == NULL && !encoded);
5754     }
5755
5756   /* First, look at the partial symtab symbols.  */
5757   {
5758     struct add_partial_datum data;
5759
5760     data.completions = &completions;
5761     data.text = text;
5762     data.text_len = text_len;
5763     data.text0 = text0;
5764     data.word = word;
5765     data.wild_match = wild_match;
5766     data.encoded = encoded;
5767     expand_partial_symbol_names (ada_expand_partial_symbol_name, &data);
5768   }
5769
5770   /* At this point scan through the misc symbol vectors and add each
5771      symbol you find to the list.  Eventually we want to ignore
5772      anything that isn't a text symbol (everything else will be
5773      handled by the psymtab code above).  */
5774
5775   ALL_MSYMBOLS (objfile, msymbol)
5776   {
5777     QUIT;
5778     symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (msymbol),
5779                            text, text_len, text0, word, wild_match, encoded);
5780   }
5781
5782   /* Search upwards from currently selected frame (so that we can
5783      complete on local vars.  */
5784
5785   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
5786     {
5787       if (!BLOCK_SUPERBLOCK (b))
5788         surrounding_static_block = b;   /* For elmin of dups */
5789
5790       ALL_BLOCK_SYMBOLS (b, iter, sym)
5791       {
5792         symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
5793                                text, text_len, text0, word,
5794                                wild_match, encoded);
5795       }
5796     }
5797
5798   /* Go through the symtabs and check the externs and statics for
5799      symbols which match.  */
5800
5801   ALL_SYMTABS (objfile, s)
5802   {
5803     QUIT;
5804     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
5805     ALL_BLOCK_SYMBOLS (b, iter, sym)
5806     {
5807       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
5808                              text, text_len, text0, word,
5809                              wild_match, encoded);
5810     }
5811   }
5812
5813   ALL_SYMTABS (objfile, s)
5814   {
5815     QUIT;
5816     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
5817     /* Don't do this block twice.  */
5818     if (b == surrounding_static_block)
5819       continue;
5820     ALL_BLOCK_SYMBOLS (b, iter, sym)
5821     {
5822       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
5823                              text, text_len, text0, word,
5824                              wild_match, encoded);
5825     }
5826   }
5827
5828   /* Append the closing NULL entry.  */
5829   VEC_safe_push (char_ptr, completions, NULL);
5830
5831   /* Make a copy of the COMPLETIONS VEC before we free it, and then
5832      return the copy.  It's unfortunate that we have to make a copy
5833      of an array that we're about to destroy, but there is nothing much
5834      we can do about it.  Fortunately, it's typically not a very large
5835      array.  */
5836   {
5837     const size_t completions_size = 
5838       VEC_length (char_ptr, completions) * sizeof (char *);
5839     char **result = xmalloc (completions_size);
5840     
5841     memcpy (result, VEC_address (char_ptr, completions), completions_size);
5842
5843     VEC_free (char_ptr, completions);
5844     return result;
5845   }
5846 }
5847
5848                                 /* Field Access */
5849
5850 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
5851    for tagged types.  */
5852
5853 static int
5854 ada_is_dispatch_table_ptr_type (struct type *type)
5855 {
5856   char *name;
5857
5858   if (TYPE_CODE (type) != TYPE_CODE_PTR)
5859     return 0;
5860
5861   name = TYPE_NAME (TYPE_TARGET_TYPE (type));
5862   if (name == NULL)
5863     return 0;
5864
5865   return (strcmp (name, "ada__tags__dispatch_table") == 0);
5866 }
5867
5868 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
5869    to be invisible to users.  */
5870
5871 int
5872 ada_is_ignored_field (struct type *type, int field_num)
5873 {
5874   if (field_num < 0 || field_num > TYPE_NFIELDS (type))
5875     return 1;
5876    
5877   /* Check the name of that field.  */
5878   {
5879     const char *name = TYPE_FIELD_NAME (type, field_num);
5880
5881     /* Anonymous field names should not be printed.
5882        brobecker/2007-02-20: I don't think this can actually happen
5883        but we don't want to print the value of annonymous fields anyway.  */
5884     if (name == NULL)
5885       return 1;
5886
5887     /* A field named "_parent" is internally generated by GNAT for
5888        tagged types, and should not be printed either.  */
5889     if (name[0] == '_' && strncmp (name, "_parent", 7) != 0)
5890       return 1;
5891   }
5892
5893   /* If this is the dispatch table of a tagged type, then ignore.  */
5894   if (ada_is_tagged_type (type, 1)
5895       && ada_is_dispatch_table_ptr_type (TYPE_FIELD_TYPE (type, field_num)))
5896     return 1;
5897
5898   /* Not a special field, so it should not be ignored.  */
5899   return 0;
5900 }
5901
5902 /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
5903    pointer or reference type whose ultimate target has a tag field.  */
5904
5905 int
5906 ada_is_tagged_type (struct type *type, int refok)
5907 {
5908   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1, NULL) != NULL);
5909 }
5910
5911 /* True iff TYPE represents the type of X'Tag */
5912
5913 int
5914 ada_is_tag_type (struct type *type)
5915 {
5916   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
5917     return 0;
5918   else
5919     {
5920       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
5921
5922       return (name != NULL
5923               && strcmp (name, "ada__tags__dispatch_table") == 0);
5924     }
5925 }
5926
5927 /* The type of the tag on VAL.  */
5928
5929 struct type *
5930 ada_tag_type (struct value *val)
5931 {
5932   return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0, NULL);
5933 }
5934
5935 /* The value of the tag on VAL.  */
5936
5937 struct value *
5938 ada_value_tag (struct value *val)
5939 {
5940   return ada_value_struct_elt (val, "_tag", 0);
5941 }
5942
5943 /* The value of the tag on the object of type TYPE whose contents are
5944    saved at VALADDR, if it is non-null, or is at memory address
5945    ADDRESS.  */
5946
5947 static struct value *
5948 value_tag_from_contents_and_address (struct type *type,
5949                                      const gdb_byte *valaddr,
5950                                      CORE_ADDR address)
5951 {
5952   int tag_byte_offset;
5953   struct type *tag_type;
5954
5955   if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
5956                          NULL, NULL, NULL))
5957     {
5958       const gdb_byte *valaddr1 = ((valaddr == NULL)
5959                                   ? NULL
5960                                   : valaddr + tag_byte_offset);
5961       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
5962
5963       return value_from_contents_and_address (tag_type, valaddr1, address1);
5964     }
5965   return NULL;
5966 }
5967
5968 static struct type *
5969 type_from_tag (struct value *tag)
5970 {
5971   const char *type_name = ada_tag_name (tag);
5972
5973   if (type_name != NULL)
5974     return ada_find_any_type (ada_encode (type_name));
5975   return NULL;
5976 }
5977
5978 struct tag_args
5979 {
5980   struct value *tag;
5981   char *name;
5982 };
5983
5984
5985 static int ada_tag_name_1 (void *);
5986 static int ada_tag_name_2 (struct tag_args *);
5987
5988 /* Wrapper function used by ada_tag_name.  Given a struct tag_args*
5989    value ARGS, sets ARGS->name to the tag name of ARGS->tag.
5990    The value stored in ARGS->name is valid until the next call to 
5991    ada_tag_name_1.  */
5992
5993 static int
5994 ada_tag_name_1 (void *args0)
5995 {
5996   struct tag_args *args = (struct tag_args *) args0;
5997   static char name[1024];
5998   char *p;
5999   struct value *val;
6000
6001   args->name = NULL;
6002   val = ada_value_struct_elt (args->tag, "tsd", 1);
6003   if (val == NULL)
6004     return ada_tag_name_2 (args);
6005   val = ada_value_struct_elt (val, "expanded_name", 1);
6006   if (val == NULL)
6007     return 0;
6008   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
6009   for (p = name; *p != '\0'; p += 1)
6010     if (isalpha (*p))
6011       *p = tolower (*p);
6012   args->name = name;
6013   return 0;
6014 }
6015
6016 /* Return the "ada__tags__type_specific_data" type.  */
6017
6018 static struct type *
6019 ada_get_tsd_type (struct inferior *inf)
6020 {
6021   struct ada_inferior_data *data = get_ada_inferior_data (inf);
6022
6023   if (data->tsd_type == 0)
6024     data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6025   return data->tsd_type;
6026 }
6027
6028 /* Utility function for ada_tag_name_1 that tries the second
6029    representation for the dispatch table (in which there is no
6030    explicit 'tsd' field in the referent of the tag pointer, and instead
6031    the tsd pointer is stored just before the dispatch table.  */
6032    
6033 static int
6034 ada_tag_name_2 (struct tag_args *args)
6035 {
6036   struct type *info_type;
6037   static char name[1024];
6038   char *p;
6039   struct value *val, *valp;
6040
6041   args->name = NULL;
6042   info_type = ada_get_tsd_type (current_inferior());
6043   if (info_type == NULL)
6044     return 0;
6045   info_type = lookup_pointer_type (lookup_pointer_type (info_type));
6046   valp = value_cast (info_type, args->tag);
6047   if (valp == NULL)
6048     return 0;
6049   val = value_ind (value_ptradd (valp, -1));
6050   if (val == NULL)
6051     return 0;
6052   val = ada_value_struct_elt (val, "expanded_name", 1);
6053   if (val == NULL)
6054     return 0;
6055   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
6056   for (p = name; *p != '\0'; p += 1)
6057     if (isalpha (*p))
6058       *p = tolower (*p);
6059   args->name = name;
6060   return 0;
6061 }
6062
6063 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6064    a C string.  */
6065
6066 const char *
6067 ada_tag_name (struct value *tag)
6068 {
6069   struct tag_args args;
6070
6071   if (!ada_is_tag_type (value_type (tag)))
6072     return NULL;
6073   args.tag = tag;
6074   args.name = NULL;
6075   catch_errors (ada_tag_name_1, &args, NULL, RETURN_MASK_ALL);
6076   return args.name;
6077 }
6078
6079 /* The parent type of TYPE, or NULL if none.  */
6080
6081 struct type *
6082 ada_parent_type (struct type *type)
6083 {
6084   int i;
6085
6086   type = ada_check_typedef (type);
6087
6088   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
6089     return NULL;
6090
6091   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6092     if (ada_is_parent_field (type, i))
6093       {
6094         struct type *parent_type = TYPE_FIELD_TYPE (type, i);
6095
6096         /* If the _parent field is a pointer, then dereference it.  */
6097         if (TYPE_CODE (parent_type) == TYPE_CODE_PTR)
6098           parent_type = TYPE_TARGET_TYPE (parent_type);
6099         /* If there is a parallel XVS type, get the actual base type.  */
6100         parent_type = ada_get_base_type (parent_type);
6101
6102         return ada_check_typedef (parent_type);
6103       }
6104
6105   return NULL;
6106 }
6107
6108 /* True iff field number FIELD_NUM of structure type TYPE contains the
6109    parent-type (inherited) fields of a derived type.  Assumes TYPE is
6110    a structure type with at least FIELD_NUM+1 fields.  */
6111
6112 int
6113 ada_is_parent_field (struct type *type, int field_num)
6114 {
6115   const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
6116
6117   return (name != NULL
6118           && (strncmp (name, "PARENT", 6) == 0
6119               || strncmp (name, "_parent", 7) == 0));
6120 }
6121
6122 /* True iff field number FIELD_NUM of structure type TYPE is a
6123    transparent wrapper field (which should be silently traversed when doing
6124    field selection and flattened when printing).  Assumes TYPE is a
6125    structure type with at least FIELD_NUM+1 fields.  Such fields are always
6126    structures.  */
6127
6128 int
6129 ada_is_wrapper_field (struct type *type, int field_num)
6130 {
6131   const char *name = TYPE_FIELD_NAME (type, field_num);
6132
6133   return (name != NULL
6134           && (strncmp (name, "PARENT", 6) == 0
6135               || strcmp (name, "REP") == 0
6136               || strncmp (name, "_parent", 7) == 0
6137               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6138 }
6139
6140 /* True iff field number FIELD_NUM of structure or union type TYPE
6141    is a variant wrapper.  Assumes TYPE is a structure type with at least
6142    FIELD_NUM+1 fields.  */
6143
6144 int
6145 ada_is_variant_part (struct type *type, int field_num)
6146 {
6147   struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
6148
6149   return (TYPE_CODE (field_type) == TYPE_CODE_UNION
6150           || (is_dynamic_field (type, field_num)
6151               && (TYPE_CODE (TYPE_TARGET_TYPE (field_type)) 
6152                   == TYPE_CODE_UNION)));
6153 }
6154
6155 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6156    whose discriminants are contained in the record type OUTER_TYPE,
6157    returns the type of the controlling discriminant for the variant.
6158    May return NULL if the type could not be found.  */
6159
6160 struct type *
6161 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6162 {
6163   char *name = ada_variant_discrim_name (var_type);
6164
6165   return ada_lookup_struct_elt_type (outer_type, name, 1, 1, NULL);
6166 }
6167
6168 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6169    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6170    represents a 'when others' clause; otherwise 0.  */
6171
6172 int
6173 ada_is_others_clause (struct type *type, int field_num)
6174 {
6175   const char *name = TYPE_FIELD_NAME (type, field_num);
6176
6177   return (name != NULL && name[0] == 'O');
6178 }
6179
6180 /* Assuming that TYPE0 is the type of the variant part of a record,
6181    returns the name of the discriminant controlling the variant.
6182    The value is valid until the next call to ada_variant_discrim_name.  */
6183
6184 char *
6185 ada_variant_discrim_name (struct type *type0)
6186 {
6187   static char *result = NULL;
6188   static size_t result_len = 0;
6189   struct type *type;
6190   const char *name;
6191   const char *discrim_end;
6192   const char *discrim_start;
6193
6194   if (TYPE_CODE (type0) == TYPE_CODE_PTR)
6195     type = TYPE_TARGET_TYPE (type0);
6196   else
6197     type = type0;
6198
6199   name = ada_type_name (type);
6200
6201   if (name == NULL || name[0] == '\000')
6202     return "";
6203
6204   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6205        discrim_end -= 1)
6206     {
6207       if (strncmp (discrim_end, "___XVN", 6) == 0)
6208         break;
6209     }
6210   if (discrim_end == name)
6211     return "";
6212
6213   for (discrim_start = discrim_end; discrim_start != name + 3;
6214        discrim_start -= 1)
6215     {
6216       if (discrim_start == name + 1)
6217         return "";
6218       if ((discrim_start > name + 3
6219            && strncmp (discrim_start - 3, "___", 3) == 0)
6220           || discrim_start[-1] == '.')
6221         break;
6222     }
6223
6224   GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
6225   strncpy (result, discrim_start, discrim_end - discrim_start);
6226   result[discrim_end - discrim_start] = '\0';
6227   return result;
6228 }
6229
6230 /* Scan STR for a subtype-encoded number, beginning at position K.
6231    Put the position of the character just past the number scanned in
6232    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
6233    Return 1 if there was a valid number at the given position, and 0
6234    otherwise.  A "subtype-encoded" number consists of the absolute value
6235    in decimal, followed by the letter 'm' to indicate a negative number.
6236    Assumes 0m does not occur.  */
6237
6238 int
6239 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6240 {
6241   ULONGEST RU;
6242
6243   if (!isdigit (str[k]))
6244     return 0;
6245
6246   /* Do it the hard way so as not to make any assumption about
6247      the relationship of unsigned long (%lu scan format code) and
6248      LONGEST.  */
6249   RU = 0;
6250   while (isdigit (str[k]))
6251     {
6252       RU = RU * 10 + (str[k] - '0');
6253       k += 1;
6254     }
6255
6256   if (str[k] == 'm')
6257     {
6258       if (R != NULL)
6259         *R = (-(LONGEST) (RU - 1)) - 1;
6260       k += 1;
6261     }
6262   else if (R != NULL)
6263     *R = (LONGEST) RU;
6264
6265   /* NOTE on the above: Technically, C does not say what the results of
6266      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6267      number representable as a LONGEST (although either would probably work
6268      in most implementations).  When RU>0, the locution in the then branch
6269      above is always equivalent to the negative of RU.  */
6270
6271   if (new_k != NULL)
6272     *new_k = k;
6273   return 1;
6274 }
6275
6276 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6277    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6278    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */
6279
6280 int
6281 ada_in_variant (LONGEST val, struct type *type, int field_num)
6282 {
6283   const char *name = TYPE_FIELD_NAME (type, field_num);
6284   int p;
6285
6286   p = 0;
6287   while (1)
6288     {
6289       switch (name[p])
6290         {
6291         case '\0':
6292           return 0;
6293         case 'S':
6294           {
6295             LONGEST W;
6296
6297             if (!ada_scan_number (name, p + 1, &W, &p))
6298               return 0;
6299             if (val == W)
6300               return 1;
6301             break;
6302           }
6303         case 'R':
6304           {
6305             LONGEST L, U;
6306
6307             if (!ada_scan_number (name, p + 1, &L, &p)
6308                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6309               return 0;
6310             if (val >= L && val <= U)
6311               return 1;
6312             break;
6313           }
6314         case 'O':
6315           return 1;
6316         default:
6317           return 0;
6318         }
6319     }
6320 }
6321
6322 /* FIXME: Lots of redundancy below.  Try to consolidate.  */
6323
6324 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6325    ARG_TYPE, extract and return the value of one of its (non-static)
6326    fields.  FIELDNO says which field.   Differs from value_primitive_field
6327    only in that it can handle packed values of arbitrary type.  */
6328
6329 static struct value *
6330 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6331                            struct type *arg_type)
6332 {
6333   struct type *type;
6334
6335   arg_type = ada_check_typedef (arg_type);
6336   type = TYPE_FIELD_TYPE (arg_type, fieldno);
6337
6338   /* Handle packed fields.  */
6339
6340   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
6341     {
6342       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
6343       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6344
6345       return ada_value_primitive_packed_val (arg1, value_contents (arg1),
6346                                              offset + bit_pos / 8,
6347                                              bit_pos % 8, bit_size, type);
6348     }
6349   else
6350     return value_primitive_field (arg1, offset, fieldno, arg_type);
6351 }
6352
6353 /* Find field with name NAME in object of type TYPE.  If found, 
6354    set the following for each argument that is non-null:
6355     - *FIELD_TYPE_P to the field's type; 
6356     - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within 
6357       an object of that type;
6358     - *BIT_OFFSET_P to the bit offset modulo byte size of the field; 
6359     - *BIT_SIZE_P to its size in bits if the field is packed, and 
6360       0 otherwise;
6361    If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6362    fields up to but not including the desired field, or by the total
6363    number of fields if not found.   A NULL value of NAME never
6364    matches; the function just counts visible fields in this case.
6365    
6366    Returns 1 if found, 0 otherwise.  */
6367
6368 static int
6369 find_struct_field (char *name, struct type *type, int offset,
6370                    struct type **field_type_p,
6371                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6372                    int *index_p)
6373 {
6374   int i;
6375
6376   type = ada_check_typedef (type);
6377
6378   if (field_type_p != NULL)
6379     *field_type_p = NULL;
6380   if (byte_offset_p != NULL)
6381     *byte_offset_p = 0;
6382   if (bit_offset_p != NULL)
6383     *bit_offset_p = 0;
6384   if (bit_size_p != NULL)
6385     *bit_size_p = 0;
6386
6387   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6388     {
6389       int bit_pos = TYPE_FIELD_BITPOS (type, i);
6390       int fld_offset = offset + bit_pos / 8;
6391       char *t_field_name = TYPE_FIELD_NAME (type, i);
6392
6393       if (t_field_name == NULL)
6394         continue;
6395
6396       else if (name != NULL && field_name_match (t_field_name, name))
6397         {
6398           int bit_size = TYPE_FIELD_BITSIZE (type, i);
6399
6400           if (field_type_p != NULL)
6401             *field_type_p = TYPE_FIELD_TYPE (type, i);
6402           if (byte_offset_p != NULL)
6403             *byte_offset_p = fld_offset;
6404           if (bit_offset_p != NULL)
6405             *bit_offset_p = bit_pos % 8;
6406           if (bit_size_p != NULL)
6407             *bit_size_p = bit_size;
6408           return 1;
6409         }
6410       else if (ada_is_wrapper_field (type, i))
6411         {
6412           if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
6413                                  field_type_p, byte_offset_p, bit_offset_p,
6414                                  bit_size_p, index_p))
6415             return 1;
6416         }
6417       else if (ada_is_variant_part (type, i))
6418         {
6419           /* PNH: Wait.  Do we ever execute this section, or is ARG always of 
6420              fixed type?? */
6421           int j;
6422           struct type *field_type
6423             = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
6424
6425           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
6426             {
6427               if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
6428                                      fld_offset
6429                                      + TYPE_FIELD_BITPOS (field_type, j) / 8,
6430                                      field_type_p, byte_offset_p,
6431                                      bit_offset_p, bit_size_p, index_p))
6432                 return 1;
6433             }
6434         }
6435       else if (index_p != NULL)
6436         *index_p += 1;
6437     }
6438   return 0;
6439 }
6440
6441 /* Number of user-visible fields in record type TYPE.  */
6442
6443 static int
6444 num_visible_fields (struct type *type)
6445 {
6446   int n;
6447
6448   n = 0;
6449   find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
6450   return n;
6451 }
6452
6453 /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
6454    and search in it assuming it has (class) type TYPE.
6455    If found, return value, else return NULL.
6456
6457    Searches recursively through wrapper fields (e.g., '_parent').  */
6458
6459 static struct value *
6460 ada_search_struct_field (char *name, struct value *arg, int offset,
6461                          struct type *type)
6462 {
6463   int i;
6464
6465   type = ada_check_typedef (type);
6466   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6467     {
6468       char *t_field_name = TYPE_FIELD_NAME (type, i);
6469
6470       if (t_field_name == NULL)
6471         continue;
6472
6473       else if (field_name_match (t_field_name, name))
6474         return ada_value_primitive_field (arg, offset, i, type);
6475
6476       else if (ada_is_wrapper_field (type, i))
6477         {
6478           struct value *v =     /* Do not let indent join lines here.  */
6479             ada_search_struct_field (name, arg,
6480                                      offset + TYPE_FIELD_BITPOS (type, i) / 8,
6481                                      TYPE_FIELD_TYPE (type, i));
6482
6483           if (v != NULL)
6484             return v;
6485         }
6486
6487       else if (ada_is_variant_part (type, i))
6488         {
6489           /* PNH: Do we ever get here?  See find_struct_field.  */
6490           int j;
6491           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
6492                                                                         i));
6493           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
6494
6495           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
6496             {
6497               struct value *v = ada_search_struct_field /* Force line
6498                                                            break.  */
6499                 (name, arg,
6500                  var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
6501                  TYPE_FIELD_TYPE (field_type, j));
6502
6503               if (v != NULL)
6504                 return v;
6505             }
6506         }
6507     }
6508   return NULL;
6509 }
6510
6511 static struct value *ada_index_struct_field_1 (int *, struct value *,
6512                                                int, struct type *);
6513
6514
6515 /* Return field #INDEX in ARG, where the index is that returned by
6516  * find_struct_field through its INDEX_P argument.  Adjust the address
6517  * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
6518  * If found, return value, else return NULL.  */
6519
6520 static struct value *
6521 ada_index_struct_field (int index, struct value *arg, int offset,
6522                         struct type *type)
6523 {
6524   return ada_index_struct_field_1 (&index, arg, offset, type);
6525 }
6526
6527
6528 /* Auxiliary function for ada_index_struct_field.  Like
6529  * ada_index_struct_field, but takes index from *INDEX_P and modifies
6530  * *INDEX_P.  */
6531
6532 static struct value *
6533 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
6534                           struct type *type)
6535 {
6536   int i;
6537   type = ada_check_typedef (type);
6538
6539   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6540     {
6541       if (TYPE_FIELD_NAME (type, i) == NULL)
6542         continue;
6543       else if (ada_is_wrapper_field (type, i))
6544         {
6545           struct value *v =     /* Do not let indent join lines here.  */
6546             ada_index_struct_field_1 (index_p, arg,
6547                                       offset + TYPE_FIELD_BITPOS (type, i) / 8,
6548                                       TYPE_FIELD_TYPE (type, i));
6549
6550           if (v != NULL)
6551             return v;
6552         }
6553
6554       else if (ada_is_variant_part (type, i))
6555         {
6556           /* PNH: Do we ever get here?  See ada_search_struct_field,
6557              find_struct_field.  */
6558           error (_("Cannot assign this kind of variant record"));
6559         }
6560       else if (*index_p == 0)
6561         return ada_value_primitive_field (arg, offset, i, type);
6562       else
6563         *index_p -= 1;
6564     }
6565   return NULL;
6566 }
6567
6568 /* Given ARG, a value of type (pointer or reference to a)*
6569    structure/union, extract the component named NAME from the ultimate
6570    target structure/union and return it as a value with its
6571    appropriate type.
6572
6573    The routine searches for NAME among all members of the structure itself
6574    and (recursively) among all members of any wrapper members
6575    (e.g., '_parent').
6576
6577    If NO_ERR, then simply return NULL in case of error, rather than 
6578    calling error.  */
6579
6580 struct value *
6581 ada_value_struct_elt (struct value *arg, char *name, int no_err)
6582 {
6583   struct type *t, *t1;
6584   struct value *v;
6585
6586   v = NULL;
6587   t1 = t = ada_check_typedef (value_type (arg));
6588   if (TYPE_CODE (t) == TYPE_CODE_REF)
6589     {
6590       t1 = TYPE_TARGET_TYPE (t);
6591       if (t1 == NULL)
6592         goto BadValue;
6593       t1 = ada_check_typedef (t1);
6594       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
6595         {
6596           arg = coerce_ref (arg);
6597           t = t1;
6598         }
6599     }
6600
6601   while (TYPE_CODE (t) == TYPE_CODE_PTR)
6602     {
6603       t1 = TYPE_TARGET_TYPE (t);
6604       if (t1 == NULL)
6605         goto BadValue;
6606       t1 = ada_check_typedef (t1);
6607       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
6608         {
6609           arg = value_ind (arg);
6610           t = t1;
6611         }
6612       else
6613         break;
6614     }
6615
6616   if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
6617     goto BadValue;
6618
6619   if (t1 == t)
6620     v = ada_search_struct_field (name, arg, 0, t);
6621   else
6622     {
6623       int bit_offset, bit_size, byte_offset;
6624       struct type *field_type;
6625       CORE_ADDR address;
6626
6627       if (TYPE_CODE (t) == TYPE_CODE_PTR)
6628         address = value_as_address (arg);
6629       else
6630         address = unpack_pointer (t, value_contents (arg));
6631
6632       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL, address, NULL, 1);
6633       if (find_struct_field (name, t1, 0,
6634                              &field_type, &byte_offset, &bit_offset,
6635                              &bit_size, NULL))
6636         {
6637           if (bit_size != 0)
6638             {
6639               if (TYPE_CODE (t) == TYPE_CODE_REF)
6640                 arg = ada_coerce_ref (arg);
6641               else
6642                 arg = ada_value_ind (arg);
6643               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
6644                                                   bit_offset, bit_size,
6645                                                   field_type);
6646             }
6647           else
6648             v = value_at_lazy (field_type, address + byte_offset);
6649         }
6650     }
6651
6652   if (v != NULL || no_err)
6653     return v;
6654   else
6655     error (_("There is no member named %s."), name);
6656
6657  BadValue:
6658   if (no_err)
6659     return NULL;
6660   else
6661     error (_("Attempt to extract a component of "
6662              "a value that is not a record."));
6663 }
6664
6665 /* Given a type TYPE, look up the type of the component of type named NAME.
6666    If DISPP is non-null, add its byte displacement from the beginning of a
6667    structure (pointed to by a value) of type TYPE to *DISPP (does not
6668    work for packed fields).
6669
6670    Matches any field whose name has NAME as a prefix, possibly
6671    followed by "___".
6672
6673    TYPE can be either a struct or union.  If REFOK, TYPE may also 
6674    be a (pointer or reference)+ to a struct or union, and the
6675    ultimate target type will be searched.
6676
6677    Looks recursively into variant clauses and parent types.
6678
6679    If NOERR is nonzero, return NULL if NAME is not suitably defined or
6680    TYPE is not a type of the right kind.  */
6681
6682 static struct type *
6683 ada_lookup_struct_elt_type (struct type *type, char *name, int refok,
6684                             int noerr, int *dispp)
6685 {
6686   int i;
6687
6688   if (name == NULL)
6689     goto BadName;
6690
6691   if (refok && type != NULL)
6692     while (1)
6693       {
6694         type = ada_check_typedef (type);
6695         if (TYPE_CODE (type) != TYPE_CODE_PTR
6696             && TYPE_CODE (type) != TYPE_CODE_REF)
6697           break;
6698         type = TYPE_TARGET_TYPE (type);
6699       }
6700
6701   if (type == NULL
6702       || (TYPE_CODE (type) != TYPE_CODE_STRUCT
6703           && TYPE_CODE (type) != TYPE_CODE_UNION))
6704     {
6705       if (noerr)
6706         return NULL;
6707       else
6708         {
6709           target_terminal_ours ();
6710           gdb_flush (gdb_stdout);
6711           if (type == NULL)
6712             error (_("Type (null) is not a structure or union type"));
6713           else
6714             {
6715               /* XXX: type_sprint */
6716               fprintf_unfiltered (gdb_stderr, _("Type "));
6717               type_print (type, "", gdb_stderr, -1);
6718               error (_(" is not a structure or union type"));
6719             }
6720         }
6721     }
6722
6723   type = to_static_fixed_type (type);
6724
6725   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6726     {
6727       char *t_field_name = TYPE_FIELD_NAME (type, i);
6728       struct type *t;
6729       int disp;
6730
6731       if (t_field_name == NULL)
6732         continue;
6733
6734       else if (field_name_match (t_field_name, name))
6735         {
6736           if (dispp != NULL)
6737             *dispp += TYPE_FIELD_BITPOS (type, i) / 8;
6738           return ada_check_typedef (TYPE_FIELD_TYPE (type, i));
6739         }
6740
6741       else if (ada_is_wrapper_field (type, i))
6742         {
6743           disp = 0;
6744           t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
6745                                           0, 1, &disp);
6746           if (t != NULL)
6747             {
6748               if (dispp != NULL)
6749                 *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
6750               return t;
6751             }
6752         }
6753
6754       else if (ada_is_variant_part (type, i))
6755         {
6756           int j;
6757           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
6758                                                                         i));
6759
6760           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
6761             {
6762               /* FIXME pnh 2008/01/26: We check for a field that is
6763                  NOT wrapped in a struct, since the compiler sometimes
6764                  generates these for unchecked variant types.  Revisit
6765                  if the compiler changes this practice.  */
6766               char *v_field_name = TYPE_FIELD_NAME (field_type, j);
6767               disp = 0;
6768               if (v_field_name != NULL 
6769                   && field_name_match (v_field_name, name))
6770                 t = ada_check_typedef (TYPE_FIELD_TYPE (field_type, j));
6771               else
6772                 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type,
6773                                                                  j),
6774                                                 name, 0, 1, &disp);
6775
6776               if (t != NULL)
6777                 {
6778                   if (dispp != NULL)
6779                     *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
6780                   return t;
6781                 }
6782             }
6783         }
6784
6785     }
6786
6787 BadName:
6788   if (!noerr)
6789     {
6790       target_terminal_ours ();
6791       gdb_flush (gdb_stdout);
6792       if (name == NULL)
6793         {
6794           /* XXX: type_sprint */
6795           fprintf_unfiltered (gdb_stderr, _("Type "));
6796           type_print (type, "", gdb_stderr, -1);
6797           error (_(" has no component named <null>"));
6798         }
6799       else
6800         {
6801           /* XXX: type_sprint */
6802           fprintf_unfiltered (gdb_stderr, _("Type "));
6803           type_print (type, "", gdb_stderr, -1);
6804           error (_(" has no component named %s"), name);
6805         }
6806     }
6807
6808   return NULL;
6809 }
6810
6811 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
6812    within a value of type OUTER_TYPE, return true iff VAR_TYPE
6813    represents an unchecked union (that is, the variant part of a
6814    record that is named in an Unchecked_Union pragma).  */
6815
6816 static int
6817 is_unchecked_variant (struct type *var_type, struct type *outer_type)
6818 {
6819   char *discrim_name = ada_variant_discrim_name (var_type);
6820
6821   return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1, NULL) 
6822           == NULL);
6823 }
6824
6825
6826 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
6827    within a value of type OUTER_TYPE that is stored in GDB at
6828    OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE,
6829    numbering from 0) is applicable.  Returns -1 if none are.  */
6830
6831 int
6832 ada_which_variant_applies (struct type *var_type, struct type *outer_type,
6833                            const gdb_byte *outer_valaddr)
6834 {
6835   int others_clause;
6836   int i;
6837   char *discrim_name = ada_variant_discrim_name (var_type);
6838   struct value *outer;
6839   struct value *discrim;
6840   LONGEST discrim_val;
6841
6842   outer = value_from_contents_and_address (outer_type, outer_valaddr, 0);
6843   discrim = ada_value_struct_elt (outer, discrim_name, 1);
6844   if (discrim == NULL)
6845     return -1;
6846   discrim_val = value_as_long (discrim);
6847
6848   others_clause = -1;
6849   for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
6850     {
6851       if (ada_is_others_clause (var_type, i))
6852         others_clause = i;
6853       else if (ada_in_variant (discrim_val, var_type, i))
6854         return i;
6855     }
6856
6857   return others_clause;
6858 }
6859 \f
6860
6861
6862                                 /* Dynamic-Sized Records */
6863
6864 /* Strategy: The type ostensibly attached to a value with dynamic size
6865    (i.e., a size that is not statically recorded in the debugging
6866    data) does not accurately reflect the size or layout of the value.
6867    Our strategy is to convert these values to values with accurate,
6868    conventional types that are constructed on the fly.  */
6869
6870 /* There is a subtle and tricky problem here.  In general, we cannot
6871    determine the size of dynamic records without its data.  However,
6872    the 'struct value' data structure, which GDB uses to represent
6873    quantities in the inferior process (the target), requires the size
6874    of the type at the time of its allocation in order to reserve space
6875    for GDB's internal copy of the data.  That's why the
6876    'to_fixed_xxx_type' routines take (target) addresses as parameters,
6877    rather than struct value*s.
6878
6879    However, GDB's internal history variables ($1, $2, etc.) are
6880    struct value*s containing internal copies of the data that are not, in
6881    general, the same as the data at their corresponding addresses in
6882    the target.  Fortunately, the types we give to these values are all
6883    conventional, fixed-size types (as per the strategy described
6884    above), so that we don't usually have to perform the
6885    'to_fixed_xxx_type' conversions to look at their values.
6886    Unfortunately, there is one exception: if one of the internal
6887    history variables is an array whose elements are unconstrained
6888    records, then we will need to create distinct fixed types for each
6889    element selected.  */
6890
6891 /* The upshot of all of this is that many routines take a (type, host
6892    address, target address) triple as arguments to represent a value.
6893    The host address, if non-null, is supposed to contain an internal
6894    copy of the relevant data; otherwise, the program is to consult the
6895    target at the target address.  */
6896
6897 /* Assuming that VAL0 represents a pointer value, the result of
6898    dereferencing it.  Differs from value_ind in its treatment of
6899    dynamic-sized types.  */
6900
6901 struct value *
6902 ada_value_ind (struct value *val0)
6903 {
6904   struct value *val = unwrap_value (value_ind (val0));
6905
6906   return ada_to_fixed_value (val);
6907 }
6908
6909 /* The value resulting from dereferencing any "reference to"
6910    qualifiers on VAL0.  */
6911
6912 static struct value *
6913 ada_coerce_ref (struct value *val0)
6914 {
6915   if (TYPE_CODE (value_type (val0)) == TYPE_CODE_REF)
6916     {
6917       struct value *val = val0;
6918
6919       val = coerce_ref (val);
6920       val = unwrap_value (val);
6921       return ada_to_fixed_value (val);
6922     }
6923   else
6924     return val0;
6925 }
6926
6927 /* Return OFF rounded upward if necessary to a multiple of
6928    ALIGNMENT (a power of 2).  */
6929
6930 static unsigned int
6931 align_value (unsigned int off, unsigned int alignment)
6932 {
6933   return (off + alignment - 1) & ~(alignment - 1);
6934 }
6935
6936 /* Return the bit alignment required for field #F of template type TYPE.  */
6937
6938 static unsigned int
6939 field_alignment (struct type *type, int f)
6940 {
6941   const char *name = TYPE_FIELD_NAME (type, f);
6942   int len;
6943   int align_offset;
6944
6945   /* The field name should never be null, unless the debugging information
6946      is somehow malformed.  In this case, we assume the field does not
6947      require any alignment.  */
6948   if (name == NULL)
6949     return 1;
6950
6951   len = strlen (name);
6952
6953   if (!isdigit (name[len - 1]))
6954     return 1;
6955
6956   if (isdigit (name[len - 2]))
6957     align_offset = len - 2;
6958   else
6959     align_offset = len - 1;
6960
6961   if (align_offset < 7 || strncmp ("___XV", name + align_offset - 6, 5) != 0)
6962     return TARGET_CHAR_BIT;
6963
6964   return atoi (name + align_offset) * TARGET_CHAR_BIT;
6965 }
6966
6967 /* Find a symbol named NAME.  Ignores ambiguity.  */
6968
6969 struct symbol *
6970 ada_find_any_symbol (const char *name)
6971 {
6972   struct symbol *sym;
6973
6974   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
6975   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
6976     return sym;
6977
6978   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
6979   return sym;
6980 }
6981
6982 /* Find a type named NAME.  Ignores ambiguity.  This routine will look
6983    solely for types defined by debug info, it will not search the GDB
6984    primitive types.  */
6985
6986 struct type *
6987 ada_find_any_type (const char *name)
6988 {
6989   struct symbol *sym = ada_find_any_symbol (name);
6990
6991   if (sym != NULL)
6992     return SYMBOL_TYPE (sym);
6993
6994   return NULL;
6995 }
6996
6997 /* Given NAME and an associated BLOCK, search all symbols for
6998    NAME suffixed with  "___XR", which is the ``renaming'' symbol
6999    associated to NAME.  Return this symbol if found, return
7000    NULL otherwise.  */
7001
7002 struct symbol *
7003 ada_find_renaming_symbol (const char *name, struct block *block)
7004 {
7005   struct symbol *sym;
7006
7007   sym = find_old_style_renaming_symbol (name, block);
7008
7009   if (sym != NULL)
7010     return sym;
7011
7012   /* Not right yet.  FIXME pnh 7/20/2007.  */
7013   sym = ada_find_any_symbol (name);
7014   if (sym != NULL && strstr (SYMBOL_LINKAGE_NAME (sym), "___XR") != NULL)
7015     return sym;
7016   else
7017     return NULL;
7018 }
7019
7020 static struct symbol *
7021 find_old_style_renaming_symbol (const char *name, struct block *block)
7022 {
7023   const struct symbol *function_sym = block_linkage_function (block);
7024   char *rename;
7025
7026   if (function_sym != NULL)
7027     {
7028       /* If the symbol is defined inside a function, NAME is not fully
7029          qualified.  This means we need to prepend the function name
7030          as well as adding the ``___XR'' suffix to build the name of
7031          the associated renaming symbol.  */
7032       char *function_name = SYMBOL_LINKAGE_NAME (function_sym);
7033       /* Function names sometimes contain suffixes used
7034          for instance to qualify nested subprograms.  When building
7035          the XR type name, we need to make sure that this suffix is
7036          not included.  So do not include any suffix in the function
7037          name length below.  */
7038       int function_name_len = ada_name_prefix_len (function_name);
7039       const int rename_len = function_name_len + 2      /*  "__" */
7040         + strlen (name) + 6 /* "___XR\0" */ ;
7041
7042       /* Strip the suffix if necessary.  */
7043       ada_remove_trailing_digits (function_name, &function_name_len);
7044       ada_remove_po_subprogram_suffix (function_name, &function_name_len);
7045       ada_remove_Xbn_suffix (function_name, &function_name_len);
7046
7047       /* Library-level functions are a special case, as GNAT adds
7048          a ``_ada_'' prefix to the function name to avoid namespace
7049          pollution.  However, the renaming symbols themselves do not
7050          have this prefix, so we need to skip this prefix if present.  */
7051       if (function_name_len > 5 /* "_ada_" */
7052           && strstr (function_name, "_ada_") == function_name)
7053         {
7054           function_name += 5;
7055           function_name_len -= 5;
7056         }
7057
7058       rename = (char *) alloca (rename_len * sizeof (char));
7059       strncpy (rename, function_name, function_name_len);
7060       xsnprintf (rename + function_name_len, rename_len - function_name_len,
7061                  "__%s___XR", name);
7062     }
7063   else
7064     {
7065       const int rename_len = strlen (name) + 6;
7066
7067       rename = (char *) alloca (rename_len * sizeof (char));
7068       xsnprintf (rename, rename_len * sizeof (char), "%s___XR", name);
7069     }
7070
7071   return ada_find_any_symbol (rename);
7072 }
7073
7074 /* Because of GNAT encoding conventions, several GDB symbols may match a
7075    given type name.  If the type denoted by TYPE0 is to be preferred to
7076    that of TYPE1 for purposes of type printing, return non-zero;
7077    otherwise return 0.  */
7078
7079 int
7080 ada_prefer_type (struct type *type0, struct type *type1)
7081 {
7082   if (type1 == NULL)
7083     return 1;
7084   else if (type0 == NULL)
7085     return 0;
7086   else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
7087     return 1;
7088   else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
7089     return 0;
7090   else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
7091     return 1;
7092   else if (ada_is_constrained_packed_array_type (type0))
7093     return 1;
7094   else if (ada_is_array_descriptor_type (type0)
7095            && !ada_is_array_descriptor_type (type1))
7096     return 1;
7097   else
7098     {
7099       const char *type0_name = type_name_no_tag (type0);
7100       const char *type1_name = type_name_no_tag (type1);
7101
7102       if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7103           && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7104         return 1;
7105     }
7106   return 0;
7107 }
7108
7109 /* The name of TYPE, which is either its TYPE_NAME, or, if that is
7110    null, its TYPE_TAG_NAME.  Null if TYPE is null.  */
7111
7112 char *
7113 ada_type_name (struct type *type)
7114 {
7115   if (type == NULL)
7116     return NULL;
7117   else if (TYPE_NAME (type) != NULL)
7118     return TYPE_NAME (type);
7119   else
7120     return TYPE_TAG_NAME (type);
7121 }
7122
7123 /* Search the list of "descriptive" types associated to TYPE for a type
7124    whose name is NAME.  */
7125
7126 static struct type *
7127 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7128 {
7129   struct type *result;
7130
7131   /* If there no descriptive-type info, then there is no parallel type
7132      to be found.  */
7133   if (!HAVE_GNAT_AUX_INFO (type))
7134     return NULL;
7135
7136   result = TYPE_DESCRIPTIVE_TYPE (type);
7137   while (result != NULL)
7138     {
7139       char *result_name = ada_type_name (result);
7140
7141       if (result_name == NULL)
7142         {
7143           warning (_("unexpected null name on descriptive type"));
7144           return NULL;
7145         }
7146
7147       /* If the names match, stop.  */
7148       if (strcmp (result_name, name) == 0)
7149         break;
7150
7151       /* Otherwise, look at the next item on the list, if any.  */
7152       if (HAVE_GNAT_AUX_INFO (result))
7153         result = TYPE_DESCRIPTIVE_TYPE (result);
7154       else
7155         result = NULL;
7156     }
7157
7158   /* If we didn't find a match, see whether this is a packed array.  With
7159      older compilers, the descriptive type information is either absent or
7160      irrelevant when it comes to packed arrays so the above lookup fails.
7161      Fall back to using a parallel lookup by name in this case.  */
7162   if (result == NULL && ada_is_constrained_packed_array_type (type))
7163     return ada_find_any_type (name);
7164
7165   return result;
7166 }
7167
7168 /* Find a parallel type to TYPE with the specified NAME, using the
7169    descriptive type taken from the debugging information, if available,
7170    and otherwise using the (slower) name-based method.  */
7171
7172 static struct type *
7173 ada_find_parallel_type_with_name (struct type *type, const char *name)
7174 {
7175   struct type *result = NULL;
7176
7177   if (HAVE_GNAT_AUX_INFO (type))
7178     result = find_parallel_type_by_descriptive_type (type, name);
7179   else
7180     result = ada_find_any_type (name);
7181
7182   return result;
7183 }
7184
7185 /* Same as above, but specify the name of the parallel type by appending
7186    SUFFIX to the name of TYPE.  */
7187
7188 struct type *
7189 ada_find_parallel_type (struct type *type, const char *suffix)
7190 {
7191   char *name, *typename = ada_type_name (type);
7192   int len;
7193
7194   if (typename == NULL)
7195     return NULL;
7196
7197   len = strlen (typename);
7198
7199   name = (char *) alloca (len + strlen (suffix) + 1);
7200
7201   strcpy (name, typename);
7202   strcpy (name + len, suffix);
7203
7204   return ada_find_parallel_type_with_name (type, name);
7205 }
7206
7207 /* If TYPE is a variable-size record type, return the corresponding template
7208    type describing its fields.  Otherwise, return NULL.  */
7209
7210 static struct type *
7211 dynamic_template_type (struct type *type)
7212 {
7213   type = ada_check_typedef (type);
7214
7215   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
7216       || ada_type_name (type) == NULL)
7217     return NULL;
7218   else
7219     {
7220       int len = strlen (ada_type_name (type));
7221
7222       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7223         return type;
7224       else
7225         return ada_find_parallel_type (type, "___XVE");
7226     }
7227 }
7228
7229 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7230    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */
7231
7232 static int
7233 is_dynamic_field (struct type *templ_type, int field_num)
7234 {
7235   const char *name = TYPE_FIELD_NAME (templ_type, field_num);
7236
7237   return name != NULL
7238     && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
7239     && strstr (name, "___XVL") != NULL;
7240 }
7241
7242 /* The index of the variant field of TYPE, or -1 if TYPE does not
7243    represent a variant record type.  */
7244
7245 static int
7246 variant_field_index (struct type *type)
7247 {
7248   int f;
7249
7250   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
7251     return -1;
7252
7253   for (f = 0; f < TYPE_NFIELDS (type); f += 1)
7254     {
7255       if (ada_is_variant_part (type, f))
7256         return f;
7257     }
7258   return -1;
7259 }
7260
7261 /* A record type with no fields.  */
7262
7263 static struct type *
7264 empty_record (struct type *template)
7265 {
7266   struct type *type = alloc_type_copy (template);
7267
7268   TYPE_CODE (type) = TYPE_CODE_STRUCT;
7269   TYPE_NFIELDS (type) = 0;
7270   TYPE_FIELDS (type) = NULL;
7271   INIT_CPLUS_SPECIFIC (type);
7272   TYPE_NAME (type) = "<empty>";
7273   TYPE_TAG_NAME (type) = NULL;
7274   TYPE_LENGTH (type) = 0;
7275   return type;
7276 }
7277
7278 /* An ordinary record type (with fixed-length fields) that describes
7279    the value of type TYPE at VALADDR or ADDRESS (see comments at
7280    the beginning of this section) VAL according to GNAT conventions.
7281    DVAL0 should describe the (portion of a) record that contains any
7282    necessary discriminants.  It should be NULL if value_type (VAL) is
7283    an outer-level type (i.e., as opposed to a branch of a variant.)  A
7284    variant field (unless unchecked) is replaced by a particular branch
7285    of the variant.
7286
7287    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7288    length are not statically known are discarded.  As a consequence,
7289    VALADDR, ADDRESS and DVAL0 are ignored.
7290
7291    NOTE: Limitations: For now, we assume that dynamic fields and
7292    variants occupy whole numbers of bytes.  However, they need not be
7293    byte-aligned.  */
7294
7295 struct type *
7296 ada_template_to_fixed_record_type_1 (struct type *type,
7297                                      const gdb_byte *valaddr,
7298                                      CORE_ADDR address, struct value *dval0,
7299                                      int keep_dynamic_fields)
7300 {
7301   struct value *mark = value_mark ();
7302   struct value *dval;
7303   struct type *rtype;
7304   int nfields, bit_len;
7305   int variant_field;
7306   long off;
7307   int fld_bit_len;
7308   int f;
7309
7310   /* Compute the number of fields in this record type that are going
7311      to be processed: unless keep_dynamic_fields, this includes only
7312      fields whose position and length are static will be processed.  */
7313   if (keep_dynamic_fields)
7314     nfields = TYPE_NFIELDS (type);
7315   else
7316     {
7317       nfields = 0;
7318       while (nfields < TYPE_NFIELDS (type)
7319              && !ada_is_variant_part (type, nfields)
7320              && !is_dynamic_field (type, nfields))
7321         nfields++;
7322     }
7323
7324   rtype = alloc_type_copy (type);
7325   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
7326   INIT_CPLUS_SPECIFIC (rtype);
7327   TYPE_NFIELDS (rtype) = nfields;
7328   TYPE_FIELDS (rtype) = (struct field *)
7329     TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7330   memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
7331   TYPE_NAME (rtype) = ada_type_name (type);
7332   TYPE_TAG_NAME (rtype) = NULL;
7333   TYPE_FIXED_INSTANCE (rtype) = 1;
7334
7335   off = 0;
7336   bit_len = 0;
7337   variant_field = -1;
7338
7339   for (f = 0; f < nfields; f += 1)
7340     {
7341       off = align_value (off, field_alignment (type, f))
7342         + TYPE_FIELD_BITPOS (type, f);
7343       TYPE_FIELD_BITPOS (rtype, f) = off;
7344       TYPE_FIELD_BITSIZE (rtype, f) = 0;
7345
7346       if (ada_is_variant_part (type, f))
7347         {
7348           variant_field = f;
7349           fld_bit_len = 0;
7350         }
7351       else if (is_dynamic_field (type, f))
7352         {
7353           const gdb_byte *field_valaddr = valaddr;
7354           CORE_ADDR field_address = address;
7355           struct type *field_type =
7356             TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f));
7357
7358           if (dval0 == NULL)
7359             {
7360               /* rtype's length is computed based on the run-time
7361                  value of discriminants.  If the discriminants are not
7362                  initialized, the type size may be completely bogus and
7363                  GDB may fail to allocate a value for it.  So check the
7364                  size first before creating the value.  */
7365               check_size (rtype);
7366               dval = value_from_contents_and_address (rtype, valaddr, address);
7367             }
7368           else
7369             dval = dval0;
7370
7371           /* If the type referenced by this field is an aligner type, we need
7372              to unwrap that aligner type, because its size might not be set.
7373              Keeping the aligner type would cause us to compute the wrong
7374              size for this field, impacting the offset of the all the fields
7375              that follow this one.  */
7376           if (ada_is_aligner_type (field_type))
7377             {
7378               long field_offset = TYPE_FIELD_BITPOS (field_type, f);
7379
7380               field_valaddr = cond_offset_host (field_valaddr, field_offset);
7381               field_address = cond_offset_target (field_address, field_offset);
7382               field_type = ada_aligned_type (field_type);
7383             }
7384
7385           field_valaddr = cond_offset_host (field_valaddr,
7386                                             off / TARGET_CHAR_BIT);
7387           field_address = cond_offset_target (field_address,
7388                                               off / TARGET_CHAR_BIT);
7389
7390           /* Get the fixed type of the field.  Note that, in this case,
7391              we do not want to get the real type out of the tag: if
7392              the current field is the parent part of a tagged record,
7393              we will get the tag of the object.  Clearly wrong: the real
7394              type of the parent is not the real type of the child.  We
7395              would end up in an infinite loop.  */
7396           field_type = ada_get_base_type (field_type);
7397           field_type = ada_to_fixed_type (field_type, field_valaddr,
7398                                           field_address, dval, 0);
7399           /* If the field size is already larger than the maximum
7400              object size, then the record itself will necessarily
7401              be larger than the maximum object size.  We need to make
7402              this check now, because the size might be so ridiculously
7403              large (due to an uninitialized variable in the inferior)
7404              that it would cause an overflow when adding it to the
7405              record size.  */
7406           check_size (field_type);
7407
7408           TYPE_FIELD_TYPE (rtype, f) = field_type;
7409           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7410           /* The multiplication can potentially overflow.  But because
7411              the field length has been size-checked just above, and
7412              assuming that the maximum size is a reasonable value,
7413              an overflow should not happen in practice.  So rather than
7414              adding overflow recovery code to this already complex code,
7415              we just assume that it's not going to happen.  */
7416           fld_bit_len =
7417             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
7418         }
7419       else
7420         {
7421           struct type *field_type = TYPE_FIELD_TYPE (type, f);
7422
7423           /* If our field is a typedef type (most likely a typedef of
7424              a fat pointer, encoding an array access), then we need to
7425              look at its target type to determine its characteristics.
7426              In particular, we would miscompute the field size if we took
7427              the size of the typedef (zero), instead of the size of
7428              the target type.  */
7429           if (TYPE_CODE (field_type) == TYPE_CODE_TYPEDEF)
7430             field_type = ada_typedef_target_type (field_type);
7431
7432           TYPE_FIELD_TYPE (rtype, f) = field_type;
7433           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7434           if (TYPE_FIELD_BITSIZE (type, f) > 0)
7435             fld_bit_len =
7436               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7437           else
7438             fld_bit_len =
7439               TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
7440         }
7441       if (off + fld_bit_len > bit_len)
7442         bit_len = off + fld_bit_len;
7443       off += fld_bit_len;
7444       TYPE_LENGTH (rtype) =
7445         align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7446     }
7447
7448   /* We handle the variant part, if any, at the end because of certain
7449      odd cases in which it is re-ordered so as NOT to be the last field of
7450      the record.  This can happen in the presence of representation
7451      clauses.  */
7452   if (variant_field >= 0)
7453     {
7454       struct type *branch_type;
7455
7456       off = TYPE_FIELD_BITPOS (rtype, variant_field);
7457
7458       if (dval0 == NULL)
7459         dval = value_from_contents_and_address (rtype, valaddr, address);
7460       else
7461         dval = dval0;
7462
7463       branch_type =
7464         to_fixed_variant_branch_type
7465         (TYPE_FIELD_TYPE (type, variant_field),
7466          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7467          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7468       if (branch_type == NULL)
7469         {
7470           for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
7471             TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
7472           TYPE_NFIELDS (rtype) -= 1;
7473         }
7474       else
7475         {
7476           TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
7477           TYPE_FIELD_NAME (rtype, variant_field) = "S";
7478           fld_bit_len =
7479             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
7480             TARGET_CHAR_BIT;
7481           if (off + fld_bit_len > bit_len)
7482             bit_len = off + fld_bit_len;
7483           TYPE_LENGTH (rtype) =
7484             align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7485         }
7486     }
7487
7488   /* According to exp_dbug.ads, the size of TYPE for variable-size records
7489      should contain the alignment of that record, which should be a strictly
7490      positive value.  If null or negative, then something is wrong, most
7491      probably in the debug info.  In that case, we don't round up the size
7492      of the resulting type.  If this record is not part of another structure,
7493      the current RTYPE length might be good enough for our purposes.  */
7494   if (TYPE_LENGTH (type) <= 0)
7495     {
7496       if (TYPE_NAME (rtype))
7497         warning (_("Invalid type size for `%s' detected: %d."),
7498                  TYPE_NAME (rtype), TYPE_LENGTH (type));
7499       else
7500         warning (_("Invalid type size for <unnamed> detected: %d."),
7501                  TYPE_LENGTH (type));
7502     }
7503   else
7504     {
7505       TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype),
7506                                          TYPE_LENGTH (type));
7507     }
7508
7509   value_free_to_mark (mark);
7510   if (TYPE_LENGTH (rtype) > varsize_limit)
7511     error (_("record type with dynamic size is larger than varsize-limit"));
7512   return rtype;
7513 }
7514
7515 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7516    of 1.  */
7517
7518 static struct type *
7519 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7520                                CORE_ADDR address, struct value *dval0)
7521 {
7522   return ada_template_to_fixed_record_type_1 (type, valaddr,
7523                                               address, dval0, 1);
7524 }
7525
7526 /* An ordinary record type in which ___XVL-convention fields and
7527    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7528    static approximations, containing all possible fields.  Uses
7529    no runtime values.  Useless for use in values, but that's OK,
7530    since the results are used only for type determinations.   Works on both
7531    structs and unions.  Representation note: to save space, we memorize
7532    the result of this function in the TYPE_TARGET_TYPE of the
7533    template type.  */
7534
7535 static struct type *
7536 template_to_static_fixed_type (struct type *type0)
7537 {
7538   struct type *type;
7539   int nfields;
7540   int f;
7541
7542   if (TYPE_TARGET_TYPE (type0) != NULL)
7543     return TYPE_TARGET_TYPE (type0);
7544
7545   nfields = TYPE_NFIELDS (type0);
7546   type = type0;
7547
7548   for (f = 0; f < nfields; f += 1)
7549     {
7550       struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type0, f));
7551       struct type *new_type;
7552
7553       if (is_dynamic_field (type0, f))
7554         new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
7555       else
7556         new_type = static_unwrap_type (field_type);
7557       if (type == type0 && new_type != field_type)
7558         {
7559           TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
7560           TYPE_CODE (type) = TYPE_CODE (type0);
7561           INIT_CPLUS_SPECIFIC (type);
7562           TYPE_NFIELDS (type) = nfields;
7563           TYPE_FIELDS (type) = (struct field *)
7564             TYPE_ALLOC (type, nfields * sizeof (struct field));
7565           memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
7566                   sizeof (struct field) * nfields);
7567           TYPE_NAME (type) = ada_type_name (type0);
7568           TYPE_TAG_NAME (type) = NULL;
7569           TYPE_FIXED_INSTANCE (type) = 1;
7570           TYPE_LENGTH (type) = 0;
7571         }
7572       TYPE_FIELD_TYPE (type, f) = new_type;
7573       TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
7574     }
7575   return type;
7576 }
7577
7578 /* Given an object of type TYPE whose contents are at VALADDR and
7579    whose address in memory is ADDRESS, returns a revision of TYPE,
7580    which should be a non-dynamic-sized record, in which the variant
7581    part, if any, is replaced with the appropriate branch.  Looks
7582    for discriminant values in DVAL0, which can be NULL if the record
7583    contains the necessary discriminant values.  */
7584
7585 static struct type *
7586 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
7587                                    CORE_ADDR address, struct value *dval0)
7588 {
7589   struct value *mark = value_mark ();
7590   struct value *dval;
7591   struct type *rtype;
7592   struct type *branch_type;
7593   int nfields = TYPE_NFIELDS (type);
7594   int variant_field = variant_field_index (type);
7595
7596   if (variant_field == -1)
7597     return type;
7598
7599   if (dval0 == NULL)
7600     dval = value_from_contents_and_address (type, valaddr, address);
7601   else
7602     dval = dval0;
7603
7604   rtype = alloc_type_copy (type);
7605   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
7606   INIT_CPLUS_SPECIFIC (rtype);
7607   TYPE_NFIELDS (rtype) = nfields;
7608   TYPE_FIELDS (rtype) =
7609     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7610   memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
7611           sizeof (struct field) * nfields);
7612   TYPE_NAME (rtype) = ada_type_name (type);
7613   TYPE_TAG_NAME (rtype) = NULL;
7614   TYPE_FIXED_INSTANCE (rtype) = 1;
7615   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
7616
7617   branch_type = to_fixed_variant_branch_type
7618     (TYPE_FIELD_TYPE (type, variant_field),
7619      cond_offset_host (valaddr,
7620                        TYPE_FIELD_BITPOS (type, variant_field)
7621                        / TARGET_CHAR_BIT),
7622      cond_offset_target (address,
7623                          TYPE_FIELD_BITPOS (type, variant_field)
7624                          / TARGET_CHAR_BIT), dval);
7625   if (branch_type == NULL)
7626     {
7627       int f;
7628
7629       for (f = variant_field + 1; f < nfields; f += 1)
7630         TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
7631       TYPE_NFIELDS (rtype) -= 1;
7632     }
7633   else
7634     {
7635       TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
7636       TYPE_FIELD_NAME (rtype, variant_field) = "S";
7637       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
7638       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
7639     }
7640   TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));
7641
7642   value_free_to_mark (mark);
7643   return rtype;
7644 }
7645
7646 /* An ordinary record type (with fixed-length fields) that describes
7647    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
7648    beginning of this section].   Any necessary discriminants' values
7649    should be in DVAL, a record value; it may be NULL if the object
7650    at ADDR itself contains any necessary discriminant values.
7651    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
7652    values from the record are needed.  Except in the case that DVAL,
7653    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
7654    unchecked) is replaced by a particular branch of the variant.
7655
7656    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
7657    is questionable and may be removed.  It can arise during the
7658    processing of an unconstrained-array-of-record type where all the
7659    variant branches have exactly the same size.  This is because in
7660    such cases, the compiler does not bother to use the XVS convention
7661    when encoding the record.  I am currently dubious of this
7662    shortcut and suspect the compiler should be altered.  FIXME.  */
7663
7664 static struct type *
7665 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
7666                       CORE_ADDR address, struct value *dval)
7667 {
7668   struct type *templ_type;
7669
7670   if (TYPE_FIXED_INSTANCE (type0))
7671     return type0;
7672
7673   templ_type = dynamic_template_type (type0);
7674
7675   if (templ_type != NULL)
7676     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
7677   else if (variant_field_index (type0) >= 0)
7678     {
7679       if (dval == NULL && valaddr == NULL && address == 0)
7680         return type0;
7681       return to_record_with_fixed_variant_part (type0, valaddr, address,
7682                                                 dval);
7683     }
7684   else
7685     {
7686       TYPE_FIXED_INSTANCE (type0) = 1;
7687       return type0;
7688     }
7689
7690 }
7691
7692 /* An ordinary record type (with fixed-length fields) that describes
7693    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
7694    union type.  Any necessary discriminants' values should be in DVAL,
7695    a record value.  That is, this routine selects the appropriate
7696    branch of the union at ADDR according to the discriminant value
7697    indicated in the union's type name.  Returns VAR_TYPE0 itself if
7698    it represents a variant subject to a pragma Unchecked_Union.  */
7699
7700 static struct type *
7701 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
7702                               CORE_ADDR address, struct value *dval)
7703 {
7704   int which;
7705   struct type *templ_type;
7706   struct type *var_type;
7707
7708   if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
7709     var_type = TYPE_TARGET_TYPE (var_type0);
7710   else
7711     var_type = var_type0;
7712
7713   templ_type = ada_find_parallel_type (var_type, "___XVU");
7714
7715   if (templ_type != NULL)
7716     var_type = templ_type;
7717
7718   if (is_unchecked_variant (var_type, value_type (dval)))
7719       return var_type0;
7720   which =
7721     ada_which_variant_applies (var_type,
7722                                value_type (dval), value_contents (dval));
7723
7724   if (which < 0)
7725     return empty_record (var_type);
7726   else if (is_dynamic_field (var_type, which))
7727     return to_fixed_record_type
7728       (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
7729        valaddr, address, dval);
7730   else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
7731     return
7732       to_fixed_record_type
7733       (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
7734   else
7735     return TYPE_FIELD_TYPE (var_type, which);
7736 }
7737
7738 /* Assuming that TYPE0 is an array type describing the type of a value
7739    at ADDR, and that DVAL describes a record containing any
7740    discriminants used in TYPE0, returns a type for the value that
7741    contains no dynamic components (that is, no components whose sizes
7742    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
7743    true, gives an error message if the resulting type's size is over
7744    varsize_limit.  */
7745
7746 static struct type *
7747 to_fixed_array_type (struct type *type0, struct value *dval,
7748                      int ignore_too_big)
7749 {
7750   struct type *index_type_desc;
7751   struct type *result;
7752   int constrained_packed_array_p;
7753
7754   type0 = ada_check_typedef (type0);
7755   if (TYPE_FIXED_INSTANCE (type0))
7756     return type0;
7757
7758   constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
7759   if (constrained_packed_array_p)
7760     type0 = decode_constrained_packed_array_type (type0);
7761
7762   index_type_desc = ada_find_parallel_type (type0, "___XA");
7763   ada_fixup_array_indexes_type (index_type_desc);
7764   if (index_type_desc == NULL)
7765     {
7766       struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
7767
7768       /* NOTE: elt_type---the fixed version of elt_type0---should never
7769          depend on the contents of the array in properly constructed
7770          debugging data.  */
7771       /* Create a fixed version of the array element type.
7772          We're not providing the address of an element here,
7773          and thus the actual object value cannot be inspected to do
7774          the conversion.  This should not be a problem, since arrays of
7775          unconstrained objects are not allowed.  In particular, all
7776          the elements of an array of a tagged type should all be of
7777          the same type specified in the debugging info.  No need to
7778          consult the object tag.  */
7779       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
7780
7781       /* Make sure we always create a new array type when dealing with
7782          packed array types, since we're going to fix-up the array
7783          type length and element bitsize a little further down.  */
7784       if (elt_type0 == elt_type && !constrained_packed_array_p)
7785         result = type0;
7786       else
7787         result = create_array_type (alloc_type_copy (type0),
7788                                     elt_type, TYPE_INDEX_TYPE (type0));
7789     }
7790   else
7791     {
7792       int i;
7793       struct type *elt_type0;
7794
7795       elt_type0 = type0;
7796       for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
7797         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
7798
7799       /* NOTE: result---the fixed version of elt_type0---should never
7800          depend on the contents of the array in properly constructed
7801          debugging data.  */
7802       /* Create a fixed version of the array element type.
7803          We're not providing the address of an element here,
7804          and thus the actual object value cannot be inspected to do
7805          the conversion.  This should not be a problem, since arrays of
7806          unconstrained objects are not allowed.  In particular, all
7807          the elements of an array of a tagged type should all be of
7808          the same type specified in the debugging info.  No need to
7809          consult the object tag.  */
7810       result =
7811         ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
7812
7813       elt_type0 = type0;
7814       for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
7815         {
7816           struct type *range_type =
7817             to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, i), dval);
7818
7819           result = create_array_type (alloc_type_copy (elt_type0),
7820                                       result, range_type);
7821           elt_type0 = TYPE_TARGET_TYPE (elt_type0);
7822         }
7823       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
7824         error (_("array type with dynamic size is larger than varsize-limit"));
7825     }
7826
7827   if (constrained_packed_array_p)
7828     {
7829       /* So far, the resulting type has been created as if the original
7830          type was a regular (non-packed) array type.  As a result, the
7831          bitsize of the array elements needs to be set again, and the array
7832          length needs to be recomputed based on that bitsize.  */
7833       int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
7834       int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
7835
7836       TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
7837       TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
7838       if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
7839         TYPE_LENGTH (result)++;
7840     }
7841
7842   TYPE_FIXED_INSTANCE (result) = 1;
7843   return result;
7844 }
7845
7846
7847 /* A standard type (containing no dynamically sized components)
7848    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
7849    DVAL describes a record containing any discriminants used in TYPE0,
7850    and may be NULL if there are none, or if the object of type TYPE at
7851    ADDRESS or in VALADDR contains these discriminants.
7852    
7853    If CHECK_TAG is not null, in the case of tagged types, this function
7854    attempts to locate the object's tag and use it to compute the actual
7855    type.  However, when ADDRESS is null, we cannot use it to determine the
7856    location of the tag, and therefore compute the tagged type's actual type.
7857    So we return the tagged type without consulting the tag.  */
7858    
7859 static struct type *
7860 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
7861                    CORE_ADDR address, struct value *dval, int check_tag)
7862 {
7863   type = ada_check_typedef (type);
7864   switch (TYPE_CODE (type))
7865     {
7866     default:
7867       return type;
7868     case TYPE_CODE_STRUCT:
7869       {
7870         struct type *static_type = to_static_fixed_type (type);
7871         struct type *fixed_record_type =
7872           to_fixed_record_type (type, valaddr, address, NULL);
7873
7874         /* If STATIC_TYPE is a tagged type and we know the object's address,
7875            then we can determine its tag, and compute the object's actual
7876            type from there.  Note that we have to use the fixed record
7877            type (the parent part of the record may have dynamic fields
7878            and the way the location of _tag is expressed may depend on
7879            them).  */
7880
7881         if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
7882           {
7883             struct type *real_type =
7884               type_from_tag (value_tag_from_contents_and_address
7885                              (fixed_record_type,
7886                               valaddr,
7887                               address));
7888
7889             if (real_type != NULL)
7890               return to_fixed_record_type (real_type, valaddr, address, NULL);
7891           }
7892
7893         /* Check to see if there is a parallel ___XVZ variable.
7894            If there is, then it provides the actual size of our type.  */
7895         else if (ada_type_name (fixed_record_type) != NULL)
7896           {
7897             char *name = ada_type_name (fixed_record_type);
7898             char *xvz_name = alloca (strlen (name) + 7 /* "___XVZ\0" */);
7899             int xvz_found = 0;
7900             LONGEST size;
7901
7902             xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
7903             size = get_int_var_value (xvz_name, &xvz_found);
7904             if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
7905               {
7906                 fixed_record_type = copy_type (fixed_record_type);
7907                 TYPE_LENGTH (fixed_record_type) = size;
7908
7909                 /* The FIXED_RECORD_TYPE may have be a stub.  We have
7910                    observed this when the debugging info is STABS, and
7911                    apparently it is something that is hard to fix.
7912
7913                    In practice, we don't need the actual type definition
7914                    at all, because the presence of the XVZ variable allows us
7915                    to assume that there must be a XVS type as well, which we
7916                    should be able to use later, when we need the actual type
7917                    definition.
7918
7919                    In the meantime, pretend that the "fixed" type we are
7920                    returning is NOT a stub, because this can cause trouble
7921                    when using this type to create new types targeting it.
7922                    Indeed, the associated creation routines often check
7923                    whether the target type is a stub and will try to replace
7924                    it, thus using a type with the wrong size.  This, in turn,
7925                    might cause the new type to have the wrong size too.
7926                    Consider the case of an array, for instance, where the size
7927                    of the array is computed from the number of elements in
7928                    our array multiplied by the size of its element.  */
7929                 TYPE_STUB (fixed_record_type) = 0;
7930               }
7931           }
7932         return fixed_record_type;
7933       }
7934     case TYPE_CODE_ARRAY:
7935       return to_fixed_array_type (type, dval, 1);
7936     case TYPE_CODE_UNION:
7937       if (dval == NULL)
7938         return type;
7939       else
7940         return to_fixed_variant_branch_type (type, valaddr, address, dval);
7941     }
7942 }
7943
7944 /* The same as ada_to_fixed_type_1, except that it preserves the type
7945    if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
7946
7947    The typedef layer needs be preserved in order to differentiate between
7948    arrays and array pointers when both types are implemented using the same
7949    fat pointer.  In the array pointer case, the pointer is encoded as
7950    a typedef of the pointer type.  For instance, considering:
7951
7952           type String_Access is access String;
7953           S1 : String_Access := null;
7954
7955    To the debugger, S1 is defined as a typedef of type String.  But
7956    to the user, it is a pointer.  So if the user tries to print S1,
7957    we should not dereference the array, but print the array address
7958    instead.
7959
7960    If we didn't preserve the typedef layer, we would lose the fact that
7961    the type is to be presented as a pointer (needs de-reference before
7962    being printed).  And we would also use the source-level type name.  */
7963
7964 struct type *
7965 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
7966                    CORE_ADDR address, struct value *dval, int check_tag)
7967
7968 {
7969   struct type *fixed_type =
7970     ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
7971
7972   /*  If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
7973       then preserve the typedef layer.
7974
7975       Implementation note: We can only check the main-type portion of
7976       the TYPE and FIXED_TYPE, because eliminating the typedef layer
7977       from TYPE now returns a type that has the same instance flags
7978       as TYPE.  For instance, if TYPE is a "typedef const", and its
7979       target type is a "struct", then the typedef elimination will return
7980       a "const" version of the target type.  See check_typedef for more
7981       details about how the typedef layer elimination is done.
7982
7983       brobecker/2010-11-19: It seems to me that the only case where it is
7984       useful to preserve the typedef layer is when dealing with fat pointers.
7985       Perhaps, we could add a check for that and preserve the typedef layer
7986       only in that situation.  But this seems unecessary so far, probably
7987       because we call check_typedef/ada_check_typedef pretty much everywhere.
7988       */
7989   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
7990       && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
7991           == TYPE_MAIN_TYPE (fixed_type)))
7992     return type;
7993
7994   return fixed_type;
7995 }
7996
7997 /* A standard (static-sized) type corresponding as well as possible to
7998    TYPE0, but based on no runtime data.  */
7999
8000 static struct type *
8001 to_static_fixed_type (struct type *type0)
8002 {
8003   struct type *type;
8004
8005   if (type0 == NULL)
8006     return NULL;
8007
8008   if (TYPE_FIXED_INSTANCE (type0))
8009     return type0;
8010
8011   type0 = ada_check_typedef (type0);
8012
8013   switch (TYPE_CODE (type0))
8014     {
8015     default:
8016       return type0;
8017     case TYPE_CODE_STRUCT:
8018       type = dynamic_template_type (type0);
8019       if (type != NULL)
8020         return template_to_static_fixed_type (type);
8021       else
8022         return template_to_static_fixed_type (type0);
8023     case TYPE_CODE_UNION:
8024       type = ada_find_parallel_type (type0, "___XVU");
8025       if (type != NULL)
8026         return template_to_static_fixed_type (type);
8027       else
8028         return template_to_static_fixed_type (type0);
8029     }
8030 }
8031
8032 /* A static approximation of TYPE with all type wrappers removed.  */
8033
8034 static struct type *
8035 static_unwrap_type (struct type *type)
8036 {
8037   if (ada_is_aligner_type (type))
8038     {
8039       struct type *type1 = TYPE_FIELD_TYPE (ada_check_typedef (type), 0);
8040       if (ada_type_name (type1) == NULL)
8041         TYPE_NAME (type1) = ada_type_name (type);
8042
8043       return static_unwrap_type (type1);
8044     }
8045   else
8046     {
8047       struct type *raw_real_type = ada_get_base_type (type);
8048
8049       if (raw_real_type == type)
8050         return type;
8051       else
8052         return to_static_fixed_type (raw_real_type);
8053     }
8054 }
8055
8056 /* In some cases, incomplete and private types require
8057    cross-references that are not resolved as records (for example,
8058       type Foo;
8059       type FooP is access Foo;
8060       V: FooP;
8061       type Foo is array ...;
8062    ).  In these cases, since there is no mechanism for producing
8063    cross-references to such types, we instead substitute for FooP a
8064    stub enumeration type that is nowhere resolved, and whose tag is
8065    the name of the actual type.  Call these types "non-record stubs".  */
8066
8067 /* A type equivalent to TYPE that is not a non-record stub, if one
8068    exists, otherwise TYPE.  */
8069
8070 struct type *
8071 ada_check_typedef (struct type *type)
8072 {
8073   if (type == NULL)
8074     return NULL;
8075
8076   /* If our type is a typedef type of a fat pointer, then we're done.
8077      We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8078      what allows us to distinguish between fat pointers that represent
8079      array types, and fat pointers that represent array access types
8080      (in both cases, the compiler implements them as fat pointers).  */
8081   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
8082       && is_thick_pntr (ada_typedef_target_type (type)))
8083     return type;
8084
8085   CHECK_TYPEDEF (type);
8086   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
8087       || !TYPE_STUB (type)
8088       || TYPE_TAG_NAME (type) == NULL)
8089     return type;
8090   else
8091     {
8092       char *name = TYPE_TAG_NAME (type);
8093       struct type *type1 = ada_find_any_type (name);
8094
8095       if (type1 == NULL)
8096         return type;
8097
8098       /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8099          stubs pointing to arrays, as we don't create symbols for array
8100          types, only for the typedef-to-array types).  If that's the case,
8101          strip the typedef layer.  */
8102       if (TYPE_CODE (type1) == TYPE_CODE_TYPEDEF)
8103         type1 = ada_check_typedef (type1);
8104
8105       return type1;
8106     }
8107 }
8108
8109 /* A value representing the data at VALADDR/ADDRESS as described by
8110    type TYPE0, but with a standard (static-sized) type that correctly
8111    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
8112    type, then return VAL0 [this feature is simply to avoid redundant
8113    creation of struct values].  */
8114
8115 static struct value *
8116 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8117                            struct value *val0)
8118 {
8119   struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8120
8121   if (type == type0 && val0 != NULL)
8122     return val0;
8123   else
8124     return value_from_contents_and_address (type, 0, address);
8125 }
8126
8127 /* A value representing VAL, but with a standard (static-sized) type
8128    that correctly describes it.  Does not necessarily create a new
8129    value.  */
8130
8131 struct value *
8132 ada_to_fixed_value (struct value *val)
8133 {
8134   return ada_to_fixed_value_create (value_type (val),
8135                                     value_address (val),
8136                                     val);
8137 }
8138 \f
8139
8140 /* Attributes */
8141
8142 /* Table mapping attribute numbers to names.
8143    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */
8144
8145 static const char *attribute_names[] = {
8146   "<?>",
8147
8148   "first",
8149   "last",
8150   "length",
8151   "image",
8152   "max",
8153   "min",
8154   "modulus",
8155   "pos",
8156   "size",
8157   "tag",
8158   "val",
8159   0
8160 };
8161
8162 const char *
8163 ada_attribute_name (enum exp_opcode n)
8164 {
8165   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8166     return attribute_names[n - OP_ATR_FIRST + 1];
8167   else
8168     return attribute_names[0];
8169 }
8170
8171 /* Evaluate the 'POS attribute applied to ARG.  */
8172
8173 static LONGEST
8174 pos_atr (struct value *arg)
8175 {
8176   struct value *val = coerce_ref (arg);
8177   struct type *type = value_type (val);
8178
8179   if (!discrete_type_p (type))
8180     error (_("'POS only defined on discrete types"));
8181
8182   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
8183     {
8184       int i;
8185       LONGEST v = value_as_long (val);
8186
8187       for (i = 0; i < TYPE_NFIELDS (type); i += 1)
8188         {
8189           if (v == TYPE_FIELD_BITPOS (type, i))
8190             return i;
8191         }
8192       error (_("enumeration value is invalid: can't find 'POS"));
8193     }
8194   else
8195     return value_as_long (val);
8196 }
8197
8198 static struct value *
8199 value_pos_atr (struct type *type, struct value *arg)
8200 {
8201   return value_from_longest (type, pos_atr (arg));
8202 }
8203
8204 /* Evaluate the TYPE'VAL attribute applied to ARG.  */
8205
8206 static struct value *
8207 value_val_atr (struct type *type, struct value *arg)
8208 {
8209   if (!discrete_type_p (type))
8210     error (_("'VAL only defined on discrete types"));
8211   if (!integer_type_p (value_type (arg)))
8212     error (_("'VAL requires integral argument"));
8213
8214   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
8215     {
8216       long pos = value_as_long (arg);
8217
8218       if (pos < 0 || pos >= TYPE_NFIELDS (type))
8219         error (_("argument to 'VAL out of range"));
8220       return value_from_longest (type, TYPE_FIELD_BITPOS (type, pos));
8221     }
8222   else
8223     return value_from_longest (type, value_as_long (arg));
8224 }
8225 \f
8226
8227                                 /* Evaluation */
8228
8229 /* True if TYPE appears to be an Ada character type.
8230    [At the moment, this is true only for Character and Wide_Character;
8231    It is a heuristic test that could stand improvement].  */
8232
8233 int
8234 ada_is_character_type (struct type *type)
8235 {
8236   const char *name;
8237
8238   /* If the type code says it's a character, then assume it really is,
8239      and don't check any further.  */
8240   if (TYPE_CODE (type) == TYPE_CODE_CHAR)
8241     return 1;
8242   
8243   /* Otherwise, assume it's a character type iff it is a discrete type
8244      with a known character type name.  */
8245   name = ada_type_name (type);
8246   return (name != NULL
8247           && (TYPE_CODE (type) == TYPE_CODE_INT
8248               || TYPE_CODE (type) == TYPE_CODE_RANGE)
8249           && (strcmp (name, "character") == 0
8250               || strcmp (name, "wide_character") == 0
8251               || strcmp (name, "wide_wide_character") == 0
8252               || strcmp (name, "unsigned char") == 0));
8253 }
8254
8255 /* True if TYPE appears to be an Ada string type.  */
8256
8257 int
8258 ada_is_string_type (struct type *type)
8259 {
8260   type = ada_check_typedef (type);
8261   if (type != NULL
8262       && TYPE_CODE (type) != TYPE_CODE_PTR
8263       && (ada_is_simple_array_type (type)
8264           || ada_is_array_descriptor_type (type))
8265       && ada_array_arity (type) == 1)
8266     {
8267       struct type *elttype = ada_array_element_type (type, 1);
8268
8269       return ada_is_character_type (elttype);
8270     }
8271   else
8272     return 0;
8273 }
8274
8275 /* The compiler sometimes provides a parallel XVS type for a given
8276    PAD type.  Normally, it is safe to follow the PAD type directly,
8277    but older versions of the compiler have a bug that causes the offset
8278    of its "F" field to be wrong.  Following that field in that case
8279    would lead to incorrect results, but this can be worked around
8280    by ignoring the PAD type and using the associated XVS type instead.
8281
8282    Set to True if the debugger should trust the contents of PAD types.
8283    Otherwise, ignore the PAD type if there is a parallel XVS type.  */
8284 static int trust_pad_over_xvs = 1;
8285
8286 /* True if TYPE is a struct type introduced by the compiler to force the
8287    alignment of a value.  Such types have a single field with a
8288    distinctive name.  */
8289
8290 int
8291 ada_is_aligner_type (struct type *type)
8292 {
8293   type = ada_check_typedef (type);
8294
8295   if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8296     return 0;
8297
8298   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
8299           && TYPE_NFIELDS (type) == 1
8300           && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
8301 }
8302
8303 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8304    the parallel type.  */
8305
8306 struct type *
8307 ada_get_base_type (struct type *raw_type)
8308 {
8309   struct type *real_type_namer;
8310   struct type *raw_real_type;
8311
8312   if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
8313     return raw_type;
8314
8315   if (ada_is_aligner_type (raw_type))
8316     /* The encoding specifies that we should always use the aligner type.
8317        So, even if this aligner type has an associated XVS type, we should
8318        simply ignore it.
8319
8320        According to the compiler gurus, an XVS type parallel to an aligner
8321        type may exist because of a stabs limitation.  In stabs, aligner
8322        types are empty because the field has a variable-sized type, and
8323        thus cannot actually be used as an aligner type.  As a result,
8324        we need the associated parallel XVS type to decode the type.
8325        Since the policy in the compiler is to not change the internal
8326        representation based on the debugging info format, we sometimes
8327        end up having a redundant XVS type parallel to the aligner type.  */
8328     return raw_type;
8329
8330   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8331   if (real_type_namer == NULL
8332       || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
8333       || TYPE_NFIELDS (real_type_namer) != 1)
8334     return raw_type;
8335
8336   if (TYPE_CODE (TYPE_FIELD_TYPE (real_type_namer, 0)) != TYPE_CODE_REF)
8337     {
8338       /* This is an older encoding form where the base type needs to be
8339          looked up by name.  We prefer the newer enconding because it is
8340          more efficient.  */
8341       raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
8342       if (raw_real_type == NULL)
8343         return raw_type;
8344       else
8345         return raw_real_type;
8346     }
8347
8348   /* The field in our XVS type is a reference to the base type.  */
8349   return TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (real_type_namer, 0));
8350 }
8351
8352 /* The type of value designated by TYPE, with all aligners removed.  */
8353
8354 struct type *
8355 ada_aligned_type (struct type *type)
8356 {
8357   if (ada_is_aligner_type (type))
8358     return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
8359   else
8360     return ada_get_base_type (type);
8361 }
8362
8363
8364 /* The address of the aligned value in an object at address VALADDR
8365    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */
8366
8367 const gdb_byte *
8368 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8369 {
8370   if (ada_is_aligner_type (type))
8371     return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
8372                                    valaddr +
8373                                    TYPE_FIELD_BITPOS (type,
8374                                                       0) / TARGET_CHAR_BIT);
8375   else
8376     return valaddr;
8377 }
8378
8379
8380
8381 /* The printed representation of an enumeration literal with encoded
8382    name NAME.  The value is good to the next call of ada_enum_name.  */
8383 const char *
8384 ada_enum_name (const char *name)
8385 {
8386   static char *result;
8387   static size_t result_len = 0;
8388   char *tmp;
8389
8390   /* First, unqualify the enumeration name:
8391      1. Search for the last '.' character.  If we find one, then skip
8392      all the preceding characters, the unqualified name starts
8393      right after that dot.
8394      2. Otherwise, we may be debugging on a target where the compiler
8395      translates dots into "__".  Search forward for double underscores,
8396      but stop searching when we hit an overloading suffix, which is
8397      of the form "__" followed by digits.  */
8398
8399   tmp = strrchr (name, '.');
8400   if (tmp != NULL)
8401     name = tmp + 1;
8402   else
8403     {
8404       while ((tmp = strstr (name, "__")) != NULL)
8405         {
8406           if (isdigit (tmp[2]))
8407             break;
8408           else
8409             name = tmp + 2;
8410         }
8411     }
8412
8413   if (name[0] == 'Q')
8414     {
8415       int v;
8416
8417       if (name[1] == 'U' || name[1] == 'W')
8418         {
8419           if (sscanf (name + 2, "%x", &v) != 1)
8420             return name;
8421         }
8422       else
8423         return name;
8424
8425       GROW_VECT (result, result_len, 16);
8426       if (isascii (v) && isprint (v))
8427         xsnprintf (result, result_len, "'%c'", v);
8428       else if (name[1] == 'U')
8429         xsnprintf (result, result_len, "[\"%02x\"]", v);
8430       else
8431         xsnprintf (result, result_len, "[\"%04x\"]", v);
8432
8433       return result;
8434     }
8435   else
8436     {
8437       tmp = strstr (name, "__");
8438       if (tmp == NULL)
8439         tmp = strstr (name, "$");
8440       if (tmp != NULL)
8441         {
8442           GROW_VECT (result, result_len, tmp - name + 1);
8443           strncpy (result, name, tmp - name);
8444           result[tmp - name] = '\0';
8445           return result;
8446         }
8447
8448       return name;
8449     }
8450 }
8451
8452 /* Evaluate the subexpression of EXP starting at *POS as for
8453    evaluate_type, updating *POS to point just past the evaluated
8454    expression.  */
8455
8456 static struct value *
8457 evaluate_subexp_type (struct expression *exp, int *pos)
8458 {
8459   return evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
8460 }
8461
8462 /* If VAL is wrapped in an aligner or subtype wrapper, return the
8463    value it wraps.  */
8464
8465 static struct value *
8466 unwrap_value (struct value *val)
8467 {
8468   struct type *type = ada_check_typedef (value_type (val));
8469
8470   if (ada_is_aligner_type (type))
8471     {
8472       struct value *v = ada_value_struct_elt (val, "F", 0);
8473       struct type *val_type = ada_check_typedef (value_type (v));
8474
8475       if (ada_type_name (val_type) == NULL)
8476         TYPE_NAME (val_type) = ada_type_name (type);
8477
8478       return unwrap_value (v);
8479     }
8480   else
8481     {
8482       struct type *raw_real_type =
8483         ada_check_typedef (ada_get_base_type (type));
8484
8485       /* If there is no parallel XVS or XVE type, then the value is
8486          already unwrapped.  Return it without further modification.  */
8487       if ((type == raw_real_type)
8488           && ada_find_parallel_type (type, "___XVE") == NULL)
8489         return val;
8490
8491       return
8492         coerce_unspec_val_to_type
8493         (val, ada_to_fixed_type (raw_real_type, 0,
8494                                  value_address (val),
8495                                  NULL, 1));
8496     }
8497 }
8498
8499 static struct value *
8500 cast_to_fixed (struct type *type, struct value *arg)
8501 {
8502   LONGEST val;
8503
8504   if (type == value_type (arg))
8505     return arg;
8506   else if (ada_is_fixed_point_type (value_type (arg)))
8507     val = ada_float_to_fixed (type,
8508                               ada_fixed_to_float (value_type (arg),
8509                                                   value_as_long (arg)));
8510   else
8511     {
8512       DOUBLEST argd = value_as_double (arg);
8513
8514       val = ada_float_to_fixed (type, argd);
8515     }
8516
8517   return value_from_longest (type, val);
8518 }
8519
8520 static struct value *
8521 cast_from_fixed (struct type *type, struct value *arg)
8522 {
8523   DOUBLEST val = ada_fixed_to_float (value_type (arg),
8524                                      value_as_long (arg));
8525
8526   return value_from_double (type, val);
8527 }
8528
8529 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
8530    return the converted value.  */
8531
8532 static struct value *
8533 coerce_for_assign (struct type *type, struct value *val)
8534 {
8535   struct type *type2 = value_type (val);
8536
8537   if (type == type2)
8538     return val;
8539
8540   type2 = ada_check_typedef (type2);
8541   type = ada_check_typedef (type);
8542
8543   if (TYPE_CODE (type2) == TYPE_CODE_PTR
8544       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
8545     {
8546       val = ada_value_ind (val);
8547       type2 = value_type (val);
8548     }
8549
8550   if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
8551       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
8552     {
8553       if (TYPE_LENGTH (type2) != TYPE_LENGTH (type)
8554           || TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
8555           != TYPE_LENGTH (TYPE_TARGET_TYPE (type2)))
8556         error (_("Incompatible types in assignment"));
8557       deprecated_set_value_type (val, type);
8558     }
8559   return val;
8560 }
8561
8562 static struct value *
8563 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
8564 {
8565   struct value *val;
8566   struct type *type1, *type2;
8567   LONGEST v, v1, v2;
8568
8569   arg1 = coerce_ref (arg1);
8570   arg2 = coerce_ref (arg2);
8571   type1 = get_base_type (ada_check_typedef (value_type (arg1)));
8572   type2 = get_base_type (ada_check_typedef (value_type (arg2)));
8573
8574   if (TYPE_CODE (type1) != TYPE_CODE_INT
8575       || TYPE_CODE (type2) != TYPE_CODE_INT)
8576     return value_binop (arg1, arg2, op);
8577
8578   switch (op)
8579     {
8580     case BINOP_MOD:
8581     case BINOP_DIV:
8582     case BINOP_REM:
8583       break;
8584     default:
8585       return value_binop (arg1, arg2, op);
8586     }
8587
8588   v2 = value_as_long (arg2);
8589   if (v2 == 0)
8590     error (_("second operand of %s must not be zero."), op_string (op));
8591
8592   if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
8593     return value_binop (arg1, arg2, op);
8594
8595   v1 = value_as_long (arg1);
8596   switch (op)
8597     {
8598     case BINOP_DIV:
8599       v = v1 / v2;
8600       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
8601         v += v > 0 ? -1 : 1;
8602       break;
8603     case BINOP_REM:
8604       v = v1 % v2;
8605       if (v * v1 < 0)
8606         v -= v2;
8607       break;
8608     default:
8609       /* Should not reach this point.  */
8610       v = 0;
8611     }
8612
8613   val = allocate_value (type1);
8614   store_unsigned_integer (value_contents_raw (val),
8615                           TYPE_LENGTH (value_type (val)),
8616                           gdbarch_byte_order (get_type_arch (type1)), v);
8617   return val;
8618 }
8619
8620 static int
8621 ada_value_equal (struct value *arg1, struct value *arg2)
8622 {
8623   if (ada_is_direct_array_type (value_type (arg1))
8624       || ada_is_direct_array_type (value_type (arg2)))
8625     {
8626       /* Automatically dereference any array reference before
8627          we attempt to perform the comparison.  */
8628       arg1 = ada_coerce_ref (arg1);
8629       arg2 = ada_coerce_ref (arg2);
8630       
8631       arg1 = ada_coerce_to_simple_array (arg1);
8632       arg2 = ada_coerce_to_simple_array (arg2);
8633       if (TYPE_CODE (value_type (arg1)) != TYPE_CODE_ARRAY
8634           || TYPE_CODE (value_type (arg2)) != TYPE_CODE_ARRAY)
8635         error (_("Attempt to compare array with non-array"));
8636       /* FIXME: The following works only for types whose
8637          representations use all bits (no padding or undefined bits)
8638          and do not have user-defined equality.  */
8639       return
8640         TYPE_LENGTH (value_type (arg1)) == TYPE_LENGTH (value_type (arg2))
8641         && memcmp (value_contents (arg1), value_contents (arg2),
8642                    TYPE_LENGTH (value_type (arg1))) == 0;
8643     }
8644   return value_equal (arg1, arg2);
8645 }
8646
8647 /* Total number of component associations in the aggregate starting at
8648    index PC in EXP.  Assumes that index PC is the start of an
8649    OP_AGGREGATE.  */
8650
8651 static int
8652 num_component_specs (struct expression *exp, int pc)
8653 {
8654   int n, m, i;
8655
8656   m = exp->elts[pc + 1].longconst;
8657   pc += 3;
8658   n = 0;
8659   for (i = 0; i < m; i += 1)
8660     {
8661       switch (exp->elts[pc].opcode) 
8662         {
8663         default:
8664           n += 1;
8665           break;
8666         case OP_CHOICES:
8667           n += exp->elts[pc + 1].longconst;
8668           break;
8669         }
8670       ada_evaluate_subexp (NULL, exp, &pc, EVAL_SKIP);
8671     }
8672   return n;
8673 }
8674
8675 /* Assign the result of evaluating EXP starting at *POS to the INDEXth 
8676    component of LHS (a simple array or a record), updating *POS past
8677    the expression, assuming that LHS is contained in CONTAINER.  Does
8678    not modify the inferior's memory, nor does it modify LHS (unless
8679    LHS == CONTAINER).  */
8680
8681 static void
8682 assign_component (struct value *container, struct value *lhs, LONGEST index,
8683                   struct expression *exp, int *pos)
8684 {
8685   struct value *mark = value_mark ();
8686   struct value *elt;
8687
8688   if (TYPE_CODE (value_type (lhs)) == TYPE_CODE_ARRAY)
8689     {
8690       struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
8691       struct value *index_val = value_from_longest (index_type, index);
8692
8693       elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
8694     }
8695   else
8696     {
8697       elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
8698       elt = ada_to_fixed_value (unwrap_value (elt));
8699     }
8700
8701   if (exp->elts[*pos].opcode == OP_AGGREGATE)
8702     assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
8703   else
8704     value_assign_to_component (container, elt, 
8705                                ada_evaluate_subexp (NULL, exp, pos, 
8706                                                     EVAL_NORMAL));
8707
8708   value_free_to_mark (mark);
8709 }
8710
8711 /* Assuming that LHS represents an lvalue having a record or array
8712    type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
8713    of that aggregate's value to LHS, advancing *POS past the
8714    aggregate.  NOSIDE is as for evaluate_subexp.  CONTAINER is an
8715    lvalue containing LHS (possibly LHS itself).  Does not modify
8716    the inferior's memory, nor does it modify the contents of 
8717    LHS (unless == CONTAINER).  Returns the modified CONTAINER.  */
8718
8719 static struct value *
8720 assign_aggregate (struct value *container, 
8721                   struct value *lhs, struct expression *exp, 
8722                   int *pos, enum noside noside)
8723 {
8724   struct type *lhs_type;
8725   int n = exp->elts[*pos+1].longconst;
8726   LONGEST low_index, high_index;
8727   int num_specs;
8728   LONGEST *indices;
8729   int max_indices, num_indices;
8730   int is_array_aggregate;
8731   int i;
8732
8733   *pos += 3;
8734   if (noside != EVAL_NORMAL)
8735     {
8736       for (i = 0; i < n; i += 1)
8737         ada_evaluate_subexp (NULL, exp, pos, noside);
8738       return container;
8739     }
8740
8741   container = ada_coerce_ref (container);
8742   if (ada_is_direct_array_type (value_type (container)))
8743     container = ada_coerce_to_simple_array (container);
8744   lhs = ada_coerce_ref (lhs);
8745   if (!deprecated_value_modifiable (lhs))
8746     error (_("Left operand of assignment is not a modifiable lvalue."));
8747
8748   lhs_type = value_type (lhs);
8749   if (ada_is_direct_array_type (lhs_type))
8750     {
8751       lhs = ada_coerce_to_simple_array (lhs);
8752       lhs_type = value_type (lhs);
8753       low_index = TYPE_ARRAY_LOWER_BOUND_VALUE (lhs_type);
8754       high_index = TYPE_ARRAY_UPPER_BOUND_VALUE (lhs_type);
8755       is_array_aggregate = 1;
8756     }
8757   else if (TYPE_CODE (lhs_type) == TYPE_CODE_STRUCT)
8758     {
8759       low_index = 0;
8760       high_index = num_visible_fields (lhs_type) - 1;
8761       is_array_aggregate = 0;
8762     }
8763   else
8764     error (_("Left-hand side must be array or record."));
8765
8766   num_specs = num_component_specs (exp, *pos - 3);
8767   max_indices = 4 * num_specs + 4;
8768   indices = alloca (max_indices * sizeof (indices[0]));
8769   indices[0] = indices[1] = low_index - 1;
8770   indices[2] = indices[3] = high_index + 1;
8771   num_indices = 4;
8772
8773   for (i = 0; i < n; i += 1)
8774     {
8775       switch (exp->elts[*pos].opcode)
8776         {
8777           case OP_CHOICES:
8778             aggregate_assign_from_choices (container, lhs, exp, pos, indices, 
8779                                            &num_indices, max_indices,
8780                                            low_index, high_index);
8781             break;
8782           case OP_POSITIONAL:
8783             aggregate_assign_positional (container, lhs, exp, pos, indices,
8784                                          &num_indices, max_indices,
8785                                          low_index, high_index);
8786             break;
8787           case OP_OTHERS:
8788             if (i != n-1)
8789               error (_("Misplaced 'others' clause"));
8790             aggregate_assign_others (container, lhs, exp, pos, indices, 
8791                                      num_indices, low_index, high_index);
8792             break;
8793           default:
8794             error (_("Internal error: bad aggregate clause"));
8795         }
8796     }
8797
8798   return container;
8799 }
8800               
8801 /* Assign into the component of LHS indexed by the OP_POSITIONAL
8802    construct at *POS, updating *POS past the construct, given that
8803    the positions are relative to lower bound LOW, where HIGH is the 
8804    upper bound.  Record the position in INDICES[0 .. MAX_INDICES-1]
8805    updating *NUM_INDICES as needed.  CONTAINER is as for
8806    assign_aggregate.  */
8807 static void
8808 aggregate_assign_positional (struct value *container,
8809                              struct value *lhs, struct expression *exp,
8810                              int *pos, LONGEST *indices, int *num_indices,
8811                              int max_indices, LONGEST low, LONGEST high) 
8812 {
8813   LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
8814   
8815   if (ind - 1 == high)
8816     warning (_("Extra components in aggregate ignored."));
8817   if (ind <= high)
8818     {
8819       add_component_interval (ind, ind, indices, num_indices, max_indices);
8820       *pos += 3;
8821       assign_component (container, lhs, ind, exp, pos);
8822     }
8823   else
8824     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8825 }
8826
8827 /* Assign into the components of LHS indexed by the OP_CHOICES
8828    construct at *POS, updating *POS past the construct, given that
8829    the allowable indices are LOW..HIGH.  Record the indices assigned
8830    to in INDICES[0 .. MAX_INDICES-1], updating *NUM_INDICES as
8831    needed.  CONTAINER is as for assign_aggregate.  */
8832 static void
8833 aggregate_assign_from_choices (struct value *container,
8834                                struct value *lhs, struct expression *exp,
8835                                int *pos, LONGEST *indices, int *num_indices,
8836                                int max_indices, LONGEST low, LONGEST high) 
8837 {
8838   int j;
8839   int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
8840   int choice_pos, expr_pc;
8841   int is_array = ada_is_direct_array_type (value_type (lhs));
8842
8843   choice_pos = *pos += 3;
8844
8845   for (j = 0; j < n_choices; j += 1)
8846     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8847   expr_pc = *pos;
8848   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8849   
8850   for (j = 0; j < n_choices; j += 1)
8851     {
8852       LONGEST lower, upper;
8853       enum exp_opcode op = exp->elts[choice_pos].opcode;
8854
8855       if (op == OP_DISCRETE_RANGE)
8856         {
8857           choice_pos += 1;
8858           lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
8859                                                       EVAL_NORMAL));
8860           upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos, 
8861                                                       EVAL_NORMAL));
8862         }
8863       else if (is_array)
8864         {
8865           lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos, 
8866                                                       EVAL_NORMAL));
8867           upper = lower;
8868         }
8869       else
8870         {
8871           int ind;
8872           char *name;
8873
8874           switch (op)
8875             {
8876             case OP_NAME:
8877               name = &exp->elts[choice_pos + 2].string;
8878               break;
8879             case OP_VAR_VALUE:
8880               name = SYMBOL_NATURAL_NAME (exp->elts[choice_pos + 2].symbol);
8881               break;
8882             default:
8883               error (_("Invalid record component association."));
8884             }
8885           ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
8886           ind = 0;
8887           if (! find_struct_field (name, value_type (lhs), 0, 
8888                                    NULL, NULL, NULL, NULL, &ind))
8889             error (_("Unknown component name: %s."), name);
8890           lower = upper = ind;
8891         }
8892
8893       if (lower <= upper && (lower < low || upper > high))
8894         error (_("Index in component association out of bounds."));
8895
8896       add_component_interval (lower, upper, indices, num_indices,
8897                               max_indices);
8898       while (lower <= upper)
8899         {
8900           int pos1;
8901
8902           pos1 = expr_pc;
8903           assign_component (container, lhs, lower, exp, &pos1);
8904           lower += 1;
8905         }
8906     }
8907 }
8908
8909 /* Assign the value of the expression in the OP_OTHERS construct in
8910    EXP at *POS into the components of LHS indexed from LOW .. HIGH that
8911    have not been previously assigned.  The index intervals already assigned
8912    are in INDICES[0 .. NUM_INDICES-1].  Updates *POS to after the 
8913    OP_OTHERS clause.  CONTAINER is as for assign_aggregate.  */
8914 static void
8915 aggregate_assign_others (struct value *container,
8916                          struct value *lhs, struct expression *exp,
8917                          int *pos, LONGEST *indices, int num_indices,
8918                          LONGEST low, LONGEST high) 
8919 {
8920   int i;
8921   int expr_pc = *pos + 1;
8922   
8923   for (i = 0; i < num_indices - 2; i += 2)
8924     {
8925       LONGEST ind;
8926
8927       for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
8928         {
8929           int localpos;
8930
8931           localpos = expr_pc;
8932           assign_component (container, lhs, ind, exp, &localpos);
8933         }
8934     }
8935   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8936 }
8937
8938 /* Add the interval [LOW .. HIGH] to the sorted set of intervals 
8939    [ INDICES[0] .. INDICES[1] ],..., [ INDICES[*SIZE-2] .. INDICES[*SIZE-1] ],
8940    modifying *SIZE as needed.  It is an error if *SIZE exceeds
8941    MAX_SIZE.  The resulting intervals do not overlap.  */
8942 static void
8943 add_component_interval (LONGEST low, LONGEST high, 
8944                         LONGEST* indices, int *size, int max_size)
8945 {
8946   int i, j;
8947
8948   for (i = 0; i < *size; i += 2) {
8949     if (high >= indices[i] && low <= indices[i + 1])
8950       {
8951         int kh;
8952
8953         for (kh = i + 2; kh < *size; kh += 2)
8954           if (high < indices[kh])
8955             break;
8956         if (low < indices[i])
8957           indices[i] = low;
8958         indices[i + 1] = indices[kh - 1];
8959         if (high > indices[i + 1])
8960           indices[i + 1] = high;
8961         memcpy (indices + i + 2, indices + kh, *size - kh);
8962         *size -= kh - i - 2;
8963         return;
8964       }
8965     else if (high < indices[i])
8966       break;
8967   }
8968         
8969   if (*size == max_size)
8970     error (_("Internal error: miscounted aggregate components."));
8971   *size += 2;
8972   for (j = *size-1; j >= i+2; j -= 1)
8973     indices[j] = indices[j - 2];
8974   indices[i] = low;
8975   indices[i + 1] = high;
8976 }
8977
8978 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
8979    is different.  */
8980
8981 static struct value *
8982 ada_value_cast (struct type *type, struct value *arg2, enum noside noside)
8983 {
8984   if (type == ada_check_typedef (value_type (arg2)))
8985     return arg2;
8986
8987   if (ada_is_fixed_point_type (type))
8988     return (cast_to_fixed (type, arg2));
8989
8990   if (ada_is_fixed_point_type (value_type (arg2)))
8991     return cast_from_fixed (type, arg2);
8992
8993   return value_cast (type, arg2);
8994 }
8995
8996 /*  Evaluating Ada expressions, and printing their result.
8997     ------------------------------------------------------
8998
8999     1. Introduction:
9000     ----------------
9001
9002     We usually evaluate an Ada expression in order to print its value.
9003     We also evaluate an expression in order to print its type, which
9004     happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9005     but we'll focus mostly on the EVAL_NORMAL phase.  In practice, the
9006     EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9007     the evaluation compared to the EVAL_NORMAL, but is otherwise very
9008     similar.
9009
9010     Evaluating expressions is a little more complicated for Ada entities
9011     than it is for entities in languages such as C.  The main reason for
9012     this is that Ada provides types whose definition might be dynamic.
9013     One example of such types is variant records.  Or another example
9014     would be an array whose bounds can only be known at run time.
9015
9016     The following description is a general guide as to what should be
9017     done (and what should NOT be done) in order to evaluate an expression
9018     involving such types, and when.  This does not cover how the semantic
9019     information is encoded by GNAT as this is covered separatly.  For the
9020     document used as the reference for the GNAT encoding, see exp_dbug.ads
9021     in the GNAT sources.
9022
9023     Ideally, we should embed each part of this description next to its
9024     associated code.  Unfortunately, the amount of code is so vast right
9025     now that it's hard to see whether the code handling a particular
9026     situation might be duplicated or not.  One day, when the code is
9027     cleaned up, this guide might become redundant with the comments
9028     inserted in the code, and we might want to remove it.
9029
9030     2. ``Fixing'' an Entity, the Simple Case:
9031     -----------------------------------------
9032
9033     When evaluating Ada expressions, the tricky issue is that they may
9034     reference entities whose type contents and size are not statically
9035     known.  Consider for instance a variant record:
9036
9037        type Rec (Empty : Boolean := True) is record
9038           case Empty is
9039              when True => null;
9040              when False => Value : Integer;
9041           end case;
9042        end record;
9043        Yes : Rec := (Empty => False, Value => 1);
9044        No  : Rec := (empty => True);
9045
9046     The size and contents of that record depends on the value of the
9047     descriminant (Rec.Empty).  At this point, neither the debugging
9048     information nor the associated type structure in GDB are able to
9049     express such dynamic types.  So what the debugger does is to create
9050     "fixed" versions of the type that applies to the specific object.
9051     We also informally refer to this opperation as "fixing" an object,
9052     which means creating its associated fixed type.
9053
9054     Example: when printing the value of variable "Yes" above, its fixed
9055     type would look like this:
9056
9057        type Rec is record
9058           Empty : Boolean;
9059           Value : Integer;
9060        end record;
9061
9062     On the other hand, if we printed the value of "No", its fixed type
9063     would become:
9064
9065        type Rec is record
9066           Empty : Boolean;
9067        end record;
9068
9069     Things become a little more complicated when trying to fix an entity
9070     with a dynamic type that directly contains another dynamic type,
9071     such as an array of variant records, for instance.  There are
9072     two possible cases: Arrays, and records.
9073
9074     3. ``Fixing'' Arrays:
9075     ---------------------
9076
9077     The type structure in GDB describes an array in terms of its bounds,
9078     and the type of its elements.  By design, all elements in the array
9079     have the same type and we cannot represent an array of variant elements
9080     using the current type structure in GDB.  When fixing an array,
9081     we cannot fix the array element, as we would potentially need one
9082     fixed type per element of the array.  As a result, the best we can do
9083     when fixing an array is to produce an array whose bounds and size
9084     are correct (allowing us to read it from memory), but without having
9085     touched its element type.  Fixing each element will be done later,
9086     when (if) necessary.
9087
9088     Arrays are a little simpler to handle than records, because the same
9089     amount of memory is allocated for each element of the array, even if
9090     the amount of space actually used by each element differs from element
9091     to element.  Consider for instance the following array of type Rec:
9092
9093        type Rec_Array is array (1 .. 2) of Rec;
9094
9095     The actual amount of memory occupied by each element might be different
9096     from element to element, depending on the value of their discriminant.
9097     But the amount of space reserved for each element in the array remains
9098     fixed regardless.  So we simply need to compute that size using
9099     the debugging information available, from which we can then determine
9100     the array size (we multiply the number of elements of the array by
9101     the size of each element).
9102
9103     The simplest case is when we have an array of a constrained element
9104     type. For instance, consider the following type declarations:
9105
9106         type Bounded_String (Max_Size : Integer) is
9107            Length : Integer;
9108            Buffer : String (1 .. Max_Size);
9109         end record;
9110         type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9111
9112     In this case, the compiler describes the array as an array of
9113     variable-size elements (identified by its XVS suffix) for which
9114     the size can be read in the parallel XVZ variable.
9115
9116     In the case of an array of an unconstrained element type, the compiler
9117     wraps the array element inside a private PAD type.  This type should not
9118     be shown to the user, and must be "unwrap"'ed before printing.  Note
9119     that we also use the adjective "aligner" in our code to designate
9120     these wrapper types.
9121
9122     In some cases, the size allocated for each element is statically
9123     known.  In that case, the PAD type already has the correct size,
9124     and the array element should remain unfixed.
9125
9126     But there are cases when this size is not statically known.
9127     For instance, assuming that "Five" is an integer variable:
9128
9129         type Dynamic is array (1 .. Five) of Integer;
9130         type Wrapper (Has_Length : Boolean := False) is record
9131            Data : Dynamic;
9132            case Has_Length is
9133               when True => Length : Integer;
9134               when False => null;
9135            end case;
9136         end record;
9137         type Wrapper_Array is array (1 .. 2) of Wrapper;
9138
9139         Hello : Wrapper_Array := (others => (Has_Length => True,
9140                                              Data => (others => 17),
9141                                              Length => 1));
9142
9143
9144     The debugging info would describe variable Hello as being an
9145     array of a PAD type.  The size of that PAD type is not statically
9146     known, but can be determined using a parallel XVZ variable.
9147     In that case, a copy of the PAD type with the correct size should
9148     be used for the fixed array.
9149
9150     3. ``Fixing'' record type objects:
9151     ----------------------------------
9152
9153     Things are slightly different from arrays in the case of dynamic
9154     record types.  In this case, in order to compute the associated
9155     fixed type, we need to determine the size and offset of each of
9156     its components.  This, in turn, requires us to compute the fixed
9157     type of each of these components.
9158
9159     Consider for instance the example:
9160
9161         type Bounded_String (Max_Size : Natural) is record
9162            Str : String (1 .. Max_Size);
9163            Length : Natural;
9164         end record;
9165         My_String : Bounded_String (Max_Size => 10);
9166
9167     In that case, the position of field "Length" depends on the size
9168     of field Str, which itself depends on the value of the Max_Size
9169     discriminant.  In order to fix the type of variable My_String,
9170     we need to fix the type of field Str.  Therefore, fixing a variant
9171     record requires us to fix each of its components.
9172
9173     However, if a component does not have a dynamic size, the component
9174     should not be fixed.  In particular, fields that use a PAD type
9175     should not fixed.  Here is an example where this might happen
9176     (assuming type Rec above):
9177
9178        type Container (Big : Boolean) is record
9179           First : Rec;
9180           After : Integer;
9181           case Big is
9182              when True => Another : Integer;
9183              when False => null;
9184           end case;
9185        end record;
9186        My_Container : Container := (Big => False,
9187                                     First => (Empty => True),
9188                                     After => 42);
9189
9190     In that example, the compiler creates a PAD type for component First,
9191     whose size is constant, and then positions the component After just
9192     right after it.  The offset of component After is therefore constant
9193     in this case.
9194
9195     The debugger computes the position of each field based on an algorithm
9196     that uses, among other things, the actual position and size of the field
9197     preceding it.  Let's now imagine that the user is trying to print
9198     the value of My_Container.  If the type fixing was recursive, we would
9199     end up computing the offset of field After based on the size of the
9200     fixed version of field First.  And since in our example First has
9201     only one actual field, the size of the fixed type is actually smaller
9202     than the amount of space allocated to that field, and thus we would
9203     compute the wrong offset of field After.
9204
9205     To make things more complicated, we need to watch out for dynamic
9206     components of variant records (identified by the ___XVL suffix in
9207     the component name).  Even if the target type is a PAD type, the size
9208     of that type might not be statically known.  So the PAD type needs
9209     to be unwrapped and the resulting type needs to be fixed.  Otherwise,
9210     we might end up with the wrong size for our component.  This can be
9211     observed with the following type declarations:
9212
9213         type Octal is new Integer range 0 .. 7;
9214         type Octal_Array is array (Positive range <>) of Octal;
9215         pragma Pack (Octal_Array);
9216
9217         type Octal_Buffer (Size : Positive) is record
9218            Buffer : Octal_Array (1 .. Size);
9219            Length : Integer;
9220         end record;
9221
9222     In that case, Buffer is a PAD type whose size is unset and needs
9223     to be computed by fixing the unwrapped type.
9224
9225     4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
9226     ----------------------------------------------------------
9227
9228     Lastly, when should the sub-elements of an entity that remained unfixed
9229     thus far, be actually fixed?
9230
9231     The answer is: Only when referencing that element.  For instance
9232     when selecting one component of a record, this specific component
9233     should be fixed at that point in time.  Or when printing the value
9234     of a record, each component should be fixed before its value gets
9235     printed.  Similarly for arrays, the element of the array should be
9236     fixed when printing each element of the array, or when extracting
9237     one element out of that array.  On the other hand, fixing should
9238     not be performed on the elements when taking a slice of an array!
9239
9240     Note that one of the side-effects of miscomputing the offset and
9241     size of each field is that we end up also miscomputing the size
9242     of the containing type.  This can have adverse results when computing
9243     the value of an entity.  GDB fetches the value of an entity based
9244     on the size of its type, and thus a wrong size causes GDB to fetch
9245     the wrong amount of memory.  In the case where the computed size is
9246     too small, GDB fetches too little data to print the value of our
9247     entiry.  Results in this case as unpredicatble, as we usually read
9248     past the buffer containing the data =:-o.  */
9249
9250 /* Implement the evaluate_exp routine in the exp_descriptor structure
9251    for the Ada language.  */
9252
9253 static struct value *
9254 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
9255                      int *pos, enum noside noside)
9256 {
9257   enum exp_opcode op;
9258   int tem;
9259   int pc;
9260   struct value *arg1 = NULL, *arg2 = NULL, *arg3;
9261   struct type *type;
9262   int nargs, oplen;
9263   struct value **argvec;
9264
9265   pc = *pos;
9266   *pos += 1;
9267   op = exp->elts[pc].opcode;
9268
9269   switch (op)
9270     {
9271     default:
9272       *pos -= 1;
9273       arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
9274       arg1 = unwrap_value (arg1);
9275
9276       /* If evaluating an OP_DOUBLE and an EXPECT_TYPE was provided,
9277          then we need to perform the conversion manually, because
9278          evaluate_subexp_standard doesn't do it.  This conversion is
9279          necessary in Ada because the different kinds of float/fixed
9280          types in Ada have different representations.
9281
9282          Similarly, we need to perform the conversion from OP_LONG
9283          ourselves.  */
9284       if ((op == OP_DOUBLE || op == OP_LONG) && expect_type != NULL)
9285         arg1 = ada_value_cast (expect_type, arg1, noside);
9286
9287       return arg1;
9288
9289     case OP_STRING:
9290       {
9291         struct value *result;
9292
9293         *pos -= 1;
9294         result = evaluate_subexp_standard (expect_type, exp, pos, noside);
9295         /* The result type will have code OP_STRING, bashed there from 
9296            OP_ARRAY.  Bash it back.  */
9297         if (TYPE_CODE (value_type (result)) == TYPE_CODE_STRING)
9298           TYPE_CODE (value_type (result)) = TYPE_CODE_ARRAY;
9299         return result;
9300       }
9301
9302     case UNOP_CAST:
9303       (*pos) += 2;
9304       type = exp->elts[pc + 1].type;
9305       arg1 = evaluate_subexp (type, exp, pos, noside);
9306       if (noside == EVAL_SKIP)
9307         goto nosideret;
9308       arg1 = ada_value_cast (type, arg1, noside);
9309       return arg1;
9310
9311     case UNOP_QUAL:
9312       (*pos) += 2;
9313       type = exp->elts[pc + 1].type;
9314       return ada_evaluate_subexp (type, exp, pos, noside);
9315
9316     case BINOP_ASSIGN:
9317       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9318       if (exp->elts[*pos].opcode == OP_AGGREGATE)
9319         {
9320           arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
9321           if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
9322             return arg1;
9323           return ada_value_assign (arg1, arg1);
9324         }
9325       /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9326          except if the lhs of our assignment is a convenience variable.
9327          In the case of assigning to a convenience variable, the lhs
9328          should be exactly the result of the evaluation of the rhs.  */
9329       type = value_type (arg1);
9330       if (VALUE_LVAL (arg1) == lval_internalvar)
9331          type = NULL;
9332       arg2 = evaluate_subexp (type, exp, pos, noside);
9333       if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
9334         return arg1;
9335       if (ada_is_fixed_point_type (value_type (arg1)))
9336         arg2 = cast_to_fixed (value_type (arg1), arg2);
9337       else if (ada_is_fixed_point_type (value_type (arg2)))
9338         error
9339           (_("Fixed-point values must be assigned to fixed-point variables"));
9340       else
9341         arg2 = coerce_for_assign (value_type (arg1), arg2);
9342       return ada_value_assign (arg1, arg2);
9343
9344     case BINOP_ADD:
9345       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
9346       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
9347       if (noside == EVAL_SKIP)
9348         goto nosideret;
9349       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
9350         return (value_from_longest
9351                  (value_type (arg1),
9352                   value_as_long (arg1) + value_as_long (arg2)));
9353       if ((ada_is_fixed_point_type (value_type (arg1))
9354            || ada_is_fixed_point_type (value_type (arg2)))
9355           && value_type (arg1) != value_type (arg2))
9356         error (_("Operands of fixed-point addition must have the same type"));
9357       /* Do the addition, and cast the result to the type of the first
9358          argument.  We cannot cast the result to a reference type, so if
9359          ARG1 is a reference type, find its underlying type.  */
9360       type = value_type (arg1);
9361       while (TYPE_CODE (type) == TYPE_CODE_REF)
9362         type = TYPE_TARGET_TYPE (type);
9363       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9364       return value_cast (type, value_binop (arg1, arg2, BINOP_ADD));
9365
9366     case BINOP_SUB:
9367       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
9368       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
9369       if (noside == EVAL_SKIP)
9370         goto nosideret;
9371       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
9372         return (value_from_longest
9373                  (value_type (arg1),
9374                   value_as_long (arg1) - value_as_long (arg2)));
9375       if ((ada_is_fixed_point_type (value_type (arg1))
9376            || ada_is_fixed_point_type (value_type (arg2)))
9377           && value_type (arg1) != value_type (arg2))
9378         error (_("Operands of fixed-point subtraction "
9379                  "must have the same type"));
9380       /* Do the substraction, and cast the result to the type of the first
9381          argument.  We cannot cast the result to a reference type, so if
9382          ARG1 is a reference type, find its underlying type.  */
9383       type = value_type (arg1);
9384       while (TYPE_CODE (type) == TYPE_CODE_REF)
9385         type = TYPE_TARGET_TYPE (type);
9386       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9387       return value_cast (type, value_binop (arg1, arg2, BINOP_SUB));
9388
9389     case BINOP_MUL:
9390     case BINOP_DIV:
9391     case BINOP_REM:
9392     case BINOP_MOD:
9393       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9394       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9395       if (noside == EVAL_SKIP)
9396         goto nosideret;
9397       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9398         {
9399           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9400           return value_zero (value_type (arg1), not_lval);
9401         }
9402       else
9403         {
9404           type = builtin_type (exp->gdbarch)->builtin_double;
9405           if (ada_is_fixed_point_type (value_type (arg1)))
9406             arg1 = cast_from_fixed (type, arg1);
9407           if (ada_is_fixed_point_type (value_type (arg2)))
9408             arg2 = cast_from_fixed (type, arg2);
9409           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9410           return ada_value_binop (arg1, arg2, op);
9411         }
9412
9413     case BINOP_EQUAL:
9414     case BINOP_NOTEQUAL:
9415       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9416       arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
9417       if (noside == EVAL_SKIP)
9418         goto nosideret;
9419       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9420         tem = 0;
9421       else
9422         {
9423           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9424           tem = ada_value_equal (arg1, arg2);
9425         }
9426       if (op == BINOP_NOTEQUAL)
9427         tem = !tem;
9428       type = language_bool_type (exp->language_defn, exp->gdbarch);
9429       return value_from_longest (type, (LONGEST) tem);
9430
9431     case UNOP_NEG:
9432       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9433       if (noside == EVAL_SKIP)
9434         goto nosideret;
9435       else if (ada_is_fixed_point_type (value_type (arg1)))
9436         return value_cast (value_type (arg1), value_neg (arg1));
9437       else
9438         {
9439           unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9440           return value_neg (arg1);
9441         }
9442
9443     case BINOP_LOGICAL_AND:
9444     case BINOP_LOGICAL_OR:
9445     case UNOP_LOGICAL_NOT:
9446       {
9447         struct value *val;
9448
9449         *pos -= 1;
9450         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
9451         type = language_bool_type (exp->language_defn, exp->gdbarch);
9452         return value_cast (type, val);
9453       }
9454
9455     case BINOP_BITWISE_AND:
9456     case BINOP_BITWISE_IOR:
9457     case BINOP_BITWISE_XOR:
9458       {
9459         struct value *val;
9460
9461         arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
9462         *pos = pc;
9463         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
9464
9465         return value_cast (value_type (arg1), val);
9466       }
9467
9468     case OP_VAR_VALUE:
9469       *pos -= 1;
9470
9471       if (noside == EVAL_SKIP)
9472         {
9473           *pos += 4;
9474           goto nosideret;
9475         }
9476       else if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
9477         /* Only encountered when an unresolved symbol occurs in a
9478            context other than a function call, in which case, it is
9479            invalid.  */
9480         error (_("Unexpected unresolved symbol, %s, during evaluation"),
9481                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
9482       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9483         {
9484           type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
9485           /* Check to see if this is a tagged type.  We also need to handle
9486              the case where the type is a reference to a tagged type, but
9487              we have to be careful to exclude pointers to tagged types.
9488              The latter should be shown as usual (as a pointer), whereas
9489              a reference should mostly be transparent to the user.  */
9490           if (ada_is_tagged_type (type, 0)
9491               || (TYPE_CODE(type) == TYPE_CODE_REF
9492                   && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
9493           {
9494             /* Tagged types are a little special in the fact that the real
9495                type is dynamic and can only be determined by inspecting the
9496                object's tag.  This means that we need to get the object's
9497                value first (EVAL_NORMAL) and then extract the actual object
9498                type from its tag.
9499
9500                Note that we cannot skip the final step where we extract
9501                the object type from its tag, because the EVAL_NORMAL phase
9502                results in dynamic components being resolved into fixed ones.
9503                This can cause problems when trying to print the type
9504                description of tagged types whose parent has a dynamic size:
9505                We use the type name of the "_parent" component in order
9506                to print the name of the ancestor type in the type description.
9507                If that component had a dynamic size, the resolution into
9508                a fixed type would result in the loss of that type name,
9509                thus preventing us from printing the name of the ancestor
9510                type in the type description.  */
9511             struct type *actual_type;
9512
9513             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_NORMAL);
9514             actual_type = type_from_tag (ada_value_tag (arg1));
9515             if (actual_type == NULL)
9516               /* If, for some reason, we were unable to determine
9517                  the actual type from the tag, then use the static
9518                  approximation that we just computed as a fallback.
9519                  This can happen if the debugging information is
9520                  incomplete, for instance.  */
9521               actual_type = type;
9522
9523             return value_zero (actual_type, not_lval);
9524           }
9525
9526           *pos += 4;
9527           return value_zero
9528             (to_static_fixed_type
9529              (static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol))),
9530              not_lval);
9531         }
9532       else
9533         {
9534           arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
9535           arg1 = unwrap_value (arg1);
9536           return ada_to_fixed_value (arg1);
9537         }
9538
9539     case OP_FUNCALL:
9540       (*pos) += 2;
9541
9542       /* Allocate arg vector, including space for the function to be
9543          called in argvec[0] and a terminating NULL.  */
9544       nargs = longest_to_int (exp->elts[pc + 1].longconst);
9545       argvec =
9546         (struct value **) alloca (sizeof (struct value *) * (nargs + 2));
9547
9548       if (exp->elts[*pos].opcode == OP_VAR_VALUE
9549           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
9550         error (_("Unexpected unresolved symbol, %s, during evaluation"),
9551                SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
9552       else
9553         {
9554           for (tem = 0; tem <= nargs; tem += 1)
9555             argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9556           argvec[tem] = 0;
9557
9558           if (noside == EVAL_SKIP)
9559             goto nosideret;
9560         }
9561
9562       if (ada_is_constrained_packed_array_type
9563           (desc_base_type (value_type (argvec[0]))))
9564         argvec[0] = ada_coerce_to_simple_array (argvec[0]);
9565       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
9566                && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
9567         /* This is a packed array that has already been fixed, and
9568            therefore already coerced to a simple array.  Nothing further
9569            to do.  */
9570         ;
9571       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_REF
9572                || (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
9573                    && VALUE_LVAL (argvec[0]) == lval_memory))
9574         argvec[0] = value_addr (argvec[0]);
9575
9576       type = ada_check_typedef (value_type (argvec[0]));
9577
9578       /* Ada allows us to implicitly dereference arrays when subscripting
9579          them.  So, if this is an array typedef (encoding use for array
9580          access types encoded as fat pointers), strip it now.  */
9581       if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
9582         type = ada_typedef_target_type (type);
9583
9584       if (TYPE_CODE (type) == TYPE_CODE_PTR)
9585         {
9586           switch (TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type))))
9587             {
9588             case TYPE_CODE_FUNC:
9589               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
9590               break;
9591             case TYPE_CODE_ARRAY:
9592               break;
9593             case TYPE_CODE_STRUCT:
9594               if (noside != EVAL_AVOID_SIDE_EFFECTS)
9595                 argvec[0] = ada_value_ind (argvec[0]);
9596               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
9597               break;
9598             default:
9599               error (_("cannot subscript or call something of type `%s'"),
9600                      ada_type_name (value_type (argvec[0])));
9601               break;
9602             }
9603         }
9604
9605       switch (TYPE_CODE (type))
9606         {
9607         case TYPE_CODE_FUNC:
9608           if (noside == EVAL_AVOID_SIDE_EFFECTS)
9609             return allocate_value (TYPE_TARGET_TYPE (type));
9610           return call_function_by_hand (argvec[0], nargs, argvec + 1);
9611         case TYPE_CODE_STRUCT:
9612           {
9613             int arity;
9614
9615             arity = ada_array_arity (type);
9616             type = ada_array_element_type (type, nargs);
9617             if (type == NULL)
9618               error (_("cannot subscript or call a record"));
9619             if (arity != nargs)
9620               error (_("wrong number of subscripts; expecting %d"), arity);
9621             if (noside == EVAL_AVOID_SIDE_EFFECTS)
9622               return value_zero (ada_aligned_type (type), lval_memory);
9623             return
9624               unwrap_value (ada_value_subscript
9625                             (argvec[0], nargs, argvec + 1));
9626           }
9627         case TYPE_CODE_ARRAY:
9628           if (noside == EVAL_AVOID_SIDE_EFFECTS)
9629             {
9630               type = ada_array_element_type (type, nargs);
9631               if (type == NULL)
9632                 error (_("element type of array unknown"));
9633               else
9634                 return value_zero (ada_aligned_type (type), lval_memory);
9635             }
9636           return
9637             unwrap_value (ada_value_subscript
9638                           (ada_coerce_to_simple_array (argvec[0]),
9639                            nargs, argvec + 1));
9640         case TYPE_CODE_PTR:     /* Pointer to array */
9641           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
9642           if (noside == EVAL_AVOID_SIDE_EFFECTS)
9643             {
9644               type = ada_array_element_type (type, nargs);
9645               if (type == NULL)
9646                 error (_("element type of array unknown"));
9647               else
9648                 return value_zero (ada_aligned_type (type), lval_memory);
9649             }
9650           return
9651             unwrap_value (ada_value_ptr_subscript (argvec[0], type,
9652                                                    nargs, argvec + 1));
9653
9654         default:
9655           error (_("Attempt to index or call something other than an "
9656                    "array or function"));
9657         }
9658
9659     case TERNOP_SLICE:
9660       {
9661         struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9662         struct value *low_bound_val =
9663           evaluate_subexp (NULL_TYPE, exp, pos, noside);
9664         struct value *high_bound_val =
9665           evaluate_subexp (NULL_TYPE, exp, pos, noside);
9666         LONGEST low_bound;
9667         LONGEST high_bound;
9668
9669         low_bound_val = coerce_ref (low_bound_val);
9670         high_bound_val = coerce_ref (high_bound_val);
9671         low_bound = pos_atr (low_bound_val);
9672         high_bound = pos_atr (high_bound_val);
9673
9674         if (noside == EVAL_SKIP)
9675           goto nosideret;
9676
9677         /* If this is a reference to an aligner type, then remove all
9678            the aligners.  */
9679         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
9680             && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
9681           TYPE_TARGET_TYPE (value_type (array)) =
9682             ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
9683
9684         if (ada_is_constrained_packed_array_type (value_type (array)))
9685           error (_("cannot slice a packed array"));
9686
9687         /* If this is a reference to an array or an array lvalue,
9688            convert to a pointer.  */
9689         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
9690             || (TYPE_CODE (value_type (array)) == TYPE_CODE_ARRAY
9691                 && VALUE_LVAL (array) == lval_memory))
9692           array = value_addr (array);
9693
9694         if (noside == EVAL_AVOID_SIDE_EFFECTS
9695             && ada_is_array_descriptor_type (ada_check_typedef
9696                                              (value_type (array))))
9697           return empty_array (ada_type_of_array (array, 0), low_bound);
9698
9699         array = ada_coerce_to_simple_array_ptr (array);
9700
9701         /* If we have more than one level of pointer indirection,
9702            dereference the value until we get only one level.  */
9703         while (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR
9704                && (TYPE_CODE (TYPE_TARGET_TYPE (value_type (array)))
9705                      == TYPE_CODE_PTR))
9706           array = value_ind (array);
9707
9708         /* Make sure we really do have an array type before going further,
9709            to avoid a SEGV when trying to get the index type or the target
9710            type later down the road if the debug info generated by
9711            the compiler is incorrect or incomplete.  */
9712         if (!ada_is_simple_array_type (value_type (array)))
9713           error (_("cannot take slice of non-array"));
9714
9715         if (TYPE_CODE (ada_check_typedef (value_type (array)))
9716             == TYPE_CODE_PTR)
9717           {
9718             struct type *type0 = ada_check_typedef (value_type (array));
9719
9720             if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
9721               return empty_array (TYPE_TARGET_TYPE (type0), low_bound);
9722             else
9723               {
9724                 struct type *arr_type0 =
9725                   to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
9726
9727                 return ada_value_slice_from_ptr (array, arr_type0,
9728                                                  longest_to_int (low_bound),
9729                                                  longest_to_int (high_bound));
9730               }
9731           }
9732         else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9733           return array;
9734         else if (high_bound < low_bound)
9735           return empty_array (value_type (array), low_bound);
9736         else
9737           return ada_value_slice (array, longest_to_int (low_bound),
9738                                   longest_to_int (high_bound));
9739       }
9740
9741     case UNOP_IN_RANGE:
9742       (*pos) += 2;
9743       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9744       type = check_typedef (exp->elts[pc + 1].type);
9745
9746       if (noside == EVAL_SKIP)
9747         goto nosideret;
9748
9749       switch (TYPE_CODE (type))
9750         {
9751         default:
9752           lim_warning (_("Membership test incompletely implemented; "
9753                          "always returns true"));
9754           type = language_bool_type (exp->language_defn, exp->gdbarch);
9755           return value_from_longest (type, (LONGEST) 1);
9756
9757         case TYPE_CODE_RANGE:
9758           arg2 = value_from_longest (type, TYPE_LOW_BOUND (type));
9759           arg3 = value_from_longest (type, TYPE_HIGH_BOUND (type));
9760           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9761           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9762           type = language_bool_type (exp->language_defn, exp->gdbarch);
9763           return
9764             value_from_longest (type,
9765                                 (value_less (arg1, arg3)
9766                                  || value_equal (arg1, arg3))
9767                                 && (value_less (arg2, arg1)
9768                                     || value_equal (arg2, arg1)));
9769         }
9770
9771     case BINOP_IN_BOUNDS:
9772       (*pos) += 2;
9773       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9774       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9775
9776       if (noside == EVAL_SKIP)
9777         goto nosideret;
9778
9779       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9780         {
9781           type = language_bool_type (exp->language_defn, exp->gdbarch);
9782           return value_zero (type, not_lval);
9783         }
9784
9785       tem = longest_to_int (exp->elts[pc + 1].longconst);
9786
9787       type = ada_index_type (value_type (arg2), tem, "range");
9788       if (!type)
9789         type = value_type (arg1);
9790
9791       arg3 = value_from_longest (type, ada_array_bound (arg2, tem, 1));
9792       arg2 = value_from_longest (type, ada_array_bound (arg2, tem, 0));
9793
9794       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9795       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9796       type = language_bool_type (exp->language_defn, exp->gdbarch);
9797       return
9798         value_from_longest (type,
9799                             (value_less (arg1, arg3)
9800                              || value_equal (arg1, arg3))
9801                             && (value_less (arg2, arg1)
9802                                 || value_equal (arg2, arg1)));
9803
9804     case TERNOP_IN_RANGE:
9805       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9806       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9807       arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9808
9809       if (noside == EVAL_SKIP)
9810         goto nosideret;
9811
9812       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9813       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9814       type = language_bool_type (exp->language_defn, exp->gdbarch);
9815       return
9816         value_from_longest (type,
9817                             (value_less (arg1, arg3)
9818                              || value_equal (arg1, arg3))
9819                             && (value_less (arg2, arg1)
9820                                 || value_equal (arg2, arg1)));
9821
9822     case OP_ATR_FIRST:
9823     case OP_ATR_LAST:
9824     case OP_ATR_LENGTH:
9825       {
9826         struct type *type_arg;
9827
9828         if (exp->elts[*pos].opcode == OP_TYPE)
9829           {
9830             evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9831             arg1 = NULL;
9832             type_arg = check_typedef (exp->elts[pc + 2].type);
9833           }
9834         else
9835           {
9836             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9837             type_arg = NULL;
9838           }
9839
9840         if (exp->elts[*pos].opcode != OP_LONG)
9841           error (_("Invalid operand to '%s"), ada_attribute_name (op));
9842         tem = longest_to_int (exp->elts[*pos + 2].longconst);
9843         *pos += 4;
9844
9845         if (noside == EVAL_SKIP)
9846           goto nosideret;
9847
9848         if (type_arg == NULL)
9849           {
9850             arg1 = ada_coerce_ref (arg1);
9851
9852             if (ada_is_constrained_packed_array_type (value_type (arg1)))
9853               arg1 = ada_coerce_to_simple_array (arg1);
9854
9855             type = ada_index_type (value_type (arg1), tem,
9856                                    ada_attribute_name (op));
9857             if (type == NULL)
9858               type = builtin_type (exp->gdbarch)->builtin_int;
9859
9860             if (noside == EVAL_AVOID_SIDE_EFFECTS)
9861               return allocate_value (type);
9862
9863             switch (op)
9864               {
9865               default:          /* Should never happen.  */
9866                 error (_("unexpected attribute encountered"));
9867               case OP_ATR_FIRST:
9868                 return value_from_longest
9869                         (type, ada_array_bound (arg1, tem, 0));
9870               case OP_ATR_LAST:
9871                 return value_from_longest
9872                         (type, ada_array_bound (arg1, tem, 1));
9873               case OP_ATR_LENGTH:
9874                 return value_from_longest
9875                         (type, ada_array_length (arg1, tem));
9876               }
9877           }
9878         else if (discrete_type_p (type_arg))
9879           {
9880             struct type *range_type;
9881             char *name = ada_type_name (type_arg);
9882
9883             range_type = NULL;
9884             if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
9885               range_type = to_fixed_range_type (type_arg, NULL);
9886             if (range_type == NULL)
9887               range_type = type_arg;
9888             switch (op)
9889               {
9890               default:
9891                 error (_("unexpected attribute encountered"));
9892               case OP_ATR_FIRST:
9893                 return value_from_longest 
9894                   (range_type, ada_discrete_type_low_bound (range_type));
9895               case OP_ATR_LAST:
9896                 return value_from_longest
9897                   (range_type, ada_discrete_type_high_bound (range_type));
9898               case OP_ATR_LENGTH:
9899                 error (_("the 'length attribute applies only to array types"));
9900               }
9901           }
9902         else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
9903           error (_("unimplemented type attribute"));
9904         else
9905           {
9906             LONGEST low, high;
9907
9908             if (ada_is_constrained_packed_array_type (type_arg))
9909               type_arg = decode_constrained_packed_array_type (type_arg);
9910
9911             type = ada_index_type (type_arg, tem, ada_attribute_name (op));
9912             if (type == NULL)
9913               type = builtin_type (exp->gdbarch)->builtin_int;
9914
9915             if (noside == EVAL_AVOID_SIDE_EFFECTS)
9916               return allocate_value (type);
9917
9918             switch (op)
9919               {
9920               default:
9921                 error (_("unexpected attribute encountered"));
9922               case OP_ATR_FIRST:
9923                 low = ada_array_bound_from_type (type_arg, tem, 0);
9924                 return value_from_longest (type, low);
9925               case OP_ATR_LAST:
9926                 high = ada_array_bound_from_type (type_arg, tem, 1);
9927                 return value_from_longest (type, high);
9928               case OP_ATR_LENGTH:
9929                 low = ada_array_bound_from_type (type_arg, tem, 0);
9930                 high = ada_array_bound_from_type (type_arg, tem, 1);
9931                 return value_from_longest (type, high - low + 1);
9932               }
9933           }
9934       }
9935
9936     case OP_ATR_TAG:
9937       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9938       if (noside == EVAL_SKIP)
9939         goto nosideret;
9940
9941       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9942         return value_zero (ada_tag_type (arg1), not_lval);
9943
9944       return ada_value_tag (arg1);
9945
9946     case OP_ATR_MIN:
9947     case OP_ATR_MAX:
9948       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9949       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9950       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9951       if (noside == EVAL_SKIP)
9952         goto nosideret;
9953       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9954         return value_zero (value_type (arg1), not_lval);
9955       else
9956         {
9957           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9958           return value_binop (arg1, arg2,
9959                               op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
9960         }
9961
9962     case OP_ATR_MODULUS:
9963       {
9964         struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
9965
9966         evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9967         if (noside == EVAL_SKIP)
9968           goto nosideret;
9969
9970         if (!ada_is_modular_type (type_arg))
9971           error (_("'modulus must be applied to modular type"));
9972
9973         return value_from_longest (TYPE_TARGET_TYPE (type_arg),
9974                                    ada_modulus (type_arg));
9975       }
9976
9977
9978     case OP_ATR_POS:
9979       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9980       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9981       if (noside == EVAL_SKIP)
9982         goto nosideret;
9983       type = builtin_type (exp->gdbarch)->builtin_int;
9984       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9985         return value_zero (type, not_lval);
9986       else
9987         return value_pos_atr (type, arg1);
9988
9989     case OP_ATR_SIZE:
9990       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9991       type = value_type (arg1);
9992
9993       /* If the argument is a reference, then dereference its type, since
9994          the user is really asking for the size of the actual object,
9995          not the size of the pointer.  */
9996       if (TYPE_CODE (type) == TYPE_CODE_REF)
9997         type = TYPE_TARGET_TYPE (type);
9998
9999       if (noside == EVAL_SKIP)
10000         goto nosideret;
10001       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10002         return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10003       else
10004         return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10005                                    TARGET_CHAR_BIT * TYPE_LENGTH (type));
10006
10007     case OP_ATR_VAL:
10008       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10009       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10010       type = exp->elts[pc + 2].type;
10011       if (noside == EVAL_SKIP)
10012         goto nosideret;
10013       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10014         return value_zero (type, not_lval);
10015       else
10016         return value_val_atr (type, arg1);
10017
10018     case BINOP_EXP:
10019       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10020       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10021       if (noside == EVAL_SKIP)
10022         goto nosideret;
10023       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10024         return value_zero (value_type (arg1), not_lval);
10025       else
10026         {
10027           /* For integer exponentiation operations,
10028              only promote the first argument.  */
10029           if (is_integral_type (value_type (arg2)))
10030             unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10031           else
10032             binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10033
10034           return value_binop (arg1, arg2, op);
10035         }
10036
10037     case UNOP_PLUS:
10038       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10039       if (noside == EVAL_SKIP)
10040         goto nosideret;
10041       else
10042         return arg1;
10043
10044     case UNOP_ABS:
10045       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10046       if (noside == EVAL_SKIP)
10047         goto nosideret;
10048       unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10049       if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10050         return value_neg (arg1);
10051       else
10052         return arg1;
10053
10054     case UNOP_IND:
10055       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10056       if (noside == EVAL_SKIP)
10057         goto nosideret;
10058       type = ada_check_typedef (value_type (arg1));
10059       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10060         {
10061           if (ada_is_array_descriptor_type (type))
10062             /* GDB allows dereferencing GNAT array descriptors.  */
10063             {
10064               struct type *arrType = ada_type_of_array (arg1, 0);
10065
10066               if (arrType == NULL)
10067                 error (_("Attempt to dereference null array pointer."));
10068               return value_at_lazy (arrType, 0);
10069             }
10070           else if (TYPE_CODE (type) == TYPE_CODE_PTR
10071                    || TYPE_CODE (type) == TYPE_CODE_REF
10072                    /* In C you can dereference an array to get the 1st elt.  */
10073                    || TYPE_CODE (type) == TYPE_CODE_ARRAY)
10074             {
10075               type = to_static_fixed_type
10076                 (ada_aligned_type
10077                  (ada_check_typedef (TYPE_TARGET_TYPE (type))));
10078               check_size (type);
10079               return value_zero (type, lval_memory);
10080             }
10081           else if (TYPE_CODE (type) == TYPE_CODE_INT)
10082             {
10083               /* GDB allows dereferencing an int.  */
10084               if (expect_type == NULL)
10085                 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10086                                    lval_memory);
10087               else
10088                 {
10089                   expect_type = 
10090                     to_static_fixed_type (ada_aligned_type (expect_type));
10091                   return value_zero (expect_type, lval_memory);
10092                 }
10093             }
10094           else
10095             error (_("Attempt to take contents of a non-pointer value."));
10096         }
10097       arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for??  */
10098       type = ada_check_typedef (value_type (arg1));
10099
10100       if (TYPE_CODE (type) == TYPE_CODE_INT)
10101           /* GDB allows dereferencing an int.  If we were given
10102              the expect_type, then use that as the target type.
10103              Otherwise, assume that the target type is an int.  */
10104         {
10105           if (expect_type != NULL)
10106             return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
10107                                               arg1));
10108           else
10109             return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
10110                                   (CORE_ADDR) value_as_address (arg1));
10111         }
10112
10113       if (ada_is_array_descriptor_type (type))
10114         /* GDB allows dereferencing GNAT array descriptors.  */
10115         return ada_coerce_to_simple_array (arg1);
10116       else
10117         return ada_value_ind (arg1);
10118
10119     case STRUCTOP_STRUCT:
10120       tem = longest_to_int (exp->elts[pc + 1].longconst);
10121       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
10122       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10123       if (noside == EVAL_SKIP)
10124         goto nosideret;
10125       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10126         {
10127           struct type *type1 = value_type (arg1);
10128
10129           if (ada_is_tagged_type (type1, 1))
10130             {
10131               type = ada_lookup_struct_elt_type (type1,
10132                                                  &exp->elts[pc + 2].string,
10133                                                  1, 1, NULL);
10134               if (type == NULL)
10135                 /* In this case, we assume that the field COULD exist
10136                    in some extension of the type.  Return an object of 
10137                    "type" void, which will match any formal 
10138                    (see ada_type_match).  */
10139                 return value_zero (builtin_type (exp->gdbarch)->builtin_void,
10140                                    lval_memory);
10141             }
10142           else
10143             type =
10144               ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
10145                                           0, NULL);
10146
10147           return value_zero (ada_aligned_type (type), lval_memory);
10148         }
10149       else
10150         arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
10151         arg1 = unwrap_value (arg1);
10152         return ada_to_fixed_value (arg1);
10153
10154     case OP_TYPE:
10155       /* The value is not supposed to be used.  This is here to make it
10156          easier to accommodate expressions that contain types.  */
10157       (*pos) += 2;
10158       if (noside == EVAL_SKIP)
10159         goto nosideret;
10160       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10161         return allocate_value (exp->elts[pc + 1].type);
10162       else
10163         error (_("Attempt to use a type name as an expression"));
10164
10165     case OP_AGGREGATE:
10166     case OP_CHOICES:
10167     case OP_OTHERS:
10168     case OP_DISCRETE_RANGE:
10169     case OP_POSITIONAL:
10170     case OP_NAME:
10171       if (noside == EVAL_NORMAL)
10172         switch (op) 
10173           {
10174           case OP_NAME:
10175             error (_("Undefined name, ambiguous name, or renaming used in "
10176                      "component association: %s."), &exp->elts[pc+2].string);
10177           case OP_AGGREGATE:
10178             error (_("Aggregates only allowed on the right of an assignment"));
10179           default:
10180             internal_error (__FILE__, __LINE__,
10181                             _("aggregate apparently mangled"));
10182           }
10183
10184       ada_forward_operator_length (exp, pc, &oplen, &nargs);
10185       *pos += oplen - 1;
10186       for (tem = 0; tem < nargs; tem += 1) 
10187         ada_evaluate_subexp (NULL, exp, pos, noside);
10188       goto nosideret;
10189     }
10190
10191 nosideret:
10192   return value_from_longest (builtin_type (exp->gdbarch)->builtin_int, 1);
10193 }
10194 \f
10195
10196                                 /* Fixed point */
10197
10198 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
10199    type name that encodes the 'small and 'delta information.
10200    Otherwise, return NULL.  */
10201
10202 static const char *
10203 fixed_type_info (struct type *type)
10204 {
10205   const char *name = ada_type_name (type);
10206   enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
10207
10208   if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
10209     {
10210       const char *tail = strstr (name, "___XF_");
10211
10212       if (tail == NULL)
10213         return NULL;
10214       else
10215         return tail + 5;
10216     }
10217   else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
10218     return fixed_type_info (TYPE_TARGET_TYPE (type));
10219   else
10220     return NULL;
10221 }
10222
10223 /* Returns non-zero iff TYPE represents an Ada fixed-point type.  */
10224
10225 int
10226 ada_is_fixed_point_type (struct type *type)
10227 {
10228   return fixed_type_info (type) != NULL;
10229 }
10230
10231 /* Return non-zero iff TYPE represents a System.Address type.  */
10232
10233 int
10234 ada_is_system_address_type (struct type *type)
10235 {
10236   return (TYPE_NAME (type)
10237           && strcmp (TYPE_NAME (type), "system__address") == 0);
10238 }
10239
10240 /* Assuming that TYPE is the representation of an Ada fixed-point
10241    type, return its delta, or -1 if the type is malformed and the
10242    delta cannot be determined.  */
10243
10244 DOUBLEST
10245 ada_delta (struct type *type)
10246 {
10247   const char *encoding = fixed_type_info (type);
10248   DOUBLEST num, den;
10249
10250   /* Strictly speaking, num and den are encoded as integer.  However,
10251      they may not fit into a long, and they will have to be converted
10252      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
10253   if (sscanf (encoding, "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
10254               &num, &den) < 2)
10255     return -1.0;
10256   else
10257     return num / den;
10258 }
10259
10260 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
10261    factor ('SMALL value) associated with the type.  */
10262
10263 static DOUBLEST
10264 scaling_factor (struct type *type)
10265 {
10266   const char *encoding = fixed_type_info (type);
10267   DOUBLEST num0, den0, num1, den1;
10268   int n;
10269
10270   /* Strictly speaking, num's and den's are encoded as integer.  However,
10271      they may not fit into a long, and they will have to be converted
10272      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
10273   n = sscanf (encoding,
10274               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT
10275               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
10276               &num0, &den0, &num1, &den1);
10277
10278   if (n < 2)
10279     return 1.0;
10280   else if (n == 4)
10281     return num1 / den1;
10282   else
10283     return num0 / den0;
10284 }
10285
10286
10287 /* Assuming that X is the representation of a value of fixed-point
10288    type TYPE, return its floating-point equivalent.  */
10289
10290 DOUBLEST
10291 ada_fixed_to_float (struct type *type, LONGEST x)
10292 {
10293   return (DOUBLEST) x *scaling_factor (type);
10294 }
10295
10296 /* The representation of a fixed-point value of type TYPE
10297    corresponding to the value X.  */
10298
10299 LONGEST
10300 ada_float_to_fixed (struct type *type, DOUBLEST x)
10301 {
10302   return (LONGEST) (x / scaling_factor (type) + 0.5);
10303 }
10304
10305 \f
10306
10307                                 /* Range types */
10308
10309 /* Scan STR beginning at position K for a discriminant name, and
10310    return the value of that discriminant field of DVAL in *PX.  If
10311    PNEW_K is not null, put the position of the character beyond the
10312    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
10313    not alter *PX and *PNEW_K if unsuccessful.  */
10314
10315 static int
10316 scan_discrim_bound (char *str, int k, struct value *dval, LONGEST * px,
10317                     int *pnew_k)
10318 {
10319   static char *bound_buffer = NULL;
10320   static size_t bound_buffer_len = 0;
10321   char *bound;
10322   char *pend;
10323   struct value *bound_val;
10324
10325   if (dval == NULL || str == NULL || str[k] == '\0')
10326     return 0;
10327
10328   pend = strstr (str + k, "__");
10329   if (pend == NULL)
10330     {
10331       bound = str + k;
10332       k += strlen (bound);
10333     }
10334   else
10335     {
10336       GROW_VECT (bound_buffer, bound_buffer_len, pend - (str + k) + 1);
10337       bound = bound_buffer;
10338       strncpy (bound_buffer, str + k, pend - (str + k));
10339       bound[pend - (str + k)] = '\0';
10340       k = pend - str;
10341     }
10342
10343   bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
10344   if (bound_val == NULL)
10345     return 0;
10346
10347   *px = value_as_long (bound_val);
10348   if (pnew_k != NULL)
10349     *pnew_k = k;
10350   return 1;
10351 }
10352
10353 /* Value of variable named NAME in the current environment.  If
10354    no such variable found, then if ERR_MSG is null, returns 0, and
10355    otherwise causes an error with message ERR_MSG.  */
10356
10357 static struct value *
10358 get_var_value (char *name, char *err_msg)
10359 {
10360   struct ada_symbol_info *syms;
10361   int nsyms;
10362
10363   nsyms = ada_lookup_symbol_list (name, get_selected_block (0), VAR_DOMAIN,
10364                                   &syms);
10365
10366   if (nsyms != 1)
10367     {
10368       if (err_msg == NULL)
10369         return 0;
10370       else
10371         error (("%s"), err_msg);
10372     }
10373
10374   return value_of_variable (syms[0].sym, syms[0].block);
10375 }
10376
10377 /* Value of integer variable named NAME in the current environment.  If
10378    no such variable found, returns 0, and sets *FLAG to 0.  If
10379    successful, sets *FLAG to 1.  */
10380
10381 LONGEST
10382 get_int_var_value (char *name, int *flag)
10383 {
10384   struct value *var_val = get_var_value (name, 0);
10385
10386   if (var_val == 0)
10387     {
10388       if (flag != NULL)
10389         *flag = 0;
10390       return 0;
10391     }
10392   else
10393     {
10394       if (flag != NULL)
10395         *flag = 1;
10396       return value_as_long (var_val);
10397     }
10398 }
10399
10400
10401 /* Return a range type whose base type is that of the range type named
10402    NAME in the current environment, and whose bounds are calculated
10403    from NAME according to the GNAT range encoding conventions.
10404    Extract discriminant values, if needed, from DVAL.  ORIG_TYPE is the
10405    corresponding range type from debug information; fall back to using it
10406    if symbol lookup fails.  If a new type must be created, allocate it
10407    like ORIG_TYPE was.  The bounds information, in general, is encoded
10408    in NAME, the base type given in the named range type.  */
10409
10410 static struct type *
10411 to_fixed_range_type (struct type *raw_type, struct value *dval)
10412 {
10413   char *name;
10414   struct type *base_type;
10415   char *subtype_info;
10416
10417   gdb_assert (raw_type != NULL);
10418   gdb_assert (TYPE_NAME (raw_type) != NULL);
10419
10420   if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
10421     base_type = TYPE_TARGET_TYPE (raw_type);
10422   else
10423     base_type = raw_type;
10424
10425   name = TYPE_NAME (raw_type);
10426   subtype_info = strstr (name, "___XD");
10427   if (subtype_info == NULL)
10428     {
10429       LONGEST L = ada_discrete_type_low_bound (raw_type);
10430       LONGEST U = ada_discrete_type_high_bound (raw_type);
10431
10432       if (L < INT_MIN || U > INT_MAX)
10433         return raw_type;
10434       else
10435         return create_range_type (alloc_type_copy (raw_type), raw_type,
10436                                   ada_discrete_type_low_bound (raw_type),
10437                                   ada_discrete_type_high_bound (raw_type));
10438     }
10439   else
10440     {
10441       static char *name_buf = NULL;
10442       static size_t name_len = 0;
10443       int prefix_len = subtype_info - name;
10444       LONGEST L, U;
10445       struct type *type;
10446       char *bounds_str;
10447       int n;
10448
10449       GROW_VECT (name_buf, name_len, prefix_len + 5);
10450       strncpy (name_buf, name, prefix_len);
10451       name_buf[prefix_len] = '\0';
10452
10453       subtype_info += 5;
10454       bounds_str = strchr (subtype_info, '_');
10455       n = 1;
10456
10457       if (*subtype_info == 'L')
10458         {
10459           if (!ada_scan_number (bounds_str, n, &L, &n)
10460               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
10461             return raw_type;
10462           if (bounds_str[n] == '_')
10463             n += 2;
10464           else if (bounds_str[n] == '.')     /* FIXME? SGI Workshop kludge.  */
10465             n += 1;
10466           subtype_info += 1;
10467         }
10468       else
10469         {
10470           int ok;
10471
10472           strcpy (name_buf + prefix_len, "___L");
10473           L = get_int_var_value (name_buf, &ok);
10474           if (!ok)
10475             {
10476               lim_warning (_("Unknown lower bound, using 1."));
10477               L = 1;
10478             }
10479         }
10480
10481       if (*subtype_info == 'U')
10482         {
10483           if (!ada_scan_number (bounds_str, n, &U, &n)
10484               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
10485             return raw_type;
10486         }
10487       else
10488         {
10489           int ok;
10490
10491           strcpy (name_buf + prefix_len, "___U");
10492           U = get_int_var_value (name_buf, &ok);
10493           if (!ok)
10494             {
10495               lim_warning (_("Unknown upper bound, using %ld."), (long) L);
10496               U = L;
10497             }
10498         }
10499
10500       type = create_range_type (alloc_type_copy (raw_type), base_type, L, U);
10501       TYPE_NAME (type) = name;
10502       return type;
10503     }
10504 }
10505
10506 /* True iff NAME is the name of a range type.  */
10507
10508 int
10509 ada_is_range_type_name (const char *name)
10510 {
10511   return (name != NULL && strstr (name, "___XD"));
10512 }
10513 \f
10514
10515                                 /* Modular types */
10516
10517 /* True iff TYPE is an Ada modular type.  */
10518
10519 int
10520 ada_is_modular_type (struct type *type)
10521 {
10522   struct type *subranged_type = get_base_type (type);
10523
10524   return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
10525           && TYPE_CODE (subranged_type) == TYPE_CODE_INT
10526           && TYPE_UNSIGNED (subranged_type));
10527 }
10528
10529 /* Try to determine the lower and upper bounds of the given modular type
10530    using the type name only.  Return non-zero and set L and U as the lower
10531    and upper bounds (respectively) if successful.  */
10532
10533 int
10534 ada_modulus_from_name (struct type *type, ULONGEST *modulus)
10535 {
10536   char *name = ada_type_name (type);
10537   char *suffix;
10538   int k;
10539   LONGEST U;
10540
10541   if (name == NULL)
10542     return 0;
10543
10544   /* Discrete type bounds are encoded using an __XD suffix.  In our case,
10545      we are looking for static bounds, which means an __XDLU suffix.
10546      Moreover, we know that the lower bound of modular types is always
10547      zero, so the actual suffix should start with "__XDLU_0__", and
10548      then be followed by the upper bound value.  */
10549   suffix = strstr (name, "__XDLU_0__");
10550   if (suffix == NULL)
10551     return 0;
10552   k = 10;
10553   if (!ada_scan_number (suffix, k, &U, NULL))
10554     return 0;
10555
10556   *modulus = (ULONGEST) U + 1;
10557   return 1;
10558 }
10559
10560 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */
10561
10562 ULONGEST
10563 ada_modulus (struct type *type)
10564 {
10565   return (ULONGEST) TYPE_HIGH_BOUND (type) + 1;
10566 }
10567 \f
10568
10569 /* Ada exception catchpoint support:
10570    ---------------------------------
10571
10572    We support 3 kinds of exception catchpoints:
10573      . catchpoints on Ada exceptions
10574      . catchpoints on unhandled Ada exceptions
10575      . catchpoints on failed assertions
10576
10577    Exceptions raised during failed assertions, or unhandled exceptions
10578    could perfectly be caught with the general catchpoint on Ada exceptions.
10579    However, we can easily differentiate these two special cases, and having
10580    the option to distinguish these two cases from the rest can be useful
10581    to zero-in on certain situations.
10582
10583    Exception catchpoints are a specialized form of breakpoint,
10584    since they rely on inserting breakpoints inside known routines
10585    of the GNAT runtime.  The implementation therefore uses a standard
10586    breakpoint structure of the BP_BREAKPOINT type, but with its own set
10587    of breakpoint_ops.
10588
10589    Support in the runtime for exception catchpoints have been changed
10590    a few times already, and these changes affect the implementation
10591    of these catchpoints.  In order to be able to support several
10592    variants of the runtime, we use a sniffer that will determine
10593    the runtime variant used by the program being debugged.  */
10594
10595 /* The different types of catchpoints that we introduced for catching
10596    Ada exceptions.  */
10597
10598 enum exception_catchpoint_kind
10599 {
10600   ex_catch_exception,
10601   ex_catch_exception_unhandled,
10602   ex_catch_assert
10603 };
10604
10605 /* Ada's standard exceptions.  */
10606
10607 static char *standard_exc[] = {
10608   "constraint_error",
10609   "program_error",
10610   "storage_error",
10611   "tasking_error"
10612 };
10613
10614 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
10615
10616 /* A structure that describes how to support exception catchpoints
10617    for a given executable.  */
10618
10619 struct exception_support_info
10620 {
10621    /* The name of the symbol to break on in order to insert
10622       a catchpoint on exceptions.  */
10623    const char *catch_exception_sym;
10624
10625    /* The name of the symbol to break on in order to insert
10626       a catchpoint on unhandled exceptions.  */
10627    const char *catch_exception_unhandled_sym;
10628
10629    /* The name of the symbol to break on in order to insert
10630       a catchpoint on failed assertions.  */
10631    const char *catch_assert_sym;
10632
10633    /* Assuming that the inferior just triggered an unhandled exception
10634       catchpoint, this function is responsible for returning the address
10635       in inferior memory where the name of that exception is stored.
10636       Return zero if the address could not be computed.  */
10637    ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
10638 };
10639
10640 static CORE_ADDR ada_unhandled_exception_name_addr (void);
10641 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
10642
10643 /* The following exception support info structure describes how to
10644    implement exception catchpoints with the latest version of the
10645    Ada runtime (as of 2007-03-06).  */
10646
10647 static const struct exception_support_info default_exception_support_info =
10648 {
10649   "__gnat_debug_raise_exception", /* catch_exception_sym */
10650   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
10651   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
10652   ada_unhandled_exception_name_addr
10653 };
10654
10655 /* The following exception support info structure describes how to
10656    implement exception catchpoints with a slightly older version
10657    of the Ada runtime.  */
10658
10659 static const struct exception_support_info exception_support_info_fallback =
10660 {
10661   "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
10662   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
10663   "system__assertions__raise_assert_failure",  /* catch_assert_sym */
10664   ada_unhandled_exception_name_addr_from_raise
10665 };
10666
10667 /* Return nonzero if we can detect the exception support routines
10668    described in EINFO.
10669
10670    This function errors out if an abnormal situation is detected
10671    (for instance, if we find the exception support routines, but
10672    that support is found to be incomplete).  */
10673
10674 static int
10675 ada_has_this_exception_support (const struct exception_support_info *einfo)
10676 {
10677   struct symbol *sym;
10678
10679   /* The symbol we're looking up is provided by a unit in the GNAT runtime
10680      that should be compiled with debugging information.  As a result, we
10681      expect to find that symbol in the symtabs.  */
10682
10683   sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
10684   if (sym == NULL)
10685     {
10686       /* Perhaps we did not find our symbol because the Ada runtime was
10687          compiled without debugging info, or simply stripped of it.
10688          It happens on some GNU/Linux distributions for instance, where
10689          users have to install a separate debug package in order to get
10690          the runtime's debugging info.  In that situation, let the user
10691          know why we cannot insert an Ada exception catchpoint.
10692
10693          Note: Just for the purpose of inserting our Ada exception
10694          catchpoint, we could rely purely on the associated minimal symbol.
10695          But we would be operating in degraded mode anyway, since we are
10696          still lacking the debugging info needed later on to extract
10697          the name of the exception being raised (this name is printed in
10698          the catchpoint message, and is also used when trying to catch
10699          a specific exception).  We do not handle this case for now.  */
10700       if (lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL))
10701         error (_("Your Ada runtime appears to be missing some debugging "
10702                  "information.\nCannot insert Ada exception catchpoint "
10703                  "in this configuration."));
10704
10705       return 0;
10706     }
10707
10708   /* Make sure that the symbol we found corresponds to a function.  */
10709
10710   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
10711     error (_("Symbol \"%s\" is not a function (class = %d)"),
10712            SYMBOL_LINKAGE_NAME (sym), SYMBOL_CLASS (sym));
10713
10714   return 1;
10715 }
10716
10717 /* Inspect the Ada runtime and determine which exception info structure
10718    should be used to provide support for exception catchpoints.
10719
10720    This function will always set the per-inferior exception_info,
10721    or raise an error.  */
10722
10723 static void
10724 ada_exception_support_info_sniffer (void)
10725 {
10726   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
10727   struct symbol *sym;
10728
10729   /* If the exception info is already known, then no need to recompute it.  */
10730   if (data->exception_info != NULL)
10731     return;
10732
10733   /* Check the latest (default) exception support info.  */
10734   if (ada_has_this_exception_support (&default_exception_support_info))
10735     {
10736       data->exception_info = &default_exception_support_info;
10737       return;
10738     }
10739
10740   /* Try our fallback exception suport info.  */
10741   if (ada_has_this_exception_support (&exception_support_info_fallback))
10742     {
10743       data->exception_info = &exception_support_info_fallback;
10744       return;
10745     }
10746
10747   /* Sometimes, it is normal for us to not be able to find the routine
10748      we are looking for.  This happens when the program is linked with
10749      the shared version of the GNAT runtime, and the program has not been
10750      started yet.  Inform the user of these two possible causes if
10751      applicable.  */
10752
10753   if (ada_update_initial_language (language_unknown) != language_ada)
10754     error (_("Unable to insert catchpoint.  Is this an Ada main program?"));
10755
10756   /* If the symbol does not exist, then check that the program is
10757      already started, to make sure that shared libraries have been
10758      loaded.  If it is not started, this may mean that the symbol is
10759      in a shared library.  */
10760
10761   if (ptid_get_pid (inferior_ptid) == 0)
10762     error (_("Unable to insert catchpoint. Try to start the program first."));
10763
10764   /* At this point, we know that we are debugging an Ada program and
10765      that the inferior has been started, but we still are not able to
10766      find the run-time symbols.  That can mean that we are in
10767      configurable run time mode, or that a-except as been optimized
10768      out by the linker...  In any case, at this point it is not worth
10769      supporting this feature.  */
10770
10771   error (_("Cannot insert Ada exception catchpoints in this configuration."));
10772 }
10773
10774 /* True iff FRAME is very likely to be that of a function that is
10775    part of the runtime system.  This is all very heuristic, but is
10776    intended to be used as advice as to what frames are uninteresting
10777    to most users.  */
10778
10779 static int
10780 is_known_support_routine (struct frame_info *frame)
10781 {
10782   struct symtab_and_line sal;
10783   char *func_name;
10784   enum language func_lang;
10785   int i;
10786
10787   /* If this code does not have any debugging information (no symtab),
10788      This cannot be any user code.  */
10789
10790   find_frame_sal (frame, &sal);
10791   if (sal.symtab == NULL)
10792     return 1;
10793
10794   /* If there is a symtab, but the associated source file cannot be
10795      located, then assume this is not user code:  Selecting a frame
10796      for which we cannot display the code would not be very helpful
10797      for the user.  This should also take care of case such as VxWorks
10798      where the kernel has some debugging info provided for a few units.  */
10799
10800   if (symtab_to_fullname (sal.symtab) == NULL)
10801     return 1;
10802
10803   /* Check the unit filename againt the Ada runtime file naming.
10804      We also check the name of the objfile against the name of some
10805      known system libraries that sometimes come with debugging info
10806      too.  */
10807
10808   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
10809     {
10810       re_comp (known_runtime_file_name_patterns[i]);
10811       if (re_exec (sal.symtab->filename))
10812         return 1;
10813       if (sal.symtab->objfile != NULL
10814           && re_exec (sal.symtab->objfile->name))
10815         return 1;
10816     }
10817
10818   /* Check whether the function is a GNAT-generated entity.  */
10819
10820   find_frame_funname (frame, &func_name, &func_lang, NULL);
10821   if (func_name == NULL)
10822     return 1;
10823
10824   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
10825     {
10826       re_comp (known_auxiliary_function_name_patterns[i]);
10827       if (re_exec (func_name))
10828         return 1;
10829     }
10830
10831   return 0;
10832 }
10833
10834 /* Find the first frame that contains debugging information and that is not
10835    part of the Ada run-time, starting from FI and moving upward.  */
10836
10837 void
10838 ada_find_printable_frame (struct frame_info *fi)
10839 {
10840   for (; fi != NULL; fi = get_prev_frame (fi))
10841     {
10842       if (!is_known_support_routine (fi))
10843         {
10844           select_frame (fi);
10845           break;
10846         }
10847     }
10848
10849 }
10850
10851 /* Assuming that the inferior just triggered an unhandled exception
10852    catchpoint, return the address in inferior memory where the name
10853    of the exception is stored.
10854    
10855    Return zero if the address could not be computed.  */
10856
10857 static CORE_ADDR
10858 ada_unhandled_exception_name_addr (void)
10859 {
10860   return parse_and_eval_address ("e.full_name");
10861 }
10862
10863 /* Same as ada_unhandled_exception_name_addr, except that this function
10864    should be used when the inferior uses an older version of the runtime,
10865    where the exception name needs to be extracted from a specific frame
10866    several frames up in the callstack.  */
10867
10868 static CORE_ADDR
10869 ada_unhandled_exception_name_addr_from_raise (void)
10870 {
10871   int frame_level;
10872   struct frame_info *fi;
10873   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
10874
10875   /* To determine the name of this exception, we need to select
10876      the frame corresponding to RAISE_SYM_NAME.  This frame is
10877      at least 3 levels up, so we simply skip the first 3 frames
10878      without checking the name of their associated function.  */
10879   fi = get_current_frame ();
10880   for (frame_level = 0; frame_level < 3; frame_level += 1)
10881     if (fi != NULL)
10882       fi = get_prev_frame (fi); 
10883
10884   while (fi != NULL)
10885     {
10886       char *func_name;
10887       enum language func_lang;
10888
10889       find_frame_funname (fi, &func_name, &func_lang, NULL);
10890       if (func_name != NULL
10891           && strcmp (func_name, data->exception_info->catch_exception_sym) == 0)
10892         break; /* We found the frame we were looking for...  */
10893       fi = get_prev_frame (fi);
10894     }
10895
10896   if (fi == NULL)
10897     return 0;
10898
10899   select_frame (fi);
10900   return parse_and_eval_address ("id.full_name");
10901 }
10902
10903 /* Assuming the inferior just triggered an Ada exception catchpoint
10904    (of any type), return the address in inferior memory where the name
10905    of the exception is stored, if applicable.
10906
10907    Return zero if the address could not be computed, or if not relevant.  */
10908
10909 static CORE_ADDR
10910 ada_exception_name_addr_1 (enum exception_catchpoint_kind ex,
10911                            struct breakpoint *b)
10912 {
10913   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
10914
10915   switch (ex)
10916     {
10917       case ex_catch_exception:
10918         return (parse_and_eval_address ("e.full_name"));
10919         break;
10920
10921       case ex_catch_exception_unhandled:
10922         return data->exception_info->unhandled_exception_name_addr ();
10923         break;
10924       
10925       case ex_catch_assert:
10926         return 0;  /* Exception name is not relevant in this case.  */
10927         break;
10928
10929       default:
10930         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
10931         break;
10932     }
10933
10934   return 0; /* Should never be reached.  */
10935 }
10936
10937 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
10938    any error that ada_exception_name_addr_1 might cause to be thrown.
10939    When an error is intercepted, a warning with the error message is printed,
10940    and zero is returned.  */
10941
10942 static CORE_ADDR
10943 ada_exception_name_addr (enum exception_catchpoint_kind ex,
10944                          struct breakpoint *b)
10945 {
10946   struct gdb_exception e;
10947   CORE_ADDR result = 0;
10948
10949   TRY_CATCH (e, RETURN_MASK_ERROR)
10950     {
10951       result = ada_exception_name_addr_1 (ex, b);
10952     }
10953
10954   if (e.reason < 0)
10955     {
10956       warning (_("failed to get exception name: %s"), e.message);
10957       return 0;
10958     }
10959
10960   return result;
10961 }
10962
10963 static struct symtab_and_line ada_exception_sal (enum exception_catchpoint_kind,
10964                                                  char *, char **,
10965                                                  const struct breakpoint_ops **);
10966 static char *ada_exception_catchpoint_cond_string (const char *excep_string);
10967
10968 /* Ada catchpoints.
10969
10970    In the case of catchpoints on Ada exceptions, the catchpoint will
10971    stop the target on every exception the program throws.  When a user
10972    specifies the name of a specific exception, we translate this
10973    request into a condition expression (in text form), and then parse
10974    it into an expression stored in each of the catchpoint's locations.
10975    We then use this condition to check whether the exception that was
10976    raised is the one the user is interested in.  If not, then the
10977    target is resumed again.  We store the name of the requested
10978    exception, in order to be able to re-set the condition expression
10979    when symbols change.  */
10980
10981 /* An instance of this type is used to represent an Ada catchpoint
10982    breakpoint location.  It includes a "struct bp_location" as a kind
10983    of base class; users downcast to "struct bp_location *" when
10984    needed.  */
10985
10986 struct ada_catchpoint_location
10987 {
10988   /* The base class.  */
10989   struct bp_location base;
10990
10991   /* The condition that checks whether the exception that was raised
10992      is the specific exception the user specified on catchpoint
10993      creation.  */
10994   struct expression *excep_cond_expr;
10995 };
10996
10997 /* Implement the DTOR method in the bp_location_ops structure for all
10998    Ada exception catchpoint kinds.  */
10999
11000 static void
11001 ada_catchpoint_location_dtor (struct bp_location *bl)
11002 {
11003   struct ada_catchpoint_location *al = (struct ada_catchpoint_location *) bl;
11004
11005   xfree (al->excep_cond_expr);
11006 }
11007
11008 /* The vtable to be used in Ada catchpoint locations.  */
11009
11010 static const struct bp_location_ops ada_catchpoint_location_ops =
11011 {
11012   ada_catchpoint_location_dtor
11013 };
11014
11015 /* An instance of this type is used to represent an Ada catchpoint.
11016    It includes a "struct breakpoint" as a kind of base class; users
11017    downcast to "struct breakpoint *" when needed.  */
11018
11019 struct ada_catchpoint
11020 {
11021   /* The base class.  */
11022   struct breakpoint base;
11023
11024   /* The name of the specific exception the user specified.  */
11025   char *excep_string;
11026 };
11027
11028 /* Parse the exception condition string in the context of each of the
11029    catchpoint's locations, and store them for later evaluation.  */
11030
11031 static void
11032 create_excep_cond_exprs (struct ada_catchpoint *c)
11033 {
11034   struct cleanup *old_chain;
11035   struct bp_location *bl;
11036   char *cond_string;
11037
11038   /* Nothing to do if there's no specific exception to catch.  */
11039   if (c->excep_string == NULL)
11040     return;
11041
11042   /* Same if there are no locations... */
11043   if (c->base.loc == NULL)
11044     return;
11045
11046   /* Compute the condition expression in text form, from the specific
11047      expection we want to catch.  */
11048   cond_string = ada_exception_catchpoint_cond_string (c->excep_string);
11049   old_chain = make_cleanup (xfree, cond_string);
11050
11051   /* Iterate over all the catchpoint's locations, and parse an
11052      expression for each.  */
11053   for (bl = c->base.loc; bl != NULL; bl = bl->next)
11054     {
11055       struct ada_catchpoint_location *ada_loc
11056         = (struct ada_catchpoint_location *) bl;
11057       struct expression *exp = NULL;
11058
11059       if (!bl->shlib_disabled)
11060         {
11061           volatile struct gdb_exception e;
11062           char *s;
11063
11064           s = cond_string;
11065           TRY_CATCH (e, RETURN_MASK_ERROR)
11066             {
11067               exp = parse_exp_1 (&s, block_for_pc (bl->address), 0);
11068             }
11069           if (e.reason < 0)
11070             warning (_("failed to reevaluate internal exception condition "
11071                        "for catchpoint %d: %s"),
11072                      c->base.number, e.message);
11073         }
11074
11075       ada_loc->excep_cond_expr = exp;
11076     }
11077
11078   do_cleanups (old_chain);
11079 }
11080
11081 /* Implement the DTOR method in the breakpoint_ops structure for all
11082    exception catchpoint kinds.  */
11083
11084 static void
11085 dtor_exception (enum exception_catchpoint_kind ex, struct breakpoint *b)
11086 {
11087   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11088
11089   xfree (c->excep_string);
11090
11091   bkpt_breakpoint_ops.dtor (b);
11092 }
11093
11094 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
11095    structure for all exception catchpoint kinds.  */
11096
11097 static struct bp_location *
11098 allocate_location_exception (enum exception_catchpoint_kind ex,
11099                              struct breakpoint *self)
11100 {
11101   struct ada_catchpoint_location *loc;
11102
11103   loc = XNEW (struct ada_catchpoint_location);
11104   init_bp_location (&loc->base, &ada_catchpoint_location_ops, self);
11105   loc->excep_cond_expr = NULL;
11106   return &loc->base;
11107 }
11108
11109 /* Implement the RE_SET method in the breakpoint_ops structure for all
11110    exception catchpoint kinds.  */
11111
11112 static void
11113 re_set_exception (enum exception_catchpoint_kind ex, struct breakpoint *b)
11114 {
11115   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11116
11117   /* Call the base class's method.  This updates the catchpoint's
11118      locations.  */
11119   bkpt_breakpoint_ops.re_set (b);
11120
11121   /* Reparse the exception conditional expressions.  One for each
11122      location.  */
11123   create_excep_cond_exprs (c);
11124 }
11125
11126 /* Returns true if we should stop for this breakpoint hit.  If the
11127    user specified a specific exception, we only want to cause a stop
11128    if the program thrown that exception.  */
11129
11130 static int
11131 should_stop_exception (const struct bp_location *bl)
11132 {
11133   struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
11134   const struct ada_catchpoint_location *ada_loc
11135     = (const struct ada_catchpoint_location *) bl;
11136   volatile struct gdb_exception ex;
11137   int stop;
11138
11139   /* With no specific exception, should always stop.  */
11140   if (c->excep_string == NULL)
11141     return 1;
11142
11143   if (ada_loc->excep_cond_expr == NULL)
11144     {
11145       /* We will have a NULL expression if back when we were creating
11146          the expressions, this location's had failed to parse.  */
11147       return 1;
11148     }
11149
11150   stop = 1;
11151   TRY_CATCH (ex, RETURN_MASK_ALL)
11152     {
11153       struct value *mark;
11154
11155       mark = value_mark ();
11156       stop = value_true (evaluate_expression (ada_loc->excep_cond_expr));
11157       value_free_to_mark (mark);
11158     }
11159   if (ex.reason < 0)
11160     exception_fprintf (gdb_stderr, ex,
11161                        _("Error in testing exception condition:\n"));
11162   return stop;
11163 }
11164
11165 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
11166    for all exception catchpoint kinds.  */
11167
11168 static void
11169 check_status_exception (enum exception_catchpoint_kind ex, bpstat bs)
11170 {
11171   bs->stop = should_stop_exception (bs->bp_location_at);
11172 }
11173
11174 /* Implement the PRINT_IT method in the breakpoint_ops structure
11175    for all exception catchpoint kinds.  */
11176
11177 static enum print_stop_action
11178 print_it_exception (enum exception_catchpoint_kind ex, bpstat bs)
11179 {
11180   struct ui_out *uiout = current_uiout;
11181   struct breakpoint *b = bs->breakpoint_at;
11182
11183   annotate_catchpoint (b->number);
11184
11185   if (ui_out_is_mi_like_p (uiout))
11186     {
11187       ui_out_field_string (uiout, "reason",
11188                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11189       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11190     }
11191
11192   ui_out_text (uiout,
11193                b->disposition == disp_del ? "\nTemporary catchpoint "
11194                                           : "\nCatchpoint ");
11195   ui_out_field_int (uiout, "bkptno", b->number);
11196   ui_out_text (uiout, ", ");
11197
11198   switch (ex)
11199     {
11200       case ex_catch_exception:
11201       case ex_catch_exception_unhandled:
11202         {
11203           const CORE_ADDR addr = ada_exception_name_addr (ex, b);
11204           char exception_name[256];
11205
11206           if (addr != 0)
11207             {
11208               read_memory (addr, exception_name, sizeof (exception_name) - 1);
11209               exception_name [sizeof (exception_name) - 1] = '\0';
11210             }
11211           else
11212             {
11213               /* For some reason, we were unable to read the exception
11214                  name.  This could happen if the Runtime was compiled
11215                  without debugging info, for instance.  In that case,
11216                  just replace the exception name by the generic string
11217                  "exception" - it will read as "an exception" in the
11218                  notification we are about to print.  */
11219               memcpy (exception_name, "exception", sizeof ("exception"));
11220             }
11221           /* In the case of unhandled exception breakpoints, we print
11222              the exception name as "unhandled EXCEPTION_NAME", to make
11223              it clearer to the user which kind of catchpoint just got
11224              hit.  We used ui_out_text to make sure that this extra
11225              info does not pollute the exception name in the MI case.  */
11226           if (ex == ex_catch_exception_unhandled)
11227             ui_out_text (uiout, "unhandled ");
11228           ui_out_field_string (uiout, "exception-name", exception_name);
11229         }
11230         break;
11231       case ex_catch_assert:
11232         /* In this case, the name of the exception is not really
11233            important.  Just print "failed assertion" to make it clearer
11234            that his program just hit an assertion-failure catchpoint.
11235            We used ui_out_text because this info does not belong in
11236            the MI output.  */
11237         ui_out_text (uiout, "failed assertion");
11238         break;
11239     }
11240   ui_out_text (uiout, " at ");
11241   ada_find_printable_frame (get_current_frame ());
11242
11243   return PRINT_SRC_AND_LOC;
11244 }
11245
11246 /* Implement the PRINT_ONE method in the breakpoint_ops structure
11247    for all exception catchpoint kinds.  */
11248
11249 static void
11250 print_one_exception (enum exception_catchpoint_kind ex,
11251                      struct breakpoint *b, struct bp_location **last_loc)
11252
11253   struct ui_out *uiout = current_uiout;
11254   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11255   struct value_print_options opts;
11256
11257   get_user_print_options (&opts);
11258   if (opts.addressprint)
11259     {
11260       annotate_field (4);
11261       ui_out_field_core_addr (uiout, "addr", b->loc->gdbarch, b->loc->address);
11262     }
11263
11264   annotate_field (5);
11265   *last_loc = b->loc;
11266   switch (ex)
11267     {
11268       case ex_catch_exception:
11269         if (c->excep_string != NULL)
11270           {
11271             char *msg = xstrprintf (_("`%s' Ada exception"), c->excep_string);
11272
11273             ui_out_field_string (uiout, "what", msg);
11274             xfree (msg);
11275           }
11276         else
11277           ui_out_field_string (uiout, "what", "all Ada exceptions");
11278         
11279         break;
11280
11281       case ex_catch_exception_unhandled:
11282         ui_out_field_string (uiout, "what", "unhandled Ada exceptions");
11283         break;
11284       
11285       case ex_catch_assert:
11286         ui_out_field_string (uiout, "what", "failed Ada assertions");
11287         break;
11288
11289       default:
11290         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11291         break;
11292     }
11293 }
11294
11295 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
11296    for all exception catchpoint kinds.  */
11297
11298 static void
11299 print_mention_exception (enum exception_catchpoint_kind ex,
11300                          struct breakpoint *b)
11301 {
11302   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11303   struct ui_out *uiout = current_uiout;
11304
11305   ui_out_text (uiout, b->disposition == disp_del ? _("Temporary catchpoint ")
11306                                                  : _("Catchpoint "));
11307   ui_out_field_int (uiout, "bkptno", b->number);
11308   ui_out_text (uiout, ": ");
11309
11310   switch (ex)
11311     {
11312       case ex_catch_exception:
11313         if (c->excep_string != NULL)
11314           {
11315             char *info = xstrprintf (_("`%s' Ada exception"), c->excep_string);
11316             struct cleanup *old_chain = make_cleanup (xfree, info);
11317
11318             ui_out_text (uiout, info);
11319             do_cleanups (old_chain);
11320           }
11321         else
11322           ui_out_text (uiout, _("all Ada exceptions"));
11323         break;
11324
11325       case ex_catch_exception_unhandled:
11326         ui_out_text (uiout, _("unhandled Ada exceptions"));
11327         break;
11328       
11329       case ex_catch_assert:
11330         ui_out_text (uiout, _("failed Ada assertions"));
11331         break;
11332
11333       default:
11334         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11335         break;
11336     }
11337 }
11338
11339 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
11340    for all exception catchpoint kinds.  */
11341
11342 static void
11343 print_recreate_exception (enum exception_catchpoint_kind ex,
11344                           struct breakpoint *b, struct ui_file *fp)
11345 {
11346   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11347
11348   switch (ex)
11349     {
11350       case ex_catch_exception:
11351         fprintf_filtered (fp, "catch exception");
11352         if (c->excep_string != NULL)
11353           fprintf_filtered (fp, " %s", c->excep_string);
11354         break;
11355
11356       case ex_catch_exception_unhandled:
11357         fprintf_filtered (fp, "catch exception unhandled");
11358         break;
11359
11360       case ex_catch_assert:
11361         fprintf_filtered (fp, "catch assert");
11362         break;
11363
11364       default:
11365         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11366     }
11367   print_recreate_thread (b, fp);
11368 }
11369
11370 /* Virtual table for "catch exception" breakpoints.  */
11371
11372 static void
11373 dtor_catch_exception (struct breakpoint *b)
11374 {
11375   dtor_exception (ex_catch_exception, b);
11376 }
11377
11378 static struct bp_location *
11379 allocate_location_catch_exception (struct breakpoint *self)
11380 {
11381   return allocate_location_exception (ex_catch_exception, self);
11382 }
11383
11384 static void
11385 re_set_catch_exception (struct breakpoint *b)
11386 {
11387   re_set_exception (ex_catch_exception, b);
11388 }
11389
11390 static void
11391 check_status_catch_exception (bpstat bs)
11392 {
11393   check_status_exception (ex_catch_exception, bs);
11394 }
11395
11396 static enum print_stop_action
11397 print_it_catch_exception (bpstat bs)
11398 {
11399   return print_it_exception (ex_catch_exception, bs);
11400 }
11401
11402 static void
11403 print_one_catch_exception (struct breakpoint *b, struct bp_location **last_loc)
11404 {
11405   print_one_exception (ex_catch_exception, b, last_loc);
11406 }
11407
11408 static void
11409 print_mention_catch_exception (struct breakpoint *b)
11410 {
11411   print_mention_exception (ex_catch_exception, b);
11412 }
11413
11414 static void
11415 print_recreate_catch_exception (struct breakpoint *b, struct ui_file *fp)
11416 {
11417   print_recreate_exception (ex_catch_exception, b, fp);
11418 }
11419
11420 static struct breakpoint_ops catch_exception_breakpoint_ops;
11421
11422 /* Virtual table for "catch exception unhandled" breakpoints.  */
11423
11424 static void
11425 dtor_catch_exception_unhandled (struct breakpoint *b)
11426 {
11427   dtor_exception (ex_catch_exception_unhandled, b);
11428 }
11429
11430 static struct bp_location *
11431 allocate_location_catch_exception_unhandled (struct breakpoint *self)
11432 {
11433   return allocate_location_exception (ex_catch_exception_unhandled, self);
11434 }
11435
11436 static void
11437 re_set_catch_exception_unhandled (struct breakpoint *b)
11438 {
11439   re_set_exception (ex_catch_exception_unhandled, b);
11440 }
11441
11442 static void
11443 check_status_catch_exception_unhandled (bpstat bs)
11444 {
11445   check_status_exception (ex_catch_exception_unhandled, bs);
11446 }
11447
11448 static enum print_stop_action
11449 print_it_catch_exception_unhandled (bpstat bs)
11450 {
11451   return print_it_exception (ex_catch_exception_unhandled, bs);
11452 }
11453
11454 static void
11455 print_one_catch_exception_unhandled (struct breakpoint *b,
11456                                      struct bp_location **last_loc)
11457 {
11458   print_one_exception (ex_catch_exception_unhandled, b, last_loc);
11459 }
11460
11461 static void
11462 print_mention_catch_exception_unhandled (struct breakpoint *b)
11463 {
11464   print_mention_exception (ex_catch_exception_unhandled, b);
11465 }
11466
11467 static void
11468 print_recreate_catch_exception_unhandled (struct breakpoint *b,
11469                                           struct ui_file *fp)
11470 {
11471   print_recreate_exception (ex_catch_exception_unhandled, b, fp);
11472 }
11473
11474 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
11475
11476 /* Virtual table for "catch assert" breakpoints.  */
11477
11478 static void
11479 dtor_catch_assert (struct breakpoint *b)
11480 {
11481   dtor_exception (ex_catch_assert, b);
11482 }
11483
11484 static struct bp_location *
11485 allocate_location_catch_assert (struct breakpoint *self)
11486 {
11487   return allocate_location_exception (ex_catch_assert, self);
11488 }
11489
11490 static void
11491 re_set_catch_assert (struct breakpoint *b)
11492 {
11493   return re_set_exception (ex_catch_assert, b);
11494 }
11495
11496 static void
11497 check_status_catch_assert (bpstat bs)
11498 {
11499   check_status_exception (ex_catch_assert, bs);
11500 }
11501
11502 static enum print_stop_action
11503 print_it_catch_assert (bpstat bs)
11504 {
11505   return print_it_exception (ex_catch_assert, bs);
11506 }
11507
11508 static void
11509 print_one_catch_assert (struct breakpoint *b, struct bp_location **last_loc)
11510 {
11511   print_one_exception (ex_catch_assert, b, last_loc);
11512 }
11513
11514 static void
11515 print_mention_catch_assert (struct breakpoint *b)
11516 {
11517   print_mention_exception (ex_catch_assert, b);
11518 }
11519
11520 static void
11521 print_recreate_catch_assert (struct breakpoint *b, struct ui_file *fp)
11522 {
11523   print_recreate_exception (ex_catch_assert, b, fp);
11524 }
11525
11526 static struct breakpoint_ops catch_assert_breakpoint_ops;
11527
11528 /* Return a newly allocated copy of the first space-separated token
11529    in ARGSP, and then adjust ARGSP to point immediately after that
11530    token.
11531
11532    Return NULL if ARGPS does not contain any more tokens.  */
11533
11534 static char *
11535 ada_get_next_arg (char **argsp)
11536 {
11537   char *args = *argsp;
11538   char *end;
11539   char *result;
11540
11541   args = skip_spaces (args);
11542   if (args[0] == '\0')
11543     return NULL; /* No more arguments.  */
11544   
11545   /* Find the end of the current argument.  */
11546
11547   end = skip_to_space (args);
11548
11549   /* Adjust ARGSP to point to the start of the next argument.  */
11550
11551   *argsp = end;
11552
11553   /* Make a copy of the current argument and return it.  */
11554
11555   result = xmalloc (end - args + 1);
11556   strncpy (result, args, end - args);
11557   result[end - args] = '\0';
11558   
11559   return result;
11560 }
11561
11562 /* Split the arguments specified in a "catch exception" command.  
11563    Set EX to the appropriate catchpoint type.
11564    Set EXCEP_STRING to the name of the specific exception if
11565    specified by the user.  */
11566
11567 static void
11568 catch_ada_exception_command_split (char *args,
11569                                    enum exception_catchpoint_kind *ex,
11570                                    char **excep_string)
11571 {
11572   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
11573   char *exception_name;
11574
11575   exception_name = ada_get_next_arg (&args);
11576   make_cleanup (xfree, exception_name);
11577
11578   /* Check that we do not have any more arguments.  Anything else
11579      is unexpected.  */
11580
11581   args = skip_spaces (args);
11582
11583   if (args[0] != '\0')
11584     error (_("Junk at end of expression"));
11585
11586   discard_cleanups (old_chain);
11587
11588   if (exception_name == NULL)
11589     {
11590       /* Catch all exceptions.  */
11591       *ex = ex_catch_exception;
11592       *excep_string = NULL;
11593     }
11594   else if (strcmp (exception_name, "unhandled") == 0)
11595     {
11596       /* Catch unhandled exceptions.  */
11597       *ex = ex_catch_exception_unhandled;
11598       *excep_string = NULL;
11599     }
11600   else
11601     {
11602       /* Catch a specific exception.  */
11603       *ex = ex_catch_exception;
11604       *excep_string = exception_name;
11605     }
11606 }
11607
11608 /* Return the name of the symbol on which we should break in order to
11609    implement a catchpoint of the EX kind.  */
11610
11611 static const char *
11612 ada_exception_sym_name (enum exception_catchpoint_kind ex)
11613 {
11614   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11615
11616   gdb_assert (data->exception_info != NULL);
11617
11618   switch (ex)
11619     {
11620       case ex_catch_exception:
11621         return (data->exception_info->catch_exception_sym);
11622         break;
11623       case ex_catch_exception_unhandled:
11624         return (data->exception_info->catch_exception_unhandled_sym);
11625         break;
11626       case ex_catch_assert:
11627         return (data->exception_info->catch_assert_sym);
11628         break;
11629       default:
11630         internal_error (__FILE__, __LINE__,
11631                         _("unexpected catchpoint kind (%d)"), ex);
11632     }
11633 }
11634
11635 /* Return the breakpoint ops "virtual table" used for catchpoints
11636    of the EX kind.  */
11637
11638 static const struct breakpoint_ops *
11639 ada_exception_breakpoint_ops (enum exception_catchpoint_kind ex)
11640 {
11641   switch (ex)
11642     {
11643       case ex_catch_exception:
11644         return (&catch_exception_breakpoint_ops);
11645         break;
11646       case ex_catch_exception_unhandled:
11647         return (&catch_exception_unhandled_breakpoint_ops);
11648         break;
11649       case ex_catch_assert:
11650         return (&catch_assert_breakpoint_ops);
11651         break;
11652       default:
11653         internal_error (__FILE__, __LINE__,
11654                         _("unexpected catchpoint kind (%d)"), ex);
11655     }
11656 }
11657
11658 /* Return the condition that will be used to match the current exception
11659    being raised with the exception that the user wants to catch.  This
11660    assumes that this condition is used when the inferior just triggered
11661    an exception catchpoint.
11662    
11663    The string returned is a newly allocated string that needs to be
11664    deallocated later.  */
11665
11666 static char *
11667 ada_exception_catchpoint_cond_string (const char *excep_string)
11668 {
11669   int i;
11670
11671   /* The standard exceptions are a special case.  They are defined in
11672      runtime units that have been compiled without debugging info; if
11673      EXCEP_STRING is the not-fully-qualified name of a standard
11674      exception (e.g. "constraint_error") then, during the evaluation
11675      of the condition expression, the symbol lookup on this name would
11676      *not* return this standard exception.  The catchpoint condition
11677      may then be set only on user-defined exceptions which have the
11678      same not-fully-qualified name (e.g. my_package.constraint_error).
11679
11680      To avoid this unexcepted behavior, these standard exceptions are
11681      systematically prefixed by "standard".  This means that "catch
11682      exception constraint_error" is rewritten into "catch exception
11683      standard.constraint_error".
11684
11685      If an exception named contraint_error is defined in another package of
11686      the inferior program, then the only way to specify this exception as a
11687      breakpoint condition is to use its fully-qualified named:
11688      e.g. my_package.constraint_error.  */
11689
11690   for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
11691     {
11692       if (strcmp (standard_exc [i], excep_string) == 0)
11693         {
11694           return xstrprintf ("long_integer (e) = long_integer (&standard.%s)",
11695                              excep_string);
11696         }
11697     }
11698   return xstrprintf ("long_integer (e) = long_integer (&%s)", excep_string);
11699 }
11700
11701 /* Return the symtab_and_line that should be used to insert an exception
11702    catchpoint of the TYPE kind.
11703
11704    EXCEP_STRING should contain the name of a specific exception that
11705    the catchpoint should catch, or NULL otherwise.
11706
11707    ADDR_STRING returns the name of the function where the real
11708    breakpoint that implements the catchpoints is set, depending on the
11709    type of catchpoint we need to create.  */
11710
11711 static struct symtab_and_line
11712 ada_exception_sal (enum exception_catchpoint_kind ex, char *excep_string,
11713                    char **addr_string, const struct breakpoint_ops **ops)
11714 {
11715   const char *sym_name;
11716   struct symbol *sym;
11717
11718   /* First, find out which exception support info to use.  */
11719   ada_exception_support_info_sniffer ();
11720
11721   /* Then lookup the function on which we will break in order to catch
11722      the Ada exceptions requested by the user.  */
11723   sym_name = ada_exception_sym_name (ex);
11724   sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
11725
11726   /* We can assume that SYM is not NULL at this stage.  If the symbol
11727      did not exist, ada_exception_support_info_sniffer would have
11728      raised an exception.
11729
11730      Also, ada_exception_support_info_sniffer should have already
11731      verified that SYM is a function symbol.  */
11732   gdb_assert (sym != NULL);
11733   gdb_assert (SYMBOL_CLASS (sym) == LOC_BLOCK);
11734
11735   /* Set ADDR_STRING.  */
11736   *addr_string = xstrdup (sym_name);
11737
11738   /* Set OPS.  */
11739   *ops = ada_exception_breakpoint_ops (ex);
11740
11741   return find_function_start_sal (sym, 1);
11742 }
11743
11744 /* Parse the arguments (ARGS) of the "catch exception" command.
11745  
11746    If the user asked the catchpoint to catch only a specific
11747    exception, then save the exception name in ADDR_STRING.
11748
11749    See ada_exception_sal for a description of all the remaining
11750    function arguments of this function.  */
11751
11752 static struct symtab_and_line
11753 ada_decode_exception_location (char *args, char **addr_string,
11754                                char **excep_string,
11755                                const struct breakpoint_ops **ops)
11756 {
11757   enum exception_catchpoint_kind ex;
11758
11759   catch_ada_exception_command_split (args, &ex, excep_string);
11760   return ada_exception_sal (ex, *excep_string, addr_string, ops);
11761 }
11762
11763 /* Create an Ada exception catchpoint.  */
11764
11765 static void
11766 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
11767                                  struct symtab_and_line sal,
11768                                  char *addr_string,
11769                                  char *excep_string,
11770                                  const struct breakpoint_ops *ops,
11771                                  int tempflag,
11772                                  int from_tty)
11773 {
11774   struct ada_catchpoint *c;
11775
11776   c = XNEW (struct ada_catchpoint);
11777   init_ada_exception_breakpoint (&c->base, gdbarch, sal, addr_string,
11778                                  ops, tempflag, from_tty);
11779   c->excep_string = excep_string;
11780   create_excep_cond_exprs (c);
11781   install_breakpoint (0, &c->base, 1);
11782 }
11783
11784 /* Implement the "catch exception" command.  */
11785
11786 static void
11787 catch_ada_exception_command (char *arg, int from_tty,
11788                              struct cmd_list_element *command)
11789 {
11790   struct gdbarch *gdbarch = get_current_arch ();
11791   int tempflag;
11792   struct symtab_and_line sal;
11793   char *addr_string = NULL;
11794   char *excep_string = NULL;
11795   const struct breakpoint_ops *ops = NULL;
11796
11797   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11798
11799   if (!arg)
11800     arg = "";
11801   sal = ada_decode_exception_location (arg, &addr_string, &excep_string, &ops);
11802   create_ada_exception_catchpoint (gdbarch, sal, addr_string,
11803                                    excep_string, ops, tempflag, from_tty);
11804 }
11805
11806 static struct symtab_and_line
11807 ada_decode_assert_location (char *args, char **addr_string,
11808                             const struct breakpoint_ops **ops)
11809 {
11810   /* Check that no argument where provided at the end of the command.  */
11811
11812   if (args != NULL)
11813     {
11814       args = skip_spaces (args);
11815       if (*args != '\0')
11816         error (_("Junk at end of arguments."));
11817     }
11818
11819   return ada_exception_sal (ex_catch_assert, NULL, addr_string, ops);
11820 }
11821
11822 /* Implement the "catch assert" command.  */
11823
11824 static void
11825 catch_assert_command (char *arg, int from_tty,
11826                       struct cmd_list_element *command)
11827 {
11828   struct gdbarch *gdbarch = get_current_arch ();
11829   int tempflag;
11830   struct symtab_and_line sal;
11831   char *addr_string = NULL;
11832   const struct breakpoint_ops *ops = NULL;
11833
11834   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11835
11836   if (!arg)
11837     arg = "";
11838   sal = ada_decode_assert_location (arg, &addr_string, &ops);
11839   create_ada_exception_catchpoint (gdbarch, sal, addr_string,
11840                                    NULL, ops, tempflag, from_tty);
11841 }
11842                                 /* Operators */
11843 /* Information about operators given special treatment in functions
11844    below.  */
11845 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>).  */
11846
11847 #define ADA_OPERATORS \
11848     OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
11849     OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
11850     OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
11851     OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
11852     OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
11853     OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
11854     OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
11855     OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
11856     OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
11857     OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
11858     OP_DEFN (OP_ATR_POS, 1, 2, 0) \
11859     OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
11860     OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
11861     OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
11862     OP_DEFN (UNOP_QUAL, 3, 1, 0) \
11863     OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
11864     OP_DEFN (OP_OTHERS, 1, 1, 0) \
11865     OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
11866     OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
11867
11868 static void
11869 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
11870                      int *argsp)
11871 {
11872   switch (exp->elts[pc - 1].opcode)
11873     {
11874     default:
11875       operator_length_standard (exp, pc, oplenp, argsp);
11876       break;
11877
11878 #define OP_DEFN(op, len, args, binop) \
11879     case op: *oplenp = len; *argsp = args; break;
11880       ADA_OPERATORS;
11881 #undef OP_DEFN
11882
11883     case OP_AGGREGATE:
11884       *oplenp = 3;
11885       *argsp = longest_to_int (exp->elts[pc - 2].longconst);
11886       break;
11887
11888     case OP_CHOICES:
11889       *oplenp = 3;
11890       *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
11891       break;
11892     }
11893 }
11894
11895 /* Implementation of the exp_descriptor method operator_check.  */
11896
11897 static int
11898 ada_operator_check (struct expression *exp, int pos,
11899                     int (*objfile_func) (struct objfile *objfile, void *data),
11900                     void *data)
11901 {
11902   const union exp_element *const elts = exp->elts;
11903   struct type *type = NULL;
11904
11905   switch (elts[pos].opcode)
11906     {
11907       case UNOP_IN_RANGE:
11908       case UNOP_QUAL:
11909         type = elts[pos + 1].type;
11910         break;
11911
11912       default:
11913         return operator_check_standard (exp, pos, objfile_func, data);
11914     }
11915
11916   /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL.  */
11917
11918   if (type && TYPE_OBJFILE (type)
11919       && (*objfile_func) (TYPE_OBJFILE (type), data))
11920     return 1;
11921
11922   return 0;
11923 }
11924
11925 static char *
11926 ada_op_name (enum exp_opcode opcode)
11927 {
11928   switch (opcode)
11929     {
11930     default:
11931       return op_name_standard (opcode);
11932
11933 #define OP_DEFN(op, len, args, binop) case op: return #op;
11934       ADA_OPERATORS;
11935 #undef OP_DEFN
11936
11937     case OP_AGGREGATE:
11938       return "OP_AGGREGATE";
11939     case OP_CHOICES:
11940       return "OP_CHOICES";
11941     case OP_NAME:
11942       return "OP_NAME";
11943     }
11944 }
11945
11946 /* As for operator_length, but assumes PC is pointing at the first
11947    element of the operator, and gives meaningful results only for the 
11948    Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise.  */
11949
11950 static void
11951 ada_forward_operator_length (struct expression *exp, int pc,
11952                              int *oplenp, int *argsp)
11953 {
11954   switch (exp->elts[pc].opcode)
11955     {
11956     default:
11957       *oplenp = *argsp = 0;
11958       break;
11959
11960 #define OP_DEFN(op, len, args, binop) \
11961     case op: *oplenp = len; *argsp = args; break;
11962       ADA_OPERATORS;
11963 #undef OP_DEFN
11964
11965     case OP_AGGREGATE:
11966       *oplenp = 3;
11967       *argsp = longest_to_int (exp->elts[pc + 1].longconst);
11968       break;
11969
11970     case OP_CHOICES:
11971       *oplenp = 3;
11972       *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
11973       break;
11974
11975     case OP_STRING:
11976     case OP_NAME:
11977       {
11978         int len = longest_to_int (exp->elts[pc + 1].longconst);
11979
11980         *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
11981         *argsp = 0;
11982         break;
11983       }
11984     }
11985 }
11986
11987 static int
11988 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
11989 {
11990   enum exp_opcode op = exp->elts[elt].opcode;
11991   int oplen, nargs;
11992   int pc = elt;
11993   int i;
11994
11995   ada_forward_operator_length (exp, elt, &oplen, &nargs);
11996
11997   switch (op)
11998     {
11999       /* Ada attributes ('Foo).  */
12000     case OP_ATR_FIRST:
12001     case OP_ATR_LAST:
12002     case OP_ATR_LENGTH:
12003     case OP_ATR_IMAGE:
12004     case OP_ATR_MAX:
12005     case OP_ATR_MIN:
12006     case OP_ATR_MODULUS:
12007     case OP_ATR_POS:
12008     case OP_ATR_SIZE:
12009     case OP_ATR_TAG:
12010     case OP_ATR_VAL:
12011       break;
12012
12013     case UNOP_IN_RANGE:
12014     case UNOP_QUAL:
12015       /* XXX: gdb_sprint_host_address, type_sprint */
12016       fprintf_filtered (stream, _("Type @"));
12017       gdb_print_host_address (exp->elts[pc + 1].type, stream);
12018       fprintf_filtered (stream, " (");
12019       type_print (exp->elts[pc + 1].type, NULL, stream, 0);
12020       fprintf_filtered (stream, ")");
12021       break;
12022     case BINOP_IN_BOUNDS:
12023       fprintf_filtered (stream, " (%d)",
12024                         longest_to_int (exp->elts[pc + 2].longconst));
12025       break;
12026     case TERNOP_IN_RANGE:
12027       break;
12028
12029     case OP_AGGREGATE:
12030     case OP_OTHERS:
12031     case OP_DISCRETE_RANGE:
12032     case OP_POSITIONAL:
12033     case OP_CHOICES:
12034       break;
12035
12036     case OP_NAME:
12037     case OP_STRING:
12038       {
12039         char *name = &exp->elts[elt + 2].string;
12040         int len = longest_to_int (exp->elts[elt + 1].longconst);
12041
12042         fprintf_filtered (stream, "Text: `%.*s'", len, name);
12043         break;
12044       }
12045
12046     default:
12047       return dump_subexp_body_standard (exp, stream, elt);
12048     }
12049
12050   elt += oplen;
12051   for (i = 0; i < nargs; i += 1)
12052     elt = dump_subexp (exp, stream, elt);
12053
12054   return elt;
12055 }
12056
12057 /* The Ada extension of print_subexp (q.v.).  */
12058
12059 static void
12060 ada_print_subexp (struct expression *exp, int *pos,
12061                   struct ui_file *stream, enum precedence prec)
12062 {
12063   int oplen, nargs, i;
12064   int pc = *pos;
12065   enum exp_opcode op = exp->elts[pc].opcode;
12066
12067   ada_forward_operator_length (exp, pc, &oplen, &nargs);
12068
12069   *pos += oplen;
12070   switch (op)
12071     {
12072     default:
12073       *pos -= oplen;
12074       print_subexp_standard (exp, pos, stream, prec);
12075       return;
12076
12077     case OP_VAR_VALUE:
12078       fputs_filtered (SYMBOL_NATURAL_NAME (exp->elts[pc + 2].symbol), stream);
12079       return;
12080
12081     case BINOP_IN_BOUNDS:
12082       /* XXX: sprint_subexp */
12083       print_subexp (exp, pos, stream, PREC_SUFFIX);
12084       fputs_filtered (" in ", stream);
12085       print_subexp (exp, pos, stream, PREC_SUFFIX);
12086       fputs_filtered ("'range", stream);
12087       if (exp->elts[pc + 1].longconst > 1)
12088         fprintf_filtered (stream, "(%ld)",
12089                           (long) exp->elts[pc + 1].longconst);
12090       return;
12091
12092     case TERNOP_IN_RANGE:
12093       if (prec >= PREC_EQUAL)
12094         fputs_filtered ("(", stream);
12095       /* XXX: sprint_subexp */
12096       print_subexp (exp, pos, stream, PREC_SUFFIX);
12097       fputs_filtered (" in ", stream);
12098       print_subexp (exp, pos, stream, PREC_EQUAL);
12099       fputs_filtered (" .. ", stream);
12100       print_subexp (exp, pos, stream, PREC_EQUAL);
12101       if (prec >= PREC_EQUAL)
12102         fputs_filtered (")", stream);
12103       return;
12104
12105     case OP_ATR_FIRST:
12106     case OP_ATR_LAST:
12107     case OP_ATR_LENGTH:
12108     case OP_ATR_IMAGE:
12109     case OP_ATR_MAX:
12110     case OP_ATR_MIN:
12111     case OP_ATR_MODULUS:
12112     case OP_ATR_POS:
12113     case OP_ATR_SIZE:
12114     case OP_ATR_TAG:
12115     case OP_ATR_VAL:
12116       if (exp->elts[*pos].opcode == OP_TYPE)
12117         {
12118           if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
12119             LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0);
12120           *pos += 3;
12121         }
12122       else
12123         print_subexp (exp, pos, stream, PREC_SUFFIX);
12124       fprintf_filtered (stream, "'%s", ada_attribute_name (op));
12125       if (nargs > 1)
12126         {
12127           int tem;
12128
12129           for (tem = 1; tem < nargs; tem += 1)
12130             {
12131               fputs_filtered ((tem == 1) ? " (" : ", ", stream);
12132               print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
12133             }
12134           fputs_filtered (")", stream);
12135         }
12136       return;
12137
12138     case UNOP_QUAL:
12139       type_print (exp->elts[pc + 1].type, "", stream, 0);
12140       fputs_filtered ("'(", stream);
12141       print_subexp (exp, pos, stream, PREC_PREFIX);
12142       fputs_filtered (")", stream);
12143       return;
12144
12145     case UNOP_IN_RANGE:
12146       /* XXX: sprint_subexp */
12147       print_subexp (exp, pos, stream, PREC_SUFFIX);
12148       fputs_filtered (" in ", stream);
12149       LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0);
12150       return;
12151
12152     case OP_DISCRETE_RANGE:
12153       print_subexp (exp, pos, stream, PREC_SUFFIX);
12154       fputs_filtered ("..", stream);
12155       print_subexp (exp, pos, stream, PREC_SUFFIX);
12156       return;
12157
12158     case OP_OTHERS:
12159       fputs_filtered ("others => ", stream);
12160       print_subexp (exp, pos, stream, PREC_SUFFIX);
12161       return;
12162
12163     case OP_CHOICES:
12164       for (i = 0; i < nargs-1; i += 1)
12165         {
12166           if (i > 0)
12167             fputs_filtered ("|", stream);
12168           print_subexp (exp, pos, stream, PREC_SUFFIX);
12169         }
12170       fputs_filtered (" => ", stream);
12171       print_subexp (exp, pos, stream, PREC_SUFFIX);
12172       return;
12173       
12174     case OP_POSITIONAL:
12175       print_subexp (exp, pos, stream, PREC_SUFFIX);
12176       return;
12177
12178     case OP_AGGREGATE:
12179       fputs_filtered ("(", stream);
12180       for (i = 0; i < nargs; i += 1)
12181         {
12182           if (i > 0)
12183             fputs_filtered (", ", stream);
12184           print_subexp (exp, pos, stream, PREC_SUFFIX);
12185         }
12186       fputs_filtered (")", stream);
12187       return;
12188     }
12189 }
12190
12191 /* Table mapping opcodes into strings for printing operators
12192    and precedences of the operators.  */
12193
12194 static const struct op_print ada_op_print_tab[] = {
12195   {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
12196   {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
12197   {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
12198   {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
12199   {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
12200   {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
12201   {"=", BINOP_EQUAL, PREC_EQUAL, 0},
12202   {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
12203   {"<=", BINOP_LEQ, PREC_ORDER, 0},
12204   {">=", BINOP_GEQ, PREC_ORDER, 0},
12205   {">", BINOP_GTR, PREC_ORDER, 0},
12206   {"<", BINOP_LESS, PREC_ORDER, 0},
12207   {">>", BINOP_RSH, PREC_SHIFT, 0},
12208   {"<<", BINOP_LSH, PREC_SHIFT, 0},
12209   {"+", BINOP_ADD, PREC_ADD, 0},
12210   {"-", BINOP_SUB, PREC_ADD, 0},
12211   {"&", BINOP_CONCAT, PREC_ADD, 0},
12212   {"*", BINOP_MUL, PREC_MUL, 0},
12213   {"/", BINOP_DIV, PREC_MUL, 0},
12214   {"rem", BINOP_REM, PREC_MUL, 0},
12215   {"mod", BINOP_MOD, PREC_MUL, 0},
12216   {"**", BINOP_EXP, PREC_REPEAT, 0},
12217   {"@", BINOP_REPEAT, PREC_REPEAT, 0},
12218   {"-", UNOP_NEG, PREC_PREFIX, 0},
12219   {"+", UNOP_PLUS, PREC_PREFIX, 0},
12220   {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
12221   {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
12222   {"abs ", UNOP_ABS, PREC_PREFIX, 0},
12223   {".all", UNOP_IND, PREC_SUFFIX, 1},
12224   {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
12225   {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
12226   {NULL, 0, 0, 0}
12227 };
12228 \f
12229 enum ada_primitive_types {
12230   ada_primitive_type_int,
12231   ada_primitive_type_long,
12232   ada_primitive_type_short,
12233   ada_primitive_type_char,
12234   ada_primitive_type_float,
12235   ada_primitive_type_double,
12236   ada_primitive_type_void,
12237   ada_primitive_type_long_long,
12238   ada_primitive_type_long_double,
12239   ada_primitive_type_natural,
12240   ada_primitive_type_positive,
12241   ada_primitive_type_system_address,
12242   nr_ada_primitive_types
12243 };
12244
12245 static void
12246 ada_language_arch_info (struct gdbarch *gdbarch,
12247                         struct language_arch_info *lai)
12248 {
12249   const struct builtin_type *builtin = builtin_type (gdbarch);
12250
12251   lai->primitive_type_vector
12252     = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_ada_primitive_types + 1,
12253                               struct type *);
12254
12255   lai->primitive_type_vector [ada_primitive_type_int]
12256     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12257                          0, "integer");
12258   lai->primitive_type_vector [ada_primitive_type_long]
12259     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
12260                          0, "long_integer");
12261   lai->primitive_type_vector [ada_primitive_type_short]
12262     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
12263                          0, "short_integer");
12264   lai->string_char_type
12265     = lai->primitive_type_vector [ada_primitive_type_char]
12266     = arch_integer_type (gdbarch, TARGET_CHAR_BIT, 0, "character");
12267   lai->primitive_type_vector [ada_primitive_type_float]
12268     = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
12269                        "float", NULL);
12270   lai->primitive_type_vector [ada_primitive_type_double]
12271     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
12272                        "long_float", NULL);
12273   lai->primitive_type_vector [ada_primitive_type_long_long]
12274     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
12275                          0, "long_long_integer");
12276   lai->primitive_type_vector [ada_primitive_type_long_double]
12277     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
12278                        "long_long_float", NULL);
12279   lai->primitive_type_vector [ada_primitive_type_natural]
12280     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12281                          0, "natural");
12282   lai->primitive_type_vector [ada_primitive_type_positive]
12283     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12284                          0, "positive");
12285   lai->primitive_type_vector [ada_primitive_type_void]
12286     = builtin->builtin_void;
12287
12288   lai->primitive_type_vector [ada_primitive_type_system_address]
12289     = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, 1, "void"));
12290   TYPE_NAME (lai->primitive_type_vector [ada_primitive_type_system_address])
12291     = "system__address";
12292
12293   lai->bool_type_symbol = NULL;
12294   lai->bool_type_default = builtin->builtin_bool;
12295 }
12296 \f
12297                                 /* Language vector */
12298
12299 /* Not really used, but needed in the ada_language_defn.  */
12300
12301 static void
12302 emit_char (int c, struct type *type, struct ui_file *stream, int quoter)
12303 {
12304   ada_emit_char (c, type, stream, quoter, 1);
12305 }
12306
12307 static int
12308 parse (void)
12309 {
12310   warnings_issued = 0;
12311   return ada_parse ();
12312 }
12313
12314 static const struct exp_descriptor ada_exp_descriptor = {
12315   ada_print_subexp,
12316   ada_operator_length,
12317   ada_operator_check,
12318   ada_op_name,
12319   ada_dump_subexp_body,
12320   ada_evaluate_subexp
12321 };
12322
12323 const struct language_defn ada_language_defn = {
12324   "ada",                        /* Language name */
12325   language_ada,
12326   range_check_off,
12327   type_check_off,
12328   case_sensitive_on,            /* Yes, Ada is case-insensitive, but
12329                                    that's not quite what this means.  */
12330   array_row_major,
12331   macro_expansion_no,
12332   &ada_exp_descriptor,
12333   parse,
12334   ada_error,
12335   resolve,
12336   ada_printchar,                /* Print a character constant */
12337   ada_printstr,                 /* Function to print string constant */
12338   emit_char,                    /* Function to print single char (not used) */
12339   ada_print_type,               /* Print a type using appropriate syntax */
12340   ada_print_typedef,            /* Print a typedef using appropriate syntax */
12341   ada_val_print,                /* Print a value using appropriate syntax */
12342   ada_value_print,              /* Print a top-level value */
12343   NULL,                         /* Language specific skip_trampoline */
12344   NULL,                         /* name_of_this */
12345   ada_lookup_symbol_nonlocal,   /* Looking up non-local symbols.  */
12346   basic_lookup_transparent_type,        /* lookup_transparent_type */
12347   ada_la_decode,                /* Language specific symbol demangler */
12348   NULL,                         /* Language specific
12349                                    class_name_from_physname */
12350   ada_op_print_tab,             /* expression operators for printing */
12351   0,                            /* c-style arrays */
12352   1,                            /* String lower bound */
12353   ada_get_gdb_completer_word_break_characters,
12354   ada_make_symbol_completion_list,
12355   ada_language_arch_info,
12356   ada_print_array_index,
12357   default_pass_by_reference,
12358   c_get_string,
12359   compare_names,
12360   ada_iterate_over_symbols,
12361   LANG_MAGIC
12362 };
12363
12364 /* Provide a prototype to silence -Wmissing-prototypes.  */
12365 extern initialize_file_ftype _initialize_ada_language;
12366
12367 /* Command-list for the "set/show ada" prefix command.  */
12368 static struct cmd_list_element *set_ada_list;
12369 static struct cmd_list_element *show_ada_list;
12370
12371 /* Implement the "set ada" prefix command.  */
12372
12373 static void
12374 set_ada_command (char *arg, int from_tty)
12375 {
12376   printf_unfiltered (_(\
12377 "\"set ada\" must be followed by the name of a setting.\n"));
12378   help_list (set_ada_list, "set ada ", -1, gdb_stdout);
12379 }
12380
12381 /* Implement the "show ada" prefix command.  */
12382
12383 static void
12384 show_ada_command (char *args, int from_tty)
12385 {
12386   cmd_show_list (show_ada_list, from_tty, "");
12387 }
12388
12389 static void
12390 initialize_ada_catchpoint_ops (void)
12391 {
12392   struct breakpoint_ops *ops;
12393
12394   initialize_breakpoint_ops ();
12395
12396   ops = &catch_exception_breakpoint_ops;
12397   *ops = bkpt_breakpoint_ops;
12398   ops->dtor = dtor_catch_exception;
12399   ops->allocate_location = allocate_location_catch_exception;
12400   ops->re_set = re_set_catch_exception;
12401   ops->check_status = check_status_catch_exception;
12402   ops->print_it = print_it_catch_exception;
12403   ops->print_one = print_one_catch_exception;
12404   ops->print_mention = print_mention_catch_exception;
12405   ops->print_recreate = print_recreate_catch_exception;
12406
12407   ops = &catch_exception_unhandled_breakpoint_ops;
12408   *ops = bkpt_breakpoint_ops;
12409   ops->dtor = dtor_catch_exception_unhandled;
12410   ops->allocate_location = allocate_location_catch_exception_unhandled;
12411   ops->re_set = re_set_catch_exception_unhandled;
12412   ops->check_status = check_status_catch_exception_unhandled;
12413   ops->print_it = print_it_catch_exception_unhandled;
12414   ops->print_one = print_one_catch_exception_unhandled;
12415   ops->print_mention = print_mention_catch_exception_unhandled;
12416   ops->print_recreate = print_recreate_catch_exception_unhandled;
12417
12418   ops = &catch_assert_breakpoint_ops;
12419   *ops = bkpt_breakpoint_ops;
12420   ops->dtor = dtor_catch_assert;
12421   ops->allocate_location = allocate_location_catch_assert;
12422   ops->re_set = re_set_catch_assert;
12423   ops->check_status = check_status_catch_assert;
12424   ops->print_it = print_it_catch_assert;
12425   ops->print_one = print_one_catch_assert;
12426   ops->print_mention = print_mention_catch_assert;
12427   ops->print_recreate = print_recreate_catch_assert;
12428 }
12429
12430 void
12431 _initialize_ada_language (void)
12432 {
12433   add_language (&ada_language_defn);
12434
12435   initialize_ada_catchpoint_ops ();
12436
12437   add_prefix_cmd ("ada", no_class, set_ada_command,
12438                   _("Prefix command for changing Ada-specfic settings"),
12439                   &set_ada_list, "set ada ", 0, &setlist);
12440
12441   add_prefix_cmd ("ada", no_class, show_ada_command,
12442                   _("Generic command for showing Ada-specific settings."),
12443                   &show_ada_list, "show ada ", 0, &showlist);
12444
12445   add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
12446                            &trust_pad_over_xvs, _("\
12447 Enable or disable an optimization trusting PAD types over XVS types"), _("\
12448 Show whether an optimization trusting PAD types over XVS types is activated"),
12449                            _("\
12450 This is related to the encoding used by the GNAT compiler.  The debugger\n\
12451 should normally trust the contents of PAD types, but certain older versions\n\
12452 of GNAT have a bug that sometimes causes the information in the PAD type\n\
12453 to be incorrect.  Turning this setting \"off\" allows the debugger to\n\
12454 work around this bug.  It is always safe to turn this option \"off\", but\n\
12455 this incurs a slight performance penalty, so it is recommended to NOT change\n\
12456 this option to \"off\" unless necessary."),
12457                             NULL, NULL, &set_ada_list, &show_ada_list);
12458
12459   add_catch_command ("exception", _("\
12460 Catch Ada exceptions, when raised.\n\
12461 With an argument, catch only exceptions with the given name."),
12462                      catch_ada_exception_command,
12463                      NULL,
12464                      CATCH_PERMANENT,
12465                      CATCH_TEMPORARY);
12466   add_catch_command ("assert", _("\
12467 Catch failed Ada assertions, when raised.\n\
12468 With an argument, catch only exceptions with the given name."),
12469                      catch_assert_command,
12470                      NULL,
12471                      CATCH_PERMANENT,
12472                      CATCH_TEMPORARY);
12473
12474   varsize_limit = 65536;
12475
12476   obstack_init (&symbol_list_obstack);
12477
12478   decoded_names_store = htab_create_alloc
12479     (256, htab_hash_string, (int (*)(const void *, const void *)) streq,
12480      NULL, xcalloc, xfree);
12481
12482   /* Setup per-inferior data.  */
12483   observer_attach_inferior_exit (ada_inferior_exit);
12484   ada_inferior_data
12485     = register_inferior_data_with_cleanup (ada_inferior_data_cleanup);
12486 }