2003-02-25 David Carlton <carlton@math.stanford.edu>
[external/binutils.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.  Copyright
2    1992, 1993, 1994, 1997, 1998, 1999, 2000, 2003
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include <stdio.h>
22 #include "gdb_string.h"
23 #include <ctype.h>
24 #include <stdarg.h>
25 #include "demangle.h"
26 #include "defs.h"
27 #include "symtab.h"
28 #include "gdbtypes.h"
29 #include "gdbcmd.h"
30 #include "expression.h"
31 #include "parser-defs.h"
32 #include "language.h"
33 #include "c-lang.h"
34 #include "inferior.h"
35 #include "symfile.h"
36 #include "objfiles.h"
37 #include "breakpoint.h"
38 #include "gdbcore.h"
39 #include "ada-lang.h"
40 #include "ui-out.h"
41 #include "block.h"
42
43 struct cleanup *unresolved_names;
44
45 void extract_string (CORE_ADDR addr, char *buf);
46
47 static struct type *ada_create_fundamental_type (struct objfile *, int);
48
49 static void modify_general_field (char *, LONGEST, int, int);
50
51 static struct type *desc_base_type (struct type *);
52
53 static struct type *desc_bounds_type (struct type *);
54
55 static struct value *desc_bounds (struct value *);
56
57 static int fat_pntr_bounds_bitpos (struct type *);
58
59 static int fat_pntr_bounds_bitsize (struct type *);
60
61 static struct type *desc_data_type (struct type *);
62
63 static struct value *desc_data (struct value *);
64
65 static int fat_pntr_data_bitpos (struct type *);
66
67 static int fat_pntr_data_bitsize (struct type *);
68
69 static struct value *desc_one_bound (struct value *, int, int);
70
71 static int desc_bound_bitpos (struct type *, int, int);
72
73 static int desc_bound_bitsize (struct type *, int, int);
74
75 static struct type *desc_index_type (struct type *, int);
76
77 static int desc_arity (struct type *);
78
79 static int ada_type_match (struct type *, struct type *, int);
80
81 static int ada_args_match (struct symbol *, struct value **, int);
82
83 static struct value *place_on_stack (struct value *, CORE_ADDR *);
84
85 static struct value *convert_actual (struct value *, struct type *,
86                                      CORE_ADDR *);
87
88 static struct value *make_array_descriptor (struct type *, struct value *,
89                                             CORE_ADDR *);
90
91 static void ada_add_block_symbols (struct block *, const char *,
92                                    namespace_enum, struct objfile *, int);
93
94 static void fill_in_ada_prototype (struct symbol *);
95
96 static int is_nonfunction (struct symbol **, int);
97
98 static void add_defn_to_vec (struct symbol *, struct block *);
99
100 static struct partial_symbol *ada_lookup_partial_symbol (struct partial_symtab
101                                                          *, const char *, int,
102                                                          namespace_enum, int);
103
104 static struct symtab *symtab_for_sym (struct symbol *);
105
106 static struct value *ada_resolve_subexp (struct expression **, int *, int,
107                                          struct type *);
108
109 static void replace_operator_with_call (struct expression **, int, int, int,
110                                         struct symbol *, struct block *);
111
112 static int possible_user_operator_p (enum exp_opcode, struct value **);
113
114 static const char *ada_op_name (enum exp_opcode);
115
116 static int numeric_type_p (struct type *);
117
118 static int integer_type_p (struct type *);
119
120 static int scalar_type_p (struct type *);
121
122 static int discrete_type_p (struct type *);
123
124 static char *extended_canonical_line_spec (struct symtab_and_line,
125                                            const char *);
126
127 static struct value *evaluate_subexp (struct type *, struct expression *,
128                                       int *, enum noside);
129
130 static struct value *evaluate_subexp_type (struct expression *, int *);
131
132 static struct type *ada_create_fundamental_type (struct objfile *, int);
133
134 static int is_dynamic_field (struct type *, int);
135
136 static struct type *to_fixed_variant_branch_type (struct type *, char *,
137                                                   CORE_ADDR, struct value *);
138
139 static struct type *to_fixed_range_type (char *, struct value *,
140                                          struct objfile *);
141
142 static struct type *to_static_fixed_type (struct type *);
143
144 static struct value *unwrap_value (struct value *);
145
146 static struct type *packed_array_type (struct type *, long *);
147
148 static struct type *decode_packed_array_type (struct type *);
149
150 static struct value *decode_packed_array (struct value *);
151
152 static struct value *value_subscript_packed (struct value *, int,
153                                              struct value **);
154
155 static struct value *coerce_unspec_val_to_type (struct value *, long,
156                                                 struct type *);
157
158 static struct value *get_var_value (char *, char *);
159
160 static int lesseq_defined_than (struct symbol *, struct symbol *);
161
162 static int equiv_types (struct type *, struct type *);
163
164 static int is_name_suffix (const char *);
165
166 static int wild_match (const char *, int, const char *);
167
168 static struct symtabs_and_lines find_sal_from_funcs_and_line (const char *,
169                                                               int,
170                                                               struct symbol
171                                                               **, int);
172
173 static int find_line_in_linetable (struct linetable *, int, struct symbol **,
174                                    int, int *);
175
176 static int find_next_line_in_linetable (struct linetable *, int, int, int);
177
178 static struct symtabs_and_lines all_sals_for_line (const char *, int,
179                                                    char ***);
180
181 static void read_all_symtabs (const char *);
182
183 static int is_plausible_func_for_line (struct symbol *, int);
184
185 static struct value *ada_coerce_ref (struct value *);
186
187 static struct value *value_pos_atr (struct value *);
188
189 static struct value *value_val_atr (struct type *, struct value *);
190
191 static struct symbol *standard_lookup (const char *, namespace_enum);
192
193 extern void markTimeStart (int index);
194 extern void markTimeStop (int index);
195 \f
196
197
198 /* Maximum-sized dynamic type. */
199 static unsigned int varsize_limit;
200
201 static const char *ada_completer_word_break_characters =
202   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
203
204 /* The name of the symbol to use to get the name of the main subprogram */
205 #define ADA_MAIN_PROGRAM_SYMBOL_NAME "__gnat_ada_main_program_name"
206
207                                 /* Utilities */
208
209 /* extract_string
210  *
211  * read the string located at ADDR from the inferior and store the
212  * result into BUF
213  */
214 void
215 extract_string (CORE_ADDR addr, char *buf)
216 {
217   int char_index = 0;
218
219   /* Loop, reading one byte at a time, until we reach the '\000' 
220      end-of-string marker */
221   do
222     {
223       target_read_memory (addr + char_index * sizeof (char),
224                           buf + char_index * sizeof (char), sizeof (char));
225       char_index++;
226     }
227   while (buf[char_index - 1] != '\000');
228 }
229
230 /* Assuming *OLD_VECT points to an array of *SIZE objects of size
231    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
232    updating *OLD_VECT and *SIZE as necessary. */
233
234 void
235 grow_vect (void **old_vect, size_t * size, size_t min_size, int element_size)
236 {
237   if (*size < min_size)
238     {
239       *size *= 2;
240       if (*size < min_size)
241         *size = min_size;
242       *old_vect = xrealloc (*old_vect, *size * element_size);
243     }
244 }
245
246 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
247    suffix of FIELD_NAME beginning "___" */
248
249 static int
250 field_name_match (const char *field_name, const char *target)
251 {
252   int len = strlen (target);
253   return
254     STREQN (field_name, target, len)
255     && (field_name[len] == '\0'
256         || (STREQN (field_name + len, "___", 3)
257             && !STREQ (field_name + strlen (field_name) - 6, "___XVN")));
258 }
259
260
261 /* The length of the prefix of NAME prior to any "___" suffix. */
262
263 int
264 ada_name_prefix_len (const char *name)
265 {
266   if (name == NULL)
267     return 0;
268   else
269     {
270       const char *p = strstr (name, "___");
271       if (p == NULL)
272         return strlen (name);
273       else
274         return p - name;
275     }
276 }
277
278 /* SUFFIX is a suffix of STR. False if STR is null. */
279 static int
280 is_suffix (const char *str, const char *suffix)
281 {
282   int len1, len2;
283   if (str == NULL)
284     return 0;
285   len1 = strlen (str);
286   len2 = strlen (suffix);
287   return (len1 >= len2 && STREQ (str + len1 - len2, suffix));
288 }
289
290 /* Create a value of type TYPE whose contents come from VALADDR, if it
291  * is non-null, and whose memory address (in the inferior) is
292  * ADDRESS. */
293 struct value *
294 value_from_contents_and_address (struct type *type, char *valaddr,
295                                  CORE_ADDR address)
296 {
297   struct value *v = allocate_value (type);
298   if (valaddr == NULL)
299     VALUE_LAZY (v) = 1;
300   else
301     memcpy (VALUE_CONTENTS_RAW (v), valaddr, TYPE_LENGTH (type));
302   VALUE_ADDRESS (v) = address;
303   if (address != 0)
304     VALUE_LVAL (v) = lval_memory;
305   return v;
306 }
307
308 /* The contents of value VAL, beginning at offset OFFSET, treated as a
309    value of type TYPE.  The result is an lval in memory if VAL is. */
310
311 static struct value *
312 coerce_unspec_val_to_type (struct value *val, long offset, struct type *type)
313 {
314   CHECK_TYPEDEF (type);
315   if (VALUE_LVAL (val) == lval_memory)
316     return value_at_lazy (type,
317                           VALUE_ADDRESS (val) + VALUE_OFFSET (val) + offset,
318                           NULL);
319   else
320     {
321       struct value *result = allocate_value (type);
322       VALUE_LVAL (result) = not_lval;
323       if (VALUE_ADDRESS (val) == 0)
324         memcpy (VALUE_CONTENTS_RAW (result), VALUE_CONTENTS (val) + offset,
325                 TYPE_LENGTH (type) > TYPE_LENGTH (VALUE_TYPE (val))
326                 ? TYPE_LENGTH (VALUE_TYPE (val)) : TYPE_LENGTH (type));
327       else
328         {
329           VALUE_ADDRESS (result) =
330             VALUE_ADDRESS (val) + VALUE_OFFSET (val) + offset;
331           VALUE_LAZY (result) = 1;
332         }
333       return result;
334     }
335 }
336
337 static char *
338 cond_offset_host (char *valaddr, long offset)
339 {
340   if (valaddr == NULL)
341     return NULL;
342   else
343     return valaddr + offset;
344 }
345
346 static CORE_ADDR
347 cond_offset_target (CORE_ADDR address, long offset)
348 {
349   if (address == 0)
350     return 0;
351   else
352     return address + offset;
353 }
354
355 /* Perform execute_command on the result of concatenating all
356    arguments up to NULL. */
357 static void
358 do_command (const char *arg, ...)
359 {
360   int len;
361   char *cmd;
362   const char *s;
363   va_list ap;
364
365   va_start (ap, arg);
366   len = 0;
367   s = arg;
368   cmd = "";
369   for (; s != NULL; s = va_arg (ap, const char *))
370     {
371       char *cmd1;
372       len += strlen (s);
373       cmd1 = alloca (len + 1);
374       strcpy (cmd1, cmd);
375       strcat (cmd1, s);
376       cmd = cmd1;
377     }
378   va_end (ap);
379   execute_command (cmd, 0);
380 }
381 \f
382
383                                 /* Language Selection */
384
385 /* If the main program is in Ada, return language_ada, otherwise return LANG
386    (the main program is in Ada iif the adainit symbol is found).
387
388    MAIN_PST is not used. */
389
390 enum language
391 ada_update_initial_language (enum language lang,
392                              struct partial_symtab *main_pst)
393 {
394   if (lookup_minimal_symbol ("adainit", (const char *) NULL,
395                              (struct objfile *) NULL) != NULL)
396     /*    return language_ada; */
397     /* FIXME: language_ada should be defined in defs.h */
398     return language_unknown;
399
400   return lang;
401 }
402 \f
403
404                                 /* Symbols */
405
406 /* Table of Ada operators and their GNAT-mangled names.  Last entry is pair 
407    of NULLs. */
408
409 const struct ada_opname_map ada_opname_table[] = {
410   {"Oadd", "\"+\"", BINOP_ADD},
411   {"Osubtract", "\"-\"", BINOP_SUB},
412   {"Omultiply", "\"*\"", BINOP_MUL},
413   {"Odivide", "\"/\"", BINOP_DIV},
414   {"Omod", "\"mod\"", BINOP_MOD},
415   {"Orem", "\"rem\"", BINOP_REM},
416   {"Oexpon", "\"**\"", BINOP_EXP},
417   {"Olt", "\"<\"", BINOP_LESS},
418   {"Ole", "\"<=\"", BINOP_LEQ},
419   {"Ogt", "\">\"", BINOP_GTR},
420   {"Oge", "\">=\"", BINOP_GEQ},
421   {"Oeq", "\"=\"", BINOP_EQUAL},
422   {"One", "\"/=\"", BINOP_NOTEQUAL},
423   {"Oand", "\"and\"", BINOP_BITWISE_AND},
424   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
425   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
426   {"Oconcat", "\"&\"", BINOP_CONCAT},
427   {"Oabs", "\"abs\"", UNOP_ABS},
428   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
429   {"Oadd", "\"+\"", UNOP_PLUS},
430   {"Osubtract", "\"-\"", UNOP_NEG},
431   {NULL, NULL}
432 };
433
434 /* True if STR should be suppressed in info listings. */
435 static int
436 is_suppressed_name (const char *str)
437 {
438   if (STREQN (str, "_ada_", 5))
439     str += 5;
440   if (str[0] == '_' || str[0] == '\000')
441     return 1;
442   else
443     {
444       const char *p;
445       const char *suffix = strstr (str, "___");
446       if (suffix != NULL && suffix[3] != 'X')
447         return 1;
448       if (suffix == NULL)
449         suffix = str + strlen (str);
450       for (p = suffix - 1; p != str; p -= 1)
451         if (isupper (*p))
452           {
453             int i;
454             if (p[0] == 'X' && p[-1] != '_')
455               goto OK;
456             if (*p != 'O')
457               return 1;
458             for (i = 0; ada_opname_table[i].mangled != NULL; i += 1)
459               if (STREQN (ada_opname_table[i].mangled, p,
460                           strlen (ada_opname_table[i].mangled)))
461                 goto OK;
462             return 1;
463           OK:;
464           }
465       return 0;
466     }
467 }
468
469 /* The "mangled" form of DEMANGLED, according to GNAT conventions.
470  * The result is valid until the next call to ada_mangle. */
471 char *
472 ada_mangle (const char *demangled)
473 {
474   static char *mangling_buffer = NULL;
475   static size_t mangling_buffer_size = 0;
476   const char *p;
477   int k;
478
479   if (demangled == NULL)
480     return NULL;
481
482   GROW_VECT (mangling_buffer, mangling_buffer_size,
483              2 * strlen (demangled) + 10);
484
485   k = 0;
486   for (p = demangled; *p != '\0'; p += 1)
487     {
488       if (*p == '.')
489         {
490           mangling_buffer[k] = mangling_buffer[k + 1] = '_';
491           k += 2;
492         }
493       else if (*p == '"')
494         {
495           const struct ada_opname_map *mapping;
496
497           for (mapping = ada_opname_table;
498                mapping->mangled != NULL &&
499                !STREQN (mapping->demangled, p, strlen (mapping->demangled));
500                p += 1)
501             ;
502           if (mapping->mangled == NULL)
503             error ("invalid Ada operator name: %s", p);
504           strcpy (mangling_buffer + k, mapping->mangled);
505           k += strlen (mapping->mangled);
506           break;
507         }
508       else
509         {
510           mangling_buffer[k] = *p;
511           k += 1;
512         }
513     }
514
515   mangling_buffer[k] = '\0';
516   return mangling_buffer;
517 }
518
519 /* Return NAME folded to lower case, or, if surrounded by single
520  * quotes, unfolded, but with the quotes stripped away.  Result good
521  * to next call. */
522 char *
523 ada_fold_name (const char *name)
524 {
525   static char *fold_buffer = NULL;
526   static size_t fold_buffer_size = 0;
527
528   int len = strlen (name);
529   GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
530
531   if (name[0] == '\'')
532     {
533       strncpy (fold_buffer, name + 1, len - 2);
534       fold_buffer[len - 2] = '\000';
535     }
536   else
537     {
538       int i;
539       for (i = 0; i <= len; i += 1)
540         fold_buffer[i] = tolower (name[i]);
541     }
542
543   return fold_buffer;
544 }
545
546 /* Demangle: 
547      1. Discard final __{DIGIT}+ or ${DIGIT}+
548      2. Convert other instances of embedded "__" to `.'.
549      3. Discard leading _ada_.
550      4. Convert operator names to the appropriate quoted symbols.
551      5. Remove everything after first ___ if it is followed by 
552         'X'.
553      6. Replace TK__ with __, and a trailing B or TKB with nothing.
554      7. Put symbols that should be suppressed in <...> brackets.
555      8. Remove trailing X[bn]* suffix (indicating names in package bodies).
556    The resulting string is valid until the next call of ada_demangle.
557   */
558
559 char *
560 ada_demangle (const char *mangled)
561 {
562   int i, j;
563   int len0;
564   const char *p;
565   char *demangled;
566   int at_start_name;
567   static char *demangling_buffer = NULL;
568   static size_t demangling_buffer_size = 0;
569
570   if (STREQN (mangled, "_ada_", 5))
571     mangled += 5;
572
573   if (mangled[0] == '_' || mangled[0] == '<')
574     goto Suppress;
575
576   p = strstr (mangled, "___");
577   if (p == NULL)
578     len0 = strlen (mangled);
579   else
580     {
581       if (p[3] == 'X')
582         len0 = p - mangled;
583       else
584         goto Suppress;
585     }
586   if (len0 > 3 && STREQ (mangled + len0 - 3, "TKB"))
587     len0 -= 3;
588   if (len0 > 1 && STREQ (mangled + len0 - 1, "B"))
589     len0 -= 1;
590
591   /* Make demangled big enough for possible expansion by operator name. */
592   GROW_VECT (demangling_buffer, demangling_buffer_size, 2 * len0 + 1);
593   demangled = demangling_buffer;
594
595   if (isdigit (mangled[len0 - 1]))
596     {
597       for (i = len0 - 2; i >= 0 && isdigit (mangled[i]); i -= 1)
598         ;
599       if (i > 1 && mangled[i] == '_' && mangled[i - 1] == '_')
600         len0 = i - 1;
601       else if (mangled[i] == '$')
602         len0 = i;
603     }
604
605   for (i = 0, j = 0; i < len0 && !isalpha (mangled[i]); i += 1, j += 1)
606     demangled[j] = mangled[i];
607
608   at_start_name = 1;
609   while (i < len0)
610     {
611       if (at_start_name && mangled[i] == 'O')
612         {
613           int k;
614           for (k = 0; ada_opname_table[k].mangled != NULL; k += 1)
615             {
616               int op_len = strlen (ada_opname_table[k].mangled);
617               if (STREQN
618                   (ada_opname_table[k].mangled + 1, mangled + i + 1,
619                    op_len - 1) && !isalnum (mangled[i + op_len]))
620                 {
621                   strcpy (demangled + j, ada_opname_table[k].demangled);
622                   at_start_name = 0;
623                   i += op_len;
624                   j += strlen (ada_opname_table[k].demangled);
625                   break;
626                 }
627             }
628           if (ada_opname_table[k].mangled != NULL)
629             continue;
630         }
631       at_start_name = 0;
632
633       if (i < len0 - 4 && STREQN (mangled + i, "TK__", 4))
634         i += 2;
635       if (mangled[i] == 'X' && i != 0 && isalnum (mangled[i - 1]))
636         {
637           do
638             i += 1;
639           while (i < len0 && (mangled[i] == 'b' || mangled[i] == 'n'));
640           if (i < len0)
641             goto Suppress;
642         }
643       else if (i < len0 - 2 && mangled[i] == '_' && mangled[i + 1] == '_')
644         {
645           demangled[j] = '.';
646           at_start_name = 1;
647           i += 2;
648           j += 1;
649         }
650       else
651         {
652           demangled[j] = mangled[i];
653           i += 1;
654           j += 1;
655         }
656     }
657   demangled[j] = '\000';
658
659   for (i = 0; demangled[i] != '\0'; i += 1)
660     if (isupper (demangled[i]) || demangled[i] == ' ')
661       goto Suppress;
662
663   return demangled;
664
665 Suppress:
666   GROW_VECT (demangling_buffer, demangling_buffer_size, strlen (mangled) + 3);
667   demangled = demangling_buffer;
668   if (mangled[0] == '<')
669     strcpy (demangled, mangled);
670   else
671     sprintf (demangled, "<%s>", mangled);
672   return demangled;
673
674 }
675
676 /* Returns non-zero iff SYM_NAME matches NAME, ignoring any trailing
677  * suffixes that encode debugging information or leading _ada_ on
678  * SYM_NAME (see is_name_suffix commentary for the debugging
679  * information that is ignored).  If WILD, then NAME need only match a
680  * suffix of SYM_NAME minus the same suffixes. Also returns 0 if
681  * either argument is NULL. */
682
683 int
684 ada_match_name (const char *sym_name, const char *name, int wild)
685 {
686   if (sym_name == NULL || name == NULL)
687     return 0;
688   else if (wild)
689     return wild_match (name, strlen (name), sym_name);
690   else
691     {
692       int len_name = strlen (name);
693       return (STREQN (sym_name, name, len_name)
694               && is_name_suffix (sym_name + len_name))
695         || (STREQN (sym_name, "_ada_", 5)
696             && STREQN (sym_name + 5, name, len_name)
697             && is_name_suffix (sym_name + len_name + 5));
698     }
699 }
700
701 /* True (non-zero) iff in Ada mode, the symbol SYM should be
702    suppressed in info listings. */
703
704 int
705 ada_suppress_symbol_printing (struct symbol *sym)
706 {
707   if (SYMBOL_NAMESPACE (sym) == STRUCT_NAMESPACE)
708     return 1;
709   else
710     return is_suppressed_name (DEPRECATED_SYMBOL_NAME (sym));
711 }
712 \f
713
714                                 /* Arrays */
715
716 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of 
717    array descriptors.  */
718
719 static char *bound_name[] = {
720   "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
721   "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
722 };
723
724 /* Maximum number of array dimensions we are prepared to handle.  */
725
726 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char*)))
727
728 /* Like modify_field, but allows bitpos > wordlength. */
729
730 static void
731 modify_general_field (char *addr, LONGEST fieldval, int bitpos, int bitsize)
732 {
733   modify_field (addr + sizeof (LONGEST) * bitpos / (8 * sizeof (LONGEST)),
734                 fieldval, bitpos % (8 * sizeof (LONGEST)), bitsize);
735 }
736
737
738 /* The desc_* routines return primitive portions of array descriptors 
739    (fat pointers). */
740
741 /* The descriptor or array type, if any, indicated by TYPE; removes
742    level of indirection, if needed. */
743 static struct type *
744 desc_base_type (struct type *type)
745 {
746   if (type == NULL)
747     return NULL;
748   CHECK_TYPEDEF (type);
749   if (type != NULL && TYPE_CODE (type) == TYPE_CODE_PTR)
750     return check_typedef (TYPE_TARGET_TYPE (type));
751   else
752     return type;
753 }
754
755 /* True iff TYPE indicates a "thin" array pointer type. */
756 static int
757 is_thin_pntr (struct type *type)
758 {
759   return
760     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
761     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
762 }
763
764 /* The descriptor type for thin pointer type TYPE. */
765 static struct type *
766 thin_descriptor_type (struct type *type)
767 {
768   struct type *base_type = desc_base_type (type);
769   if (base_type == NULL)
770     return NULL;
771   if (is_suffix (ada_type_name (base_type), "___XVE"))
772     return base_type;
773   else
774     {
775       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
776       if (alt_type == NULL)
777         return base_type;
778       else
779         return alt_type;
780     }
781 }
782
783 /* A pointer to the array data for thin-pointer value VAL. */
784 static struct value *
785 thin_data_pntr (struct value *val)
786 {
787   struct type *type = VALUE_TYPE (val);
788   if (TYPE_CODE (type) == TYPE_CODE_PTR)
789     return value_cast (desc_data_type (thin_descriptor_type (type)),
790                        value_copy (val));
791   else
792     return value_from_longest (desc_data_type (thin_descriptor_type (type)),
793                                VALUE_ADDRESS (val) + VALUE_OFFSET (val));
794 }
795
796 /* True iff TYPE indicates a "thick" array pointer type. */
797 static int
798 is_thick_pntr (struct type *type)
799 {
800   type = desc_base_type (type);
801   return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
802           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
803 }
804
805 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a 
806    pointer to one, the type of its bounds data; otherwise, NULL. */
807 static struct type *
808 desc_bounds_type (struct type *type)
809 {
810   struct type *r;
811
812   type = desc_base_type (type);
813
814   if (type == NULL)
815     return NULL;
816   else if (is_thin_pntr (type))
817     {
818       type = thin_descriptor_type (type);
819       if (type == NULL)
820         return NULL;
821       r = lookup_struct_elt_type (type, "BOUNDS", 1);
822       if (r != NULL)
823         return check_typedef (r);
824     }
825   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
826     {
827       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
828       if (r != NULL)
829         return check_typedef (TYPE_TARGET_TYPE (check_typedef (r)));
830     }
831   return NULL;
832 }
833
834 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
835    one, a pointer to its bounds data.   Otherwise NULL. */
836 static struct value *
837 desc_bounds (struct value *arr)
838 {
839   struct type *type = check_typedef (VALUE_TYPE (arr));
840   if (is_thin_pntr (type))
841     {
842       struct type *bounds_type =
843         desc_bounds_type (thin_descriptor_type (type));
844       LONGEST addr;
845
846       if (desc_bounds_type == NULL)
847         error ("Bad GNAT array descriptor");
848
849       /* NOTE: The following calculation is not really kosher, but
850          since desc_type is an XVE-encoded type (and shouldn't be),
851          the correct calculation is a real pain. FIXME (and fix GCC). */
852       if (TYPE_CODE (type) == TYPE_CODE_PTR)
853         addr = value_as_long (arr);
854       else
855         addr = VALUE_ADDRESS (arr) + VALUE_OFFSET (arr);
856
857       return
858         value_from_longest (lookup_pointer_type (bounds_type),
859                             addr - TYPE_LENGTH (bounds_type));
860     }
861
862   else if (is_thick_pntr (type))
863     return value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
864                              "Bad GNAT array descriptor");
865   else
866     return NULL;
867 }
868
869 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
870    position of the field containing the address of the bounds data. */
871 static int
872 fat_pntr_bounds_bitpos (struct type *type)
873 {
874   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
875 }
876
877 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
878    size of the field containing the address of the bounds data. */
879 static int
880 fat_pntr_bounds_bitsize (struct type *type)
881 {
882   type = desc_base_type (type);
883
884   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
885     return TYPE_FIELD_BITSIZE (type, 1);
886   else
887     return 8 * TYPE_LENGTH (check_typedef (TYPE_FIELD_TYPE (type, 1)));
888 }
889
890 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a 
891    pointer to one, the type of its array data (a
892    pointer-to-array-with-no-bounds type); otherwise,  NULL.  Use
893    ada_type_of_array to get an array type with bounds data. */
894 static struct type *
895 desc_data_type (struct type *type)
896 {
897   type = desc_base_type (type);
898
899   /* NOTE: The following is bogus; see comment in desc_bounds. */
900   if (is_thin_pntr (type))
901     return lookup_pointer_type
902       (desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1)));
903   else if (is_thick_pntr (type))
904     return lookup_struct_elt_type (type, "P_ARRAY", 1);
905   else
906     return NULL;
907 }
908
909 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
910    its array data.  */
911 static struct value *
912 desc_data (struct value *arr)
913 {
914   struct type *type = VALUE_TYPE (arr);
915   if (is_thin_pntr (type))
916     return thin_data_pntr (arr);
917   else if (is_thick_pntr (type))
918     return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
919                              "Bad GNAT array descriptor");
920   else
921     return NULL;
922 }
923
924
925 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
926    position of the field containing the address of the data. */
927 static int
928 fat_pntr_data_bitpos (struct type *type)
929 {
930   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
931 }
932
933 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
934    size of the field containing the address of the data. */
935 static int
936 fat_pntr_data_bitsize (struct type *type)
937 {
938   type = desc_base_type (type);
939
940   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
941     return TYPE_FIELD_BITSIZE (type, 0);
942   else
943     return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
944 }
945
946 /* If BOUNDS is an array-bounds structure (or pointer to one), return 
947    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
948    bound, if WHICH is 1.  The first bound is I=1. */
949 static struct value *
950 desc_one_bound (struct value *bounds, int i, int which)
951 {
952   return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
953                            "Bad GNAT array descriptor bounds");
954 }
955
956 /* If BOUNDS is an array-bounds structure type, return the bit position
957    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
958    bound, if WHICH is 1.  The first bound is I=1. */
959 static int
960 desc_bound_bitpos (struct type *type, int i, int which)
961 {
962   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
963 }
964
965 /* If BOUNDS is an array-bounds structure type, return the bit field size
966    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
967    bound, if WHICH is 1.  The first bound is I=1. */
968 static int
969 desc_bound_bitsize (struct type *type, int i, int which)
970 {
971   type = desc_base_type (type);
972
973   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
974     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
975   else
976     return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
977 }
978
979 /* If TYPE is the type of an array-bounds structure, the type of its
980    Ith bound (numbering from 1). Otherwise, NULL. */
981 static struct type *
982 desc_index_type (struct type *type, int i)
983 {
984   type = desc_base_type (type);
985
986   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
987     return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
988   else
989     return NULL;
990 }
991
992 /* The number of index positions in the array-bounds type TYPE.  0
993    if TYPE is NULL. */
994 static int
995 desc_arity (struct type *type)
996 {
997   type = desc_base_type (type);
998
999   if (type != NULL)
1000     return TYPE_NFIELDS (type) / 2;
1001   return 0;
1002 }
1003
1004
1005 /* Non-zero iff type is a simple array type (or pointer to one). */
1006 int
1007 ada_is_simple_array (struct type *type)
1008 {
1009   if (type == NULL)
1010     return 0;
1011   CHECK_TYPEDEF (type);
1012   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1013           || (TYPE_CODE (type) == TYPE_CODE_PTR
1014               && TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_ARRAY));
1015 }
1016
1017 /* Non-zero iff type belongs to a GNAT array descriptor. */
1018 int
1019 ada_is_array_descriptor (struct type *type)
1020 {
1021   struct type *data_type = desc_data_type (type);
1022
1023   if (type == NULL)
1024     return 0;
1025   CHECK_TYPEDEF (type);
1026   return
1027     data_type != NULL
1028     && ((TYPE_CODE (data_type) == TYPE_CODE_PTR
1029          && TYPE_TARGET_TYPE (data_type) != NULL
1030          && TYPE_CODE (TYPE_TARGET_TYPE (data_type)) == TYPE_CODE_ARRAY)
1031         ||
1032         TYPE_CODE (data_type) == TYPE_CODE_ARRAY)
1033     && desc_arity (desc_bounds_type (type)) > 0;
1034 }
1035
1036 /* Non-zero iff type is a partially mal-formed GNAT array
1037    descriptor.  (FIXME: This is to compensate for some problems with 
1038    debugging output from GNAT.  Re-examine periodically to see if it
1039    is still needed. */
1040 int
1041 ada_is_bogus_array_descriptor (struct type *type)
1042 {
1043   return
1044     type != NULL
1045     && TYPE_CODE (type) == TYPE_CODE_STRUCT
1046     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1047         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1048     && !ada_is_array_descriptor (type);
1049 }
1050
1051
1052 /* If ARR has a record type in the form of a standard GNAT array descriptor, 
1053    (fat pointer) returns the type of the array data described---specifically,
1054    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled 
1055    in from the descriptor; otherwise, they are left unspecified.  If
1056    the ARR denotes a null array descriptor and BOUNDS is non-zero, 
1057    returns NULL.  The result is simply the type of ARR if ARR is not 
1058    a descriptor.  */
1059 struct type *
1060 ada_type_of_array (struct value *arr, int bounds)
1061 {
1062   if (ada_is_packed_array_type (VALUE_TYPE (arr)))
1063     return decode_packed_array_type (VALUE_TYPE (arr));
1064
1065   if (!ada_is_array_descriptor (VALUE_TYPE (arr)))
1066     return VALUE_TYPE (arr);
1067
1068   if (!bounds)
1069     return
1070       check_typedef (TYPE_TARGET_TYPE (desc_data_type (VALUE_TYPE (arr))));
1071   else
1072     {
1073       struct type *elt_type;
1074       int arity;
1075       struct value *descriptor;
1076       struct objfile *objf = TYPE_OBJFILE (VALUE_TYPE (arr));
1077
1078       elt_type = ada_array_element_type (VALUE_TYPE (arr), -1);
1079       arity = ada_array_arity (VALUE_TYPE (arr));
1080
1081       if (elt_type == NULL || arity == 0)
1082         return check_typedef (VALUE_TYPE (arr));
1083
1084       descriptor = desc_bounds (arr);
1085       if (value_as_long (descriptor) == 0)
1086         return NULL;
1087       while (arity > 0)
1088         {
1089           struct type *range_type = alloc_type (objf);
1090           struct type *array_type = alloc_type (objf);
1091           struct value *low = desc_one_bound (descriptor, arity, 0);
1092           struct value *high = desc_one_bound (descriptor, arity, 1);
1093           arity -= 1;
1094
1095           create_range_type (range_type, VALUE_TYPE (low),
1096                              (int) value_as_long (low),
1097                              (int) value_as_long (high));
1098           elt_type = create_array_type (array_type, elt_type, range_type);
1099         }
1100
1101       return lookup_pointer_type (elt_type);
1102     }
1103 }
1104
1105 /* If ARR does not represent an array, returns ARR unchanged.
1106    Otherwise, returns either a standard GDB array with bounds set 
1107    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard 
1108    GDB array.  Returns NULL if ARR is a null fat pointer. */
1109 struct value *
1110 ada_coerce_to_simple_array_ptr (struct value *arr)
1111 {
1112   if (ada_is_array_descriptor (VALUE_TYPE (arr)))
1113     {
1114       struct type *arrType = ada_type_of_array (arr, 1);
1115       if (arrType == NULL)
1116         return NULL;
1117       return value_cast (arrType, value_copy (desc_data (arr)));
1118     }
1119   else if (ada_is_packed_array_type (VALUE_TYPE (arr)))
1120     return decode_packed_array (arr);
1121   else
1122     return arr;
1123 }
1124
1125 /* If ARR does not represent an array, returns ARR unchanged.
1126    Otherwise, returns a standard GDB array describing ARR (which may
1127    be ARR itself if it already is in the proper form). */
1128 struct value *
1129 ada_coerce_to_simple_array (struct value *arr)
1130 {
1131   if (ada_is_array_descriptor (VALUE_TYPE (arr)))
1132     {
1133       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1134       if (arrVal == NULL)
1135         error ("Bounds unavailable for null array pointer.");
1136       return value_ind (arrVal);
1137     }
1138   else if (ada_is_packed_array_type (VALUE_TYPE (arr)))
1139     return decode_packed_array (arr);
1140   else
1141     return arr;
1142 }
1143
1144 /* If TYPE represents a GNAT array type, return it translated to an
1145    ordinary GDB array type (possibly with BITSIZE fields indicating
1146    packing). For other types, is the identity. */
1147 struct type *
1148 ada_coerce_to_simple_array_type (struct type *type)
1149 {
1150   struct value *mark = value_mark ();
1151   struct value *dummy = value_from_longest (builtin_type_long, 0);
1152   struct type *result;
1153   VALUE_TYPE (dummy) = type;
1154   result = ada_type_of_array (dummy, 0);
1155   value_free_to_mark (dummy);
1156   return result;
1157 }
1158
1159 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
1160 int
1161 ada_is_packed_array_type (struct type *type)
1162 {
1163   if (type == NULL)
1164     return 0;
1165   CHECK_TYPEDEF (type);
1166   return
1167     ada_type_name (type) != NULL
1168     && strstr (ada_type_name (type), "___XP") != NULL;
1169 }
1170
1171 /* Given that TYPE is a standard GDB array type with all bounds filled
1172    in, and that the element size of its ultimate scalar constituents
1173    (that is, either its elements, or, if it is an array of arrays, its
1174    elements' elements, etc.) is *ELT_BITS, return an identical type,
1175    but with the bit sizes of its elements (and those of any
1176    constituent arrays) recorded in the BITSIZE components of its
1177    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size 
1178    in bits. */
1179 static struct type *
1180 packed_array_type (struct type *type, long *elt_bits)
1181 {
1182   struct type *new_elt_type;
1183   struct type *new_type;
1184   LONGEST low_bound, high_bound;
1185
1186   CHECK_TYPEDEF (type);
1187   if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
1188     return type;
1189
1190   new_type = alloc_type (TYPE_OBJFILE (type));
1191   new_elt_type = packed_array_type (check_typedef (TYPE_TARGET_TYPE (type)),
1192                                     elt_bits);
1193   create_array_type (new_type, new_elt_type, TYPE_FIELD_TYPE (type, 0));
1194   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
1195   TYPE_NAME (new_type) = ada_type_name (type);
1196
1197   if (get_discrete_bounds (TYPE_FIELD_TYPE (type, 0),
1198                            &low_bound, &high_bound) < 0)
1199     low_bound = high_bound = 0;
1200   if (high_bound < low_bound)
1201     *elt_bits = TYPE_LENGTH (new_type) = 0;
1202   else
1203     {
1204       *elt_bits *= (high_bound - low_bound + 1);
1205       TYPE_LENGTH (new_type) =
1206         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
1207     }
1208
1209   /*  TYPE_FLAGS (new_type) |= TYPE_FLAG_FIXED_INSTANCE; */
1210   /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
1211   return new_type;
1212 }
1213
1214 /* The array type encoded by TYPE, where ada_is_packed_array_type (TYPE).
1215  */
1216 static struct type *
1217 decode_packed_array_type (struct type *type)
1218 {
1219   struct symbol **syms;
1220   struct block **blocks;
1221   const char *raw_name = ada_type_name (check_typedef (type));
1222   char *name = (char *) alloca (strlen (raw_name) + 1);
1223   char *tail = strstr (raw_name, "___XP");
1224   struct type *shadow_type;
1225   long bits;
1226   int i, n;
1227
1228   memcpy (name, raw_name, tail - raw_name);
1229   name[tail - raw_name] = '\000';
1230
1231   /* NOTE: Use ada_lookup_symbol_list because of bug in some versions
1232    * of gcc (Solaris, e.g.). FIXME when compiler is fixed. */
1233   n = ada_lookup_symbol_list (name, get_selected_block (NULL),
1234                               VAR_NAMESPACE, &syms, &blocks);
1235   for (i = 0; i < n; i += 1)
1236     if (syms[i] != NULL && SYMBOL_CLASS (syms[i]) == LOC_TYPEDEF
1237         && STREQ (name, ada_type_name (SYMBOL_TYPE (syms[i]))))
1238       break;
1239   if (i >= n)
1240     {
1241       warning ("could not find bounds information on packed array");
1242       return NULL;
1243     }
1244   shadow_type = SYMBOL_TYPE (syms[i]);
1245
1246   if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
1247     {
1248       warning ("could not understand bounds information on packed array");
1249       return NULL;
1250     }
1251
1252   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
1253     {
1254       warning ("could not understand bit size information on packed array");
1255       return NULL;
1256     }
1257
1258   return packed_array_type (shadow_type, &bits);
1259 }
1260
1261 /* Given that ARR is a struct value* indicating a GNAT packed array,
1262    returns a simple array that denotes that array.  Its type is a
1263    standard GDB array type except that the BITSIZEs of the array
1264    target types are set to the number of bits in each element, and the
1265    type length is set appropriately. */
1266
1267 static struct value *
1268 decode_packed_array (struct value *arr)
1269 {
1270   struct type *type = decode_packed_array_type (VALUE_TYPE (arr));
1271
1272   if (type == NULL)
1273     {
1274       error ("can't unpack array");
1275       return NULL;
1276     }
1277   else
1278     return coerce_unspec_val_to_type (arr, 0, type);
1279 }
1280
1281
1282 /* The value of the element of packed array ARR at the ARITY indices
1283    given in IND.   ARR must be a simple array. */
1284
1285 static struct value *
1286 value_subscript_packed (struct value *arr, int arity, struct value **ind)
1287 {
1288   int i;
1289   int bits, elt_off, bit_off;
1290   long elt_total_bit_offset;
1291   struct type *elt_type;
1292   struct value *v;
1293
1294   bits = 0;
1295   elt_total_bit_offset = 0;
1296   elt_type = check_typedef (VALUE_TYPE (arr));
1297   for (i = 0; i < arity; i += 1)
1298     {
1299       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
1300           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
1301         error
1302           ("attempt to do packed indexing of something other than a packed array");
1303       else
1304         {
1305           struct type *range_type = TYPE_INDEX_TYPE (elt_type);
1306           LONGEST lowerbound, upperbound;
1307           LONGEST idx;
1308
1309           if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
1310             {
1311               warning ("don't know bounds of array");
1312               lowerbound = upperbound = 0;
1313             }
1314
1315           idx = value_as_long (value_pos_atr (ind[i]));
1316           if (idx < lowerbound || idx > upperbound)
1317             warning ("packed array index %ld out of bounds", (long) idx);
1318           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
1319           elt_total_bit_offset += (idx - lowerbound) * bits;
1320           elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
1321         }
1322     }
1323   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
1324   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
1325
1326   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
1327                                       bits, elt_type);
1328   if (VALUE_LVAL (arr) == lval_internalvar)
1329     VALUE_LVAL (v) = lval_internalvar_component;
1330   else
1331     VALUE_LVAL (v) = VALUE_LVAL (arr);
1332   return v;
1333 }
1334
1335 /* Non-zero iff TYPE includes negative integer values. */
1336
1337 static int
1338 has_negatives (struct type *type)
1339 {
1340   switch (TYPE_CODE (type))
1341     {
1342     default:
1343       return 0;
1344     case TYPE_CODE_INT:
1345       return !TYPE_UNSIGNED (type);
1346     case TYPE_CODE_RANGE:
1347       return TYPE_LOW_BOUND (type) < 0;
1348     }
1349 }
1350
1351
1352 /* Create a new value of type TYPE from the contents of OBJ starting
1353    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
1354    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
1355    assigning through the result will set the field fetched from. OBJ
1356    may also be NULL, in which case, VALADDR+OFFSET must address the
1357    start of storage containing the packed value.  The value returned 
1358    in this case is never an lval.   
1359    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
1360
1361 struct value *
1362 ada_value_primitive_packed_val (struct value *obj, char *valaddr, long offset,
1363                                 int bit_offset, int bit_size,
1364                                 struct type *type)
1365 {
1366   struct value *v;
1367   int src,                      /* Index into the source area. */
1368     targ,                       /* Index into the target area. */
1369     i, srcBitsLeft,             /* Number of source bits left to move. */
1370     nsrc, ntarg,                /* Number of source and target bytes. */
1371     unusedLS,                   /* Number of bits in next significant
1372                                  * byte of source that are unused. */
1373     accumSize;                  /* Number of meaningful bits in accum */
1374   unsigned char *bytes;         /* First byte containing data to unpack. */
1375   unsigned char *unpacked;
1376   unsigned long accum;          /* Staging area for bits being transferred */
1377   unsigned char sign;
1378   int len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
1379   /* Transmit bytes from least to most significant; delta is the
1380    * direction the indices move. */
1381   int delta = BITS_BIG_ENDIAN ? -1 : 1;
1382
1383   CHECK_TYPEDEF (type);
1384
1385   if (obj == NULL)
1386     {
1387       v = allocate_value (type);
1388       bytes = (unsigned char *) (valaddr + offset);
1389     }
1390   else if (VALUE_LAZY (obj))
1391     {
1392       v = value_at (type,
1393                     VALUE_ADDRESS (obj) + VALUE_OFFSET (obj) + offset, NULL);
1394       bytes = (unsigned char *) alloca (len);
1395       read_memory (VALUE_ADDRESS (v), bytes, len);
1396     }
1397   else
1398     {
1399       v = allocate_value (type);
1400       bytes = (unsigned char *) VALUE_CONTENTS (obj) + offset;
1401     }
1402
1403   if (obj != NULL)
1404     {
1405       VALUE_LVAL (v) = VALUE_LVAL (obj);
1406       if (VALUE_LVAL (obj) == lval_internalvar)
1407         VALUE_LVAL (v) = lval_internalvar_component;
1408       VALUE_ADDRESS (v) = VALUE_ADDRESS (obj) + VALUE_OFFSET (obj) + offset;
1409       VALUE_BITPOS (v) = bit_offset + VALUE_BITPOS (obj);
1410       VALUE_BITSIZE (v) = bit_size;
1411       if (VALUE_BITPOS (v) >= HOST_CHAR_BIT)
1412         {
1413           VALUE_ADDRESS (v) += 1;
1414           VALUE_BITPOS (v) -= HOST_CHAR_BIT;
1415         }
1416     }
1417   else
1418     VALUE_BITSIZE (v) = bit_size;
1419   unpacked = (unsigned char *) VALUE_CONTENTS (v);
1420
1421   srcBitsLeft = bit_size;
1422   nsrc = len;
1423   ntarg = TYPE_LENGTH (type);
1424   sign = 0;
1425   if (bit_size == 0)
1426     {
1427       memset (unpacked, 0, TYPE_LENGTH (type));
1428       return v;
1429     }
1430   else if (BITS_BIG_ENDIAN)
1431     {
1432       src = len - 1;
1433       if (has_negatives (type) &&
1434           ((bytes[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
1435         sign = ~0;
1436
1437       unusedLS =
1438         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
1439         % HOST_CHAR_BIT;
1440
1441       switch (TYPE_CODE (type))
1442         {
1443         case TYPE_CODE_ARRAY:
1444         case TYPE_CODE_UNION:
1445         case TYPE_CODE_STRUCT:
1446           /* Non-scalar values must be aligned at a byte boundary. */
1447           accumSize =
1448             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
1449           /* And are placed at the beginning (most-significant) bytes
1450            * of the target. */
1451           targ = src;
1452           break;
1453         default:
1454           accumSize = 0;
1455           targ = TYPE_LENGTH (type) - 1;
1456           break;
1457         }
1458     }
1459   else
1460     {
1461       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
1462
1463       src = targ = 0;
1464       unusedLS = bit_offset;
1465       accumSize = 0;
1466
1467       if (has_negatives (type) && (bytes[len - 1] & (1 << sign_bit_offset)))
1468         sign = ~0;
1469     }
1470
1471   accum = 0;
1472   while (nsrc > 0)
1473     {
1474       /* Mask for removing bits of the next source byte that are not
1475        * part of the value. */
1476       unsigned int unusedMSMask =
1477         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
1478         1;
1479       /* Sign-extend bits for this byte. */
1480       unsigned int signMask = sign & ~unusedMSMask;
1481       accum |=
1482         (((bytes[src] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
1483       accumSize += HOST_CHAR_BIT - unusedLS;
1484       if (accumSize >= HOST_CHAR_BIT)
1485         {
1486           unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
1487           accumSize -= HOST_CHAR_BIT;
1488           accum >>= HOST_CHAR_BIT;
1489           ntarg -= 1;
1490           targ += delta;
1491         }
1492       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
1493       unusedLS = 0;
1494       nsrc -= 1;
1495       src += delta;
1496     }
1497   while (ntarg > 0)
1498     {
1499       accum |= sign << accumSize;
1500       unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
1501       accumSize -= HOST_CHAR_BIT;
1502       accum >>= HOST_CHAR_BIT;
1503       ntarg -= 1;
1504       targ += delta;
1505     }
1506
1507   return v;
1508 }
1509
1510 /* Move N bits from SOURCE, starting at bit offset SRC_OFFSET to
1511    TARGET, starting at bit offset TARG_OFFSET.  SOURCE and TARGET must
1512    not overlap. */
1513 static void
1514 move_bits (char *target, int targ_offset, char *source, int src_offset, int n)
1515 {
1516   unsigned int accum, mask;
1517   int accum_bits, chunk_size;
1518
1519   target += targ_offset / HOST_CHAR_BIT;
1520   targ_offset %= HOST_CHAR_BIT;
1521   source += src_offset / HOST_CHAR_BIT;
1522   src_offset %= HOST_CHAR_BIT;
1523   if (BITS_BIG_ENDIAN)
1524     {
1525       accum = (unsigned char) *source;
1526       source += 1;
1527       accum_bits = HOST_CHAR_BIT - src_offset;
1528
1529       while (n > 0)
1530         {
1531           int unused_right;
1532           accum = (accum << HOST_CHAR_BIT) + (unsigned char) *source;
1533           accum_bits += HOST_CHAR_BIT;
1534           source += 1;
1535           chunk_size = HOST_CHAR_BIT - targ_offset;
1536           if (chunk_size > n)
1537             chunk_size = n;
1538           unused_right = HOST_CHAR_BIT - (chunk_size + targ_offset);
1539           mask = ((1 << chunk_size) - 1) << unused_right;
1540           *target =
1541             (*target & ~mask)
1542             | ((accum >> (accum_bits - chunk_size - unused_right)) & mask);
1543           n -= chunk_size;
1544           accum_bits -= chunk_size;
1545           target += 1;
1546           targ_offset = 0;
1547         }
1548     }
1549   else
1550     {
1551       accum = (unsigned char) *source >> src_offset;
1552       source += 1;
1553       accum_bits = HOST_CHAR_BIT - src_offset;
1554
1555       while (n > 0)
1556         {
1557           accum = accum + ((unsigned char) *source << accum_bits);
1558           accum_bits += HOST_CHAR_BIT;
1559           source += 1;
1560           chunk_size = HOST_CHAR_BIT - targ_offset;
1561           if (chunk_size > n)
1562             chunk_size = n;
1563           mask = ((1 << chunk_size) - 1) << targ_offset;
1564           *target = (*target & ~mask) | ((accum << targ_offset) & mask);
1565           n -= chunk_size;
1566           accum_bits -= chunk_size;
1567           accum >>= chunk_size;
1568           target += 1;
1569           targ_offset = 0;
1570         }
1571     }
1572 }
1573
1574
1575 /* Store the contents of FROMVAL into the location of TOVAL.
1576    Return a new value with the location of TOVAL and contents of
1577    FROMVAL.   Handles assignment into packed fields that have
1578    floating-point or non-scalar types. */
1579
1580 static struct value *
1581 ada_value_assign (struct value *toval, struct value *fromval)
1582 {
1583   struct type *type = VALUE_TYPE (toval);
1584   int bits = VALUE_BITSIZE (toval);
1585
1586   if (!toval->modifiable)
1587     error ("Left operand of assignment is not a modifiable lvalue.");
1588
1589   COERCE_REF (toval);
1590
1591   if (VALUE_LVAL (toval) == lval_memory
1592       && bits > 0
1593       && (TYPE_CODE (type) == TYPE_CODE_FLT
1594           || TYPE_CODE (type) == TYPE_CODE_STRUCT))
1595     {
1596       int len =
1597         (VALUE_BITPOS (toval) + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
1598       char *buffer = (char *) alloca (len);
1599       struct value *val;
1600
1601       if (TYPE_CODE (type) == TYPE_CODE_FLT)
1602         fromval = value_cast (type, fromval);
1603
1604       read_memory (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval), buffer, len);
1605       if (BITS_BIG_ENDIAN)
1606         move_bits (buffer, VALUE_BITPOS (toval),
1607                    VALUE_CONTENTS (fromval),
1608                    TYPE_LENGTH (VALUE_TYPE (fromval)) * TARGET_CHAR_BIT -
1609                    bits, bits);
1610       else
1611         move_bits (buffer, VALUE_BITPOS (toval), VALUE_CONTENTS (fromval),
1612                    0, bits);
1613       write_memory (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval), buffer,
1614                     len);
1615
1616       val = value_copy (toval);
1617       memcpy (VALUE_CONTENTS_RAW (val), VALUE_CONTENTS (fromval),
1618               TYPE_LENGTH (type));
1619       VALUE_TYPE (val) = type;
1620
1621       return val;
1622     }
1623
1624   return value_assign (toval, fromval);
1625 }
1626
1627
1628 /* The value of the element of array ARR at the ARITY indices given in IND. 
1629    ARR may be either a simple array, GNAT array descriptor, or pointer 
1630    thereto.  */
1631
1632 struct value *
1633 ada_value_subscript (struct value *arr, int arity, struct value **ind)
1634 {
1635   int k;
1636   struct value *elt;
1637   struct type *elt_type;
1638
1639   elt = ada_coerce_to_simple_array (arr);
1640
1641   elt_type = check_typedef (VALUE_TYPE (elt));
1642   if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
1643       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
1644     return value_subscript_packed (elt, arity, ind);
1645
1646   for (k = 0; k < arity; k += 1)
1647     {
1648       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
1649         error ("too many subscripts (%d expected)", k);
1650       elt = value_subscript (elt, value_pos_atr (ind[k]));
1651     }
1652   return elt;
1653 }
1654
1655 /* Assuming ARR is a pointer to a standard GDB array of type TYPE, the
1656    value of the element of *ARR at the ARITY indices given in
1657    IND. Does not read the entire array into memory. */
1658
1659 struct value *
1660 ada_value_ptr_subscript (struct value *arr, struct type *type, int arity,
1661                          struct value **ind)
1662 {
1663   int k;
1664
1665   for (k = 0; k < arity; k += 1)
1666     {
1667       LONGEST lwb, upb;
1668       struct value *idx;
1669
1670       if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
1671         error ("too many subscripts (%d expected)", k);
1672       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
1673                         value_copy (arr));
1674       get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
1675       if (lwb == 0)
1676         idx = ind[k];
1677       else
1678         idx = value_sub (ind[k], value_from_longest (builtin_type_int, lwb));
1679       arr = value_add (arr, idx);
1680       type = TYPE_TARGET_TYPE (type);
1681     }
1682
1683   return value_ind (arr);
1684 }
1685
1686 /* If type is a record type in the form of a standard GNAT array
1687    descriptor, returns the number of dimensions for type.  If arr is a
1688    simple array, returns the number of "array of"s that prefix its
1689    type designation. Otherwise, returns 0. */
1690
1691 int
1692 ada_array_arity (struct type *type)
1693 {
1694   int arity;
1695
1696   if (type == NULL)
1697     return 0;
1698
1699   type = desc_base_type (type);
1700
1701   arity = 0;
1702   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1703     return desc_arity (desc_bounds_type (type));
1704   else
1705     while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
1706       {
1707         arity += 1;
1708         type = check_typedef (TYPE_TARGET_TYPE (type));
1709       }
1710
1711   return arity;
1712 }
1713
1714 /* If TYPE is a record type in the form of a standard GNAT array
1715    descriptor or a simple array type, returns the element type for
1716    TYPE after indexing by NINDICES indices, or by all indices if
1717    NINDICES is -1. Otherwise, returns NULL. */
1718
1719 struct type *
1720 ada_array_element_type (struct type *type, int nindices)
1721 {
1722   type = desc_base_type (type);
1723
1724   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1725     {
1726       int k;
1727       struct type *p_array_type;
1728
1729       p_array_type = desc_data_type (type);
1730
1731       k = ada_array_arity (type);
1732       if (k == 0)
1733         return NULL;
1734
1735       /* Initially p_array_type = elt_type(*)[]...(k times)...[] */
1736       if (nindices >= 0 && k > nindices)
1737         k = nindices;
1738       p_array_type = TYPE_TARGET_TYPE (p_array_type);
1739       while (k > 0 && p_array_type != NULL)
1740         {
1741           p_array_type = check_typedef (TYPE_TARGET_TYPE (p_array_type));
1742           k -= 1;
1743         }
1744       return p_array_type;
1745     }
1746   else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
1747     {
1748       while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
1749         {
1750           type = TYPE_TARGET_TYPE (type);
1751           nindices -= 1;
1752         }
1753       return type;
1754     }
1755
1756   return NULL;
1757 }
1758
1759 /* The type of nth index in arrays of given type (n numbering from 1).  Does 
1760    not examine memory. */
1761
1762 struct type *
1763 ada_index_type (struct type *type, int n)
1764 {
1765   type = desc_base_type (type);
1766
1767   if (n > ada_array_arity (type))
1768     return NULL;
1769
1770   if (ada_is_simple_array (type))
1771     {
1772       int i;
1773
1774       for (i = 1; i < n; i += 1)
1775         type = TYPE_TARGET_TYPE (type);
1776
1777       return TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, 0));
1778     }
1779   else
1780     return desc_index_type (desc_bounds_type (type), n);
1781 }
1782
1783 /* Given that arr is an array type, returns the lower bound of the
1784    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
1785    WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
1786    array-descriptor type.  If TYPEP is non-null, *TYPEP is set to the 
1787    bounds type.  It works for other arrays with bounds supplied by 
1788    run-time quantities other than discriminants. */
1789
1790 LONGEST
1791 ada_array_bound_from_type (struct type * arr_type, int n, int which,
1792                            struct type ** typep)
1793 {
1794   struct type *type;
1795   struct type *index_type_desc;
1796
1797   if (ada_is_packed_array_type (arr_type))
1798     arr_type = decode_packed_array_type (arr_type);
1799
1800   if (arr_type == NULL || !ada_is_simple_array (arr_type))
1801     {
1802       if (typep != NULL)
1803         *typep = builtin_type_int;
1804       return (LONGEST) - which;
1805     }
1806
1807   if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
1808     type = TYPE_TARGET_TYPE (arr_type);
1809   else
1810     type = arr_type;
1811
1812   index_type_desc = ada_find_parallel_type (type, "___XA");
1813   if (index_type_desc == NULL)
1814     {
1815       struct type *range_type;
1816       struct type *index_type;
1817
1818       while (n > 1)
1819         {
1820           type = TYPE_TARGET_TYPE (type);
1821           n -= 1;
1822         }
1823
1824       range_type = TYPE_INDEX_TYPE (type);
1825       index_type = TYPE_TARGET_TYPE (range_type);
1826       if (TYPE_CODE (index_type) == TYPE_CODE_UNDEF)
1827         index_type = builtin_type_long;
1828       if (typep != NULL)
1829         *typep = index_type;
1830       return
1831         (LONGEST) (which == 0
1832                    ? TYPE_LOW_BOUND (range_type)
1833                    : TYPE_HIGH_BOUND (range_type));
1834     }
1835   else
1836     {
1837       struct type *index_type =
1838         to_fixed_range_type (TYPE_FIELD_NAME (index_type_desc, n - 1),
1839                              NULL, TYPE_OBJFILE (arr_type));
1840       if (typep != NULL)
1841         *typep = TYPE_TARGET_TYPE (index_type);
1842       return
1843         (LONGEST) (which == 0
1844                    ? TYPE_LOW_BOUND (index_type)
1845                    : TYPE_HIGH_BOUND (index_type));
1846     }
1847 }
1848
1849 /* Given that arr is an array value, returns the lower bound of the
1850    nth index (numbering from 1) if which is 0, and the upper bound if
1851    which is 1. This routine will also work for arrays with bounds
1852    supplied by run-time quantities other than discriminants. */
1853
1854 struct value *
1855 ada_array_bound (struct value *arr, int n, int which)
1856 {
1857   struct type *arr_type = VALUE_TYPE (arr);
1858
1859   if (ada_is_packed_array_type (arr_type))
1860     return ada_array_bound (decode_packed_array (arr), n, which);
1861   else if (ada_is_simple_array (arr_type))
1862     {
1863       struct type *type;
1864       LONGEST v = ada_array_bound_from_type (arr_type, n, which, &type);
1865       return value_from_longest (type, v);
1866     }
1867   else
1868     return desc_one_bound (desc_bounds (arr), n, which);
1869 }
1870
1871 /* Given that arr is an array value, returns the length of the
1872    nth index.  This routine will also work for arrays with bounds
1873    supplied by run-time quantities other than discriminants. Does not
1874    work for arrays indexed by enumeration types with representation
1875    clauses at the moment. */
1876
1877 struct value *
1878 ada_array_length (struct value *arr, int n)
1879 {
1880   struct type *arr_type = check_typedef (VALUE_TYPE (arr));
1881   struct type *index_type_desc;
1882
1883   if (ada_is_packed_array_type (arr_type))
1884     return ada_array_length (decode_packed_array (arr), n);
1885
1886   if (ada_is_simple_array (arr_type))
1887     {
1888       struct type *type;
1889       LONGEST v =
1890         ada_array_bound_from_type (arr_type, n, 1, &type) -
1891         ada_array_bound_from_type (arr_type, n, 0, NULL) + 1;
1892       return value_from_longest (type, v);
1893     }
1894   else
1895     return
1896       value_from_longest (builtin_type_ada_int,
1897                           value_as_long (desc_one_bound (desc_bounds (arr),
1898                                                          n, 1))
1899                           - value_as_long (desc_one_bound (desc_bounds (arr),
1900                                                            n, 0)) + 1);
1901 }
1902 \f
1903
1904                                 /* Name resolution */
1905
1906 /* The "demangled" name for the user-definable Ada operator corresponding
1907    to op. */
1908
1909 static const char *
1910 ada_op_name (enum exp_opcode op)
1911 {
1912   int i;
1913
1914   for (i = 0; ada_opname_table[i].mangled != NULL; i += 1)
1915     {
1916       if (ada_opname_table[i].op == op)
1917         return ada_opname_table[i].demangled;
1918     }
1919   error ("Could not find operator name for opcode");
1920 }
1921
1922
1923 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol 
1924    references (OP_UNRESOLVED_VALUES) and converts operators that are 
1925    user-defined into appropriate function calls.  If CONTEXT_TYPE is 
1926    non-null, it provides a preferred result type [at the moment, only
1927    type void has any effect---causing procedures to be preferred over
1928    functions in calls].  A null CONTEXT_TYPE indicates that a non-void
1929    return type is preferred.  The variable unresolved_names contains a list
1930    of character strings referenced by expout that should be freed.  
1931    May change (expand) *EXP.  */
1932
1933 void
1934 ada_resolve (struct expression **expp, struct type *context_type)
1935 {
1936   int pc;
1937   pc = 0;
1938   ada_resolve_subexp (expp, &pc, 1, context_type);
1939 }
1940
1941 /* Resolve the operator of the subexpression beginning at 
1942    position *POS of *EXPP. "Resolving" consists of replacing
1943    OP_UNRESOLVED_VALUE with an appropriate OP_VAR_VALUE, replacing
1944    built-in operators with function calls to user-defined operators,
1945    where appropriate, and (when DEPROCEDURE_P is non-zero), converting
1946    function-valued variables into parameterless calls.  May expand
1947    EXP. The CONTEXT_TYPE functions as in ada_resolve, above. */
1948
1949 static struct value *
1950 ada_resolve_subexp (struct expression **expp, int *pos, int deprocedure_p,
1951                     struct type *context_type)
1952 {
1953   int pc = *pos;
1954   int i;
1955   struct expression *exp;       /* Convenience: == *expp */
1956   enum exp_opcode op = (*expp)->elts[pc].opcode;
1957   struct value **argvec;        /* Vector of operand types (alloca'ed). */
1958   int nargs;                    /* Number of operands */
1959
1960   argvec = NULL;
1961   nargs = 0;
1962   exp = *expp;
1963
1964   /* Pass one: resolve operands, saving their types and updating *pos. */
1965   switch (op)
1966     {
1967     case OP_VAR_VALUE:
1968       /*    case OP_UNRESOLVED_VALUE: */
1969       /* FIXME:  OP_UNRESOLVED_VALUE should be defined in expression.h */
1970       *pos += 4;
1971       break;
1972
1973     case OP_FUNCALL:
1974       nargs = longest_to_int (exp->elts[pc + 1].longconst) + 1;
1975       /* FIXME:  OP_UNRESOLVED_VALUE should be defined in expression.h */
1976       /*      if (exp->elts[pc+3].opcode == OP_UNRESOLVED_VALUE)        
1977          {
1978          *pos += 7;
1979
1980          argvec = (struct value* *) alloca (sizeof (struct value*) * (nargs + 1));
1981          for (i = 0; i < nargs-1; i += 1)
1982          argvec[i] = ada_resolve_subexp (expp, pos, 1, NULL);
1983          argvec[i] = NULL;
1984          }
1985          else
1986          {
1987          *pos += 3;
1988          ada_resolve_subexp (expp, pos, 0, NULL);
1989          for (i = 1; i < nargs; i += 1)
1990          ada_resolve_subexp (expp, pos, 1, NULL);
1991          }
1992        */
1993       exp = *expp;
1994       break;
1995
1996       /* FIXME:  UNOP_QUAL should be defined in expression.h */
1997       /*    case UNOP_QUAL:
1998          nargs = 1;
1999          *pos += 3;
2000          ada_resolve_subexp (expp, pos, 1, exp->elts[pc + 1].type);
2001          exp = *expp;
2002          break;
2003        */
2004       /* FIXME:  OP_ATTRIBUTE should be defined in expression.h */
2005       /*    case OP_ATTRIBUTE:
2006          nargs = longest_to_int (exp->elts[pc + 1].longconst) + 1;
2007          *pos += 4;
2008          for (i = 0; i < nargs; i += 1)
2009          ada_resolve_subexp (expp, pos, 1, NULL);
2010          exp = *expp;
2011          break;
2012        */
2013     case UNOP_ADDR:
2014       nargs = 1;
2015       *pos += 1;
2016       ada_resolve_subexp (expp, pos, 0, NULL);
2017       exp = *expp;
2018       break;
2019
2020     case BINOP_ASSIGN:
2021       {
2022         struct value *arg1;
2023         nargs = 2;
2024         *pos += 1;
2025         arg1 = ada_resolve_subexp (expp, pos, 0, NULL);
2026         if (arg1 == NULL)
2027           ada_resolve_subexp (expp, pos, 1, NULL);
2028         else
2029           ada_resolve_subexp (expp, pos, 1, VALUE_TYPE (arg1));
2030         break;
2031       }
2032
2033     default:
2034       switch (op)
2035         {
2036         default:
2037           error ("Unexpected operator during name resolution");
2038         case UNOP_CAST:
2039           /*    case UNOP_MBR:
2040              nargs = 1;
2041              *pos += 3;
2042              break;
2043            */
2044         case BINOP_ADD:
2045         case BINOP_SUB:
2046         case BINOP_MUL:
2047         case BINOP_DIV:
2048         case BINOP_REM:
2049         case BINOP_MOD:
2050         case BINOP_EXP:
2051         case BINOP_CONCAT:
2052         case BINOP_LOGICAL_AND:
2053         case BINOP_LOGICAL_OR:
2054         case BINOP_BITWISE_AND:
2055         case BINOP_BITWISE_IOR:
2056         case BINOP_BITWISE_XOR:
2057
2058         case BINOP_EQUAL:
2059         case BINOP_NOTEQUAL:
2060         case BINOP_LESS:
2061         case BINOP_GTR:
2062         case BINOP_LEQ:
2063         case BINOP_GEQ:
2064
2065         case BINOP_REPEAT:
2066         case BINOP_SUBSCRIPT:
2067         case BINOP_COMMA:
2068           nargs = 2;
2069           *pos += 1;
2070           break;
2071
2072         case UNOP_NEG:
2073         case UNOP_PLUS:
2074         case UNOP_LOGICAL_NOT:
2075         case UNOP_ABS:
2076         case UNOP_IND:
2077           nargs = 1;
2078           *pos += 1;
2079           break;
2080
2081         case OP_LONG:
2082         case OP_DOUBLE:
2083         case OP_VAR_VALUE:
2084           *pos += 4;
2085           break;
2086
2087         case OP_TYPE:
2088         case OP_BOOL:
2089         case OP_LAST:
2090         case OP_REGISTER:
2091         case OP_INTERNALVAR:
2092           *pos += 3;
2093           break;
2094
2095         case UNOP_MEMVAL:
2096           *pos += 3;
2097           nargs = 1;
2098           break;
2099
2100         case STRUCTOP_STRUCT:
2101         case STRUCTOP_PTR:
2102           nargs = 1;
2103           *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
2104           break;
2105
2106         case OP_ARRAY:
2107           *pos += 4;
2108           nargs = longest_to_int (exp->elts[pc + 2].longconst) + 1;
2109           nargs -= longest_to_int (exp->elts[pc + 1].longconst);
2110           /* A null array contains one dummy element to give the type. */
2111           /*      if (nargs == 0)
2112              nargs = 1;
2113              break; */
2114
2115         case TERNOP_SLICE:
2116           /* FIXME: TERNOP_MBR should be defined in expression.h */
2117           /*    case TERNOP_MBR:
2118              *pos += 1;
2119              nargs = 3;
2120              break;
2121            */
2122           /* FIXME: BINOP_MBR should be defined in expression.h */
2123           /*    case BINOP_MBR:
2124              *pos += 3;
2125              nargs = 2;
2126              break; */
2127         }
2128
2129       argvec =
2130         (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
2131       for (i = 0; i < nargs; i += 1)
2132         argvec[i] = ada_resolve_subexp (expp, pos, 1, NULL);
2133       argvec[i] = NULL;
2134       exp = *expp;
2135       break;
2136     }
2137
2138   /* Pass two: perform any resolution on principal operator. */
2139   switch (op)
2140     {
2141     default:
2142       break;
2143
2144       /* FIXME:  OP_UNRESOLVED_VALUE should be defined in expression.h */
2145       /*    case OP_UNRESOLVED_VALUE:
2146          {
2147          struct symbol** candidate_syms;
2148          struct block** candidate_blocks;
2149          int n_candidates;
2150
2151          n_candidates = ada_lookup_symbol_list (exp->elts[pc + 2].name,
2152          exp->elts[pc + 1].block,
2153          VAR_NAMESPACE,
2154          &candidate_syms,
2155          &candidate_blocks);
2156
2157          if (n_candidates > 1) 
2158          { */
2159       /* Types tend to get re-introduced locally, so if there
2160          are any local symbols that are not types, first filter
2161    out all types. *//*
2162    int j;
2163    for (j = 0; j < n_candidates; j += 1) 
2164    switch (SYMBOL_CLASS (candidate_syms[j])) 
2165    {
2166    case LOC_REGISTER:
2167    case LOC_ARG:
2168    case LOC_REF_ARG:
2169    case LOC_REGPARM:
2170    case LOC_REGPARM_ADDR:
2171    case LOC_LOCAL:
2172    case LOC_LOCAL_ARG:
2173    case LOC_BASEREG:
2174    case LOC_BASEREG_ARG:
2175    case LOC_COMPUTED:
2176    case LOC_COMPUTED_ARG:
2177    goto FoundNonType;
2178    default:
2179    break;
2180    }
2181    FoundNonType:
2182    if (j < n_candidates) 
2183    {
2184    j = 0;
2185    while (j < n_candidates) 
2186    {
2187    if (SYMBOL_CLASS (candidate_syms[j]) == LOC_TYPEDEF)
2188    {
2189    candidate_syms[j] = candidate_syms[n_candidates-1];
2190    candidate_blocks[j] = candidate_blocks[n_candidates-1];
2191    n_candidates -= 1;
2192    }
2193    else
2194    j += 1;
2195    }
2196    }
2197    }
2198
2199    if (n_candidates == 0)
2200    error ("No definition found for %s", 
2201    ada_demangle (exp->elts[pc + 2].name));
2202    else if (n_candidates == 1)
2203    i = 0;
2204    else if (deprocedure_p 
2205    && ! is_nonfunction (candidate_syms, n_candidates))
2206    {
2207    i = ada_resolve_function (candidate_syms, candidate_blocks,
2208    n_candidates, NULL, 0,
2209    exp->elts[pc + 2].name, context_type);
2210    if (i < 0) 
2211    error ("Could not find a match for %s", 
2212    ada_demangle (exp->elts[pc + 2].name));
2213    }
2214    else 
2215    {
2216    printf_filtered ("Multiple matches for %s\n", 
2217    ada_demangle (exp->elts[pc+2].name));
2218    user_select_syms (candidate_syms, candidate_blocks, 
2219    n_candidates, 1);
2220    i = 0;
2221    }
2222
2223    exp->elts[pc].opcode = exp->elts[pc + 3].opcode = OP_VAR_VALUE;
2224    exp->elts[pc + 1].block = candidate_blocks[i];
2225    exp->elts[pc + 2].symbol = candidate_syms[i];
2226    if (innermost_block == NULL ||
2227    contained_in (candidate_blocks[i], innermost_block))
2228    innermost_block = candidate_blocks[i];
2229    } */
2230       /* FALL THROUGH */
2231
2232     case OP_VAR_VALUE:
2233       if (deprocedure_p &&
2234           TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol)) ==
2235           TYPE_CODE_FUNC)
2236         {
2237           replace_operator_with_call (expp, pc, 0, 0,
2238                                       exp->elts[pc + 2].symbol,
2239                                       exp->elts[pc + 1].block);
2240           exp = *expp;
2241         }
2242       break;
2243
2244     case OP_FUNCALL:
2245       {
2246         /* FIXME:  OP_UNRESOLVED_VALUE should be defined in expression.h */
2247         /*      if (exp->elts[pc+3].opcode == OP_UNRESOLVED_VALUE)      
2248            {
2249            struct symbol** candidate_syms;
2250            struct block** candidate_blocks;
2251            int n_candidates;
2252
2253            n_candidates = ada_lookup_symbol_list (exp->elts[pc + 5].name,
2254            exp->elts[pc + 4].block,
2255            VAR_NAMESPACE,
2256            &candidate_syms,
2257            &candidate_blocks);
2258            if (n_candidates == 1)
2259            i = 0;
2260            else
2261            {
2262            i = ada_resolve_function (candidate_syms, candidate_blocks,
2263            n_candidates, argvec, nargs-1,
2264            exp->elts[pc + 5].name, context_type);
2265            if (i < 0) 
2266            error ("Could not find a match for %s", 
2267            ada_demangle (exp->elts[pc + 5].name));
2268            }
2269
2270            exp->elts[pc + 3].opcode = exp->elts[pc + 6].opcode = OP_VAR_VALUE;
2271            exp->elts[pc + 4].block = candidate_blocks[i];
2272            exp->elts[pc + 5].symbol = candidate_syms[i];
2273            if (innermost_block == NULL ||
2274            contained_in (candidate_blocks[i], innermost_block))
2275            innermost_block = candidate_blocks[i];
2276            } */
2277
2278       }
2279       break;
2280     case BINOP_ADD:
2281     case BINOP_SUB:
2282     case BINOP_MUL:
2283     case BINOP_DIV:
2284     case BINOP_REM:
2285     case BINOP_MOD:
2286     case BINOP_CONCAT:
2287     case BINOP_BITWISE_AND:
2288     case BINOP_BITWISE_IOR:
2289     case BINOP_BITWISE_XOR:
2290     case BINOP_EQUAL:
2291     case BINOP_NOTEQUAL:
2292     case BINOP_LESS:
2293     case BINOP_GTR:
2294     case BINOP_LEQ:
2295     case BINOP_GEQ:
2296     case BINOP_EXP:
2297     case UNOP_NEG:
2298     case UNOP_PLUS:
2299     case UNOP_LOGICAL_NOT:
2300     case UNOP_ABS:
2301       if (possible_user_operator_p (op, argvec))
2302         {
2303           struct symbol **candidate_syms;
2304           struct block **candidate_blocks;
2305           int n_candidates;
2306
2307           n_candidates =
2308             ada_lookup_symbol_list (ada_mangle (ada_op_name (op)),
2309                                     (struct block *) NULL, VAR_NAMESPACE,
2310                                     &candidate_syms, &candidate_blocks);
2311           i =
2312             ada_resolve_function (candidate_syms, candidate_blocks,
2313                                   n_candidates, argvec, nargs,
2314                                   ada_op_name (op), NULL);
2315           if (i < 0)
2316             break;
2317
2318           replace_operator_with_call (expp, pc, nargs, 1,
2319                                       candidate_syms[i], candidate_blocks[i]);
2320           exp = *expp;
2321         }
2322       break;
2323     }
2324
2325   *pos = pc;
2326   return evaluate_subexp_type (exp, pos);
2327 }
2328
2329 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  If
2330    MAY_DEREF is non-zero, the formal may be a pointer and the actual 
2331    a non-pointer. */
2332 /* The term "match" here is rather loose.  The match is heuristic and
2333    liberal.  FIXME: TOO liberal, in fact. */
2334
2335 static int
2336 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
2337 {
2338   CHECK_TYPEDEF (ftype);
2339   CHECK_TYPEDEF (atype);
2340
2341   if (TYPE_CODE (ftype) == TYPE_CODE_REF)
2342     ftype = TYPE_TARGET_TYPE (ftype);
2343   if (TYPE_CODE (atype) == TYPE_CODE_REF)
2344     atype = TYPE_TARGET_TYPE (atype);
2345
2346   if (TYPE_CODE (ftype) == TYPE_CODE_VOID
2347       || TYPE_CODE (atype) == TYPE_CODE_VOID)
2348     return 1;
2349
2350   switch (TYPE_CODE (ftype))
2351     {
2352     default:
2353       return 1;
2354     case TYPE_CODE_PTR:
2355       if (TYPE_CODE (atype) == TYPE_CODE_PTR)
2356         return ada_type_match (TYPE_TARGET_TYPE (ftype),
2357                                TYPE_TARGET_TYPE (atype), 0);
2358       else
2359         return (may_deref &&
2360                 ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
2361     case TYPE_CODE_INT:
2362     case TYPE_CODE_ENUM:
2363     case TYPE_CODE_RANGE:
2364       switch (TYPE_CODE (atype))
2365         {
2366         case TYPE_CODE_INT:
2367         case TYPE_CODE_ENUM:
2368         case TYPE_CODE_RANGE:
2369           return 1;
2370         default:
2371           return 0;
2372         }
2373
2374     case TYPE_CODE_ARRAY:
2375       return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
2376               || ada_is_array_descriptor (atype));
2377
2378     case TYPE_CODE_STRUCT:
2379       if (ada_is_array_descriptor (ftype))
2380         return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
2381                 || ada_is_array_descriptor (atype));
2382       else
2383         return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
2384                 && !ada_is_array_descriptor (atype));
2385
2386     case TYPE_CODE_UNION:
2387     case TYPE_CODE_FLT:
2388       return (TYPE_CODE (atype) == TYPE_CODE (ftype));
2389     }
2390 }
2391
2392 /* Return non-zero if the formals of FUNC "sufficiently match" the
2393    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
2394    may also be an enumeral, in which case it is treated as a 0-
2395    argument function. */
2396
2397 static int
2398 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
2399 {
2400   int i;
2401   struct type *func_type = SYMBOL_TYPE (func);
2402
2403   if (SYMBOL_CLASS (func) == LOC_CONST &&
2404       TYPE_CODE (func_type) == TYPE_CODE_ENUM)
2405     return (n_actuals == 0);
2406   else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
2407     return 0;
2408
2409   if (TYPE_NFIELDS (func_type) != n_actuals)
2410     return 0;
2411
2412   for (i = 0; i < n_actuals; i += 1)
2413     {
2414       struct type *ftype = check_typedef (TYPE_FIELD_TYPE (func_type, i));
2415       struct type *atype = check_typedef (VALUE_TYPE (actuals[i]));
2416
2417       if (!ada_type_match (TYPE_FIELD_TYPE (func_type, i),
2418                            VALUE_TYPE (actuals[i]), 1))
2419         return 0;
2420     }
2421   return 1;
2422 }
2423
2424 /* False iff function type FUNC_TYPE definitely does not produce a value
2425    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
2426    FUNC_TYPE is not a valid function type with a non-null return type
2427    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
2428
2429 static int
2430 return_match (struct type *func_type, struct type *context_type)
2431 {
2432   struct type *return_type;
2433
2434   if (func_type == NULL)
2435     return 1;
2436
2437   /* FIXME: base_type should be declared in gdbtypes.h, implemented in valarith.c */
2438   /*  if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
2439      return_type = base_type (TYPE_TARGET_TYPE (func_type));
2440      else 
2441      return_type = base_type (func_type); */
2442   if (return_type == NULL)
2443     return 1;
2444
2445   /* FIXME: base_type should be declared in gdbtypes.h, implemented in valarith.c */
2446   /*  context_type = base_type (context_type); */
2447
2448   if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
2449     return context_type == NULL || return_type == context_type;
2450   else if (context_type == NULL)
2451     return TYPE_CODE (return_type) != TYPE_CODE_VOID;
2452   else
2453     return TYPE_CODE (return_type) == TYPE_CODE (context_type);
2454 }
2455
2456
2457 /* Return the index in SYMS[0..NSYMS-1] of symbol for the 
2458    function (if any) that matches the types of the NARGS arguments in
2459    ARGS.  If CONTEXT_TYPE is non-null, and there is at least one match
2460    that returns type CONTEXT_TYPE, then eliminate other matches.  If
2461    CONTEXT_TYPE is null, prefer a non-void-returning function.
2462    Asks the user if there is more than one match remaining.  Returns -1
2463    if there is no such symbol or none is selected.  NAME is used
2464    solely for messages.   May re-arrange and modify SYMS in
2465    the process; the index returned is for the modified vector.  BLOCKS
2466    is modified in parallel to SYMS. */
2467
2468 int
2469 ada_resolve_function (struct symbol *syms[], struct block *blocks[],
2470                       int nsyms, struct value **args, int nargs,
2471                       const char *name, struct type *context_type)
2472 {
2473   int k;
2474   int m;                        /* Number of hits */
2475   struct type *fallback;
2476   struct type *return_type;
2477
2478   return_type = context_type;
2479   if (context_type == NULL)
2480     fallback = builtin_type_void;
2481   else
2482     fallback = NULL;
2483
2484   m = 0;
2485   while (1)
2486     {
2487       for (k = 0; k < nsyms; k += 1)
2488         {
2489           struct type *type = check_typedef (SYMBOL_TYPE (syms[k]));
2490
2491           if (ada_args_match (syms[k], args, nargs)
2492               && return_match (SYMBOL_TYPE (syms[k]), return_type))
2493             {
2494               syms[m] = syms[k];
2495               if (blocks != NULL)
2496                 blocks[m] = blocks[k];
2497               m += 1;
2498             }
2499         }
2500       if (m > 0 || return_type == fallback)
2501         break;
2502       else
2503         return_type = fallback;
2504     }
2505
2506   if (m == 0)
2507     return -1;
2508   else if (m > 1)
2509     {
2510       printf_filtered ("Multiple matches for %s\n", name);
2511       user_select_syms (syms, blocks, m, 1);
2512       return 0;
2513     }
2514   return 0;
2515 }
2516
2517 /* Returns true (non-zero) iff demangled name N0 should appear before N1 */
2518 /* in a listing of choices during disambiguation (see sort_choices, below). */
2519 /* The idea is that overloadings of a subprogram name from the */
2520 /* same package should sort in their source order.  We settle for ordering */
2521 /* such symbols by their trailing number (__N  or $N). */
2522 static int
2523 mangled_ordered_before (char *N0, char *N1)
2524 {
2525   if (N1 == NULL)
2526     return 0;
2527   else if (N0 == NULL)
2528     return 1;
2529   else
2530     {
2531       int k0, k1;
2532       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
2533         ;
2534       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
2535         ;
2536       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
2537           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
2538         {
2539           int n0, n1;
2540           n0 = k0;
2541           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
2542             n0 -= 1;
2543           n1 = k1;
2544           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
2545             n1 -= 1;
2546           if (n0 == n1 && STREQN (N0, N1, n0))
2547             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
2548         }
2549       return (strcmp (N0, N1) < 0);
2550     }
2551 }
2552
2553 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by their */
2554 /* mangled names, rearranging BLOCKS[0..NSYMS-1] according to the same */
2555 /* permutation. */
2556 static void
2557 sort_choices (struct symbol *syms[], struct block *blocks[], int nsyms)
2558 {
2559   int i, j;
2560   for (i = 1; i < nsyms; i += 1)
2561     {
2562       struct symbol *sym = syms[i];
2563       struct block *block = blocks[i];
2564       int j;
2565
2566       for (j = i - 1; j >= 0; j -= 1)
2567         {
2568           if (mangled_ordered_before (DEPRECATED_SYMBOL_NAME (syms[j]),
2569                                       DEPRECATED_SYMBOL_NAME (sym)))
2570             break;
2571           syms[j + 1] = syms[j];
2572           blocks[j + 1] = blocks[j];
2573         }
2574       syms[j + 1] = sym;
2575       blocks[j + 1] = block;
2576     }
2577 }
2578
2579 /* Given a list of NSYMS symbols in SYMS and corresponding blocks in */
2580 /* BLOCKS, select up to MAX_RESULTS>0 by asking the user (if */
2581 /* necessary), returning the number selected, and setting the first */
2582 /* elements of SYMS and BLOCKS to the selected symbols and */
2583 /* corresponding blocks.  Error if no symbols selected.   BLOCKS may */
2584 /* be NULL, in which case it is ignored. */
2585
2586 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
2587    to be re-integrated one of these days. */
2588
2589 int
2590 user_select_syms (struct symbol *syms[], struct block *blocks[], int nsyms,
2591                   int max_results)
2592 {
2593   int i;
2594   int *chosen = (int *) alloca (sizeof (int) * nsyms);
2595   int n_chosen;
2596   int first_choice = (max_results == 1) ? 1 : 2;
2597
2598   if (max_results < 1)
2599     error ("Request to select 0 symbols!");
2600   if (nsyms <= 1)
2601     return nsyms;
2602
2603   printf_unfiltered ("[0] cancel\n");
2604   if (max_results > 1)
2605     printf_unfiltered ("[1] all\n");
2606
2607   sort_choices (syms, blocks, nsyms);
2608
2609   for (i = 0; i < nsyms; i += 1)
2610     {
2611       if (syms[i] == NULL)
2612         continue;
2613
2614       if (SYMBOL_CLASS (syms[i]) == LOC_BLOCK)
2615         {
2616           struct symtab_and_line sal = find_function_start_sal (syms[i], 1);
2617           printf_unfiltered ("[%d] %s at %s:%d\n",
2618                              i + first_choice,
2619                              SYMBOL_PRINT_NAME (syms[i]),
2620                              sal.symtab == NULL
2621                              ? "<no source file available>"
2622                              : sal.symtab->filename, sal.line);
2623           continue;
2624         }
2625       else
2626         {
2627           int is_enumeral =
2628             (SYMBOL_CLASS (syms[i]) == LOC_CONST
2629              && SYMBOL_TYPE (syms[i]) != NULL
2630              && TYPE_CODE (SYMBOL_TYPE (syms[i])) == TYPE_CODE_ENUM);
2631           struct symtab *symtab = symtab_for_sym (syms[i]);
2632
2633           if (SYMBOL_LINE (syms[i]) != 0 && symtab != NULL)
2634             printf_unfiltered ("[%d] %s at %s:%d\n",
2635                                i + first_choice,
2636                                SYMBOL_PRINT_NAME (syms[i]),
2637                                symtab->filename, SYMBOL_LINE (syms[i]));
2638           else if (is_enumeral && TYPE_NAME (SYMBOL_TYPE (syms[i])) != NULL)
2639             {
2640               printf_unfiltered ("[%d] ", i + first_choice);
2641               ada_print_type (SYMBOL_TYPE (syms[i]), NULL, gdb_stdout, -1, 0);
2642               printf_unfiltered ("'(%s) (enumeral)\n",
2643                                  SYMBOL_PRINT_NAME (syms[i]));
2644             }
2645           else if (symtab != NULL)
2646             printf_unfiltered (is_enumeral
2647                                ? "[%d] %s in %s (enumeral)\n"
2648                                : "[%d] %s at %s:?\n",
2649                                i + first_choice,
2650                                SYMBOL_PRINT_NAME (syms[i]),
2651                                symtab->filename);
2652           else
2653             printf_unfiltered (is_enumeral
2654                                ? "[%d] %s (enumeral)\n"
2655                                : "[%d] %s at ?\n",
2656                                i + first_choice,
2657                                SYMBOL_PRINT_NAME (syms[i]));
2658         }
2659     }
2660
2661   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
2662                              "overload-choice");
2663
2664   for (i = 0; i < n_chosen; i += 1)
2665     {
2666       syms[i] = syms[chosen[i]];
2667       if (blocks != NULL)
2668         blocks[i] = blocks[chosen[i]];
2669     }
2670
2671   return n_chosen;
2672 }
2673
2674 /* Read and validate a set of numeric choices from the user in the
2675    range 0 .. N_CHOICES-1. Place the results in increasing
2676    order in CHOICES[0 .. N-1], and return N.
2677
2678    The user types choices as a sequence of numbers on one line
2679    separated by blanks, encoding them as follows:
2680
2681      + A choice of 0 means to cancel the selection, throwing an error.  
2682      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
2683      + The user chooses k by typing k+IS_ALL_CHOICE+1.
2684
2685    The user is not allowed to choose more than MAX_RESULTS values. 
2686
2687    ANNOTATION_SUFFIX, if present, is used to annotate the input
2688    prompts (for use with the -f switch). */
2689
2690 int
2691 get_selections (int *choices, int n_choices, int max_results,
2692                 int is_all_choice, char *annotation_suffix)
2693 {
2694   int i;
2695   char *args;
2696   const char *prompt;
2697   int n_chosen;
2698   int first_choice = is_all_choice ? 2 : 1;
2699
2700   prompt = getenv ("PS2");
2701   if (prompt == NULL)
2702     prompt = ">";
2703
2704   printf_unfiltered ("%s ", prompt);
2705   gdb_flush (gdb_stdout);
2706
2707   args = command_line_input ((char *) NULL, 0, annotation_suffix);
2708
2709   if (args == NULL)
2710     error_no_arg ("one or more choice numbers");
2711
2712   n_chosen = 0;
2713
2714   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending 
2715      order, as given in args.   Choices are validated. */
2716   while (1)
2717     {
2718       char *args2;
2719       int choice, j;
2720
2721       while (isspace (*args))
2722         args += 1;
2723       if (*args == '\0' && n_chosen == 0)
2724         error_no_arg ("one or more choice numbers");
2725       else if (*args == '\0')
2726         break;
2727
2728       choice = strtol (args, &args2, 10);
2729       if (args == args2 || choice < 0
2730           || choice > n_choices + first_choice - 1)
2731         error ("Argument must be choice number");
2732       args = args2;
2733
2734       if (choice == 0)
2735         error ("cancelled");
2736
2737       if (choice < first_choice)
2738         {
2739           n_chosen = n_choices;
2740           for (j = 0; j < n_choices; j += 1)
2741             choices[j] = j;
2742           break;
2743         }
2744       choice -= first_choice;
2745
2746       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
2747         {
2748         }
2749
2750       if (j < 0 || choice != choices[j])
2751         {
2752           int k;
2753           for (k = n_chosen - 1; k > j; k -= 1)
2754             choices[k + 1] = choices[k];
2755           choices[j + 1] = choice;
2756           n_chosen += 1;
2757         }
2758     }
2759
2760   if (n_chosen > max_results)
2761     error ("Select no more than %d of the above", max_results);
2762
2763   return n_chosen;
2764 }
2765
2766 /* Replace the operator of length OPLEN at position PC in *EXPP with a call */
2767 /* on the function identified by SYM and BLOCK, and taking NARGS */
2768 /* arguments.  Update *EXPP as needed to hold more space. */
2769
2770 static void
2771 replace_operator_with_call (struct expression **expp, int pc, int nargs,
2772                             int oplen, struct symbol *sym,
2773                             struct block *block)
2774 {
2775   /* A new expression, with 6 more elements (3 for funcall, 4 for function
2776      symbol, -oplen for operator being replaced). */
2777   struct expression *newexp = (struct expression *)
2778     xmalloc (sizeof (struct expression)
2779              + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
2780   struct expression *exp = *expp;
2781
2782   newexp->nelts = exp->nelts + 7 - oplen;
2783   newexp->language_defn = exp->language_defn;
2784   memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
2785   memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
2786           EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
2787
2788   newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
2789   newexp->elts[pc + 1].longconst = (LONGEST) nargs;
2790
2791   newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
2792   newexp->elts[pc + 4].block = block;
2793   newexp->elts[pc + 5].symbol = sym;
2794
2795   *expp = newexp;
2796   xfree (exp);
2797 }
2798
2799 /* Type-class predicates */
2800
2801 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type), or */
2802 /* FLOAT.) */
2803
2804 static int
2805 numeric_type_p (struct type *type)
2806 {
2807   if (type == NULL)
2808     return 0;
2809   else
2810     {
2811       switch (TYPE_CODE (type))
2812         {
2813         case TYPE_CODE_INT:
2814         case TYPE_CODE_FLT:
2815           return 1;
2816         case TYPE_CODE_RANGE:
2817           return (type == TYPE_TARGET_TYPE (type)
2818                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
2819         default:
2820           return 0;
2821         }
2822     }
2823 }
2824
2825 /* True iff TYPE is integral (an INT or RANGE of INTs). */
2826
2827 static int
2828 integer_type_p (struct type *type)
2829 {
2830   if (type == NULL)
2831     return 0;
2832   else
2833     {
2834       switch (TYPE_CODE (type))
2835         {
2836         case TYPE_CODE_INT:
2837           return 1;
2838         case TYPE_CODE_RANGE:
2839           return (type == TYPE_TARGET_TYPE (type)
2840                   || integer_type_p (TYPE_TARGET_TYPE (type)));
2841         default:
2842           return 0;
2843         }
2844     }
2845 }
2846
2847 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
2848
2849 static int
2850 scalar_type_p (struct type *type)
2851 {
2852   if (type == NULL)
2853     return 0;
2854   else
2855     {
2856       switch (TYPE_CODE (type))
2857         {
2858         case TYPE_CODE_INT:
2859         case TYPE_CODE_RANGE:
2860         case TYPE_CODE_ENUM:
2861         case TYPE_CODE_FLT:
2862           return 1;
2863         default:
2864           return 0;
2865         }
2866     }
2867 }
2868
2869 /* True iff TYPE is discrete (INT, RANGE, ENUM). */
2870
2871 static int
2872 discrete_type_p (struct type *type)
2873 {
2874   if (type == NULL)
2875     return 0;
2876   else
2877     {
2878       switch (TYPE_CODE (type))
2879         {
2880         case TYPE_CODE_INT:
2881         case TYPE_CODE_RANGE:
2882         case TYPE_CODE_ENUM:
2883           return 1;
2884         default:
2885           return 0;
2886         }
2887     }
2888 }
2889
2890 /* Returns non-zero if OP with operatands in the vector ARGS could be
2891    a user-defined function. Errs on the side of pre-defined operators
2892    (i.e., result 0). */
2893
2894 static int
2895 possible_user_operator_p (enum exp_opcode op, struct value *args[])
2896 {
2897   struct type *type0 = check_typedef (VALUE_TYPE (args[0]));
2898   struct type *type1 =
2899     (args[1] == NULL) ? NULL : check_typedef (VALUE_TYPE (args[1]));
2900
2901   switch (op)
2902     {
2903     default:
2904       return 0;
2905
2906     case BINOP_ADD:
2907     case BINOP_SUB:
2908     case BINOP_MUL:
2909     case BINOP_DIV:
2910       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
2911
2912     case BINOP_REM:
2913     case BINOP_MOD:
2914     case BINOP_BITWISE_AND:
2915     case BINOP_BITWISE_IOR:
2916     case BINOP_BITWISE_XOR:
2917       return (!(integer_type_p (type0) && integer_type_p (type1)));
2918
2919     case BINOP_EQUAL:
2920     case BINOP_NOTEQUAL:
2921     case BINOP_LESS:
2922     case BINOP_GTR:
2923     case BINOP_LEQ:
2924     case BINOP_GEQ:
2925       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
2926
2927     case BINOP_CONCAT:
2928       return ((TYPE_CODE (type0) != TYPE_CODE_ARRAY &&
2929                (TYPE_CODE (type0) != TYPE_CODE_PTR ||
2930                 TYPE_CODE (TYPE_TARGET_TYPE (type0))
2931                 != TYPE_CODE_ARRAY))
2932               || (TYPE_CODE (type1) != TYPE_CODE_ARRAY &&
2933                   (TYPE_CODE (type1) != TYPE_CODE_PTR ||
2934                    TYPE_CODE (TYPE_TARGET_TYPE (type1)) != TYPE_CODE_ARRAY)));
2935
2936     case BINOP_EXP:
2937       return (!(numeric_type_p (type0) && integer_type_p (type1)));
2938
2939     case UNOP_NEG:
2940     case UNOP_PLUS:
2941     case UNOP_LOGICAL_NOT:
2942     case UNOP_ABS:
2943       return (!numeric_type_p (type0));
2944
2945     }
2946 }
2947 \f
2948                                 /* Renaming */
2949
2950 /** NOTE: In the following, we assume that a renaming type's name may
2951  *  have an ___XD suffix.  It would be nice if this went away at some
2952  *  point. */
2953
2954 /* If TYPE encodes a renaming, returns the renaming suffix, which
2955  * is XR for an object renaming, XRP for a procedure renaming, XRE for
2956  * an exception renaming, and XRS for a subprogram renaming.  Returns
2957  * NULL if NAME encodes none of these. */
2958 const char *
2959 ada_renaming_type (struct type *type)
2960 {
2961   if (type != NULL && TYPE_CODE (type) == TYPE_CODE_ENUM)
2962     {
2963       const char *name = type_name_no_tag (type);
2964       const char *suffix = (name == NULL) ? NULL : strstr (name, "___XR");
2965       if (suffix == NULL
2966           || (suffix[5] != '\000' && strchr ("PES_", suffix[5]) == NULL))
2967         return NULL;
2968       else
2969         return suffix + 3;
2970     }
2971   else
2972     return NULL;
2973 }
2974
2975 /* Return non-zero iff SYM encodes an object renaming. */
2976 int
2977 ada_is_object_renaming (struct symbol *sym)
2978 {
2979   const char *renaming_type = ada_renaming_type (SYMBOL_TYPE (sym));
2980   return renaming_type != NULL
2981     && (renaming_type[2] == '\0' || renaming_type[2] == '_');
2982 }
2983
2984 /* Assuming that SYM encodes a non-object renaming, returns the original
2985  * name of the renamed entity.   The name is good until the end of
2986  * parsing. */
2987 const char *
2988 ada_simple_renamed_entity (struct symbol *sym)
2989 {
2990   struct type *type;
2991   const char *raw_name;
2992   int len;
2993   char *result;
2994
2995   type = SYMBOL_TYPE (sym);
2996   if (type == NULL || TYPE_NFIELDS (type) < 1)
2997     error ("Improperly encoded renaming.");
2998
2999   raw_name = TYPE_FIELD_NAME (type, 0);
3000   len = (raw_name == NULL ? 0 : strlen (raw_name)) - 5;
3001   if (len <= 0)
3002     error ("Improperly encoded renaming.");
3003
3004   result = xmalloc (len + 1);
3005   /* FIXME: add_name_string_cleanup should be defined in parse.c */
3006   /*  add_name_string_cleanup (result); */
3007   strncpy (result, raw_name, len);
3008   result[len] = '\000';
3009   return result;
3010 }
3011 \f
3012
3013                                 /* Evaluation: Function Calls */
3014
3015 /* Copy VAL onto the stack, using and updating *SP as the stack 
3016    pointer. Return VAL as an lvalue. */
3017
3018 static struct value *
3019 place_on_stack (struct value *val, CORE_ADDR *sp)
3020 {
3021   CORE_ADDR old_sp = *sp;
3022
3023 #ifdef STACK_ALIGN
3024   *sp = push_bytes (*sp, VALUE_CONTENTS_RAW (val),
3025                     STACK_ALIGN (TYPE_LENGTH
3026                                  (check_typedef (VALUE_TYPE (val)))));
3027 #else
3028   *sp = push_bytes (*sp, VALUE_CONTENTS_RAW (val),
3029                     TYPE_LENGTH (check_typedef (VALUE_TYPE (val))));
3030 #endif
3031
3032   VALUE_LVAL (val) = lval_memory;
3033   if (INNER_THAN (1, 2))
3034     VALUE_ADDRESS (val) = *sp;
3035   else
3036     VALUE_ADDRESS (val) = old_sp;
3037
3038   return val;
3039 }
3040
3041 /* Return the value ACTUAL, converted to be an appropriate value for a
3042    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
3043    allocating any necessary descriptors (fat pointers), or copies of
3044    values not residing in memory, updating it as needed. */
3045
3046 static struct value *
3047 convert_actual (struct value *actual, struct type *formal_type0,
3048                 CORE_ADDR *sp)
3049 {
3050   struct type *actual_type = check_typedef (VALUE_TYPE (actual));
3051   struct type *formal_type = check_typedef (formal_type0);
3052   struct type *formal_target =
3053     TYPE_CODE (formal_type) == TYPE_CODE_PTR
3054     ? check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
3055   struct type *actual_target =
3056     TYPE_CODE (actual_type) == TYPE_CODE_PTR
3057     ? check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
3058
3059   if (ada_is_array_descriptor (formal_target)
3060       && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
3061     return make_array_descriptor (formal_type, actual, sp);
3062   else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR)
3063     {
3064       if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
3065           && ada_is_array_descriptor (actual_target))
3066         return desc_data (actual);
3067       else if (TYPE_CODE (actual_type) != TYPE_CODE_PTR)
3068         {
3069           if (VALUE_LVAL (actual) != lval_memory)
3070             {
3071               struct value *val;
3072               actual_type = check_typedef (VALUE_TYPE (actual));
3073               val = allocate_value (actual_type);
3074               memcpy ((char *) VALUE_CONTENTS_RAW (val),
3075                       (char *) VALUE_CONTENTS (actual),
3076                       TYPE_LENGTH (actual_type));
3077               actual = place_on_stack (val, sp);
3078             }
3079           return value_addr (actual);
3080         }
3081     }
3082   else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
3083     return ada_value_ind (actual);
3084
3085   return actual;
3086 }
3087
3088
3089 /* Push a descriptor of type TYPE for array value ARR on the stack at 
3090    *SP, updating *SP to reflect the new descriptor.  Return either 
3091    an lvalue representing the new descriptor, or (if TYPE is a pointer-
3092    to-descriptor type rather than a descriptor type), a struct value*
3093    representing a pointer to this descriptor. */
3094
3095 static struct value *
3096 make_array_descriptor (struct type *type, struct value *arr, CORE_ADDR *sp)
3097 {
3098   struct type *bounds_type = desc_bounds_type (type);
3099   struct type *desc_type = desc_base_type (type);
3100   struct value *descriptor = allocate_value (desc_type);
3101   struct value *bounds = allocate_value (bounds_type);
3102   CORE_ADDR bounds_addr;
3103   int i;
3104
3105   for (i = ada_array_arity (check_typedef (VALUE_TYPE (arr))); i > 0; i -= 1)
3106     {
3107       modify_general_field (VALUE_CONTENTS (bounds),
3108                             value_as_long (ada_array_bound (arr, i, 0)),
3109                             desc_bound_bitpos (bounds_type, i, 0),
3110                             desc_bound_bitsize (bounds_type, i, 0));
3111       modify_general_field (VALUE_CONTENTS (bounds),
3112                             value_as_long (ada_array_bound (arr, i, 1)),
3113                             desc_bound_bitpos (bounds_type, i, 1),
3114                             desc_bound_bitsize (bounds_type, i, 1));
3115     }
3116
3117   bounds = place_on_stack (bounds, sp);
3118
3119   modify_general_field (VALUE_CONTENTS (descriptor),
3120                         arr,
3121                         fat_pntr_data_bitpos (desc_type),
3122                         fat_pntr_data_bitsize (desc_type));
3123   modify_general_field (VALUE_CONTENTS (descriptor),
3124                         VALUE_ADDRESS (bounds),
3125                         fat_pntr_bounds_bitpos (desc_type),
3126                         fat_pntr_bounds_bitsize (desc_type));
3127
3128   descriptor = place_on_stack (descriptor, sp);
3129
3130   if (TYPE_CODE (type) == TYPE_CODE_PTR)
3131     return value_addr (descriptor);
3132   else
3133     return descriptor;
3134 }
3135
3136
3137 /* Assuming a dummy frame has been established on the target, perform any 
3138    conversions needed for calling function FUNC on the NARGS actual
3139    parameters in ARGS, other than standard C conversions.   Does
3140    nothing if FUNC does not have Ada-style prototype data, or if NARGS
3141    does not match the number of arguments expected.   Use *SP as a
3142    stack pointer for additional data that must be pushed, updating its
3143    value as needed. */
3144
3145 void
3146 ada_convert_actuals (struct value *func, int nargs, struct value *args[],
3147                      CORE_ADDR *sp)
3148 {
3149   int i;
3150
3151   if (TYPE_NFIELDS (VALUE_TYPE (func)) == 0
3152       || nargs != TYPE_NFIELDS (VALUE_TYPE (func)))
3153     return;
3154
3155   for (i = 0; i < nargs; i += 1)
3156     args[i] =
3157       convert_actual (args[i], TYPE_FIELD_TYPE (VALUE_TYPE (func), i), sp);
3158 }
3159 \f
3160
3161                                 /* Symbol Lookup */
3162
3163
3164 /* The vectors of symbols and blocks ultimately returned from */
3165 /* ada_lookup_symbol_list. */
3166
3167 /* Current size of defn_symbols and defn_blocks */
3168 static size_t defn_vector_size = 0;
3169
3170 /* Current number of symbols found. */
3171 static int ndefns = 0;
3172
3173 static struct symbol **defn_symbols = NULL;
3174 static struct block **defn_blocks = NULL;
3175
3176 /* Return the result of a standard (literal, C-like) lookup of NAME in 
3177  * given NAMESPACE. */
3178
3179 static struct symbol *
3180 standard_lookup (const char *name, namespace_enum namespace)
3181 {
3182   struct symbol *sym;
3183   struct symtab *symtab;
3184   sym = lookup_symbol (name, (struct block *) NULL, namespace, 0, &symtab);
3185   return sym;
3186 }
3187
3188
3189 /* Non-zero iff there is at least one non-function/non-enumeral symbol */
3190 /* in SYMS[0..N-1].  We treat enumerals as functions, since they */
3191 /* contend in overloading in the same way. */
3192 static int
3193 is_nonfunction (struct symbol *syms[], int n)
3194 {
3195   int i;
3196
3197   for (i = 0; i < n; i += 1)
3198     if (TYPE_CODE (SYMBOL_TYPE (syms[i])) != TYPE_CODE_FUNC
3199         && TYPE_CODE (SYMBOL_TYPE (syms[i])) != TYPE_CODE_ENUM)
3200       return 1;
3201
3202   return 0;
3203 }
3204
3205 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
3206    struct types.  Otherwise, they may not. */
3207
3208 static int
3209 equiv_types (struct type *type0, struct type *type1)
3210 {
3211   if (type0 == type1)
3212     return 1;
3213   if (type0 == NULL || type1 == NULL
3214       || TYPE_CODE (type0) != TYPE_CODE (type1))
3215     return 0;
3216   if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
3217        || TYPE_CODE (type0) == TYPE_CODE_ENUM)
3218       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
3219       && STREQ (ada_type_name (type0), ada_type_name (type1)))
3220     return 1;
3221
3222   return 0;
3223 }
3224
3225 /* True iff SYM0 represents the same entity as SYM1, or one that is
3226    no more defined than that of SYM1. */
3227
3228 static int
3229 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
3230 {
3231   if (sym0 == sym1)
3232     return 1;
3233   if (SYMBOL_NAMESPACE (sym0) != SYMBOL_NAMESPACE (sym1)
3234       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
3235     return 0;
3236
3237   switch (SYMBOL_CLASS (sym0))
3238     {
3239     case LOC_UNDEF:
3240       return 1;
3241     case LOC_TYPEDEF:
3242       {
3243         struct type *type0 = SYMBOL_TYPE (sym0);
3244         struct type *type1 = SYMBOL_TYPE (sym1);
3245         char *name0 = DEPRECATED_SYMBOL_NAME (sym0);
3246         char *name1 = DEPRECATED_SYMBOL_NAME (sym1);
3247         int len0 = strlen (name0);
3248         return
3249           TYPE_CODE (type0) == TYPE_CODE (type1)
3250           && (equiv_types (type0, type1)
3251               || (len0 < strlen (name1) && STREQN (name0, name1, len0)
3252                   && STREQN (name1 + len0, "___XV", 5)));
3253       }
3254     case LOC_CONST:
3255       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
3256         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
3257     default:
3258       return 0;
3259     }
3260 }
3261
3262 /* Append SYM to the end of defn_symbols, and BLOCK to the end of
3263    defn_blocks, updating ndefns, and expanding defn_symbols and
3264    defn_blocks as needed.   Do not include SYM if it is a duplicate.  */
3265
3266 static void
3267 add_defn_to_vec (struct symbol *sym, struct block *block)
3268 {
3269   int i;
3270   size_t tmp;
3271
3272   if (SYMBOL_TYPE (sym) != NULL)
3273     CHECK_TYPEDEF (SYMBOL_TYPE (sym));
3274   for (i = 0; i < ndefns; i += 1)
3275     {
3276       if (lesseq_defined_than (sym, defn_symbols[i]))
3277         return;
3278       else if (lesseq_defined_than (defn_symbols[i], sym))
3279         {
3280           defn_symbols[i] = sym;
3281           defn_blocks[i] = block;
3282           return;
3283         }
3284     }
3285
3286   tmp = defn_vector_size;
3287   GROW_VECT (defn_symbols, tmp, ndefns + 2);
3288   GROW_VECT (defn_blocks, defn_vector_size, ndefns + 2);
3289
3290   defn_symbols[ndefns] = sym;
3291   defn_blocks[ndefns] = block;
3292   ndefns += 1;
3293 }
3294
3295 /* Look, in partial_symtab PST, for symbol NAME in given namespace.
3296    Check the global symbols if GLOBAL, the static symbols if not.  Do
3297    wild-card match if WILD. */
3298
3299 static struct partial_symbol *
3300 ada_lookup_partial_symbol (struct partial_symtab *pst, const char *name,
3301                            int global, namespace_enum namespace, int wild)
3302 {
3303   struct partial_symbol **start;
3304   int name_len = strlen (name);
3305   int length = (global ? pst->n_global_syms : pst->n_static_syms);
3306   int i;
3307
3308   if (length == 0)
3309     {
3310       return (NULL);
3311     }
3312
3313   start = (global ?
3314            pst->objfile->global_psymbols.list + pst->globals_offset :
3315            pst->objfile->static_psymbols.list + pst->statics_offset);
3316
3317   if (wild)
3318     {
3319       for (i = 0; i < length; i += 1)
3320         {
3321           struct partial_symbol *psym = start[i];
3322
3323           if (SYMBOL_NAMESPACE (psym) == namespace &&
3324               wild_match (name, name_len, DEPRECATED_SYMBOL_NAME (psym)))
3325             return psym;
3326         }
3327       return NULL;
3328     }
3329   else
3330     {
3331       if (global)
3332         {
3333           int U;
3334           i = 0;
3335           U = length - 1;
3336           while (U - i > 4)
3337             {
3338               int M = (U + i) >> 1;
3339               struct partial_symbol *psym = start[M];
3340               if (DEPRECATED_SYMBOL_NAME (psym)[0] < name[0])
3341                 i = M + 1;
3342               else if (DEPRECATED_SYMBOL_NAME (psym)[0] > name[0])
3343                 U = M - 1;
3344               else if (strcmp (DEPRECATED_SYMBOL_NAME (psym), name) < 0)
3345                 i = M + 1;
3346               else
3347                 U = M;
3348             }
3349         }
3350       else
3351         i = 0;
3352
3353       while (i < length)
3354         {
3355           struct partial_symbol *psym = start[i];
3356
3357           if (SYMBOL_NAMESPACE (psym) == namespace)
3358             {
3359               int cmp = strncmp (name, DEPRECATED_SYMBOL_NAME (psym), name_len);
3360
3361               if (cmp < 0)
3362                 {
3363                   if (global)
3364                     break;
3365                 }
3366               else if (cmp == 0
3367                        && is_name_suffix (DEPRECATED_SYMBOL_NAME (psym) + name_len))
3368                 return psym;
3369             }
3370           i += 1;
3371         }
3372
3373       if (global)
3374         {
3375           int U;
3376           i = 0;
3377           U = length - 1;
3378           while (U - i > 4)
3379             {
3380               int M = (U + i) >> 1;
3381               struct partial_symbol *psym = start[M];
3382               if (DEPRECATED_SYMBOL_NAME (psym)[0] < '_')
3383                 i = M + 1;
3384               else if (DEPRECATED_SYMBOL_NAME (psym)[0] > '_')
3385                 U = M - 1;
3386               else if (strcmp (DEPRECATED_SYMBOL_NAME (psym), "_ada_") < 0)
3387                 i = M + 1;
3388               else
3389                 U = M;
3390             }
3391         }
3392       else
3393         i = 0;
3394
3395       while (i < length)
3396         {
3397           struct partial_symbol *psym = start[i];
3398
3399           if (SYMBOL_NAMESPACE (psym) == namespace)
3400             {
3401               int cmp;
3402
3403               cmp = (int) '_' - (int) DEPRECATED_SYMBOL_NAME (psym)[0];
3404               if (cmp == 0)
3405                 {
3406                   cmp = strncmp ("_ada_", DEPRECATED_SYMBOL_NAME (psym), 5);
3407                   if (cmp == 0)
3408                     cmp = strncmp (name, DEPRECATED_SYMBOL_NAME (psym) + 5, name_len);
3409                 }
3410
3411               if (cmp < 0)
3412                 {
3413                   if (global)
3414                     break;
3415                 }
3416               else if (cmp == 0
3417                        && is_name_suffix (DEPRECATED_SYMBOL_NAME (psym) + name_len + 5))
3418                 return psym;
3419             }
3420           i += 1;
3421         }
3422
3423     }
3424   return NULL;
3425 }
3426
3427
3428 /* Find a symbol table containing symbol SYM or NULL if none.  */
3429 static struct symtab *
3430 symtab_for_sym (struct symbol *sym)
3431 {
3432   struct symtab *s;
3433   struct objfile *objfile;
3434   struct block *b;
3435   struct symbol *tmp_sym;
3436   int i, j;
3437
3438   ALL_SYMTABS (objfile, s)
3439   {
3440     switch (SYMBOL_CLASS (sym))
3441       {
3442       case LOC_CONST:
3443       case LOC_STATIC:
3444       case LOC_TYPEDEF:
3445       case LOC_REGISTER:
3446       case LOC_LABEL:
3447       case LOC_BLOCK:
3448       case LOC_CONST_BYTES:
3449         b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
3450         ALL_BLOCK_SYMBOLS (b, i, tmp_sym) if (sym == tmp_sym)
3451           return s;
3452         b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
3453         ALL_BLOCK_SYMBOLS (b, i, tmp_sym) if (sym == tmp_sym)
3454           return s;
3455         break;
3456       default:
3457         break;
3458       }
3459     switch (SYMBOL_CLASS (sym))
3460       {
3461       case LOC_REGISTER:
3462       case LOC_ARG:
3463       case LOC_REF_ARG:
3464       case LOC_REGPARM:
3465       case LOC_REGPARM_ADDR:
3466       case LOC_LOCAL:
3467       case LOC_TYPEDEF:
3468       case LOC_LOCAL_ARG:
3469       case LOC_BASEREG:
3470       case LOC_BASEREG_ARG:
3471       case LOC_COMPUTED:
3472       case LOC_COMPUTED_ARG:
3473         for (j = FIRST_LOCAL_BLOCK;
3474              j < BLOCKVECTOR_NBLOCKS (BLOCKVECTOR (s)); j += 1)
3475           {
3476             b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), j);
3477             ALL_BLOCK_SYMBOLS (b, i, tmp_sym) if (sym == tmp_sym)
3478               return s;
3479           }
3480         break;
3481       default:
3482         break;
3483       }
3484   }
3485   return NULL;
3486 }
3487
3488 /* Return a minimal symbol matching NAME according to Ada demangling 
3489    rules. Returns NULL if there is no such minimal symbol. */
3490
3491 struct minimal_symbol *
3492 ada_lookup_minimal_symbol (const char *name)
3493 {
3494   struct objfile *objfile;
3495   struct minimal_symbol *msymbol;
3496   int wild_match = (strstr (name, "__") == NULL);
3497
3498   ALL_MSYMBOLS (objfile, msymbol)
3499   {
3500     if (ada_match_name (DEPRECATED_SYMBOL_NAME (msymbol), name, wild_match)
3501         && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
3502       return msymbol;
3503   }
3504
3505   return NULL;
3506 }
3507
3508 /* For all subprograms that statically enclose the subprogram of the
3509  * selected frame, add symbols matching identifier NAME in NAMESPACE
3510  * and their blocks to vectors *defn_symbols and *defn_blocks, as for
3511  * ada_add_block_symbols (q.v.).   If WILD, treat as NAME with a
3512  * wildcard prefix.  At the moment, this function uses a heuristic to
3513  * find the frames of enclosing subprograms: it treats the
3514  * pointer-sized value at location 0 from the local-variable base of a
3515  * frame as a static link, and then searches up the call stack for a
3516  * frame with that same local-variable base. */
3517 static void
3518 add_symbols_from_enclosing_procs (const char *name, namespace_enum namespace,
3519                                   int wild_match)
3520 {
3521 #ifdef i386
3522   static struct symbol static_link_sym;
3523   static struct symbol *static_link;
3524
3525   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
3526   struct frame_info *frame;
3527   struct frame_info *target_frame;
3528
3529   if (static_link == NULL)
3530     {
3531       /* Initialize the local variable symbol that stands for the
3532        * static link (when it exists). */
3533       static_link = &static_link_sym;
3534       DEPRECATED_SYMBOL_NAME (static_link) = "";
3535       SYMBOL_LANGUAGE (static_link) = language_unknown;
3536       SYMBOL_CLASS (static_link) = LOC_LOCAL;
3537       SYMBOL_NAMESPACE (static_link) = VAR_NAMESPACE;
3538       SYMBOL_TYPE (static_link) = lookup_pointer_type (builtin_type_void);
3539       SYMBOL_VALUE (static_link) =
3540         -(long) TYPE_LENGTH (SYMBOL_TYPE (static_link));
3541     }
3542
3543   frame = deprecated_selected_frame;
3544   while (frame != NULL && ndefns == 0)
3545     {
3546       struct block *block;
3547       struct value *target_link_val = read_var_value (static_link, frame);
3548       CORE_ADDR target_link;
3549
3550       if (target_link_val == NULL)
3551         break;
3552       QUIT;
3553
3554       target_link = target_link_val;
3555       do
3556         {
3557           QUIT;
3558           frame = get_prev_frame (frame);
3559         }
3560       while (frame != NULL && FRAME_LOCALS_ADDRESS (frame) != target_link);
3561
3562       if (frame == NULL)
3563         break;
3564
3565       block = get_frame_block (frame, 0);
3566       while (block != NULL && block_function (block) != NULL && ndefns == 0)
3567         {
3568           ada_add_block_symbols (block, name, namespace, NULL, wild_match);
3569
3570           block = BLOCK_SUPERBLOCK (block);
3571         }
3572     }
3573
3574   do_cleanups (old_chain);
3575 #endif
3576 }
3577
3578 /* True if TYPE is definitely an artificial type supplied to a symbol
3579  * for which no debugging information was given in the symbol file. */
3580 static int
3581 is_nondebugging_type (struct type *type)
3582 {
3583   char *name = ada_type_name (type);
3584   return (name != NULL && STREQ (name, "<variable, no debug info>"));
3585 }
3586
3587 /* Remove any non-debugging symbols in SYMS[0 .. NSYMS-1] that definitely 
3588  * duplicate other symbols in the list.  (The only case I know of where
3589  * this happens is when object files containing stabs-in-ecoff are
3590  * linked with files containing ordinary ecoff debugging symbols (or no
3591  * debugging symbols)). Modifies SYMS to squeeze out deleted symbols,
3592  * and applies the same modification to BLOCKS to maintain the
3593  * correspondence between SYMS[i] and BLOCKS[i].  Returns the number
3594  * of symbols in the modified list. */
3595 static int
3596 remove_extra_symbols (struct symbol **syms, struct block **blocks, int nsyms)
3597 {
3598   int i, j;
3599
3600   i = 0;
3601   while (i < nsyms)
3602     {
3603       if (DEPRECATED_SYMBOL_NAME (syms[i]) != NULL
3604           && SYMBOL_CLASS (syms[i]) == LOC_STATIC
3605           && is_nondebugging_type (SYMBOL_TYPE (syms[i])))
3606         {
3607           for (j = 0; j < nsyms; j += 1)
3608             {
3609               if (i != j
3610                   && DEPRECATED_SYMBOL_NAME (syms[j]) != NULL
3611                   && STREQ (DEPRECATED_SYMBOL_NAME (syms[i]), DEPRECATED_SYMBOL_NAME (syms[j]))
3612                   && SYMBOL_CLASS (syms[i]) == SYMBOL_CLASS (syms[j])
3613                   && SYMBOL_VALUE_ADDRESS (syms[i])
3614                   == SYMBOL_VALUE_ADDRESS (syms[j]))
3615                 {
3616                   int k;
3617                   for (k = i + 1; k < nsyms; k += 1)
3618                     {
3619                       syms[k - 1] = syms[k];
3620                       blocks[k - 1] = blocks[k];
3621                     }
3622                   nsyms -= 1;
3623                   goto NextSymbol;
3624                 }
3625             }
3626         }
3627       i += 1;
3628     NextSymbol:
3629       ;
3630     }
3631   return nsyms;
3632 }
3633
3634 /* Find symbols in NAMESPACE matching NAME, in BLOCK0 and enclosing 
3635    scope and in global scopes, returning the number of matches.  Sets 
3636    *SYMS to point to a vector of matching symbols, with *BLOCKS
3637    pointing to the vector of corresponding blocks in which those
3638    symbols reside.  These two vectors are transient---good only to the
3639    next call of ada_lookup_symbol_list.  Any non-function/non-enumeral symbol
3640    match within the nest of blocks whose innermost member is BLOCK0,
3641    is the outermost match returned (no other matches in that or
3642    enclosing blocks is returned).  If there are any matches in or
3643    surrounding BLOCK0, then these alone are returned. */
3644
3645 int
3646 ada_lookup_symbol_list (const char *name, struct block *block0,
3647                         namespace_enum namespace, struct symbol ***syms,
3648                         struct block ***blocks)
3649 {
3650   struct symbol *sym;
3651   struct symtab *s;
3652   struct partial_symtab *ps;
3653   struct blockvector *bv;
3654   struct objfile *objfile;
3655   struct block *b;
3656   struct block *block;
3657   struct minimal_symbol *msymbol;
3658   int wild_match = (strstr (name, "__") == NULL);
3659   int cacheIfUnique;
3660
3661 #ifdef TIMING
3662   markTimeStart (0);
3663 #endif
3664
3665   ndefns = 0;
3666   cacheIfUnique = 0;
3667
3668   /* Search specified block and its superiors.  */
3669
3670   block = block0;
3671   while (block != NULL)
3672     {
3673       ada_add_block_symbols (block, name, namespace, NULL, wild_match);
3674
3675       /* If we found a non-function match, assume that's the one. */
3676       if (is_nonfunction (defn_symbols, ndefns))
3677         goto done;
3678
3679       block = BLOCK_SUPERBLOCK (block);
3680     }
3681
3682   /* If we found ANY matches in the specified BLOCK, we're done. */
3683
3684   if (ndefns > 0)
3685     goto done;
3686
3687   cacheIfUnique = 1;
3688
3689   /* Now add symbols from all global blocks: symbol tables, minimal symbol
3690      tables, and psymtab's */
3691
3692   ALL_SYMTABS (objfile, s)
3693   {
3694     QUIT;
3695     if (!s->primary)
3696       continue;
3697     bv = BLOCKVECTOR (s);
3698     block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3699     ada_add_block_symbols (block, name, namespace, objfile, wild_match);
3700   }
3701
3702   if (namespace == VAR_NAMESPACE)
3703     {
3704       ALL_MSYMBOLS (objfile, msymbol)
3705       {
3706         if (ada_match_name (DEPRECATED_SYMBOL_NAME (msymbol), name, wild_match))
3707           {
3708             switch (MSYMBOL_TYPE (msymbol))
3709               {
3710               case mst_solib_trampoline:
3711                 break;
3712               default:
3713                 s = find_pc_symtab (SYMBOL_VALUE_ADDRESS (msymbol));
3714                 if (s != NULL)
3715                   {
3716                     int old_ndefns = ndefns;
3717                     QUIT;
3718                     bv = BLOCKVECTOR (s);
3719                     block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3720                     ada_add_block_symbols (block,
3721                                            DEPRECATED_SYMBOL_NAME (msymbol),
3722                                            namespace, objfile, wild_match);
3723                     if (ndefns == old_ndefns)
3724                       {
3725                         block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
3726                         ada_add_block_symbols (block,
3727                                                DEPRECATED_SYMBOL_NAME (msymbol),
3728                                                namespace, objfile,
3729                                                wild_match);
3730                       }
3731                   }
3732               }
3733           }
3734       }
3735     }
3736
3737   ALL_PSYMTABS (objfile, ps)
3738   {
3739     QUIT;
3740     if (!ps->readin
3741         && ada_lookup_partial_symbol (ps, name, 1, namespace, wild_match))
3742       {
3743         s = PSYMTAB_TO_SYMTAB (ps);
3744         if (!s->primary)
3745           continue;
3746         bv = BLOCKVECTOR (s);
3747         block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3748         ada_add_block_symbols (block, name, namespace, objfile, wild_match);
3749       }
3750   }
3751
3752   /* Now add symbols from all per-file blocks if we've gotten no hits.  
3753      (Not strictly correct, but perhaps better than an error).
3754      Do the symtabs first, then check the psymtabs */
3755
3756   if (ndefns == 0)
3757     {
3758
3759       ALL_SYMTABS (objfile, s)
3760       {
3761         QUIT;
3762         if (!s->primary)
3763           continue;
3764         bv = BLOCKVECTOR (s);
3765         block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
3766         ada_add_block_symbols (block, name, namespace, objfile, wild_match);
3767       }
3768
3769       ALL_PSYMTABS (objfile, ps)
3770       {
3771         QUIT;
3772         if (!ps->readin
3773             && ada_lookup_partial_symbol (ps, name, 0, namespace, wild_match))
3774           {
3775             s = PSYMTAB_TO_SYMTAB (ps);
3776             bv = BLOCKVECTOR (s);
3777             if (!s->primary)
3778               continue;
3779             block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
3780             ada_add_block_symbols (block, name, namespace,
3781                                    objfile, wild_match);
3782           }
3783       }
3784     }
3785
3786   /* Finally, we try to find NAME as a local symbol in some lexically
3787      enclosing block.  We do this last, expecting this case to be
3788      rare. */
3789   if (ndefns == 0)
3790     {
3791       add_symbols_from_enclosing_procs (name, namespace, wild_match);
3792       if (ndefns > 0)
3793         goto done;
3794     }
3795
3796 done:
3797   ndefns = remove_extra_symbols (defn_symbols, defn_blocks, ndefns);
3798
3799
3800   *syms = defn_symbols;
3801   *blocks = defn_blocks;
3802 #ifdef TIMING
3803   markTimeStop (0);
3804 #endif
3805   return ndefns;
3806 }
3807
3808 /* Return a symbol in NAMESPACE matching NAME, in BLOCK0 and enclosing 
3809  * scope and in global scopes, or NULL if none.  NAME is folded to
3810  * lower case first, unless it is surrounded in single quotes. 
3811  * Otherwise, the result is as for ada_lookup_symbol_list, but is 
3812  * disambiguated by user query if needed. */
3813
3814 struct symbol *
3815 ada_lookup_symbol (const char *name, struct block *block0,
3816                    namespace_enum namespace)
3817 {
3818   struct symbol **candidate_syms;
3819   struct block **candidate_blocks;
3820   int n_candidates;
3821
3822   n_candidates = ada_lookup_symbol_list (name,
3823                                          block0, namespace,
3824                                          &candidate_syms, &candidate_blocks);
3825
3826   if (n_candidates == 0)
3827     return NULL;
3828   else if (n_candidates != 1)
3829     user_select_syms (candidate_syms, candidate_blocks, n_candidates, 1);
3830
3831   return candidate_syms[0];
3832 }
3833
3834
3835 /* True iff STR is a possible encoded suffix of a normal Ada name 
3836  * that is to be ignored for matching purposes.  Suffixes of parallel
3837  * names (e.g., XVE) are not included here.  Currently, the possible suffixes 
3838  * are given by the regular expression:
3839  *        (X[nb]*)?(__[0-9]+|\$[0-9]+|___(LJM|X([FDBUP].*|R[^T]?)))?$
3840  * 
3841  */
3842 static int
3843 is_name_suffix (const char *str)
3844 {
3845   int k;
3846   if (str[0] == 'X')
3847     {
3848       str += 1;
3849       while (str[0] != '_' && str[0] != '\0')
3850         {
3851           if (str[0] != 'n' && str[0] != 'b')
3852             return 0;
3853           str += 1;
3854         }
3855     }
3856   if (str[0] == '\000')
3857     return 1;
3858   if (str[0] == '_')
3859     {
3860       if (str[1] != '_' || str[2] == '\000')
3861         return 0;
3862       if (str[2] == '_')
3863         {
3864           if (STREQ (str + 3, "LJM"))
3865             return 1;
3866           if (str[3] != 'X')
3867             return 0;
3868           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B' ||
3869               str[4] == 'U' || str[4] == 'P')
3870             return 1;
3871           if (str[4] == 'R' && str[5] != 'T')
3872             return 1;
3873           return 0;
3874         }
3875       for (k = 2; str[k] != '\0'; k += 1)
3876         if (!isdigit (str[k]))
3877           return 0;
3878       return 1;
3879     }
3880   if (str[0] == '$' && str[1] != '\000')
3881     {
3882       for (k = 1; str[k] != '\0'; k += 1)
3883         if (!isdigit (str[k]))
3884           return 0;
3885       return 1;
3886     }
3887   return 0;
3888 }
3889
3890 /* True if NAME represents a name of the form A1.A2....An, n>=1 and 
3891  * PATN[0..PATN_LEN-1] = Ak.Ak+1.....An for some k >= 1.  Ignores
3892  * informational suffixes of NAME (i.e., for which is_name_suffix is
3893  * true). */
3894 static int
3895 wild_match (const char *patn, int patn_len, const char *name)
3896 {
3897   int name_len;
3898   int s, e;
3899
3900   name_len = strlen (name);
3901   if (name_len >= patn_len + 5 && STREQN (name, "_ada_", 5)
3902       && STREQN (patn, name + 5, patn_len)
3903       && is_name_suffix (name + patn_len + 5))
3904     return 1;
3905
3906   while (name_len >= patn_len)
3907     {
3908       if (STREQN (patn, name, patn_len) && is_name_suffix (name + patn_len))
3909         return 1;
3910       do
3911         {
3912           name += 1;
3913           name_len -= 1;
3914         }
3915       while (name_len > 0
3916              && name[0] != '.' && (name[0] != '_' || name[1] != '_'));
3917       if (name_len <= 0)
3918         return 0;
3919       if (name[0] == '_')
3920         {
3921           if (!islower (name[2]))
3922             return 0;
3923           name += 2;
3924           name_len -= 2;
3925         }
3926       else
3927         {
3928           if (!islower (name[1]))
3929             return 0;
3930           name += 1;
3931           name_len -= 1;
3932         }
3933     }
3934
3935   return 0;
3936 }
3937
3938
3939 /* Add symbols from BLOCK matching identifier NAME in NAMESPACE to 
3940    vector *defn_symbols, updating *defn_symbols (if necessary), *SZ (the size of
3941    the vector *defn_symbols), and *ndefns (the number of symbols
3942    currently stored in *defn_symbols).  If WILD, treat as NAME with a
3943    wildcard prefix. OBJFILE is the section containing BLOCK. */
3944
3945 static void
3946 ada_add_block_symbols (struct block *block, const char *name,
3947                        namespace_enum namespace, struct objfile *objfile,
3948                        int wild)
3949 {
3950   int i;
3951   int name_len = strlen (name);
3952   /* A matching argument symbol, if any. */
3953   struct symbol *arg_sym;
3954   /* Set true when we find a matching non-argument symbol */
3955   int found_sym;
3956   int is_sorted = BLOCK_SHOULD_SORT (block);
3957   struct symbol *sym;
3958
3959   arg_sym = NULL;
3960   found_sym = 0;
3961   if (wild)
3962     {
3963       struct symbol *sym;
3964       ALL_BLOCK_SYMBOLS (block, i, sym)
3965       {
3966         if (SYMBOL_NAMESPACE (sym) == namespace &&
3967             wild_match (name, name_len, DEPRECATED_SYMBOL_NAME (sym)))
3968           {
3969             switch (SYMBOL_CLASS (sym))
3970               {
3971               case LOC_ARG:
3972               case LOC_LOCAL_ARG:
3973               case LOC_REF_ARG:
3974               case LOC_REGPARM:
3975               case LOC_REGPARM_ADDR:
3976               case LOC_BASEREG_ARG:
3977               case LOC_COMPUTED_ARG:
3978                 arg_sym = sym;
3979                 break;
3980               case LOC_UNRESOLVED:
3981                 continue;
3982               default:
3983                 found_sym = 1;
3984                 fill_in_ada_prototype (sym);
3985                 add_defn_to_vec (fixup_symbol_section (sym, objfile), block);
3986                 break;
3987               }
3988           }
3989       }
3990     }
3991   else
3992     {
3993       if (is_sorted)
3994         {
3995           int U;
3996           i = 0;
3997           U = BLOCK_NSYMS (block) - 1;
3998           while (U - i > 4)
3999             {
4000               int M = (U + i) >> 1;
4001               struct symbol *sym = BLOCK_SYM (block, M);
4002               if (DEPRECATED_SYMBOL_NAME (sym)[0] < name[0])
4003                 i = M + 1;
4004               else if (DEPRECATED_SYMBOL_NAME (sym)[0] > name[0])
4005                 U = M - 1;
4006               else if (strcmp (DEPRECATED_SYMBOL_NAME (sym), name) < 0)
4007                 i = M + 1;
4008               else
4009                 U = M;
4010             }
4011         }
4012       else
4013         i = 0;
4014
4015       for (; i < BLOCK_BUCKETS (block); i += 1)
4016         for (sym = BLOCK_BUCKET (block, i); sym != NULL; sym = sym->hash_next)
4017           {
4018             if (SYMBOL_NAMESPACE (sym) == namespace)
4019               {
4020                 int cmp = strncmp (name, DEPRECATED_SYMBOL_NAME (sym), name_len);
4021
4022                 if (cmp < 0)
4023                   {
4024                     if (is_sorted)
4025                       {
4026                         i = BLOCK_BUCKETS (block);
4027                         break;
4028                       }
4029                   }
4030                 else if (cmp == 0
4031                          && is_name_suffix (DEPRECATED_SYMBOL_NAME (sym) + name_len))
4032                   {
4033                     switch (SYMBOL_CLASS (sym))
4034                       {
4035                       case LOC_ARG:
4036                       case LOC_LOCAL_ARG:
4037                       case LOC_REF_ARG:
4038                       case LOC_REGPARM:
4039                       case LOC_REGPARM_ADDR:
4040                       case LOC_BASEREG_ARG:
4041                       case LOC_COMPUTED_ARG:
4042                         arg_sym = sym;
4043                         break;
4044                       case LOC_UNRESOLVED:
4045                         break;
4046                       default:
4047                         found_sym = 1;
4048                         fill_in_ada_prototype (sym);
4049                         add_defn_to_vec (fixup_symbol_section (sym, objfile),
4050                                          block);
4051                         break;
4052                       }
4053                   }
4054               }
4055           }
4056     }
4057
4058   if (!found_sym && arg_sym != NULL)
4059     {
4060       fill_in_ada_prototype (arg_sym);
4061       add_defn_to_vec (fixup_symbol_section (arg_sym, objfile), block);
4062     }
4063
4064   if (!wild)
4065     {
4066       arg_sym = NULL;
4067       found_sym = 0;
4068       if (is_sorted)
4069         {
4070           int U;
4071           i = 0;
4072           U = BLOCK_NSYMS (block) - 1;
4073           while (U - i > 4)
4074             {
4075               int M = (U + i) >> 1;
4076               struct symbol *sym = BLOCK_SYM (block, M);
4077               if (DEPRECATED_SYMBOL_NAME (sym)[0] < '_')
4078                 i = M + 1;
4079               else if (DEPRECATED_SYMBOL_NAME (sym)[0] > '_')
4080                 U = M - 1;
4081               else if (strcmp (DEPRECATED_SYMBOL_NAME (sym), "_ada_") < 0)
4082                 i = M + 1;
4083               else
4084                 U = M;
4085             }
4086         }
4087       else
4088         i = 0;
4089
4090       for (; i < BLOCK_BUCKETS (block); i += 1)
4091         for (sym = BLOCK_BUCKET (block, i); sym != NULL; sym = sym->hash_next)
4092           {
4093             struct symbol *sym = BLOCK_SYM (block, i);
4094
4095             if (SYMBOL_NAMESPACE (sym) == namespace)
4096               {
4097                 int cmp;
4098
4099                 cmp = (int) '_' - (int) DEPRECATED_SYMBOL_NAME (sym)[0];
4100                 if (cmp == 0)
4101                   {
4102                     cmp = strncmp ("_ada_", DEPRECATED_SYMBOL_NAME (sym), 5);
4103                     if (cmp == 0)
4104                       cmp = strncmp (name, DEPRECATED_SYMBOL_NAME (sym) + 5, name_len);
4105                   }
4106
4107                 if (cmp < 0)
4108                   {
4109                     if (is_sorted)
4110                       {
4111                         i = BLOCK_BUCKETS (block);
4112                         break;
4113                       }
4114                   }
4115                 else if (cmp == 0
4116                          && is_name_suffix (DEPRECATED_SYMBOL_NAME (sym) + name_len + 5))
4117                   {
4118                     switch (SYMBOL_CLASS (sym))
4119                       {
4120                       case LOC_ARG:
4121                       case LOC_LOCAL_ARG:
4122                       case LOC_REF_ARG:
4123                       case LOC_REGPARM:
4124                       case LOC_REGPARM_ADDR:
4125                       case LOC_BASEREG_ARG:
4126                       case LOC_COMPUTED_ARG:
4127                         arg_sym = sym;
4128                         break;
4129                       case LOC_UNRESOLVED:
4130                         break;
4131                       default:
4132                         found_sym = 1;
4133                         fill_in_ada_prototype (sym);
4134                         add_defn_to_vec (fixup_symbol_section (sym, objfile),
4135                                          block);
4136                         break;
4137                       }
4138                   }
4139               }
4140           }
4141
4142       /* NOTE: This really shouldn't be needed for _ada_ symbols.
4143          They aren't parameters, right? */
4144       if (!found_sym && arg_sym != NULL)
4145         {
4146           fill_in_ada_prototype (arg_sym);
4147           add_defn_to_vec (fixup_symbol_section (arg_sym, objfile), block);
4148         }
4149     }
4150 }
4151 \f
4152
4153                                 /* Function Types */
4154
4155 /* Assuming that SYM is the symbol for a function, fill in its type 
4156    with prototype information, if it is not already there.  */
4157
4158 static void
4159 fill_in_ada_prototype (struct symbol *func)
4160 {
4161   struct block *b;
4162   int nargs, nsyms;
4163   int i;
4164   struct type *ftype;
4165   struct type *rtype;
4166   size_t max_fields;
4167   struct symbol *sym;
4168
4169   if (func == NULL
4170       || TYPE_CODE (SYMBOL_TYPE (func)) != TYPE_CODE_FUNC
4171       || TYPE_FIELDS (SYMBOL_TYPE (func)) != NULL)
4172     return;
4173
4174   /* We make each function type unique, so that each may have its own */
4175   /* parameter types.  This particular way of doing so wastes space: */
4176   /* it would be nicer to build the argument types while the original */
4177   /* function type is being built (FIXME). */
4178   rtype = check_typedef (TYPE_TARGET_TYPE (SYMBOL_TYPE (func)));
4179   ftype = alloc_type (TYPE_OBJFILE (SYMBOL_TYPE (func)));
4180   make_function_type (rtype, &ftype);
4181   SYMBOL_TYPE (func) = ftype;
4182
4183   b = SYMBOL_BLOCK_VALUE (func);
4184
4185   nargs = 0;
4186   max_fields = 8;
4187   TYPE_FIELDS (ftype) =
4188     (struct field *) xmalloc (sizeof (struct field) * max_fields);
4189   ALL_BLOCK_SYMBOLS (b, i, sym)
4190   {
4191     GROW_VECT (TYPE_FIELDS (ftype), max_fields, nargs + 1);
4192
4193     switch (SYMBOL_CLASS (sym))
4194       {
4195       case LOC_REF_ARG:
4196       case LOC_REGPARM_ADDR:
4197         TYPE_FIELD_BITPOS (ftype, nargs) = nargs;
4198         TYPE_FIELD_BITSIZE (ftype, nargs) = 0;
4199         TYPE_FIELD_STATIC_KIND (ftype, nargs) = 0;
4200         TYPE_FIELD_TYPE (ftype, nargs) =
4201           lookup_pointer_type (check_typedef (SYMBOL_TYPE (sym)));
4202         TYPE_FIELD_NAME (ftype, nargs) = DEPRECATED_SYMBOL_NAME (sym);
4203         nargs += 1;
4204
4205         break;
4206
4207       case LOC_ARG:
4208       case LOC_REGPARM:
4209       case LOC_LOCAL_ARG:
4210       case LOC_BASEREG_ARG:
4211       case LOC_COMPUTED_ARG:
4212         TYPE_FIELD_BITPOS (ftype, nargs) = nargs;
4213         TYPE_FIELD_BITSIZE (ftype, nargs) = 0;
4214         TYPE_FIELD_STATIC_KIND (ftype, nargs) = 0;
4215         TYPE_FIELD_TYPE (ftype, nargs) = check_typedef (SYMBOL_TYPE (sym));
4216         TYPE_FIELD_NAME (ftype, nargs) = DEPRECATED_SYMBOL_NAME (sym);
4217         nargs += 1;
4218
4219         break;
4220
4221       default:
4222         break;
4223       }
4224   }
4225
4226   /* Re-allocate fields vector; if there are no fields, make the */
4227   /* fields pointer non-null anyway, to mark that this function type */
4228   /* has been filled in. */
4229
4230   TYPE_NFIELDS (ftype) = nargs;
4231   if (nargs == 0)
4232     {
4233       static struct field dummy_field = { 0, 0, 0, 0 };
4234       xfree (TYPE_FIELDS (ftype));
4235       TYPE_FIELDS (ftype) = &dummy_field;
4236     }
4237   else
4238     {
4239       struct field *fields =
4240         (struct field *) TYPE_ALLOC (ftype, nargs * sizeof (struct field));
4241       memcpy ((char *) fields,
4242               (char *) TYPE_FIELDS (ftype), nargs * sizeof (struct field));
4243       xfree (TYPE_FIELDS (ftype));
4244       TYPE_FIELDS (ftype) = fields;
4245     }
4246 }
4247 \f
4248
4249                                 /* Breakpoint-related */
4250
4251 char no_symtab_msg[] =
4252   "No symbol table is loaded.  Use the \"file\" command.";
4253
4254 /* Assuming that LINE is pointing at the beginning of an argument to
4255    'break', return a pointer to the delimiter for the initial segment
4256    of that name.  This is the first ':', ' ', or end of LINE. 
4257 */
4258 char *
4259 ada_start_decode_line_1 (char *line)
4260 {
4261   /* [NOTE: strpbrk would be more elegant, but I am reluctant to be
4262      the first to use such a library function in GDB code.] */
4263   char *p;
4264   for (p = line; *p != '\000' && *p != ' ' && *p != ':'; p += 1)
4265     ;
4266   return p;
4267 }
4268
4269 /* *SPEC points to a function and line number spec (as in a break
4270    command), following any initial file name specification.
4271
4272    Return all symbol table/line specfications (sals) consistent with the
4273    information in *SPEC and FILE_TABLE in the
4274    following sense: 
4275      + FILE_TABLE is null, or the sal refers to a line in the file
4276        named by FILE_TABLE.
4277      + If *SPEC points to an argument with a trailing ':LINENUM',
4278        then the sal refers to that line (or one following it as closely as 
4279        possible).
4280      + If *SPEC does not start with '*', the sal is in a function with 
4281        that name.
4282
4283    Returns with 0 elements if no matching non-minimal symbols found.
4284
4285    If *SPEC begins with a function name of the form <NAME>, then NAME
4286    is taken as a literal name; otherwise the function name is subject
4287    to the usual mangling.
4288
4289    *SPEC is updated to point after the function/line number specification.
4290
4291    FUNFIRSTLINE is non-zero if we desire the first line of real code
4292    in each function (this is ignored in the presence of a LINENUM spec.).
4293
4294    If CANONICAL is non-NULL, and if any of the sals require a
4295    'canonical line spec', then *CANONICAL is set to point to an array
4296    of strings, corresponding to and equal in length to the returned
4297    list of sals, such that (*CANONICAL)[i] is non-null and contains a 
4298    canonical line spec for the ith returned sal, if needed.  If no 
4299    canonical line specs are required and CANONICAL is non-null, 
4300    *CANONICAL is set to NULL.
4301
4302    A 'canonical line spec' is simply a name (in the format of the
4303    breakpoint command) that uniquely identifies a breakpoint position,
4304    with no further contextual information or user selection.  It is
4305    needed whenever the file name, function name, and line number
4306    information supplied is insufficient for this unique
4307    identification.  Currently overloaded functions, the name '*', 
4308    or static functions without a filename yield a canonical line spec.
4309    The array and the line spec strings are allocated on the heap; it
4310    is the caller's responsibility to free them.   */
4311
4312 struct symtabs_and_lines
4313 ada_finish_decode_line_1 (char **spec, struct symtab *file_table,
4314                           int funfirstline, char ***canonical)
4315 {
4316   struct symbol **symbols;
4317   struct block **blocks;
4318   struct block *block;
4319   int n_matches, i, line_num;
4320   struct symtabs_and_lines selected;
4321   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
4322   char *name;
4323
4324   int len;
4325   char *lower_name;
4326   char *unquoted_name;
4327
4328   if (file_table == NULL)
4329     block = get_selected_block (NULL);
4330   else
4331     block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (file_table), STATIC_BLOCK);
4332
4333   if (canonical != NULL)
4334     *canonical = (char **) NULL;
4335
4336   name = *spec;
4337   if (**spec == '*')
4338     *spec += 1;
4339   else
4340     {
4341       while (**spec != '\000' &&
4342              !strchr (ada_completer_word_break_characters, **spec))
4343         *spec += 1;
4344     }
4345   len = *spec - name;
4346
4347   line_num = -1;
4348   if (file_table != NULL && (*spec)[0] == ':' && isdigit ((*spec)[1]))
4349     {
4350       line_num = strtol (*spec + 1, spec, 10);
4351       while (**spec == ' ' || **spec == '\t')
4352         *spec += 1;
4353     }
4354
4355   if (name[0] == '*')
4356     {
4357       if (line_num == -1)
4358         error ("Wild-card function with no line number or file name.");
4359
4360       return all_sals_for_line (file_table->filename, line_num, canonical);
4361     }
4362
4363   if (name[0] == '\'')
4364     {
4365       name += 1;
4366       len -= 2;
4367     }
4368
4369   if (name[0] == '<')
4370     {
4371       unquoted_name = (char *) alloca (len - 1);
4372       memcpy (unquoted_name, name + 1, len - 2);
4373       unquoted_name[len - 2] = '\000';
4374       lower_name = NULL;
4375     }
4376   else
4377     {
4378       unquoted_name = (char *) alloca (len + 1);
4379       memcpy (unquoted_name, name, len);
4380       unquoted_name[len] = '\000';
4381       lower_name = (char *) alloca (len + 1);
4382       for (i = 0; i < len; i += 1)
4383         lower_name[i] = tolower (name[i]);
4384       lower_name[len] = '\000';
4385     }
4386
4387   n_matches = 0;
4388   if (lower_name != NULL)
4389     n_matches = ada_lookup_symbol_list (ada_mangle (lower_name), block,
4390                                         VAR_NAMESPACE, &symbols, &blocks);
4391   if (n_matches == 0)
4392     n_matches = ada_lookup_symbol_list (unquoted_name, block,
4393                                         VAR_NAMESPACE, &symbols, &blocks);
4394   if (n_matches == 0 && line_num >= 0)
4395     error ("No line number information found for %s.", unquoted_name);
4396   else if (n_matches == 0)
4397     {
4398 #ifdef HPPA_COMPILER_BUG
4399       /* FIXME: See comment in symtab.c::decode_line_1 */
4400 #undef volatile
4401       volatile struct symtab_and_line val;
4402 #define volatile                /*nothing */
4403 #else
4404       struct symtab_and_line val;
4405 #endif
4406       struct minimal_symbol *msymbol;
4407
4408       init_sal (&val);
4409
4410       msymbol = NULL;
4411       if (lower_name != NULL)
4412         msymbol = ada_lookup_minimal_symbol (ada_mangle (lower_name));
4413       if (msymbol == NULL)
4414         msymbol = ada_lookup_minimal_symbol (unquoted_name);
4415       if (msymbol != NULL)
4416         {
4417           val.pc = SYMBOL_VALUE_ADDRESS (msymbol);
4418           val.section = SYMBOL_BFD_SECTION (msymbol);
4419           if (funfirstline)
4420             {
4421               val.pc += FUNCTION_START_OFFSET;
4422               SKIP_PROLOGUE (val.pc);
4423             }
4424           selected.sals = (struct symtab_and_line *)
4425             xmalloc (sizeof (struct symtab_and_line));
4426           selected.sals[0] = val;
4427           selected.nelts = 1;
4428           return selected;
4429         }
4430
4431       if (!have_full_symbols () &&
4432           !have_partial_symbols () && !have_minimal_symbols ())
4433         error (no_symtab_msg);
4434
4435       error ("Function \"%s\" not defined.", unquoted_name);
4436       return selected;          /* for lint */
4437     }
4438
4439   if (line_num >= 0)
4440     {
4441       return
4442         find_sal_from_funcs_and_line (file_table->filename, line_num,
4443                                       symbols, n_matches);
4444     }
4445   else
4446     {
4447       selected.nelts =
4448         user_select_syms (symbols, blocks, n_matches, n_matches);
4449     }
4450
4451   selected.sals = (struct symtab_and_line *)
4452     xmalloc (sizeof (struct symtab_and_line) * selected.nelts);
4453   memset (selected.sals, 0, selected.nelts * sizeof (selected.sals[i]));
4454   make_cleanup (xfree, selected.sals);
4455
4456   i = 0;
4457   while (i < selected.nelts)
4458     {
4459       if (SYMBOL_CLASS (symbols[i]) == LOC_BLOCK)
4460         selected.sals[i] = find_function_start_sal (symbols[i], funfirstline);
4461       else if (SYMBOL_LINE (symbols[i]) != 0)
4462         {
4463           selected.sals[i].symtab = symtab_for_sym (symbols[i]);
4464           selected.sals[i].line = SYMBOL_LINE (symbols[i]);
4465         }
4466       else if (line_num >= 0)
4467         {
4468           /* Ignore this choice */
4469           symbols[i] = symbols[selected.nelts - 1];
4470           blocks[i] = blocks[selected.nelts - 1];
4471           selected.nelts -= 1;
4472           continue;
4473         }
4474       else
4475         error ("Line number not known for symbol \"%s\"", unquoted_name);
4476       i += 1;
4477     }
4478
4479   if (canonical != NULL && (line_num >= 0 || n_matches > 1))
4480     {
4481       *canonical = (char **) xmalloc (sizeof (char *) * selected.nelts);
4482       for (i = 0; i < selected.nelts; i += 1)
4483         (*canonical)[i] =
4484           extended_canonical_line_spec (selected.sals[i],
4485                                         SYMBOL_PRINT_NAME (symbols[i]));
4486     }
4487
4488   discard_cleanups (old_chain);
4489   return selected;
4490 }
4491
4492 /* The (single) sal corresponding to line LINE_NUM in a symbol table
4493    with file name FILENAME that occurs in one of the functions listed 
4494    in SYMBOLS[0 .. NSYMS-1]. */
4495 static struct symtabs_and_lines
4496 find_sal_from_funcs_and_line (const char *filename, int line_num,
4497                               struct symbol **symbols, int nsyms)
4498 {
4499   struct symtabs_and_lines sals;
4500   int best_index, best;
4501   struct linetable *best_linetable;
4502   struct objfile *objfile;
4503   struct symtab *s;
4504   struct symtab *best_symtab;
4505
4506   read_all_symtabs (filename);
4507
4508   best_index = 0;
4509   best_linetable = NULL;
4510   best_symtab = NULL;
4511   best = 0;
4512   ALL_SYMTABS (objfile, s)
4513   {
4514     struct linetable *l;
4515     int ind, exact;
4516
4517     QUIT;
4518
4519     if (!STREQ (filename, s->filename))
4520       continue;
4521     l = LINETABLE (s);
4522     ind = find_line_in_linetable (l, line_num, symbols, nsyms, &exact);
4523     if (ind >= 0)
4524       {
4525         if (exact)
4526           {
4527             best_index = ind;
4528             best_linetable = l;
4529             best_symtab = s;
4530             goto done;
4531           }
4532         if (best == 0 || l->item[ind].line < best)
4533           {
4534             best = l->item[ind].line;
4535             best_index = ind;
4536             best_linetable = l;
4537             best_symtab = s;
4538           }
4539       }
4540   }
4541
4542   if (best == 0)
4543     error ("Line number not found in designated function.");
4544
4545 done:
4546
4547   sals.nelts = 1;
4548   sals.sals = (struct symtab_and_line *) xmalloc (sizeof (sals.sals[0]));
4549
4550   init_sal (&sals.sals[0]);
4551
4552   sals.sals[0].line = best_linetable->item[best_index].line;
4553   sals.sals[0].pc = best_linetable->item[best_index].pc;
4554   sals.sals[0].symtab = best_symtab;
4555
4556   return sals;
4557 }
4558
4559 /* Return the index in LINETABLE of the best match for LINE_NUM whose
4560    pc falls within one of the functions denoted by SYMBOLS[0..NSYMS-1].  
4561    Set *EXACTP to the 1 if the match is exact, and 0 otherwise. */
4562 static int
4563 find_line_in_linetable (struct linetable *linetable, int line_num,
4564                         struct symbol **symbols, int nsyms, int *exactp)
4565 {
4566   int i, len, best_index, best;
4567
4568   if (line_num <= 0 || linetable == NULL)
4569     return -1;
4570
4571   len = linetable->nitems;
4572   for (i = 0, best_index = -1, best = 0; i < len; i += 1)
4573     {
4574       int k;
4575       struct linetable_entry *item = &(linetable->item[i]);
4576
4577       for (k = 0; k < nsyms; k += 1)
4578         {
4579           if (symbols[k] != NULL && SYMBOL_CLASS (symbols[k]) == LOC_BLOCK
4580               && item->pc >= BLOCK_START (SYMBOL_BLOCK_VALUE (symbols[k]))
4581               && item->pc < BLOCK_END (SYMBOL_BLOCK_VALUE (symbols[k])))
4582             goto candidate;
4583         }
4584       continue;
4585
4586     candidate:
4587
4588       if (item->line == line_num)
4589         {
4590           *exactp = 1;
4591           return i;
4592         }
4593
4594       if (item->line > line_num && (best == 0 || item->line < best))
4595         {
4596           best = item->line;
4597           best_index = i;
4598         }
4599     }
4600
4601   *exactp = 0;
4602   return best_index;
4603 }
4604
4605 /* Find the smallest k >= LINE_NUM such that k is a line number in
4606    LINETABLE, and k falls strictly within a named function that begins at
4607    or before LINE_NUM.  Return -1 if there is no such k. */
4608 static int
4609 nearest_line_number_in_linetable (struct linetable *linetable, int line_num)
4610 {
4611   int i, len, best;
4612
4613   if (line_num <= 0 || linetable == NULL || linetable->nitems == 0)
4614     return -1;
4615   len = linetable->nitems;
4616
4617   i = 0;
4618   best = INT_MAX;
4619   while (i < len)
4620     {
4621       int k;
4622       struct linetable_entry *item = &(linetable->item[i]);
4623
4624       if (item->line >= line_num && item->line < best)
4625         {
4626           char *func_name;
4627           CORE_ADDR start, end;
4628
4629           func_name = NULL;
4630           find_pc_partial_function (item->pc, &func_name, &start, &end);
4631
4632           if (func_name != NULL && item->pc < end)
4633             {
4634               if (item->line == line_num)
4635                 return line_num;
4636               else
4637                 {
4638                   struct symbol *sym =
4639                     standard_lookup (func_name, VAR_NAMESPACE);
4640                   if (is_plausible_func_for_line (sym, line_num))
4641                     best = item->line;
4642                   else
4643                     {
4644                       do
4645                         i += 1;
4646                       while (i < len && linetable->item[i].pc < end);
4647                       continue;
4648                     }
4649                 }
4650             }
4651         }
4652
4653       i += 1;
4654     }
4655
4656   return (best == INT_MAX) ? -1 : best;
4657 }
4658
4659
4660 /* Return the next higher index, k, into LINETABLE such that k > IND, 
4661    entry k in LINETABLE has a line number equal to LINE_NUM, k
4662    corresponds to a PC that is in a function different from that 
4663    corresponding to IND, and falls strictly within a named function
4664    that begins at a line at or preceding STARTING_LINE.  
4665    Return -1 if there is no such k.  
4666    IND == -1 corresponds to no function. */
4667
4668 static int
4669 find_next_line_in_linetable (struct linetable *linetable, int line_num,
4670                              int starting_line, int ind)
4671 {
4672   int i, len;
4673
4674   if (line_num <= 0 || linetable == NULL || ind >= linetable->nitems)
4675     return -1;
4676   len = linetable->nitems;
4677
4678   if (ind >= 0)
4679     {
4680       CORE_ADDR start, end;
4681
4682       if (find_pc_partial_function (linetable->item[ind].pc,
4683                                     (char **) NULL, &start, &end))
4684         {
4685           while (ind < len && linetable->item[ind].pc < end)
4686             ind += 1;
4687         }
4688       else
4689         ind += 1;
4690     }
4691   else
4692     ind = 0;
4693
4694   i = ind;
4695   while (i < len)
4696     {
4697       int k;
4698       struct linetable_entry *item = &(linetable->item[i]);
4699
4700       if (item->line >= line_num)
4701         {
4702           char *func_name;
4703           CORE_ADDR start, end;
4704
4705           func_name = NULL;
4706           find_pc_partial_function (item->pc, &func_name, &start, &end);
4707
4708           if (func_name != NULL && item->pc < end)
4709             {
4710               if (item->line == line_num)
4711                 {
4712                   struct symbol *sym =
4713                     standard_lookup (func_name, VAR_NAMESPACE);
4714                   if (is_plausible_func_for_line (sym, starting_line))
4715                     return i;
4716                   else
4717                     {
4718                       while ((i + 1) < len && linetable->item[i + 1].pc < end)
4719                         i += 1;
4720                     }
4721                 }
4722             }
4723         }
4724       i += 1;
4725     }
4726
4727   return -1;
4728 }
4729
4730 /* True iff function symbol SYM starts somewhere at or before line #
4731    LINE_NUM. */
4732 static int
4733 is_plausible_func_for_line (struct symbol *sym, int line_num)
4734 {
4735   struct symtab_and_line start_sal;
4736
4737   if (sym == NULL)
4738     return 0;
4739
4740   start_sal = find_function_start_sal (sym, 0);
4741
4742   return (start_sal.line != 0 && line_num >= start_sal.line);
4743 }
4744
4745 static void
4746 debug_print_lines (struct linetable *lt)
4747 {
4748   int i;
4749
4750   if (lt == NULL)
4751     return;
4752
4753   fprintf (stderr, "\t");
4754   for (i = 0; i < lt->nitems; i += 1)
4755     fprintf (stderr, "(%d->%p) ", lt->item[i].line, (void *) lt->item[i].pc);
4756   fprintf (stderr, "\n");
4757 }
4758
4759 static void
4760 debug_print_block (struct block *b)
4761 {
4762   int i;
4763   struct symbol *i;
4764
4765   fprintf (stderr, "Block: %p; [0x%lx, 0x%lx]",
4766            b, BLOCK_START (b), BLOCK_END (b));
4767   if (BLOCK_FUNCTION (b) != NULL)
4768     fprintf (stderr, " Function: %s", DEPRECATED_SYMBOL_NAME (BLOCK_FUNCTION (b)));
4769   fprintf (stderr, "\n");
4770   fprintf (stderr, "\t    Superblock: %p\n", BLOCK_SUPERBLOCK (b));
4771   fprintf (stderr, "\t    Symbols:");
4772   ALL_BLOCK_SYMBOLS (b, i, sym)
4773   {
4774     if (i > 0 && i % 4 == 0)
4775       fprintf (stderr, "\n\t\t    ");
4776     fprintf (stderr, " %s", DEPRECATED_SYMBOL_NAME (sym));
4777   }
4778   fprintf (stderr, "\n");
4779 }
4780
4781 static void
4782 debug_print_blocks (struct blockvector *bv)
4783 {
4784   int i;
4785
4786   if (bv == NULL)
4787     return;
4788   for (i = 0; i < BLOCKVECTOR_NBLOCKS (bv); i += 1)
4789     {
4790       fprintf (stderr, "%6d. ", i);
4791       debug_print_block (BLOCKVECTOR_BLOCK (bv, i));
4792     }
4793 }
4794
4795 static void
4796 debug_print_symtab (struct symtab *s)
4797 {
4798   fprintf (stderr, "Symtab %p\n    File: %s; Dir: %s\n", s,
4799            s->filename, s->dirname);
4800   fprintf (stderr, "    Blockvector: %p, Primary: %d\n",
4801            BLOCKVECTOR (s), s->primary);
4802   debug_print_blocks (BLOCKVECTOR (s));
4803   fprintf (stderr, "    Line table: %p\n", LINETABLE (s));
4804   debug_print_lines (LINETABLE (s));
4805 }
4806
4807 /* Read in all symbol tables corresponding to partial symbol tables
4808    with file name FILENAME. */
4809 static void
4810 read_all_symtabs (const char *filename)
4811 {
4812   struct partial_symtab *ps;
4813   struct objfile *objfile;
4814
4815   ALL_PSYMTABS (objfile, ps)
4816   {
4817     QUIT;
4818
4819     if (STREQ (filename, ps->filename))
4820       PSYMTAB_TO_SYMTAB (ps);
4821   }
4822 }
4823
4824 /* All sals corresponding to line LINE_NUM in a symbol table from file
4825    FILENAME, as filtered by the user.  If CANONICAL is not null, set
4826    it to a corresponding array of canonical line specs. */
4827 static struct symtabs_and_lines
4828 all_sals_for_line (const char *filename, int line_num, char ***canonical)
4829 {
4830   struct symtabs_and_lines result;
4831   struct objfile *objfile;
4832   struct symtab *s;
4833   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
4834   size_t len;
4835
4836   read_all_symtabs (filename);
4837
4838   result.sals =
4839     (struct symtab_and_line *) xmalloc (4 * sizeof (result.sals[0]));
4840   result.nelts = 0;
4841   len = 4;
4842   make_cleanup (free_current_contents, &result.sals);
4843
4844   ALL_SYMTABS (objfile, s)
4845   {
4846     int ind, target_line_num;
4847
4848     QUIT;
4849
4850     if (!STREQ (s->filename, filename))
4851       continue;
4852
4853     target_line_num =
4854       nearest_line_number_in_linetable (LINETABLE (s), line_num);
4855     if (target_line_num == -1)
4856       continue;
4857
4858     ind = -1;
4859     while (1)
4860       {
4861         ind =
4862           find_next_line_in_linetable (LINETABLE (s),
4863                                        target_line_num, line_num, ind);
4864
4865         if (ind < 0)
4866           break;
4867
4868         GROW_VECT (result.sals, len, result.nelts + 1);
4869         init_sal (&result.sals[result.nelts]);
4870         result.sals[result.nelts].line = LINETABLE (s)->item[ind].line;
4871         result.sals[result.nelts].pc = LINETABLE (s)->item[ind].pc;
4872         result.sals[result.nelts].symtab = s;
4873         result.nelts += 1;
4874       }
4875   }
4876
4877   if (canonical != NULL || result.nelts > 1)
4878     {
4879       int k;
4880       char **func_names = (char **) alloca (result.nelts * sizeof (char *));
4881       int first_choice = (result.nelts > 1) ? 2 : 1;
4882       int n;
4883       int *choices = (int *) alloca (result.nelts * sizeof (int));
4884
4885       for (k = 0; k < result.nelts; k += 1)
4886         {
4887           find_pc_partial_function (result.sals[k].pc, &func_names[k],
4888                                     (CORE_ADDR *) NULL, (CORE_ADDR *) NULL);
4889           if (func_names[k] == NULL)
4890             error ("Could not find function for one or more breakpoints.");
4891         }
4892
4893       if (result.nelts > 1)
4894         {
4895           printf_unfiltered ("[0] cancel\n");
4896           if (result.nelts > 1)
4897             printf_unfiltered ("[1] all\n");
4898           for (k = 0; k < result.nelts; k += 1)
4899             printf_unfiltered ("[%d] %s\n", k + first_choice,
4900                                ada_demangle (func_names[k]));
4901
4902           n = get_selections (choices, result.nelts, result.nelts,
4903                               result.nelts > 1, "instance-choice");
4904
4905           for (k = 0; k < n; k += 1)
4906             {
4907               result.sals[k] = result.sals[choices[k]];
4908               func_names[k] = func_names[choices[k]];
4909             }
4910           result.nelts = n;
4911         }
4912
4913       if (canonical != NULL)
4914         {
4915           *canonical = (char **) xmalloc (result.nelts * sizeof (char **));
4916           make_cleanup (xfree, *canonical);
4917           for (k = 0; k < result.nelts; k += 1)
4918             {
4919               (*canonical)[k] =
4920                 extended_canonical_line_spec (result.sals[k], func_names[k]);
4921               if ((*canonical)[k] == NULL)
4922                 error ("Could not locate one or more breakpoints.");
4923               make_cleanup (xfree, (*canonical)[k]);
4924             }
4925         }
4926     }
4927
4928   discard_cleanups (old_chain);
4929   return result;
4930 }
4931
4932
4933 /* A canonical line specification of the form FILE:NAME:LINENUM for
4934    symbol table and line data SAL.  NULL if insufficient
4935    information. The caller is responsible for releasing any space
4936    allocated. */
4937
4938 static char *
4939 extended_canonical_line_spec (struct symtab_and_line sal, const char *name)
4940 {
4941   char *r;
4942
4943   if (sal.symtab == NULL || sal.symtab->filename == NULL || sal.line <= 0)
4944     return NULL;
4945
4946   r = (char *) xmalloc (strlen (name) + strlen (sal.symtab->filename)
4947                         + sizeof (sal.line) * 3 + 3);
4948   sprintf (r, "%s:'%s':%d", sal.symtab->filename, name, sal.line);
4949   return r;
4950 }
4951
4952 #if 0
4953 int begin_bnum = -1;
4954 #endif
4955 int begin_annotate_level = 0;
4956
4957 static void
4958 begin_cleanup (void *dummy)
4959 {
4960   begin_annotate_level = 0;
4961 }
4962
4963 static void
4964 begin_command (char *args, int from_tty)
4965 {
4966   struct minimal_symbol *msym;
4967   CORE_ADDR main_program_name_addr;
4968   char main_program_name[1024];
4969   struct cleanup *old_chain = make_cleanup (begin_cleanup, NULL);
4970   begin_annotate_level = 2;
4971
4972   /* Check that there is a program to debug */
4973   if (!have_full_symbols () && !have_partial_symbols ())
4974     error ("No symbol table is loaded.  Use the \"file\" command.");
4975
4976   /* Check that we are debugging an Ada program */
4977   /*  if (ada_update_initial_language (language_unknown, NULL) != language_ada)
4978      error ("Cannot find the Ada initialization procedure.  Is this an Ada main program?");
4979    */
4980   /* FIXME: language_ada should be defined in defs.h */
4981
4982   /* Get the address of the name of the main procedure */
4983   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
4984
4985   if (msym != NULL)
4986     {
4987       main_program_name_addr = SYMBOL_VALUE_ADDRESS (msym);
4988       if (main_program_name_addr == 0)
4989         error ("Invalid address for Ada main program name.");
4990
4991       /* Read the name of the main procedure */
4992       extract_string (main_program_name_addr, main_program_name);
4993
4994       /* Put a temporary breakpoint in the Ada main program and run */
4995       do_command ("tbreak ", main_program_name, 0);
4996       do_command ("run ", args, 0);
4997     }
4998   else
4999     {
5000       /* If we could not find the symbol containing the name of the
5001          main program, that means that the compiler that was used to build
5002          was not recent enough. In that case, we fallback to the previous
5003          mechanism, which is a little bit less reliable, but has proved to work
5004          in most cases. The only cases where it will fail is when the user
5005          has set some breakpoints which will be hit before the end of the
5006          begin command processing (eg in the initialization code).
5007
5008          The begining of the main Ada subprogram is located by breaking
5009          on the adainit procedure. Since we know that the binder generates
5010          the call to this procedure exactly 2 calls before the call to the
5011          Ada main subprogram, it is then easy to put a breakpoint on this
5012          Ada main subprogram once we hit adainit.
5013        */
5014       do_command ("tbreak adainit", 0);
5015       do_command ("run ", args, 0);
5016       do_command ("up", 0);
5017       do_command ("tbreak +2", 0);
5018       do_command ("continue", 0);
5019       do_command ("step", 0);
5020     }
5021
5022   do_cleanups (old_chain);
5023 }
5024
5025 int
5026 is_ada_runtime_file (char *filename)
5027 {
5028   return (STREQN (filename, "s-", 2) ||
5029           STREQN (filename, "a-", 2) ||
5030           STREQN (filename, "g-", 2) || STREQN (filename, "i-", 2));
5031 }
5032
5033 /* find the first frame that contains debugging information and that is not
5034    part of the Ada run-time, starting from fi and moving upward. */
5035
5036 int
5037 find_printable_frame (struct frame_info *fi, int level)
5038 {
5039   struct symtab_and_line sal;
5040
5041   for (; fi != NULL; level += 1, fi = get_prev_frame (fi))
5042     {
5043       find_frame_sal (fi, &sal);
5044       if (sal.symtab && !is_ada_runtime_file (sal.symtab->filename))
5045         {
5046 #if defined(__alpha__) && defined(__osf__) && !defined(VXWORKS_TARGET)
5047           /* libpthread.so contains some debugging information that prevents us
5048              from finding the right frame */
5049
5050           if (sal.symtab->objfile &&
5051               STREQ (sal.symtab->objfile->name, "/usr/shlib/libpthread.so"))
5052             continue;
5053 #endif
5054           deprecated_selected_frame = fi;
5055           break;
5056         }
5057     }
5058
5059   return level;
5060 }
5061
5062 void
5063 ada_report_exception_break (struct breakpoint *b)
5064 {
5065   /* FIXME: break_on_exception should be defined in breakpoint.h */
5066   /*  if (b->break_on_exception == 1)
5067      {
5068      /* Assume that cond has 16 elements, the 15th
5069    being the exception *//*
5070    if (b->cond && b->cond->nelts == 16)
5071    {
5072    ui_out_text (uiout, "on ");
5073    ui_out_field_string (uiout, "exception",
5074    SYMBOL_NAME (b->cond->elts[14].symbol));
5075    }
5076    else
5077    ui_out_text (uiout, "on all exceptions");
5078    }
5079    else if (b->break_on_exception == 2)
5080    ui_out_text (uiout, "on unhandled exception");
5081    else if (b->break_on_exception == 3)
5082    ui_out_text (uiout, "on assert failure");
5083    #else
5084    if (b->break_on_exception == 1)
5085    { */
5086   /* Assume that cond has 16 elements, the 15th
5087    being the exception *//*
5088    if (b->cond && b->cond->nelts == 16)
5089    {
5090    fputs_filtered ("on ", gdb_stdout);
5091    fputs_filtered (SYMBOL_NAME
5092    (b->cond->elts[14].symbol), gdb_stdout);
5093    }
5094    else
5095    fputs_filtered ("on all exceptions", gdb_stdout);
5096    }
5097    else if (b->break_on_exception == 2)
5098    fputs_filtered ("on unhandled exception", gdb_stdout);
5099    else if (b->break_on_exception == 3)
5100    fputs_filtered ("on assert failure", gdb_stdout);
5101  */
5102 }
5103
5104 int
5105 ada_is_exception_sym (struct symbol *sym)
5106 {
5107   char *type_name = type_name_no_tag (SYMBOL_TYPE (sym));
5108
5109   return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
5110           && SYMBOL_CLASS (sym) != LOC_BLOCK
5111           && SYMBOL_CLASS (sym) != LOC_CONST
5112           && type_name != NULL && STREQ (type_name, "exception"));
5113 }
5114
5115 int
5116 ada_maybe_exception_partial_symbol (struct partial_symbol *sym)
5117 {
5118   return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
5119           && SYMBOL_CLASS (sym) != LOC_BLOCK
5120           && SYMBOL_CLASS (sym) != LOC_CONST);
5121 }
5122
5123 /* If ARG points to an Ada exception or assert breakpoint, rewrite
5124    into equivalent form.  Return resulting argument string. Set
5125    *BREAK_ON_EXCEPTIONP to 1 for ordinary break on exception, 2 for
5126    break on unhandled, 3 for assert, 0 otherwise. */
5127 char *
5128 ada_breakpoint_rewrite (char *arg, int *break_on_exceptionp)
5129 {
5130   if (arg == NULL)
5131     return arg;
5132   *break_on_exceptionp = 0;
5133   /* FIXME: language_ada should be defined in defs.h */
5134   /*  if (current_language->la_language == language_ada
5135      && STREQN (arg, "exception", 9) &&
5136      (arg[9] == ' ' || arg[9] == '\t' || arg[9] == '\0'))
5137      {
5138      char *tok, *end_tok;
5139      int toklen;
5140
5141      *break_on_exceptionp = 1;
5142
5143      tok = arg+9;
5144      while (*tok == ' ' || *tok == '\t')
5145      tok += 1;
5146
5147      end_tok = tok;
5148
5149      while (*end_tok != ' ' && *end_tok != '\t' && *end_tok != '\000')
5150      end_tok += 1;
5151
5152      toklen = end_tok - tok;
5153
5154      arg = (char*) xmalloc (sizeof ("__gnat_raise_nodefer_with_msg if "
5155      "long_integer(e) = long_integer(&)")
5156      + toklen + 1);
5157      make_cleanup (xfree, arg);
5158      if (toklen == 0)
5159      strcpy (arg, "__gnat_raise_nodefer_with_msg");
5160      else if (STREQN (tok, "unhandled", toklen))
5161      {
5162      *break_on_exceptionp = 2;
5163      strcpy (arg, "__gnat_unhandled_exception");
5164      }
5165      else
5166      {
5167      sprintf (arg, "__gnat_raise_nodefer_with_msg if "
5168      "long_integer(e) = long_integer(&%.*s)", 
5169      toklen, tok);
5170      }
5171      }
5172      else if (current_language->la_language == language_ada
5173      && STREQN (arg, "assert", 6) &&
5174      (arg[6] == ' ' || arg[6] == '\t' || arg[6] == '\0'))
5175      {
5176      char *tok = arg + 6;
5177
5178      *break_on_exceptionp = 3;
5179
5180      arg = (char*) 
5181      xmalloc (sizeof ("system__assertions__raise_assert_failure")
5182      + strlen (tok) + 1);
5183      make_cleanup (xfree, arg);
5184      sprintf (arg, "system__assertions__raise_assert_failure%s", tok);
5185      }
5186    */
5187   return arg;
5188 }
5189 \f
5190
5191                                 /* Field Access */
5192
5193 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
5194    to be invisible to users. */
5195
5196 int
5197 ada_is_ignored_field (struct type *type, int field_num)
5198 {
5199   if (field_num < 0 || field_num > TYPE_NFIELDS (type))
5200     return 1;
5201   else
5202     {
5203       const char *name = TYPE_FIELD_NAME (type, field_num);
5204       return (name == NULL
5205               || (name[0] == '_' && !STREQN (name, "_parent", 7)));
5206     }
5207 }
5208
5209 /* True iff structure type TYPE has a tag field. */
5210
5211 int
5212 ada_is_tagged_type (struct type *type)
5213 {
5214   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
5215     return 0;
5216
5217   return (ada_lookup_struct_elt_type (type, "_tag", 1, NULL) != NULL);
5218 }
5219
5220 /* The type of the tag on VAL. */
5221
5222 struct type *
5223 ada_tag_type (struct value *val)
5224 {
5225   return ada_lookup_struct_elt_type (VALUE_TYPE (val), "_tag", 0, NULL);
5226 }
5227
5228 /* The value of the tag on VAL. */
5229
5230 struct value *
5231 ada_value_tag (struct value *val)
5232 {
5233   return ada_value_struct_elt (val, "_tag", "record");
5234 }
5235
5236 /* The parent type of TYPE, or NULL if none. */
5237
5238 struct type *
5239 ada_parent_type (struct type *type)
5240 {
5241   int i;
5242
5243   CHECK_TYPEDEF (type);
5244
5245   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
5246     return NULL;
5247
5248   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
5249     if (ada_is_parent_field (type, i))
5250       return check_typedef (TYPE_FIELD_TYPE (type, i));
5251
5252   return NULL;
5253 }
5254
5255 /* True iff field number FIELD_NUM of structure type TYPE contains the 
5256    parent-type (inherited) fields of a derived type.  Assumes TYPE is 
5257    a structure type with at least FIELD_NUM+1 fields. */
5258
5259 int
5260 ada_is_parent_field (struct type *type, int field_num)
5261 {
5262   const char *name = TYPE_FIELD_NAME (check_typedef (type), field_num);
5263   return (name != NULL &&
5264           (STREQN (name, "PARENT", 6) || STREQN (name, "_parent", 7)));
5265 }
5266
5267 /* True iff field number FIELD_NUM of structure type TYPE is a 
5268    transparent wrapper field (which should be silently traversed when doing
5269    field selection and flattened when printing).  Assumes TYPE is a 
5270    structure type with at least FIELD_NUM+1 fields.  Such fields are always
5271    structures. */
5272
5273 int
5274 ada_is_wrapper_field (struct type *type, int field_num)
5275 {
5276   const char *name = TYPE_FIELD_NAME (type, field_num);
5277   return (name != NULL
5278           && (STREQN (name, "PARENT", 6) || STREQ (name, "REP")
5279               || STREQN (name, "_parent", 7)
5280               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
5281 }
5282
5283 /* True iff field number FIELD_NUM of structure or union type TYPE 
5284    is a variant wrapper.  Assumes TYPE is a structure type with at least 
5285    FIELD_NUM+1 fields. */
5286
5287 int
5288 ada_is_variant_part (struct type *type, int field_num)
5289 {
5290   struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
5291   return (TYPE_CODE (field_type) == TYPE_CODE_UNION
5292           || (is_dynamic_field (type, field_num)
5293               && TYPE_CODE (TYPE_TARGET_TYPE (field_type)) ==
5294               TYPE_CODE_UNION));
5295 }
5296
5297 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
5298    whose discriminants are contained in the record type OUTER_TYPE, 
5299    returns the type of the controlling discriminant for the variant.  */
5300
5301 struct type *
5302 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
5303 {
5304   char *name = ada_variant_discrim_name (var_type);
5305   struct type *type = ada_lookup_struct_elt_type (outer_type, name, 1, NULL);
5306   if (type == NULL)
5307     return builtin_type_int;
5308   else
5309     return type;
5310 }
5311
5312 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a 
5313    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
5314    represents a 'when others' clause; otherwise 0. */
5315
5316 int
5317 ada_is_others_clause (struct type *type, int field_num)
5318 {
5319   const char *name = TYPE_FIELD_NAME (type, field_num);
5320   return (name != NULL && name[0] == 'O');
5321 }
5322
5323 /* Assuming that TYPE0 is the type of the variant part of a record,
5324    returns the name of the discriminant controlling the variant.  The
5325    value is valid until the next call to ada_variant_discrim_name. */
5326
5327 char *
5328 ada_variant_discrim_name (struct type *type0)
5329 {
5330   static char *result = NULL;
5331   static size_t result_len = 0;
5332   struct type *type;
5333   const char *name;
5334   const char *discrim_end;
5335   const char *discrim_start;
5336
5337   if (TYPE_CODE (type0) == TYPE_CODE_PTR)
5338     type = TYPE_TARGET_TYPE (type0);
5339   else
5340     type = type0;
5341
5342   name = ada_type_name (type);
5343
5344   if (name == NULL || name[0] == '\000')
5345     return "";
5346
5347   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
5348        discrim_end -= 1)
5349     {
5350       if (STREQN (discrim_end, "___XVN", 6))
5351         break;
5352     }
5353   if (discrim_end == name)
5354     return "";
5355
5356   for (discrim_start = discrim_end; discrim_start != name + 3;
5357        discrim_start -= 1)
5358     {
5359       if (discrim_start == name + 1)
5360         return "";
5361       if ((discrim_start > name + 3 && STREQN (discrim_start - 3, "___", 3))
5362           || discrim_start[-1] == '.')
5363         break;
5364     }
5365
5366   GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
5367   strncpy (result, discrim_start, discrim_end - discrim_start);
5368   result[discrim_end - discrim_start] = '\0';
5369   return result;
5370 }
5371
5372 /* Scan STR for a subtype-encoded number, beginning at position K. Put the 
5373    position of the character just past the number scanned in *NEW_K, 
5374    if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.  Return 1 
5375    if there was a valid number at the given position, and 0 otherwise.  A 
5376    "subtype-encoded" number consists of the absolute value in decimal, 
5377    followed by the letter 'm' to indicate a negative number.  Assumes 0m 
5378    does not occur. */
5379
5380 int
5381 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
5382 {
5383   ULONGEST RU;
5384
5385   if (!isdigit (str[k]))
5386     return 0;
5387
5388   /* Do it the hard way so as not to make any assumption about 
5389      the relationship of unsigned long (%lu scan format code) and
5390      LONGEST. */
5391   RU = 0;
5392   while (isdigit (str[k]))
5393     {
5394       RU = RU * 10 + (str[k] - '0');
5395       k += 1;
5396     }
5397
5398   if (str[k] == 'm')
5399     {
5400       if (R != NULL)
5401         *R = (-(LONGEST) (RU - 1)) - 1;
5402       k += 1;
5403     }
5404   else if (R != NULL)
5405     *R = (LONGEST) RU;
5406
5407   /* NOTE on the above: Technically, C does not say what the results of 
5408      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
5409      number representable as a LONGEST (although either would probably work
5410      in most implementations).  When RU>0, the locution in the then branch
5411      above is always equivalent to the negative of RU. */
5412
5413   if (new_k != NULL)
5414     *new_k = k;
5415   return 1;
5416 }
5417
5418 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field), 
5419    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is 
5420    in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
5421
5422 int
5423 ada_in_variant (LONGEST val, struct type *type, int field_num)
5424 {
5425   const char *name = TYPE_FIELD_NAME (type, field_num);
5426   int p;
5427
5428   p = 0;
5429   while (1)
5430     {
5431       switch (name[p])
5432         {
5433         case '\0':
5434           return 0;
5435         case 'S':
5436           {
5437             LONGEST W;
5438             if (!ada_scan_number (name, p + 1, &W, &p))
5439               return 0;
5440             if (val == W)
5441               return 1;
5442             break;
5443           }
5444         case 'R':
5445           {
5446             LONGEST L, U;
5447             if (!ada_scan_number (name, p + 1, &L, &p)
5448                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
5449               return 0;
5450             if (val >= L && val <= U)
5451               return 1;
5452             break;
5453           }
5454         case 'O':
5455           return 1;
5456         default:
5457           return 0;
5458         }
5459     }
5460 }
5461
5462 /* Given a value ARG1 (offset by OFFSET bytes)
5463    of a struct or union type ARG_TYPE,
5464    extract and return the value of one of its (non-static) fields.
5465    FIELDNO says which field.   Differs from value_primitive_field only
5466    in that it can handle packed values of arbitrary type. */
5467
5468 struct value *
5469 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
5470                            struct type *arg_type)
5471 {
5472   struct value *v;
5473   struct type *type;
5474
5475   CHECK_TYPEDEF (arg_type);
5476   type = TYPE_FIELD_TYPE (arg_type, fieldno);
5477
5478   /* Handle packed fields */
5479
5480   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
5481     {
5482       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
5483       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
5484
5485       return ada_value_primitive_packed_val (arg1, VALUE_CONTENTS (arg1),
5486                                              offset + bit_pos / 8,
5487                                              bit_pos % 8, bit_size, type);
5488     }
5489   else
5490     return value_primitive_field (arg1, offset, fieldno, arg_type);
5491 }
5492
5493
5494 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
5495    and search in it assuming it has (class) type TYPE.
5496    If found, return value, else return NULL.
5497
5498    Searches recursively through wrapper fields (e.g., '_parent'). */
5499
5500 struct value *
5501 ada_search_struct_field (char *name, struct value *arg, int offset,
5502                          struct type *type)
5503 {
5504   int i;
5505   CHECK_TYPEDEF (type);
5506
5507   for (i = TYPE_NFIELDS (type) - 1; i >= 0; i -= 1)
5508     {
5509       char *t_field_name = TYPE_FIELD_NAME (type, i);
5510
5511       if (t_field_name == NULL)
5512         continue;
5513
5514       else if (field_name_match (t_field_name, name))
5515         return ada_value_primitive_field (arg, offset, i, type);
5516
5517       else if (ada_is_wrapper_field (type, i))
5518         {
5519           struct value *v = ada_search_struct_field (name, arg,
5520                                                      offset +
5521                                                      TYPE_FIELD_BITPOS (type,
5522                                                                         i) /
5523                                                      8,
5524                                                      TYPE_FIELD_TYPE (type,
5525                                                                       i));
5526           if (v != NULL)
5527             return v;
5528         }
5529
5530       else if (ada_is_variant_part (type, i))
5531         {
5532           int j;
5533           struct type *field_type = check_typedef (TYPE_FIELD_TYPE (type, i));
5534           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
5535
5536           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
5537             {
5538               struct value *v = ada_search_struct_field (name, arg,
5539                                                          var_offset
5540                                                          +
5541                                                          TYPE_FIELD_BITPOS
5542                                                          (field_type, j) / 8,
5543                                                          TYPE_FIELD_TYPE
5544                                                          (field_type, j));
5545               if (v != NULL)
5546                 return v;
5547             }
5548         }
5549     }
5550   return NULL;
5551 }
5552
5553 /* Given ARG, a value of type (pointer to a)* structure/union,
5554    extract the component named NAME from the ultimate target structure/union
5555    and return it as a value with its appropriate type.
5556
5557    The routine searches for NAME among all members of the structure itself 
5558    and (recursively) among all members of any wrapper members 
5559    (e.g., '_parent').
5560
5561    ERR is a name (for use in error messages) that identifies the class 
5562    of entity that ARG is supposed to be. */
5563
5564 struct value *
5565 ada_value_struct_elt (struct value *arg, char *name, char *err)
5566 {
5567   struct type *t;
5568   struct value *v;
5569
5570   arg = ada_coerce_ref (arg);
5571   t = check_typedef (VALUE_TYPE (arg));
5572
5573   /* Follow pointers until we get to a non-pointer.  */
5574
5575   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_CODE (t) == TYPE_CODE_REF)
5576     {
5577       arg = ada_value_ind (arg);
5578       t = check_typedef (VALUE_TYPE (arg));
5579     }
5580
5581   if (TYPE_CODE (t) != TYPE_CODE_STRUCT && TYPE_CODE (t) != TYPE_CODE_UNION)
5582     error ("Attempt to extract a component of a value that is not a %s.",
5583            err);
5584
5585   v = ada_search_struct_field (name, arg, 0, t);
5586   if (v == NULL)
5587     error ("There is no member named %s.", name);
5588
5589   return v;
5590 }
5591
5592 /* Given a type TYPE, look up the type of the component of type named NAME.
5593    If DISPP is non-null, add its byte displacement from the beginning of a 
5594    structure (pointed to by a value) of type TYPE to *DISPP (does not 
5595    work for packed fields).
5596
5597    Matches any field whose name has NAME as a prefix, possibly
5598    followed by "___". 
5599
5600    TYPE can be either a struct or union, or a pointer or reference to 
5601    a struct or union.  If it is a pointer or reference, its target 
5602    type is automatically used.
5603
5604    Looks recursively into variant clauses and parent types.
5605
5606    If NOERR is nonzero, return NULL if NAME is not suitably defined. */
5607
5608 struct type *
5609 ada_lookup_struct_elt_type (struct type *type, char *name, int noerr,
5610                             int *dispp)
5611 {
5612   int i;
5613
5614   if (name == NULL)
5615     goto BadName;
5616
5617   while (1)
5618     {
5619       CHECK_TYPEDEF (type);
5620       if (TYPE_CODE (type) != TYPE_CODE_PTR
5621           && TYPE_CODE (type) != TYPE_CODE_REF)
5622         break;
5623       type = TYPE_TARGET_TYPE (type);
5624     }
5625
5626   if (TYPE_CODE (type) != TYPE_CODE_STRUCT &&
5627       TYPE_CODE (type) != TYPE_CODE_UNION)
5628     {
5629       target_terminal_ours ();
5630       gdb_flush (gdb_stdout);
5631       fprintf_unfiltered (gdb_stderr, "Type ");
5632       type_print (type, "", gdb_stderr, -1);
5633       error (" is not a structure or union type");
5634     }
5635
5636   type = to_static_fixed_type (type);
5637
5638   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
5639     {
5640       char *t_field_name = TYPE_FIELD_NAME (type, i);
5641       struct type *t;
5642       int disp;
5643
5644       if (t_field_name == NULL)
5645         continue;
5646
5647       else if (field_name_match (t_field_name, name))
5648         {
5649           if (dispp != NULL)
5650             *dispp += TYPE_FIELD_BITPOS (type, i) / 8;
5651           return check_typedef (TYPE_FIELD_TYPE (type, i));
5652         }
5653
5654       else if (ada_is_wrapper_field (type, i))
5655         {
5656           disp = 0;
5657           t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
5658                                           1, &disp);
5659           if (t != NULL)
5660             {
5661               if (dispp != NULL)
5662                 *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
5663               return t;
5664             }
5665         }
5666
5667       else if (ada_is_variant_part (type, i))
5668         {
5669           int j;
5670           struct type *field_type = check_typedef (TYPE_FIELD_TYPE (type, i));
5671
5672           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
5673             {
5674               disp = 0;
5675               t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type, j),
5676                                               name, 1, &disp);
5677               if (t != NULL)
5678                 {
5679                   if (dispp != NULL)
5680                     *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
5681                   return t;
5682                 }
5683             }
5684         }
5685
5686     }
5687
5688 BadName:
5689   if (!noerr)
5690     {
5691       target_terminal_ours ();
5692       gdb_flush (gdb_stdout);
5693       fprintf_unfiltered (gdb_stderr, "Type ");
5694       type_print (type, "", gdb_stderr, -1);
5695       fprintf_unfiltered (gdb_stderr, " has no component named ");
5696       error ("%s", name == NULL ? "<null>" : name);
5697     }
5698
5699   return NULL;
5700 }
5701
5702 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
5703    within a value of type OUTER_TYPE that is stored in GDB at
5704    OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE, 
5705    numbering from 0) is applicable.  Returns -1 if none are. */
5706
5707 int
5708 ada_which_variant_applies (struct type *var_type, struct type *outer_type,
5709                            char *outer_valaddr)
5710 {
5711   int others_clause;
5712   int i;
5713   int disp;
5714   struct type *discrim_type;
5715   char *discrim_name = ada_variant_discrim_name (var_type);
5716   LONGEST discrim_val;
5717
5718   disp = 0;
5719   discrim_type =
5720     ada_lookup_struct_elt_type (outer_type, discrim_name, 1, &disp);
5721   if (discrim_type == NULL)
5722     return -1;
5723   discrim_val = unpack_long (discrim_type, outer_valaddr + disp);
5724
5725   others_clause = -1;
5726   for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
5727     {
5728       if (ada_is_others_clause (var_type, i))
5729         others_clause = i;
5730       else if (ada_in_variant (discrim_val, var_type, i))
5731         return i;
5732     }
5733
5734   return others_clause;
5735 }
5736 \f
5737
5738
5739                                 /* Dynamic-Sized Records */
5740
5741 /* Strategy: The type ostensibly attached to a value with dynamic size
5742    (i.e., a size that is not statically recorded in the debugging
5743    data) does not accurately reflect the size or layout of the value.
5744    Our strategy is to convert these values to values with accurate,
5745    conventional types that are constructed on the fly. */
5746
5747 /* There is a subtle and tricky problem here.  In general, we cannot
5748    determine the size of dynamic records without its data.  However,
5749    the 'struct value' data structure, which GDB uses to represent
5750    quantities in the inferior process (the target), requires the size
5751    of the type at the time of its allocation in order to reserve space
5752    for GDB's internal copy of the data.  That's why the
5753    'to_fixed_xxx_type' routines take (target) addresses as parameters,
5754    rather than struct value*s.  
5755
5756    However, GDB's internal history variables ($1, $2, etc.) are
5757    struct value*s containing internal copies of the data that are not, in
5758    general, the same as the data at their corresponding addresses in
5759    the target.  Fortunately, the types we give to these values are all
5760    conventional, fixed-size types (as per the strategy described
5761    above), so that we don't usually have to perform the
5762    'to_fixed_xxx_type' conversions to look at their values.
5763    Unfortunately, there is one exception: if one of the internal
5764    history variables is an array whose elements are unconstrained
5765    records, then we will need to create distinct fixed types for each
5766    element selected.  */
5767
5768 /* The upshot of all of this is that many routines take a (type, host
5769    address, target address) triple as arguments to represent a value.
5770    The host address, if non-null, is supposed to contain an internal
5771    copy of the relevant data; otherwise, the program is to consult the
5772    target at the target address. */
5773
5774 /* Assuming that VAL0 represents a pointer value, the result of
5775    dereferencing it.  Differs from value_ind in its treatment of
5776    dynamic-sized types. */
5777
5778 struct value *
5779 ada_value_ind (struct value *val0)
5780 {
5781   struct value *val = unwrap_value (value_ind (val0));
5782   return ada_to_fixed_value (VALUE_TYPE (val), 0,
5783                              VALUE_ADDRESS (val) + VALUE_OFFSET (val), val);
5784 }
5785
5786 /* The value resulting from dereferencing any "reference to"
5787  * qualifiers on VAL0. */
5788 static struct value *
5789 ada_coerce_ref (struct value *val0)
5790 {
5791   if (TYPE_CODE (VALUE_TYPE (val0)) == TYPE_CODE_REF)
5792     {
5793       struct value *val = val0;
5794       COERCE_REF (val);
5795       val = unwrap_value (val);
5796       return ada_to_fixed_value (VALUE_TYPE (val), 0,
5797                                  VALUE_ADDRESS (val) + VALUE_OFFSET (val),
5798                                  val);
5799     }
5800   else
5801     return val0;
5802 }
5803
5804 /* Return OFF rounded upward if necessary to a multiple of
5805    ALIGNMENT (a power of 2). */
5806
5807 static unsigned int
5808 align_value (unsigned int off, unsigned int alignment)
5809 {
5810   return (off + alignment - 1) & ~(alignment - 1);
5811 }
5812
5813 /* Return the additional bit offset required by field F of template
5814    type TYPE. */
5815
5816 static unsigned int
5817 field_offset (struct type *type, int f)
5818 {
5819   int n = TYPE_FIELD_BITPOS (type, f);
5820   /* Kludge (temporary?) to fix problem with dwarf output. */
5821   if (n < 0)
5822     return (unsigned int) n & 0xffff;
5823   else
5824     return n;
5825 }
5826
5827
5828 /* Return the bit alignment required for field #F of template type TYPE. */
5829
5830 static unsigned int
5831 field_alignment (struct type *type, int f)
5832 {
5833   const char *name = TYPE_FIELD_NAME (type, f);
5834   int len = (name == NULL) ? 0 : strlen (name);
5835   int align_offset;
5836
5837   if (len < 8 || !isdigit (name[len - 1]))
5838     return TARGET_CHAR_BIT;
5839
5840   if (isdigit (name[len - 2]))
5841     align_offset = len - 2;
5842   else
5843     align_offset = len - 1;
5844
5845   if (align_offset < 7 || !STREQN ("___XV", name + align_offset - 6, 5))
5846     return TARGET_CHAR_BIT;
5847
5848   return atoi (name + align_offset) * TARGET_CHAR_BIT;
5849 }
5850
5851 /* Find a type named NAME.  Ignores ambiguity.  */
5852 struct type *
5853 ada_find_any_type (const char *name)
5854 {
5855   struct symbol *sym;
5856
5857   sym = standard_lookup (name, VAR_NAMESPACE);
5858   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
5859     return SYMBOL_TYPE (sym);
5860
5861   sym = standard_lookup (name, STRUCT_NAMESPACE);
5862   if (sym != NULL)
5863     return SYMBOL_TYPE (sym);
5864
5865   return NULL;
5866 }
5867
5868 /* Because of GNAT encoding conventions, several GDB symbols may match a
5869    given type name. If the type denoted by TYPE0 is to be preferred to
5870    that of TYPE1 for purposes of type printing, return non-zero;
5871    otherwise return 0. */
5872 int
5873 ada_prefer_type (struct type *type0, struct type *type1)
5874 {
5875   if (type1 == NULL)
5876     return 1;
5877   else if (type0 == NULL)
5878     return 0;
5879   else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
5880     return 1;
5881   else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
5882     return 0;
5883   else if (ada_is_packed_array_type (type0))
5884     return 1;
5885   else if (ada_is_array_descriptor (type0)
5886            && !ada_is_array_descriptor (type1))
5887     return 1;
5888   else if (ada_renaming_type (type0) != NULL
5889            && ada_renaming_type (type1) == NULL)
5890     return 1;
5891   return 0;
5892 }
5893
5894 /* The name of TYPE, which is either its TYPE_NAME, or, if that is
5895    null, its TYPE_TAG_NAME.  Null if TYPE is null. */
5896 char *
5897 ada_type_name (struct type *type)
5898 {
5899   if (type == NULL)
5900     return NULL;
5901   else if (TYPE_NAME (type) != NULL)
5902     return TYPE_NAME (type);
5903   else
5904     return TYPE_TAG_NAME (type);
5905 }
5906
5907 /* Find a parallel type to TYPE whose name is formed by appending
5908    SUFFIX to the name of TYPE. */
5909
5910 struct type *
5911 ada_find_parallel_type (struct type *type, const char *suffix)
5912 {
5913   static char *name;
5914   static size_t name_len = 0;
5915   struct symbol **syms;
5916   struct block **blocks;
5917   int nsyms;
5918   int len;
5919   char *typename = ada_type_name (type);
5920
5921   if (typename == NULL)
5922     return NULL;
5923
5924   len = strlen (typename);
5925
5926   GROW_VECT (name, name_len, len + strlen (suffix) + 1);
5927
5928   strcpy (name, typename);
5929   strcpy (name + len, suffix);
5930
5931   return ada_find_any_type (name);
5932 }
5933
5934
5935 /* If TYPE is a variable-size record type, return the corresponding template
5936    type describing its fields.  Otherwise, return NULL. */
5937
5938 static struct type *
5939 dynamic_template_type (struct type *type)
5940 {
5941   CHECK_TYPEDEF (type);
5942
5943   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
5944       || ada_type_name (type) == NULL)
5945     return NULL;
5946   else
5947     {
5948       int len = strlen (ada_type_name (type));
5949       if (len > 6 && STREQ (ada_type_name (type) + len - 6, "___XVE"))
5950         return type;
5951       else
5952         return ada_find_parallel_type (type, "___XVE");
5953     }
5954 }
5955
5956 /* Assuming that TEMPL_TYPE is a union or struct type, returns
5957    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
5958
5959 static int
5960 is_dynamic_field (struct type *templ_type, int field_num)
5961 {
5962   const char *name = TYPE_FIELD_NAME (templ_type, field_num);
5963   return name != NULL
5964     && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
5965     && strstr (name, "___XVL") != NULL;
5966 }
5967
5968 /* Assuming that TYPE is a struct type, returns non-zero iff TYPE
5969    contains a variant part. */
5970
5971 static int
5972 contains_variant_part (struct type *type)
5973 {
5974   int f;
5975
5976   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
5977       || TYPE_NFIELDS (type) <= 0)
5978     return 0;
5979   return ada_is_variant_part (type, TYPE_NFIELDS (type) - 1);
5980 }
5981
5982 /* A record type with no fields, . */
5983 static struct type *
5984 empty_record (struct objfile *objfile)
5985 {
5986   struct type *type = alloc_type (objfile);
5987   TYPE_CODE (type) = TYPE_CODE_STRUCT;
5988   TYPE_NFIELDS (type) = 0;
5989   TYPE_FIELDS (type) = NULL;
5990   TYPE_NAME (type) = "<empty>";
5991   TYPE_TAG_NAME (type) = NULL;
5992   TYPE_FLAGS (type) = 0;
5993   TYPE_LENGTH (type) = 0;
5994   return type;
5995 }
5996
5997 /* An ordinary record type (with fixed-length fields) that describes
5998    the value of type TYPE at VALADDR or ADDRESS (see comments at 
5999    the beginning of this section) VAL according to GNAT conventions.  
6000    DVAL0 should describe the (portion of a) record that contains any 
6001    necessary discriminants.  It should be NULL if VALUE_TYPE (VAL) is
6002    an outer-level type (i.e., as opposed to a branch of a variant.)  A
6003    variant field (unless unchecked) is replaced by a particular branch
6004    of the variant. */
6005 /* NOTE: Limitations: For now, we assume that dynamic fields and
6006  * variants occupy whole numbers of bytes.  However, they need not be
6007  * byte-aligned.  */
6008
6009 static struct type *
6010 template_to_fixed_record_type (struct type *type, char *valaddr,
6011                                CORE_ADDR address, struct value *dval0)
6012 {
6013   struct value *mark = value_mark ();
6014   struct value *dval;
6015   struct type *rtype;
6016   int nfields, bit_len;
6017   long off;
6018   int f;
6019
6020   nfields = TYPE_NFIELDS (type);
6021   rtype = alloc_type (TYPE_OBJFILE (type));
6022   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
6023   INIT_CPLUS_SPECIFIC (rtype);
6024   TYPE_NFIELDS (rtype) = nfields;
6025   TYPE_FIELDS (rtype) = (struct field *)
6026     TYPE_ALLOC (rtype, nfields * sizeof (struct field));
6027   memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
6028   TYPE_NAME (rtype) = ada_type_name (type);
6029   TYPE_TAG_NAME (rtype) = NULL;
6030   /* FIXME: TYPE_FLAG_FIXED_INSTANCE should be defined in
6031      gdbtypes.h */
6032   /*  TYPE_FLAGS (rtype) |= TYPE_FLAG_FIXED_INSTANCE; */
6033
6034   off = 0;
6035   bit_len = 0;
6036   for (f = 0; f < nfields; f += 1)
6037     {
6038       int fld_bit_len, bit_incr;
6039       off =
6040         align_value (off,
6041                      field_alignment (type, f)) + TYPE_FIELD_BITPOS (type, f);
6042       /* NOTE: used to use field_offset above, but that causes
6043        * problems with really negative bit positions.  So, let's
6044        * rediscover why we needed field_offset and fix it properly. */
6045       TYPE_FIELD_BITPOS (rtype, f) = off;
6046       TYPE_FIELD_BITSIZE (rtype, f) = 0;
6047       TYPE_FIELD_STATIC_KIND (rtype, f) = 0;
6048
6049       if (ada_is_variant_part (type, f))
6050         {
6051           struct type *branch_type;
6052
6053           if (dval0 == NULL)
6054             dval = value_from_contents_and_address (rtype, valaddr, address);
6055           else
6056             dval = dval0;
6057
6058           branch_type =
6059             to_fixed_variant_branch_type
6060             (TYPE_FIELD_TYPE (type, f),
6061              cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
6062              cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
6063           if (branch_type == NULL)
6064             TYPE_NFIELDS (rtype) -= 1;
6065           else
6066             {
6067               TYPE_FIELD_TYPE (rtype, f) = branch_type;
6068               TYPE_FIELD_NAME (rtype, f) = "S";
6069             }
6070           bit_incr = 0;
6071           fld_bit_len =
6072             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
6073         }
6074       else if (is_dynamic_field (type, f))
6075         {
6076           if (dval0 == NULL)
6077             dval = value_from_contents_and_address (rtype, valaddr, address);
6078           else
6079             dval = dval0;
6080
6081           TYPE_FIELD_TYPE (rtype, f) =
6082             ada_to_fixed_type
6083             (ada_get_base_type
6084              (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f))),
6085              cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
6086              cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
6087           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
6088           bit_incr = fld_bit_len =
6089             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
6090         }
6091       else
6092         {
6093           TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
6094           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
6095           if (TYPE_FIELD_BITSIZE (type, f) > 0)
6096             bit_incr = fld_bit_len =
6097               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
6098           else
6099             bit_incr = fld_bit_len =
6100               TYPE_LENGTH (TYPE_FIELD_TYPE (type, f)) * TARGET_CHAR_BIT;
6101         }
6102       if (off + fld_bit_len > bit_len)
6103         bit_len = off + fld_bit_len;
6104       off += bit_incr;
6105       TYPE_LENGTH (rtype) = bit_len / TARGET_CHAR_BIT;
6106     }
6107   TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype), TYPE_LENGTH (type));
6108
6109   value_free_to_mark (mark);
6110   if (TYPE_LENGTH (rtype) > varsize_limit)
6111     error ("record type with dynamic size is larger than varsize-limit");
6112   return rtype;
6113 }
6114
6115 /* As for template_to_fixed_record_type, but uses no run-time values.
6116    As a result, this type can only be approximate, but that's OK,
6117    since it is used only for type determinations.   Works on both
6118    structs and unions.
6119    Representation note: to save space, we memoize the result of this
6120    function in the TYPE_TARGET_TYPE of the template type. */
6121
6122 static struct type *
6123 template_to_static_fixed_type (struct type *templ_type)
6124 {
6125   struct type *type;
6126   int nfields;
6127   int f;
6128
6129   if (TYPE_TARGET_TYPE (templ_type) != NULL)
6130     return TYPE_TARGET_TYPE (templ_type);
6131
6132   nfields = TYPE_NFIELDS (templ_type);
6133   TYPE_TARGET_TYPE (templ_type) = type =
6134     alloc_type (TYPE_OBJFILE (templ_type));
6135   TYPE_CODE (type) = TYPE_CODE (templ_type);
6136   INIT_CPLUS_SPECIFIC (type);
6137   TYPE_NFIELDS (type) = nfields;
6138   TYPE_FIELDS (type) = (struct field *)
6139     TYPE_ALLOC (type, nfields * sizeof (struct field));
6140   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
6141   TYPE_NAME (type) = ada_type_name (templ_type);
6142   TYPE_TAG_NAME (type) = NULL;
6143   /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6144   /*  TYPE_FLAGS (type) |= TYPE_FLAG_FIXED_INSTANCE; */
6145   TYPE_LENGTH (type) = 0;
6146
6147   for (f = 0; f < nfields; f += 1)
6148     {
6149       TYPE_FIELD_BITPOS (type, f) = 0;
6150       TYPE_FIELD_BITSIZE (type, f) = 0;
6151       TYPE_FIELD_STATIC_KIND (type, f) = 0;
6152
6153       if (is_dynamic_field (templ_type, f))
6154         {
6155           TYPE_FIELD_TYPE (type, f) =
6156             to_static_fixed_type (TYPE_TARGET_TYPE
6157                                   (TYPE_FIELD_TYPE (templ_type, f)));
6158           TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (templ_type, f);
6159         }
6160       else
6161         {
6162           TYPE_FIELD_TYPE (type, f) =
6163             check_typedef (TYPE_FIELD_TYPE (templ_type, f));
6164           TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (templ_type, f);
6165         }
6166     }
6167
6168   return type;
6169 }
6170
6171 /* A revision of TYPE0 -- a non-dynamic-sized record with a variant
6172    part -- in which the variant part is replaced with the appropriate
6173    branch. */
6174 static struct type *
6175 to_record_with_fixed_variant_part (struct type *type, char *valaddr,
6176                                    CORE_ADDR address, struct value *dval)
6177 {
6178   struct value *mark = value_mark ();
6179   struct type *rtype;
6180   struct type *branch_type;
6181   int nfields = TYPE_NFIELDS (type);
6182
6183   if (dval == NULL)
6184     return type;
6185
6186   rtype = alloc_type (TYPE_OBJFILE (type));
6187   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
6188   INIT_CPLUS_SPECIFIC (type);
6189   TYPE_NFIELDS (rtype) = TYPE_NFIELDS (type);
6190   TYPE_FIELDS (rtype) =
6191     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
6192   memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
6193           sizeof (struct field) * nfields);
6194   TYPE_NAME (rtype) = ada_type_name (type);
6195   TYPE_TAG_NAME (rtype) = NULL;
6196   /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6197   /*  TYPE_FLAGS (rtype) |= TYPE_FLAG_FIXED_INSTANCE; */
6198   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
6199
6200   branch_type =
6201     to_fixed_variant_branch_type
6202     (TYPE_FIELD_TYPE (type, nfields - 1),
6203      cond_offset_host (valaddr,
6204                        TYPE_FIELD_BITPOS (type,
6205                                           nfields - 1) / TARGET_CHAR_BIT),
6206      cond_offset_target (address,
6207                          TYPE_FIELD_BITPOS (type,
6208                                             nfields - 1) / TARGET_CHAR_BIT),
6209      dval);
6210   if (branch_type == NULL)
6211     {
6212       TYPE_NFIELDS (rtype) -= 1;
6213       TYPE_LENGTH (rtype) -=
6214         TYPE_LENGTH (TYPE_FIELD_TYPE (type, nfields - 1));
6215     }
6216   else
6217     {
6218       TYPE_FIELD_TYPE (rtype, nfields - 1) = branch_type;
6219       TYPE_FIELD_NAME (rtype, nfields - 1) = "S";
6220       TYPE_FIELD_BITSIZE (rtype, nfields - 1) = 0;
6221       TYPE_FIELD_STATIC_KIND (rtype, nfields - 1) = 0;
6222       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
6223       -TYPE_LENGTH (TYPE_FIELD_TYPE (type, nfields - 1));
6224     }
6225
6226   return rtype;
6227 }
6228
6229 /* An ordinary record type (with fixed-length fields) that describes
6230    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
6231    beginning of this section].   Any necessary discriminants' values
6232    should be in DVAL, a record value; it should be NULL if the object
6233    at ADDR itself contains any necessary  discriminant values.  A
6234    variant field (unless unchecked) is replaced by a particular branch
6235    of the variant. */
6236
6237 static struct type *
6238 to_fixed_record_type (struct type *type0, char *valaddr, CORE_ADDR address,
6239                       struct value *dval)
6240 {
6241   struct type *templ_type;
6242
6243   /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6244   /*  if (TYPE_FLAGS (type0) & TYPE_FLAG_FIXED_INSTANCE)
6245      return type0;
6246    */
6247   templ_type = dynamic_template_type (type0);
6248
6249   if (templ_type != NULL)
6250     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
6251   else if (contains_variant_part (type0))
6252     return to_record_with_fixed_variant_part (type0, valaddr, address, dval);
6253   else
6254     {
6255       /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6256       /*      TYPE_FLAGS (type0) |= TYPE_FLAG_FIXED_INSTANCE; */
6257       return type0;
6258     }
6259
6260 }
6261
6262 /* An ordinary record type (with fixed-length fields) that describes
6263    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
6264    union type.  Any necessary discriminants' values should be in DVAL,
6265    a record value.  That is, this routine selects the appropriate
6266    branch of the union at ADDR according to the discriminant value
6267    indicated in the union's type name. */
6268
6269 static struct type *
6270 to_fixed_variant_branch_type (struct type *var_type0, char *valaddr,
6271                               CORE_ADDR address, struct value *dval)
6272 {
6273   int which;
6274   struct type *templ_type;
6275   struct type *var_type;
6276
6277   if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
6278     var_type = TYPE_TARGET_TYPE (var_type0);
6279   else
6280     var_type = var_type0;
6281
6282   templ_type = ada_find_parallel_type (var_type, "___XVU");
6283
6284   if (templ_type != NULL)
6285     var_type = templ_type;
6286
6287   which =
6288     ada_which_variant_applies (var_type,
6289                                VALUE_TYPE (dval), VALUE_CONTENTS (dval));
6290
6291   if (which < 0)
6292     return empty_record (TYPE_OBJFILE (var_type));
6293   else if (is_dynamic_field (var_type, which))
6294     return
6295       to_fixed_record_type
6296       (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
6297        valaddr, address, dval);
6298   else if (contains_variant_part (TYPE_FIELD_TYPE (var_type, which)))
6299     return
6300       to_fixed_record_type
6301       (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
6302   else
6303     return TYPE_FIELD_TYPE (var_type, which);
6304 }
6305
6306 /* Assuming that TYPE0 is an array type describing the type of a value
6307    at ADDR, and that DVAL describes a record containing any
6308    discriminants used in TYPE0, returns a type for the value that
6309    contains no dynamic components (that is, no components whose sizes
6310    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
6311    true, gives an error message if the resulting type's size is over
6312    varsize_limit.
6313 */
6314
6315 static struct type *
6316 to_fixed_array_type (struct type *type0, struct value *dval,
6317                      int ignore_too_big)
6318 {
6319   struct type *index_type_desc;
6320   struct type *result;
6321
6322   /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6323 /*  if (ada_is_packed_array_type (type0)  /* revisit? *//*
6324    || (TYPE_FLAGS (type0) & TYPE_FLAG_FIXED_INSTANCE))
6325    return type0; */
6326
6327   index_type_desc = ada_find_parallel_type (type0, "___XA");
6328   if (index_type_desc == NULL)
6329     {
6330       struct type *elt_type0 = check_typedef (TYPE_TARGET_TYPE (type0));
6331       /* NOTE: elt_type---the fixed version of elt_type0---should never
6332        * depend on the contents of the array in properly constructed
6333        * debugging data. */
6334       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval);
6335
6336       if (elt_type0 == elt_type)
6337         result = type0;
6338       else
6339         result = create_array_type (alloc_type (TYPE_OBJFILE (type0)),
6340                                     elt_type, TYPE_INDEX_TYPE (type0));
6341     }
6342   else
6343     {
6344       int i;
6345       struct type *elt_type0;
6346
6347       elt_type0 = type0;
6348       for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
6349         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
6350
6351       /* NOTE: result---the fixed version of elt_type0---should never
6352        * depend on the contents of the array in properly constructed
6353        * debugging data. */
6354       result = ada_to_fixed_type (check_typedef (elt_type0), 0, 0, dval);
6355       for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
6356         {
6357           struct type *range_type =
6358             to_fixed_range_type (TYPE_FIELD_NAME (index_type_desc, i),
6359                                  dval, TYPE_OBJFILE (type0));
6360           result = create_array_type (alloc_type (TYPE_OBJFILE (type0)),
6361                                       result, range_type);
6362         }
6363       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
6364         error ("array type with dynamic size is larger than varsize-limit");
6365     }
6366
6367 /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6368 /*  TYPE_FLAGS (result) |= TYPE_FLAG_FIXED_INSTANCE; */
6369   return result;
6370 }
6371
6372
6373 /* A standard type (containing no dynamically sized components)
6374    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
6375    DVAL describes a record containing any discriminants used in TYPE0,
6376    and may be NULL if there are none. */
6377
6378 struct type *
6379 ada_to_fixed_type (struct type *type, char *valaddr, CORE_ADDR address,
6380                    struct value *dval)
6381 {
6382   CHECK_TYPEDEF (type);
6383   switch (TYPE_CODE (type))
6384     {
6385     default:
6386       return type;
6387     case TYPE_CODE_STRUCT:
6388       return to_fixed_record_type (type, valaddr, address, NULL);
6389     case TYPE_CODE_ARRAY:
6390       return to_fixed_array_type (type, dval, 0);
6391     case TYPE_CODE_UNION:
6392       if (dval == NULL)
6393         return type;
6394       else
6395         return to_fixed_variant_branch_type (type, valaddr, address, dval);
6396     }
6397 }
6398
6399 /* A standard (static-sized) type corresponding as well as possible to
6400    TYPE0, but based on no runtime data. */
6401
6402 static struct type *
6403 to_static_fixed_type (struct type *type0)
6404 {
6405   struct type *type;
6406
6407   if (type0 == NULL)
6408     return NULL;
6409
6410   /* FIXME:  TYPE_FLAG_FIXED_INSTANCE should be defined in gdbtypes.h */
6411   /*  if (TYPE_FLAGS (type0) & TYPE_FLAG_FIXED_INSTANCE)
6412      return type0;
6413    */
6414   CHECK_TYPEDEF (type0);
6415
6416   switch (TYPE_CODE (type0))
6417     {
6418     default:
6419       return type0;
6420     case TYPE_CODE_STRUCT:
6421       type = dynamic_template_type (type0);
6422       if (type != NULL)
6423         return template_to_static_fixed_type (type);
6424       return type0;
6425     case TYPE_CODE_UNION:
6426       type = ada_find_parallel_type (type0, "___XVU");
6427       if (type != NULL)
6428         return template_to_static_fixed_type (type);
6429       return type0;
6430     }
6431 }
6432
6433 /* A static approximation of TYPE with all type wrappers removed. */
6434 static struct type *
6435 static_unwrap_type (struct type *type)
6436 {
6437   if (ada_is_aligner_type (type))
6438     {
6439       struct type *type1 = TYPE_FIELD_TYPE (check_typedef (type), 0);
6440       if (ada_type_name (type1) == NULL)
6441         TYPE_NAME (type1) = ada_type_name (type);
6442
6443       return static_unwrap_type (type1);
6444     }
6445   else
6446     {
6447       struct type *raw_real_type = ada_get_base_type (type);
6448       if (raw_real_type == type)
6449         return type;
6450       else
6451         return to_static_fixed_type (raw_real_type);
6452     }
6453 }
6454
6455 /* In some cases, incomplete and private types require
6456    cross-references that are not resolved as records (for example, 
6457       type Foo;
6458       type FooP is access Foo;
6459       V: FooP;
6460       type Foo is array ...;
6461    ). In these cases, since there is no mechanism for producing 
6462    cross-references to such types, we instead substitute for FooP a
6463    stub enumeration type that is nowhere resolved, and whose tag is
6464    the name of the actual type.  Call these types "non-record stubs". */
6465
6466 /* A type equivalent to TYPE that is not a non-record stub, if one
6467    exists, otherwise TYPE. */
6468 struct type *
6469 ada_completed_type (struct type *type)
6470 {
6471   CHECK_TYPEDEF (type);
6472   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
6473       || (TYPE_FLAGS (type) & TYPE_FLAG_STUB) == 0
6474       || TYPE_TAG_NAME (type) == NULL)
6475     return type;
6476   else
6477     {
6478       char *name = TYPE_TAG_NAME (type);
6479       struct type *type1 = ada_find_any_type (name);
6480       return (type1 == NULL) ? type : type1;
6481     }
6482 }
6483
6484 /* A value representing the data at VALADDR/ADDRESS as described by
6485    type TYPE0, but with a standard (static-sized) type that correctly
6486    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
6487    type, then return VAL0 [this feature is simply to avoid redundant
6488    creation of struct values]. */
6489
6490 struct value *
6491 ada_to_fixed_value (struct type *type0, char *valaddr, CORE_ADDR address,
6492                     struct value *val0)
6493 {
6494   struct type *type = ada_to_fixed_type (type0, valaddr, address, NULL);
6495   if (type == type0 && val0 != NULL)
6496     return val0;
6497   else
6498     return value_from_contents_and_address (type, valaddr, address);
6499 }
6500
6501 /* A value representing VAL, but with a standard (static-sized) type 
6502    chosen to approximate the real type of VAL as well as possible, but
6503    without consulting any runtime values.  For Ada dynamic-sized
6504    types, therefore, the type of the result is likely to be inaccurate. */
6505
6506 struct value *
6507 ada_to_static_fixed_value (struct value *val)
6508 {
6509   struct type *type =
6510     to_static_fixed_type (static_unwrap_type (VALUE_TYPE (val)));
6511   if (type == VALUE_TYPE (val))
6512     return val;
6513   else
6514     return coerce_unspec_val_to_type (val, 0, type);
6515 }
6516 \f
6517
6518
6519
6520
6521 /* Attributes */
6522
6523 /* Table mapping attribute numbers to names */
6524 /* NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h */
6525
6526 static const char *attribute_names[] = {
6527   "<?>",
6528
6529   "first",
6530   "last",
6531   "length",
6532   "image",
6533   "img",
6534   "max",
6535   "min",
6536   "pos" "tag",
6537   "val",
6538
6539   0
6540 };
6541
6542 const char *
6543 ada_attribute_name (int n)
6544 {
6545   if (n > 0 && n < (int) ATR_END)
6546     return attribute_names[n];
6547   else
6548     return attribute_names[0];
6549 }
6550
6551 /* Evaluate the 'POS attribute applied to ARG. */
6552
6553 static struct value *
6554 value_pos_atr (struct value *arg)
6555 {
6556   struct type *type = VALUE_TYPE (arg);
6557
6558   if (!discrete_type_p (type))
6559     error ("'POS only defined on discrete types");
6560
6561   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
6562     {
6563       int i;
6564       LONGEST v = value_as_long (arg);
6565
6566       for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6567         {
6568           if (v == TYPE_FIELD_BITPOS (type, i))
6569             return value_from_longest (builtin_type_ada_int, i);
6570         }
6571       error ("enumeration value is invalid: can't find 'POS");
6572     }
6573   else
6574     return value_from_longest (builtin_type_ada_int, value_as_long (arg));
6575 }
6576
6577 /* Evaluate the TYPE'VAL attribute applied to ARG. */
6578
6579 static struct value *
6580 value_val_atr (struct type *type, struct value *arg)
6581 {
6582   if (!discrete_type_p (type))
6583     error ("'VAL only defined on discrete types");
6584   if (!integer_type_p (VALUE_TYPE (arg)))
6585     error ("'VAL requires integral argument");
6586
6587   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
6588     {
6589       long pos = value_as_long (arg);
6590       if (pos < 0 || pos >= TYPE_NFIELDS (type))
6591         error ("argument to 'VAL out of range");
6592       return value_from_longest (type, TYPE_FIELD_BITPOS (type, pos));
6593     }
6594   else
6595     return value_from_longest (type, value_as_long (arg));
6596 }
6597 \f
6598
6599                                 /* Evaluation */
6600
6601 /* True if TYPE appears to be an Ada character type.  
6602  * [At the moment, this is true only for Character and Wide_Character;
6603  * It is a heuristic test that could stand improvement]. */
6604
6605 int
6606 ada_is_character_type (struct type *type)
6607 {
6608   const char *name = ada_type_name (type);
6609   return
6610     name != NULL
6611     && (TYPE_CODE (type) == TYPE_CODE_CHAR
6612         || TYPE_CODE (type) == TYPE_CODE_INT
6613         || TYPE_CODE (type) == TYPE_CODE_RANGE)
6614     && (STREQ (name, "character") || STREQ (name, "wide_character")
6615         || STREQ (name, "unsigned char"));
6616 }
6617
6618 /* True if TYPE appears to be an Ada string type. */
6619
6620 int
6621 ada_is_string_type (struct type *type)
6622 {
6623   CHECK_TYPEDEF (type);
6624   if (type != NULL
6625       && TYPE_CODE (type) != TYPE_CODE_PTR
6626       && (ada_is_simple_array (type) || ada_is_array_descriptor (type))
6627       && ada_array_arity (type) == 1)
6628     {
6629       struct type *elttype = ada_array_element_type (type, 1);
6630
6631       return ada_is_character_type (elttype);
6632     }
6633   else
6634     return 0;
6635 }
6636
6637
6638 /* True if TYPE is a struct type introduced by the compiler to force the
6639    alignment of a value.  Such types have a single field with a
6640    distinctive name. */
6641
6642 int
6643 ada_is_aligner_type (struct type *type)
6644 {
6645   CHECK_TYPEDEF (type);
6646   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
6647           && TYPE_NFIELDS (type) == 1
6648           && STREQ (TYPE_FIELD_NAME (type, 0), "F"));
6649 }
6650
6651 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
6652    the parallel type. */
6653
6654 struct type *
6655 ada_get_base_type (struct type *raw_type)
6656 {
6657   struct type *real_type_namer;
6658   struct type *raw_real_type;
6659   struct type *real_type;
6660
6661   if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
6662     return raw_type;
6663
6664   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
6665   if (real_type_namer == NULL
6666       || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
6667       || TYPE_NFIELDS (real_type_namer) != 1)
6668     return raw_type;
6669
6670   raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
6671   if (raw_real_type == NULL)
6672     return raw_type;
6673   else
6674     return raw_real_type;
6675 }
6676
6677 /* The type of value designated by TYPE, with all aligners removed. */
6678
6679 struct type *
6680 ada_aligned_type (struct type *type)
6681 {
6682   if (ada_is_aligner_type (type))
6683     return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
6684   else
6685     return ada_get_base_type (type);
6686 }
6687
6688
6689 /* The address of the aligned value in an object at address VALADDR
6690    having type TYPE.  Assumes ada_is_aligner_type (TYPE). */
6691
6692 char *
6693 ada_aligned_value_addr (struct type *type, char *valaddr)
6694 {
6695   if (ada_is_aligner_type (type))
6696     return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
6697                                    valaddr +
6698                                    TYPE_FIELD_BITPOS (type,
6699                                                       0) / TARGET_CHAR_BIT);
6700   else
6701     return valaddr;
6702 }
6703
6704 /* The printed representation of an enumeration literal with encoded
6705    name NAME. The value is good to the next call of ada_enum_name. */
6706 const char *
6707 ada_enum_name (const char *name)
6708 {
6709   char *tmp;
6710
6711   while (1)
6712     {
6713       if ((tmp = strstr (name, "__")) != NULL)
6714         name = tmp + 2;
6715       else if ((tmp = strchr (name, '.')) != NULL)
6716         name = tmp + 1;
6717       else
6718         break;
6719     }
6720
6721   if (name[0] == 'Q')
6722     {
6723       static char result[16];
6724       int v;
6725       if (name[1] == 'U' || name[1] == 'W')
6726         {
6727           if (sscanf (name + 2, "%x", &v) != 1)
6728             return name;
6729         }
6730       else
6731         return name;
6732
6733       if (isascii (v) && isprint (v))
6734         sprintf (result, "'%c'", v);
6735       else if (name[1] == 'U')
6736         sprintf (result, "[\"%02x\"]", v);
6737       else
6738         sprintf (result, "[\"%04x\"]", v);
6739
6740       return result;
6741     }
6742   else
6743     return name;
6744 }
6745
6746 static struct value *
6747 evaluate_subexp (struct type *expect_type, struct expression *exp, int *pos,
6748                  enum noside noside)
6749 {
6750   return (*exp->language_defn->evaluate_exp) (expect_type, exp, pos, noside);
6751 }
6752
6753 /* Evaluate the subexpression of EXP starting at *POS as for
6754    evaluate_type, updating *POS to point just past the evaluated
6755    expression. */
6756
6757 static struct value *
6758 evaluate_subexp_type (struct expression *exp, int *pos)
6759 {
6760   return (*exp->language_defn->evaluate_exp)
6761     (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
6762 }
6763
6764 /* If VAL is wrapped in an aligner or subtype wrapper, return the
6765    value it wraps. */
6766
6767 static struct value *
6768 unwrap_value (struct value *val)
6769 {
6770   struct type *type = check_typedef (VALUE_TYPE (val));
6771   if (ada_is_aligner_type (type))
6772     {
6773       struct value *v = value_struct_elt (&val, NULL, "F",
6774                                           NULL, "internal structure");
6775       struct type *val_type = check_typedef (VALUE_TYPE (v));
6776       if (ada_type_name (val_type) == NULL)
6777         TYPE_NAME (val_type) = ada_type_name (type);
6778
6779       return unwrap_value (v);
6780     }
6781   else
6782     {
6783       struct type *raw_real_type =
6784         ada_completed_type (ada_get_base_type (type));
6785
6786       if (type == raw_real_type)
6787         return val;
6788
6789       return
6790         coerce_unspec_val_to_type
6791         (val, 0, ada_to_fixed_type (raw_real_type, 0,
6792                                     VALUE_ADDRESS (val) + VALUE_OFFSET (val),
6793                                     NULL));
6794     }
6795 }
6796
6797 static struct value *
6798 cast_to_fixed (struct type *type, struct value *arg)
6799 {
6800   LONGEST val;
6801
6802   if (type == VALUE_TYPE (arg))
6803     return arg;
6804   else if (ada_is_fixed_point_type (VALUE_TYPE (arg)))
6805     val = ada_float_to_fixed (type,
6806                               ada_fixed_to_float (VALUE_TYPE (arg),
6807                                                   value_as_long (arg)));
6808   else
6809     {
6810       DOUBLEST argd =
6811         value_as_double (value_cast (builtin_type_double, value_copy (arg)));
6812       val = ada_float_to_fixed (type, argd);
6813     }
6814
6815   return value_from_longest (type, val);
6816 }
6817
6818 static struct value *
6819 cast_from_fixed_to_double (struct value *arg)
6820 {
6821   DOUBLEST val = ada_fixed_to_float (VALUE_TYPE (arg),
6822                                      value_as_long (arg));
6823   return value_from_double (builtin_type_double, val);
6824 }
6825
6826 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and 
6827  * return the converted value. */
6828 static struct value *
6829 coerce_for_assign (struct type *type, struct value *val)
6830 {
6831   struct type *type2 = VALUE_TYPE (val);
6832   if (type == type2)
6833     return val;
6834
6835   CHECK_TYPEDEF (type2);
6836   CHECK_TYPEDEF (type);
6837
6838   if (TYPE_CODE (type2) == TYPE_CODE_PTR
6839       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
6840     {
6841       val = ada_value_ind (val);
6842       type2 = VALUE_TYPE (val);
6843     }
6844
6845   if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
6846       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
6847     {
6848       if (TYPE_LENGTH (type2) != TYPE_LENGTH (type)
6849           || TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
6850           != TYPE_LENGTH (TYPE_TARGET_TYPE (type2)))
6851         error ("Incompatible types in assignment");
6852       VALUE_TYPE (val) = type;
6853     }
6854   return val;
6855 }
6856
6857 struct value *
6858 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
6859                      int *pos, enum noside noside)
6860 {
6861   enum exp_opcode op;
6862   enum ada_attribute atr;
6863   int tem, tem2, tem3;
6864   int pc;
6865   struct value *arg1 = NULL, *arg2 = NULL, *arg3;
6866   struct type *type;
6867   int nargs;
6868   struct value **argvec;
6869
6870   pc = *pos;
6871   *pos += 1;
6872   op = exp->elts[pc].opcode;
6873
6874   switch (op)
6875     {
6876     default:
6877       *pos -= 1;
6878       return
6879         unwrap_value (evaluate_subexp_standard
6880                       (expect_type, exp, pos, noside));
6881
6882     case UNOP_CAST:
6883       (*pos) += 2;
6884       type = exp->elts[pc + 1].type;
6885       arg1 = evaluate_subexp (type, exp, pos, noside);
6886       if (noside == EVAL_SKIP)
6887         goto nosideret;
6888       if (type != check_typedef (VALUE_TYPE (arg1)))
6889         {
6890           if (ada_is_fixed_point_type (type))
6891             arg1 = cast_to_fixed (type, arg1);
6892           else if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
6893             arg1 = value_cast (type, cast_from_fixed_to_double (arg1));
6894           else if (VALUE_LVAL (arg1) == lval_memory)
6895             {
6896               /* This is in case of the really obscure (and undocumented,
6897                  but apparently expected) case of (Foo) Bar.all, where Bar 
6898                  is an integer constant and Foo is a dynamic-sized type.
6899                  If we don't do this, ARG1 will simply be relabeled with
6900                  TYPE. */
6901               if (noside == EVAL_AVOID_SIDE_EFFECTS)
6902                 return value_zero (to_static_fixed_type (type), not_lval);
6903               arg1 =
6904                 ada_to_fixed_value
6905                 (type, 0, VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1), 0);
6906             }
6907           else
6908             arg1 = value_cast (type, arg1);
6909         }
6910       return arg1;
6911
6912       /* FIXME:  UNOP_QUAL should be defined in expression.h */
6913       /*    case UNOP_QUAL:
6914          (*pos) += 2;
6915          type = exp->elts[pc + 1].type;
6916          return ada_evaluate_subexp (type, exp, pos, noside);
6917        */
6918     case BINOP_ASSIGN:
6919       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
6920       arg2 = evaluate_subexp (VALUE_TYPE (arg1), exp, pos, noside);
6921       if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
6922         return arg1;
6923       if (binop_user_defined_p (op, arg1, arg2))
6924         return value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
6925       else
6926         {
6927           if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
6928             arg2 = cast_to_fixed (VALUE_TYPE (arg1), arg2);
6929           else if (ada_is_fixed_point_type (VALUE_TYPE (arg2)))
6930             error
6931               ("Fixed-point values must be assigned to fixed-point variables");
6932           else
6933             arg2 = coerce_for_assign (VALUE_TYPE (arg1), arg2);
6934           return ada_value_assign (arg1, arg2);
6935         }
6936
6937     case BINOP_ADD:
6938       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
6939       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
6940       if (noside == EVAL_SKIP)
6941         goto nosideret;
6942       if (binop_user_defined_p (op, arg1, arg2))
6943         return value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
6944       else
6945         {
6946           if ((ada_is_fixed_point_type (VALUE_TYPE (arg1))
6947                || ada_is_fixed_point_type (VALUE_TYPE (arg2)))
6948               && VALUE_TYPE (arg1) != VALUE_TYPE (arg2))
6949             error
6950               ("Operands of fixed-point addition must have the same type");
6951           return value_cast (VALUE_TYPE (arg1), value_add (arg1, arg2));
6952         }
6953
6954     case BINOP_SUB:
6955       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
6956       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
6957       if (noside == EVAL_SKIP)
6958         goto nosideret;
6959       if (binop_user_defined_p (op, arg1, arg2))
6960         return value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
6961       else
6962         {
6963           if ((ada_is_fixed_point_type (VALUE_TYPE (arg1))
6964                || ada_is_fixed_point_type (VALUE_TYPE (arg2)))
6965               && VALUE_TYPE (arg1) != VALUE_TYPE (arg2))
6966             error
6967               ("Operands of fixed-point subtraction must have the same type");
6968           return value_cast (VALUE_TYPE (arg1), value_sub (arg1, arg2));
6969         }
6970
6971     case BINOP_MUL:
6972     case BINOP_DIV:
6973       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
6974       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
6975       if (noside == EVAL_SKIP)
6976         goto nosideret;
6977       if (binop_user_defined_p (op, arg1, arg2))
6978         return value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
6979       else
6980         if (noside == EVAL_AVOID_SIDE_EFFECTS
6981             && (op == BINOP_DIV || op == BINOP_REM || op == BINOP_MOD))
6982         return value_zero (VALUE_TYPE (arg1), not_lval);
6983       else
6984         {
6985           if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
6986             arg1 = cast_from_fixed_to_double (arg1);
6987           if (ada_is_fixed_point_type (VALUE_TYPE (arg2)))
6988             arg2 = cast_from_fixed_to_double (arg2);
6989           return value_binop (arg1, arg2, op);
6990         }
6991
6992     case UNOP_NEG:
6993       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
6994       if (noside == EVAL_SKIP)
6995         goto nosideret;
6996       if (unop_user_defined_p (op, arg1))
6997         return value_x_unop (arg1, op, EVAL_NORMAL);
6998       else if (ada_is_fixed_point_type (VALUE_TYPE (arg1)))
6999         return value_cast (VALUE_TYPE (arg1), value_neg (arg1));
7000       else
7001         return value_neg (arg1);
7002
7003       /* FIXME:  OP_UNRESOLVED_VALUE should be defined in expression.h */
7004       /*    case OP_UNRESOLVED_VALUE:
7005          /* Only encountered when an unresolved symbol occurs in a
7006          context other than a function call, in which case, it is
7007    illegal. *//*
7008    (*pos) += 3;
7009    if (noside == EVAL_SKIP)
7010    goto nosideret;
7011    else 
7012    error ("Unexpected unresolved symbol, %s, during evaluation",
7013    ada_demangle (exp->elts[pc + 2].name));
7014  */
7015     case OP_VAR_VALUE:
7016       *pos -= 1;
7017       if (noside == EVAL_SKIP)
7018         {
7019           *pos += 4;
7020           goto nosideret;
7021         }
7022       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7023         {
7024           *pos += 4;
7025           return value_zero
7026             (to_static_fixed_type
7027              (static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol))),
7028              not_lval);
7029         }
7030       else
7031         {
7032           arg1 =
7033             unwrap_value (evaluate_subexp_standard
7034                           (expect_type, exp, pos, noside));
7035           return ada_to_fixed_value (VALUE_TYPE (arg1), 0,
7036                                      VALUE_ADDRESS (arg1) +
7037                                      VALUE_OFFSET (arg1), arg1);
7038         }
7039
7040     case OP_ARRAY:
7041       (*pos) += 3;
7042       tem2 = longest_to_int (exp->elts[pc + 1].longconst);
7043       tem3 = longest_to_int (exp->elts[pc + 2].longconst);
7044       nargs = tem3 - tem2 + 1;
7045       type = expect_type ? check_typedef (expect_type) : NULL_TYPE;
7046
7047       argvec =
7048         (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
7049       for (tem = 0; tem == 0 || tem < nargs; tem += 1)
7050         /* At least one element gets inserted for the type */
7051         {
7052           /* Ensure that array expressions are coerced into pointer objects. */
7053           argvec[tem] = evaluate_subexp_with_coercion (exp, pos, noside);
7054         }
7055       if (noside == EVAL_SKIP)
7056         goto nosideret;
7057       return value_array (tem2, tem3, argvec);
7058
7059     case OP_FUNCALL:
7060       (*pos) += 2;
7061
7062       /* Allocate arg vector, including space for the function to be
7063          called in argvec[0] and a terminating NULL */
7064       nargs = longest_to_int (exp->elts[pc + 1].longconst);
7065       argvec =
7066         (struct value * *) alloca (sizeof (struct value *) * (nargs + 2));
7067
7068       /* FIXME: OP_UNRESOLVED_VALUE should be defined in expression.h */
7069       /* FIXME: name should be defined in expresion.h */
7070       /*      if (exp->elts[*pos].opcode == OP_UNRESOLVED_VALUE)
7071          error ("Unexpected unresolved symbol, %s, during evaluation",
7072          ada_demangle (exp->elts[pc + 5].name));
7073        */
7074       if (0)
7075         {
7076           error ("unexpected code path, FIXME");
7077         }
7078       else
7079         {
7080           for (tem = 0; tem <= nargs; tem += 1)
7081             argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7082           argvec[tem] = 0;
7083
7084           if (noside == EVAL_SKIP)
7085             goto nosideret;
7086         }
7087
7088       if (TYPE_CODE (VALUE_TYPE (argvec[0])) == TYPE_CODE_REF)
7089         argvec[0] = value_addr (argvec[0]);
7090
7091       if (ada_is_packed_array_type (VALUE_TYPE (argvec[0])))
7092         argvec[0] = ada_coerce_to_simple_array (argvec[0]);
7093
7094       type = check_typedef (VALUE_TYPE (argvec[0]));
7095       if (TYPE_CODE (type) == TYPE_CODE_PTR)
7096         {
7097           switch (TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (type))))
7098             {
7099             case TYPE_CODE_FUNC:
7100               type = check_typedef (TYPE_TARGET_TYPE (type));
7101               break;
7102             case TYPE_CODE_ARRAY:
7103               break;
7104             case TYPE_CODE_STRUCT:
7105               if (noside != EVAL_AVOID_SIDE_EFFECTS)
7106                 argvec[0] = ada_value_ind (argvec[0]);
7107               type = check_typedef (TYPE_TARGET_TYPE (type));
7108               break;
7109             default:
7110               error ("cannot subscript or call something of type `%s'",
7111                      ada_type_name (VALUE_TYPE (argvec[0])));
7112               break;
7113             }
7114         }
7115
7116       switch (TYPE_CODE (type))
7117         {
7118         case TYPE_CODE_FUNC:
7119           if (noside == EVAL_AVOID_SIDE_EFFECTS)
7120             return allocate_value (TYPE_TARGET_TYPE (type));
7121           return call_function_by_hand (argvec[0], nargs, argvec + 1);
7122         case TYPE_CODE_STRUCT:
7123           {
7124             int arity = ada_array_arity (type);
7125             type = ada_array_element_type (type, nargs);
7126             if (type == NULL)
7127               error ("cannot subscript or call a record");
7128             if (arity != nargs)
7129               error ("wrong number of subscripts; expecting %d", arity);
7130             if (noside == EVAL_AVOID_SIDE_EFFECTS)
7131               return allocate_value (ada_aligned_type (type));
7132             return
7133               unwrap_value (ada_value_subscript
7134                             (argvec[0], nargs, argvec + 1));
7135           }
7136         case TYPE_CODE_ARRAY:
7137           if (noside == EVAL_AVOID_SIDE_EFFECTS)
7138             {
7139               type = ada_array_element_type (type, nargs);
7140               if (type == NULL)
7141                 error ("element type of array unknown");
7142               else
7143                 return allocate_value (ada_aligned_type (type));
7144             }
7145           return
7146             unwrap_value (ada_value_subscript
7147                           (ada_coerce_to_simple_array (argvec[0]),
7148                            nargs, argvec + 1));
7149         case TYPE_CODE_PTR:     /* Pointer to array */
7150           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
7151           if (noside == EVAL_AVOID_SIDE_EFFECTS)
7152             {
7153               type = ada_array_element_type (type, nargs);
7154               if (type == NULL)
7155                 error ("element type of array unknown");
7156               else
7157                 return allocate_value (ada_aligned_type (type));
7158             }
7159           return
7160             unwrap_value (ada_value_ptr_subscript (argvec[0], type,
7161                                                    nargs, argvec + 1));
7162
7163         default:
7164           error ("Internal error in evaluate_subexp");
7165         }
7166
7167     case TERNOP_SLICE:
7168       {
7169         struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7170         int lowbound
7171           = value_as_long (evaluate_subexp (NULL_TYPE, exp, pos, noside));
7172         int upper
7173           = value_as_long (evaluate_subexp (NULL_TYPE, exp, pos, noside));
7174         if (noside == EVAL_SKIP)
7175           goto nosideret;
7176
7177         /* If this is a reference to an array, then dereference it */
7178         if (TYPE_CODE (VALUE_TYPE (array)) == TYPE_CODE_REF
7179             && TYPE_TARGET_TYPE (VALUE_TYPE (array)) != NULL
7180             && TYPE_CODE (TYPE_TARGET_TYPE (VALUE_TYPE (array))) ==
7181             TYPE_CODE_ARRAY
7182             && !ada_is_array_descriptor (check_typedef (VALUE_TYPE (array))))
7183           {
7184             array = ada_coerce_ref (array);
7185           }
7186
7187         if (noside == EVAL_AVOID_SIDE_EFFECTS &&
7188             ada_is_array_descriptor (check_typedef (VALUE_TYPE (array))))
7189           {
7190             /* Try to dereference the array, in case it is an access to array */
7191             struct type *arrType = ada_type_of_array (array, 0);
7192             if (arrType != NULL)
7193               array = value_at_lazy (arrType, 0, NULL);
7194           }
7195         if (ada_is_array_descriptor (VALUE_TYPE (array)))
7196           array = ada_coerce_to_simple_array (array);
7197
7198         /* If at this point we have a pointer to an array, it means that
7199            it is a pointer to a simple (non-ada) array. We just then
7200            dereference it */
7201         if (TYPE_CODE (VALUE_TYPE (array)) == TYPE_CODE_PTR
7202             && TYPE_TARGET_TYPE (VALUE_TYPE (array)) != NULL
7203             && TYPE_CODE (TYPE_TARGET_TYPE (VALUE_TYPE (array))) ==
7204             TYPE_CODE_ARRAY)
7205           {
7206             array = ada_value_ind (array);
7207           }
7208
7209         if (noside == EVAL_AVOID_SIDE_EFFECTS)
7210           /* The following will get the bounds wrong, but only in contexts
7211              where the value is not being requested (FIXME?). */
7212           return array;
7213         else
7214           return value_slice (array, lowbound, upper - lowbound + 1);
7215       }
7216
7217       /* FIXME: UNOP_MBR should be defined in expression.h */
7218       /*    case UNOP_MBR:
7219          (*pos) += 2;
7220          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7221          type = exp->elts[pc + 1].type;
7222
7223          if (noside == EVAL_SKIP)
7224          goto nosideret;
7225
7226          switch (TYPE_CODE (type)) 
7227          {
7228          default:
7229          warning ("Membership test incompletely implemented; always returns true");
7230          return value_from_longest (builtin_type_int, (LONGEST) 1);
7231
7232          case TYPE_CODE_RANGE:
7233          arg2 = value_from_longest (builtin_type_int, 
7234          (LONGEST) TYPE_LOW_BOUND (type));
7235          arg3 = value_from_longest (builtin_type_int, 
7236          (LONGEST) TYPE_HIGH_BOUND (type));
7237          return 
7238          value_from_longest (builtin_type_int,
7239          (value_less (arg1,arg3) 
7240          || value_equal (arg1,arg3))
7241          && (value_less (arg2,arg1)
7242          || value_equal (arg2,arg1)));
7243          }
7244        */
7245       /* FIXME: BINOP_MBR should be defined in expression.h */
7246       /*    case BINOP_MBR:
7247          (*pos) += 2;
7248          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7249          arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7250
7251          if (noside == EVAL_SKIP)
7252          goto nosideret;
7253
7254          if (noside == EVAL_AVOID_SIDE_EFFECTS)
7255          return value_zero (builtin_type_int, not_lval);
7256
7257          tem = longest_to_int (exp->elts[pc + 1].longconst);
7258
7259          if (tem < 1 || tem > ada_array_arity (VALUE_TYPE (arg2)))
7260          error ("invalid dimension number to '%s", "range");
7261
7262          arg3 = ada_array_bound (arg2, tem, 1);
7263          arg2 = ada_array_bound (arg2, tem, 0);
7264
7265          return 
7266          value_from_longest (builtin_type_int,
7267          (value_less (arg1,arg3) 
7268          || value_equal (arg1,arg3))
7269          && (value_less (arg2,arg1)
7270          || value_equal (arg2,arg1)));
7271        */
7272       /* FIXME: TERNOP_MBR should be defined in expression.h */
7273       /*    case TERNOP_MBR:
7274          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7275          arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7276          arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7277
7278          if (noside == EVAL_SKIP)
7279          goto nosideret;
7280
7281          return 
7282          value_from_longest (builtin_type_int,
7283          (value_less (arg1,arg3) 
7284          || value_equal (arg1,arg3))
7285          && (value_less (arg2,arg1)
7286          || value_equal (arg2,arg1)));
7287        */
7288       /* FIXME: OP_ATTRIBUTE should be defined in expression.h */
7289       /*    case OP_ATTRIBUTE:
7290          *pos += 3;
7291          atr = (enum ada_attribute) longest_to_int (exp->elts[pc + 2].longconst);
7292          switch (atr) 
7293          {
7294          default:
7295          error ("unexpected attribute encountered");
7296
7297          case ATR_FIRST:
7298          case ATR_LAST:
7299          case ATR_LENGTH:
7300          {
7301          struct type* type_arg;
7302          if (exp->elts[*pos].opcode == OP_TYPE)
7303          {
7304          evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
7305          arg1 = NULL;
7306          type_arg = exp->elts[pc + 5].type;
7307          }
7308          else
7309          {
7310          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7311          type_arg = NULL;
7312          }
7313
7314          if (exp->elts[*pos].opcode != OP_LONG) 
7315          error ("illegal operand to '%s", ada_attribute_name (atr));
7316          tem = longest_to_int (exp->elts[*pos+2].longconst);
7317          *pos += 4;
7318
7319          if (noside == EVAL_SKIP)
7320          goto nosideret;
7321
7322          if (type_arg == NULL)
7323          {
7324          arg1 = ada_coerce_ref (arg1);
7325
7326          if (ada_is_packed_array_type (VALUE_TYPE (arg1)))
7327          arg1 = ada_coerce_to_simple_array (arg1);
7328
7329          if (tem < 1 || tem > ada_array_arity (VALUE_TYPE (arg1)))
7330          error ("invalid dimension number to '%s", 
7331          ada_attribute_name (atr));
7332
7333          if (noside == EVAL_AVOID_SIDE_EFFECTS)
7334          {
7335          type = ada_index_type (VALUE_TYPE (arg1), tem);
7336          if (type == NULL) 
7337          error ("attempt to take bound of something that is not an array");
7338          return allocate_value (type);
7339          }
7340
7341          switch (atr) 
7342          {
7343          default: 
7344          error ("unexpected attribute encountered");
7345          case ATR_FIRST:
7346          return ada_array_bound (arg1, tem, 0);
7347          case ATR_LAST:
7348          return ada_array_bound (arg1, tem, 1);
7349          case ATR_LENGTH:
7350          return ada_array_length (arg1, tem);
7351          }
7352          }
7353          else if (TYPE_CODE (type_arg) == TYPE_CODE_RANGE
7354          || TYPE_CODE (type_arg) == TYPE_CODE_INT) 
7355          {
7356          struct type* range_type;
7357          char* name = ada_type_name (type_arg);
7358          if (name == NULL)
7359          {
7360          if (TYPE_CODE (type_arg) == TYPE_CODE_RANGE) 
7361          range_type = type_arg;
7362          else
7363          error ("unimplemented type attribute");
7364          }
7365          else 
7366          range_type = 
7367          to_fixed_range_type (name, NULL, TYPE_OBJFILE (type_arg));
7368          switch (atr) 
7369          {
7370          default: 
7371          error ("unexpected attribute encountered");
7372          case ATR_FIRST:
7373          return value_from_longest (TYPE_TARGET_TYPE (range_type),
7374          TYPE_LOW_BOUND (range_type));
7375          case ATR_LAST:
7376          return value_from_longest (TYPE_TARGET_TYPE (range_type),
7377          TYPE_HIGH_BOUND (range_type));
7378          }
7379          }              
7380          else if (TYPE_CODE (type_arg) == TYPE_CODE_ENUM)
7381          {
7382          switch (atr) 
7383          {
7384          default: 
7385          error ("unexpected attribute encountered");
7386          case ATR_FIRST:
7387          return value_from_longest 
7388          (type_arg, TYPE_FIELD_BITPOS (type_arg, 0));
7389          case ATR_LAST:
7390          return value_from_longest 
7391          (type_arg, 
7392          TYPE_FIELD_BITPOS (type_arg,
7393          TYPE_NFIELDS (type_arg) - 1));
7394          }
7395          }
7396          else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
7397          error ("unimplemented type attribute");
7398          else 
7399          {
7400          LONGEST low, high;
7401
7402          if (ada_is_packed_array_type (type_arg))
7403          type_arg = decode_packed_array_type (type_arg);
7404
7405          if (tem < 1 || tem > ada_array_arity (type_arg))
7406          error ("invalid dimension number to '%s", 
7407          ada_attribute_name (atr));
7408
7409          if (noside == EVAL_AVOID_SIDE_EFFECTS)
7410          {
7411          type = ada_index_type (type_arg, tem);
7412          if (type == NULL) 
7413          error ("attempt to take bound of something that is not an array");
7414          return allocate_value (type);
7415          }
7416
7417          switch (atr) 
7418          {
7419          default: 
7420          error ("unexpected attribute encountered");
7421          case ATR_FIRST:
7422          low = ada_array_bound_from_type (type_arg, tem, 0, &type);
7423          return value_from_longest (type, low);
7424          case ATR_LAST:
7425          high = ada_array_bound_from_type (type_arg, tem, 1, &type);
7426          return value_from_longest (type, high);
7427          case ATR_LENGTH:
7428          low = ada_array_bound_from_type (type_arg, tem, 0, &type);
7429          high = ada_array_bound_from_type (type_arg, tem, 1, NULL);
7430          return value_from_longest (type, high-low+1);
7431          }
7432          }
7433          }
7434
7435          case ATR_TAG:
7436          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7437          if (noside == EVAL_SKIP)
7438          goto nosideret;
7439
7440          if (noside == EVAL_AVOID_SIDE_EFFECTS)
7441          return         
7442          value_zero (ada_tag_type (arg1), not_lval);
7443
7444          return ada_value_tag (arg1);
7445
7446          case ATR_MIN:
7447          case ATR_MAX:
7448          evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
7449          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7450          arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7451          if (noside == EVAL_SKIP)
7452          goto nosideret;
7453          else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7454          return value_zero (VALUE_TYPE (arg1), not_lval);
7455          else
7456          return value_binop (arg1, arg2, 
7457          atr == ATR_MIN ? BINOP_MIN : BINOP_MAX);
7458
7459          case ATR_MODULUS:
7460          {
7461          struct type* type_arg = exp->elts[pc + 5].type;
7462          evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
7463          *pos += 4;
7464
7465          if (noside == EVAL_SKIP)
7466          goto nosideret;
7467
7468          if (! ada_is_modular_type (type_arg))
7469          error ("'modulus must be applied to modular type");
7470
7471          return value_from_longest (TYPE_TARGET_TYPE (type_arg),
7472          ada_modulus (type_arg));
7473          }
7474
7475
7476          case ATR_POS:
7477          evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
7478          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7479          if (noside == EVAL_SKIP)
7480          goto nosideret;
7481          else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7482          return value_zero (builtin_type_ada_int, not_lval);
7483          else 
7484          return value_pos_atr (arg1);
7485
7486          case ATR_SIZE:
7487          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7488          if (noside == EVAL_SKIP)
7489          goto nosideret;
7490          else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7491          return value_zero (builtin_type_ada_int, not_lval);
7492          else
7493          return value_from_longest (builtin_type_ada_int,
7494          TARGET_CHAR_BIT 
7495          * TYPE_LENGTH (VALUE_TYPE (arg1)));
7496
7497          case ATR_VAL:
7498          evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
7499          arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7500          type = exp->elts[pc + 5].type;
7501          if (noside == EVAL_SKIP)
7502          goto nosideret;
7503          else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7504          return value_zero (type, not_lval);
7505          else 
7506          return value_val_atr (type, arg1);
7507          } */
7508     case BINOP_EXP:
7509       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7510       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7511       if (noside == EVAL_SKIP)
7512         goto nosideret;
7513       if (binop_user_defined_p (op, arg1, arg2))
7514         return unwrap_value (value_x_binop (arg1, arg2, op, OP_NULL,
7515                                             EVAL_NORMAL));
7516       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7517         return value_zero (VALUE_TYPE (arg1), not_lval);
7518       else
7519         return value_binop (arg1, arg2, op);
7520
7521     case UNOP_PLUS:
7522       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7523       if (noside == EVAL_SKIP)
7524         goto nosideret;
7525       if (unop_user_defined_p (op, arg1))
7526         return unwrap_value (value_x_unop (arg1, op, EVAL_NORMAL));
7527       else
7528         return arg1;
7529
7530     case UNOP_ABS:
7531       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7532       if (noside == EVAL_SKIP)
7533         goto nosideret;
7534       if (value_less (arg1, value_zero (VALUE_TYPE (arg1), not_lval)))
7535         return value_neg (arg1);
7536       else
7537         return arg1;
7538
7539     case UNOP_IND:
7540       if (expect_type && TYPE_CODE (expect_type) == TYPE_CODE_PTR)
7541         expect_type = TYPE_TARGET_TYPE (check_typedef (expect_type));
7542       arg1 = evaluate_subexp (expect_type, exp, pos, noside);
7543       if (noside == EVAL_SKIP)
7544         goto nosideret;
7545       type = check_typedef (VALUE_TYPE (arg1));
7546       if (noside == EVAL_AVOID_SIDE_EFFECTS)
7547         {
7548           if (ada_is_array_descriptor (type))
7549             /* GDB allows dereferencing GNAT array descriptors. */
7550             {
7551               struct type *arrType = ada_type_of_array (arg1, 0);
7552               if (arrType == NULL)
7553                 error ("Attempt to dereference null array pointer.");
7554               return value_at_lazy (arrType, 0, NULL);
7555             }
7556           else if (TYPE_CODE (type) == TYPE_CODE_PTR
7557                    || TYPE_CODE (type) == TYPE_CODE_REF
7558                    /* In C you can dereference an array to get the 1st elt.  */
7559                    || TYPE_CODE (type) == TYPE_CODE_ARRAY)
7560             return
7561               value_zero
7562               (to_static_fixed_type
7563                (ada_aligned_type (check_typedef (TYPE_TARGET_TYPE (type)))),
7564                lval_memory);
7565           else if (TYPE_CODE (type) == TYPE_CODE_INT)
7566             /* GDB allows dereferencing an int.  */
7567             return value_zero (builtin_type_int, lval_memory);
7568           else
7569             error ("Attempt to take contents of a non-pointer value.");
7570         }
7571       arg1 = ada_coerce_ref (arg1);
7572       type = check_typedef (VALUE_TYPE (arg1));
7573
7574       if (ada_is_array_descriptor (type))
7575         /* GDB allows dereferencing GNAT array descriptors. */
7576         return ada_coerce_to_simple_array (arg1);
7577       else
7578         return ada_value_ind (arg1);
7579
7580     case STRUCTOP_STRUCT:
7581       tem = longest_to_int (exp->elts[pc + 1].longconst);
7582       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
7583       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7584       if (noside == EVAL_SKIP)
7585         goto nosideret;
7586       if (noside == EVAL_AVOID_SIDE_EFFECTS)
7587         return value_zero (ada_aligned_type
7588                            (ada_lookup_struct_elt_type (VALUE_TYPE (arg1),
7589                                                         &exp->elts[pc +
7590                                                                    2].string,
7591                                                         0, NULL)),
7592                            lval_memory);
7593       else
7594         return unwrap_value (ada_value_struct_elt (arg1,
7595                                                    &exp->elts[pc + 2].string,
7596                                                    "record"));
7597     case OP_TYPE:
7598       /* The value is not supposed to be used. This is here to make it
7599          easier to accommodate expressions that contain types. */
7600       (*pos) += 2;
7601       if (noside == EVAL_SKIP)
7602         goto nosideret;
7603       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
7604         return allocate_value (builtin_type_void);
7605       else
7606         error ("Attempt to use a type name as an expression");
7607
7608     case STRUCTOP_PTR:
7609       tem = longest_to_int (exp->elts[pc + 1].longconst);
7610       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
7611       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
7612       if (noside == EVAL_SKIP)
7613         goto nosideret;
7614       if (noside == EVAL_AVOID_SIDE_EFFECTS)
7615         return value_zero (ada_aligned_type
7616                            (ada_lookup_struct_elt_type (VALUE_TYPE (arg1),
7617                                                         &exp->elts[pc +
7618                                                                    2].string,
7619                                                         0, NULL)),
7620                            lval_memory);
7621       else
7622         return unwrap_value (ada_value_struct_elt (arg1,
7623                                                    &exp->elts[pc + 2].string,
7624                                                    "record access"));
7625     }
7626
7627 nosideret:
7628   return value_from_longest (builtin_type_long, (LONGEST) 1);
7629 }
7630 \f
7631
7632                                 /* Fixed point */
7633
7634 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
7635    type name that encodes the 'small and 'delta information.
7636    Otherwise, return NULL. */
7637
7638 static const char *
7639 fixed_type_info (struct type *type)
7640 {
7641   const char *name = ada_type_name (type);
7642   enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
7643
7644   if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
7645     {
7646       const char *tail = strstr (name, "___XF_");
7647       if (tail == NULL)
7648         return NULL;
7649       else
7650         return tail + 5;
7651     }
7652   else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
7653     return fixed_type_info (TYPE_TARGET_TYPE (type));
7654   else
7655     return NULL;
7656 }
7657
7658 /* Returns non-zero iff TYPE represents an Ada fixed-point type. */
7659
7660 int
7661 ada_is_fixed_point_type (struct type *type)
7662 {
7663   return fixed_type_info (type) != NULL;
7664 }
7665
7666 /* Assuming that TYPE is the representation of an Ada fixed-point
7667    type, return its delta, or -1 if the type is malformed and the
7668    delta cannot be determined. */
7669
7670 DOUBLEST
7671 ada_delta (struct type *type)
7672 {
7673   const char *encoding = fixed_type_info (type);
7674   long num, den;
7675
7676   if (sscanf (encoding, "_%ld_%ld", &num, &den) < 2)
7677     return -1.0;
7678   else
7679     return (DOUBLEST) num / (DOUBLEST) den;
7680 }
7681
7682 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
7683    factor ('SMALL value) associated with the type. */
7684
7685 static DOUBLEST
7686 scaling_factor (struct type *type)
7687 {
7688   const char *encoding = fixed_type_info (type);
7689   unsigned long num0, den0, num1, den1;
7690   int n;
7691
7692   n = sscanf (encoding, "_%lu_%lu_%lu_%lu", &num0, &den0, &num1, &den1);
7693
7694   if (n < 2)
7695     return 1.0;
7696   else if (n == 4)
7697     return (DOUBLEST) num1 / (DOUBLEST) den1;
7698   else
7699     return (DOUBLEST) num0 / (DOUBLEST) den0;
7700 }
7701
7702
7703 /* Assuming that X is the representation of a value of fixed-point
7704    type TYPE, return its floating-point equivalent. */
7705
7706 DOUBLEST
7707 ada_fixed_to_float (struct type *type, LONGEST x)
7708 {
7709   return (DOUBLEST) x *scaling_factor (type);
7710 }
7711
7712 /* The representation of a fixed-point value of type TYPE 
7713    corresponding to the value X. */
7714
7715 LONGEST
7716 ada_float_to_fixed (struct type *type, DOUBLEST x)
7717 {
7718   return (LONGEST) (x / scaling_factor (type) + 0.5);
7719 }
7720
7721
7722                                 /* VAX floating formats */
7723
7724 /* Non-zero iff TYPE represents one of the special VAX floating-point
7725    types. */
7726 int
7727 ada_is_vax_floating_type (struct type *type)
7728 {
7729   int name_len =
7730     (ada_type_name (type) == NULL) ? 0 : strlen (ada_type_name (type));
7731   return
7732     name_len > 6
7733     && (TYPE_CODE (type) == TYPE_CODE_INT
7734         || TYPE_CODE (type) == TYPE_CODE_RANGE)
7735     && STREQN (ada_type_name (type) + name_len - 6, "___XF", 5);
7736 }
7737
7738 /* The type of special VAX floating-point type this is, assuming
7739    ada_is_vax_floating_point */
7740 int
7741 ada_vax_float_type_suffix (struct type *type)
7742 {
7743   return ada_type_name (type)[strlen (ada_type_name (type)) - 1];
7744 }
7745
7746 /* A value representing the special debugging function that outputs 
7747    VAX floating-point values of the type represented by TYPE.  Assumes
7748    ada_is_vax_floating_type (TYPE). */
7749 struct value *
7750 ada_vax_float_print_function (struct type *type)
7751 {
7752   switch (ada_vax_float_type_suffix (type))
7753     {
7754     case 'F':
7755       return get_var_value ("DEBUG_STRING_F", 0);
7756     case 'D':
7757       return get_var_value ("DEBUG_STRING_D", 0);
7758     case 'G':
7759       return get_var_value ("DEBUG_STRING_G", 0);
7760     default:
7761       error ("invalid VAX floating-point type");
7762     }
7763 }
7764 \f
7765
7766                                 /* Range types */
7767
7768 /* Scan STR beginning at position K for a discriminant name, and
7769    return the value of that discriminant field of DVAL in *PX.  If
7770    PNEW_K is not null, put the position of the character beyond the
7771    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
7772    not alter *PX and *PNEW_K if unsuccessful. */
7773
7774 static int
7775 scan_discrim_bound (char *, int k, struct value *dval, LONGEST * px,
7776                     int *pnew_k)
7777 {
7778   static char *bound_buffer = NULL;
7779   static size_t bound_buffer_len = 0;
7780   char *bound;
7781   char *pend;
7782   struct value *bound_val;
7783
7784   if (dval == NULL || str == NULL || str[k] == '\0')
7785     return 0;
7786
7787   pend = strstr (str + k, "__");
7788   if (pend == NULL)
7789     {
7790       bound = str + k;
7791       k += strlen (bound);
7792     }
7793   else
7794     {
7795       GROW_VECT (bound_buffer, bound_buffer_len, pend - (str + k) + 1);
7796       bound = bound_buffer;
7797       strncpy (bound_buffer, str + k, pend - (str + k));
7798       bound[pend - (str + k)] = '\0';
7799       k = pend - str;
7800     }
7801
7802   bound_val = ada_search_struct_field (bound, dval, 0, VALUE_TYPE (dval));
7803   if (bound_val == NULL)
7804     return 0;
7805
7806   *px = value_as_long (bound_val);
7807   if (pnew_k != NULL)
7808     *pnew_k = k;
7809   return 1;
7810 }
7811
7812 /* Value of variable named NAME in the current environment.  If
7813    no such variable found, then if ERR_MSG is null, returns 0, and
7814    otherwise causes an error with message ERR_MSG. */
7815 static struct value *
7816 get_var_value (char *name, char *err_msg)
7817 {
7818   struct symbol **syms;
7819   struct block **blocks;
7820   int nsyms;
7821
7822   nsyms =
7823     ada_lookup_symbol_list (name, get_selected_block (NULL), VAR_NAMESPACE,
7824                             &syms, &blocks);
7825
7826   if (nsyms != 1)
7827     {
7828       if (err_msg == NULL)
7829         return 0;
7830       else
7831         error ("%s", err_msg);
7832     }
7833
7834   return value_of_variable (syms[0], blocks[0]);
7835 }
7836
7837 /* Value of integer variable named NAME in the current environment.  If
7838    no such variable found, then if ERR_MSG is null, returns 0, and sets
7839    *FLAG to 0.  If successful, sets *FLAG to 1. */
7840 LONGEST
7841 get_int_var_value (char *name, char *err_msg, int *flag)
7842 {
7843   struct value *var_val = get_var_value (name, err_msg);
7844
7845   if (var_val == 0)
7846     {
7847       if (flag != NULL)
7848         *flag = 0;
7849       return 0;
7850     }
7851   else
7852     {
7853       if (flag != NULL)
7854         *flag = 1;
7855       return value_as_long (var_val);
7856     }
7857 }
7858
7859
7860 /* Return a range type whose base type is that of the range type named
7861    NAME in the current environment, and whose bounds are calculated
7862    from NAME according to the GNAT range encoding conventions. 
7863    Extract discriminant values, if needed, from DVAL.  If a new type
7864    must be created, allocate in OBJFILE's space.  The bounds
7865    information, in general, is encoded in NAME, the base type given in
7866    the named range type. */
7867
7868 static struct type *
7869 to_fixed_range_type (char *name, struct value *dval, struct objfile *objfile)
7870 {
7871   struct type *raw_type = ada_find_any_type (name);
7872   struct type *base_type;
7873   LONGEST low, high;
7874   char *subtype_info;
7875
7876   if (raw_type == NULL)
7877     base_type = builtin_type_int;
7878   else if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
7879     base_type = TYPE_TARGET_TYPE (raw_type);
7880   else
7881     base_type = raw_type;
7882
7883   subtype_info = strstr (name, "___XD");
7884   if (subtype_info == NULL)
7885     return raw_type;
7886   else
7887     {
7888       static char *name_buf = NULL;
7889       static size_t name_len = 0;
7890       int prefix_len = subtype_info - name;
7891       LONGEST L, U;
7892       struct type *type;
7893       char *bounds_str;
7894       int n;
7895
7896       GROW_VECT (name_buf, name_len, prefix_len + 5);
7897       strncpy (name_buf, name, prefix_len);
7898       name_buf[prefix_len] = '\0';
7899
7900       subtype_info += 5;
7901       bounds_str = strchr (subtype_info, '_');
7902       n = 1;
7903
7904       if (*subtype_info == 'L')
7905         {
7906           if (!ada_scan_number (bounds_str, n, &L, &n)
7907               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
7908             return raw_type;
7909           if (bounds_str[n] == '_')
7910             n += 2;
7911           else if (bounds_str[n] == '.')        /* FIXME? SGI Workshop kludge. */
7912             n += 1;
7913           subtype_info += 1;
7914         }
7915       else
7916         {
7917           strcpy (name_buf + prefix_len, "___L");
7918           L = get_int_var_value (name_buf, "Index bound unknown.", NULL);
7919         }
7920
7921       if (*subtype_info == 'U')
7922         {
7923           if (!ada_scan_number (bounds_str, n, &U, &n)
7924               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
7925             return raw_type;
7926         }
7927       else
7928         {
7929           strcpy (name_buf + prefix_len, "___U");
7930           U = get_int_var_value (name_buf, "Index bound unknown.", NULL);
7931         }
7932
7933       if (objfile == NULL)
7934         objfile = TYPE_OBJFILE (base_type);
7935       type = create_range_type (alloc_type (objfile), base_type, L, U);
7936       TYPE_NAME (type) = name;
7937       return type;
7938     }
7939 }
7940
7941 /* True iff NAME is the name of a range type. */
7942 int
7943 ada_is_range_type_name (const char *name)
7944 {
7945   return (name != NULL && strstr (name, "___XD"));
7946 }
7947 \f
7948
7949                                 /* Modular types */
7950
7951 /* True iff TYPE is an Ada modular type. */
7952 int
7953 ada_is_modular_type (struct type *type)
7954 {
7955   /* FIXME: base_type should be declared in gdbtypes.h, implemented in
7956      valarith.c */
7957   struct type *subranged_type;  /* = base_type (type); */
7958
7959   return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
7960           && TYPE_CODE (subranged_type) != TYPE_CODE_ENUM
7961           && TYPE_UNSIGNED (subranged_type));
7962 }
7963
7964 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
7965 LONGEST
7966 ada_modulus (struct type * type)
7967 {
7968   return TYPE_HIGH_BOUND (type) + 1;
7969 }
7970 \f
7971
7972
7973                                 /* Operators */
7974
7975 /* Table mapping opcodes into strings for printing operators
7976    and precedences of the operators.  */
7977
7978 static const struct op_print ada_op_print_tab[] = {
7979   {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
7980   {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
7981   {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
7982   {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
7983   {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
7984   {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
7985   {"=", BINOP_EQUAL, PREC_EQUAL, 0},
7986   {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
7987   {"<=", BINOP_LEQ, PREC_ORDER, 0},
7988   {">=", BINOP_GEQ, PREC_ORDER, 0},
7989   {">", BINOP_GTR, PREC_ORDER, 0},
7990   {"<", BINOP_LESS, PREC_ORDER, 0},
7991   {">>", BINOP_RSH, PREC_SHIFT, 0},
7992   {"<<", BINOP_LSH, PREC_SHIFT, 0},
7993   {"+", BINOP_ADD, PREC_ADD, 0},
7994   {"-", BINOP_SUB, PREC_ADD, 0},
7995   {"&", BINOP_CONCAT, PREC_ADD, 0},
7996   {"*", BINOP_MUL, PREC_MUL, 0},
7997   {"/", BINOP_DIV, PREC_MUL, 0},
7998   {"rem", BINOP_REM, PREC_MUL, 0},
7999   {"mod", BINOP_MOD, PREC_MUL, 0},
8000   {"**", BINOP_EXP, PREC_REPEAT, 0},
8001   {"@", BINOP_REPEAT, PREC_REPEAT, 0},
8002   {"-", UNOP_NEG, PREC_PREFIX, 0},
8003   {"+", UNOP_PLUS, PREC_PREFIX, 0},
8004   {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
8005   {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
8006   {"abs ", UNOP_ABS, PREC_PREFIX, 0},
8007   {".all", UNOP_IND, PREC_SUFFIX, 1},   /* FIXME: postfix .ALL */
8008   {"'access", UNOP_ADDR, PREC_SUFFIX, 1},       /* FIXME: postfix 'ACCESS */
8009   {NULL, 0, 0, 0}
8010 };
8011 \f
8012                         /* Assorted Types and Interfaces */
8013
8014 struct type *builtin_type_ada_int;
8015 struct type *builtin_type_ada_short;
8016 struct type *builtin_type_ada_long;
8017 struct type *builtin_type_ada_long_long;
8018 struct type *builtin_type_ada_char;
8019 struct type *builtin_type_ada_float;
8020 struct type *builtin_type_ada_double;
8021 struct type *builtin_type_ada_long_double;
8022 struct type *builtin_type_ada_natural;
8023 struct type *builtin_type_ada_positive;
8024 struct type *builtin_type_ada_system_address;
8025
8026 struct type **const (ada_builtin_types[]) =
8027 {
8028
8029   &builtin_type_ada_int,
8030     &builtin_type_ada_long,
8031     &builtin_type_ada_short,
8032     &builtin_type_ada_char,
8033     &builtin_type_ada_float,
8034     &builtin_type_ada_double,
8035     &builtin_type_ada_long_long,
8036     &builtin_type_ada_long_double,
8037     &builtin_type_ada_natural, &builtin_type_ada_positive,
8038     /* The following types are carried over from C for convenience. */
8039 &builtin_type_int,
8040     &builtin_type_long,
8041     &builtin_type_short,
8042     &builtin_type_char,
8043     &builtin_type_float,
8044     &builtin_type_double,
8045     &builtin_type_long_long,
8046     &builtin_type_void,
8047     &builtin_type_signed_char,
8048     &builtin_type_unsigned_char,
8049     &builtin_type_unsigned_short,
8050     &builtin_type_unsigned_int,
8051     &builtin_type_unsigned_long,
8052     &builtin_type_unsigned_long_long,
8053     &builtin_type_long_double,
8054     &builtin_type_complex, &builtin_type_double_complex, 0};
8055
8056 /* Not really used, but needed in the ada_language_defn. */
8057 static void
8058 emit_char (int c, struct ui_file *stream, int quoter)
8059 {
8060   ada_emit_char (c, stream, quoter, 1);
8061 }
8062
8063 const struct language_defn ada_language_defn = {
8064   "ada",                        /* Language name */
8065   /*  language_ada, */
8066   language_unknown,
8067   /* FIXME: language_ada should be defined in defs.h */
8068   ada_builtin_types,
8069   range_check_off,
8070   type_check_off,
8071   case_sensitive_on,            /* Yes, Ada is case-insensitive, but
8072                                  * that's not quite what this means. */
8073   ada_parse,
8074   ada_error,
8075   ada_evaluate_subexp,
8076   ada_printchar,                /* Print a character constant */
8077   ada_printstr,                 /* Function to print string constant */
8078   emit_char,                    /* Function to print single char (not used) */
8079   ada_create_fundamental_type,  /* Create fundamental type in this language */
8080   ada_print_type,               /* Print a type using appropriate syntax */
8081   ada_val_print,                /* Print a value using appropriate syntax */
8082   ada_value_print,              /* Print a top-level value */
8083   {"", "", "", ""},             /* Binary format info */
8084 #if 0
8085   {"8#%lo#", "8#", "o", "#"},   /* Octal format info */
8086   {"%ld", "", "d", ""},         /* Decimal format info */
8087   {"16#%lx#", "16#", "x", "#"}, /* Hex format info */
8088 #else
8089   /* Copied from c-lang.c. */
8090   {"0%lo", "0", "o", ""},       /* Octal format info */
8091   {"%ld", "", "d", ""},         /* Decimal format info */
8092   {"0x%lx", "0x", "x", ""},     /* Hex format info */
8093 #endif
8094   ada_op_print_tab,             /* expression operators for printing */
8095   1,                            /* c-style arrays (FIXME?) */
8096   0,                            /* String lower bound (FIXME?) */
8097   &builtin_type_ada_char,
8098   LANG_MAGIC
8099 };
8100
8101 void
8102 _initialize_ada_language (void)
8103 {
8104   builtin_type_ada_int =
8105     init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT,
8106                0, "integer", (struct objfile *) NULL);
8107   builtin_type_ada_long =
8108     init_type (TYPE_CODE_INT, TARGET_LONG_BIT / TARGET_CHAR_BIT,
8109                0, "long_integer", (struct objfile *) NULL);
8110   builtin_type_ada_short =
8111     init_type (TYPE_CODE_INT, TARGET_SHORT_BIT / TARGET_CHAR_BIT,
8112                0, "short_integer", (struct objfile *) NULL);
8113   builtin_type_ada_char =
8114     init_type (TYPE_CODE_INT, TARGET_CHAR_BIT / TARGET_CHAR_BIT,
8115                0, "character", (struct objfile *) NULL);
8116   builtin_type_ada_float =
8117     init_type (TYPE_CODE_FLT, TARGET_FLOAT_BIT / TARGET_CHAR_BIT,
8118                0, "float", (struct objfile *) NULL);
8119   builtin_type_ada_double =
8120     init_type (TYPE_CODE_FLT, TARGET_DOUBLE_BIT / TARGET_CHAR_BIT,
8121                0, "long_float", (struct objfile *) NULL);
8122   builtin_type_ada_long_long =
8123     init_type (TYPE_CODE_INT, TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
8124                0, "long_long_integer", (struct objfile *) NULL);
8125   builtin_type_ada_long_double =
8126     init_type (TYPE_CODE_FLT, TARGET_LONG_DOUBLE_BIT / TARGET_CHAR_BIT,
8127                0, "long_long_float", (struct objfile *) NULL);
8128   builtin_type_ada_natural =
8129     init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT,
8130                0, "natural", (struct objfile *) NULL);
8131   builtin_type_ada_positive =
8132     init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT,
8133                0, "positive", (struct objfile *) NULL);
8134
8135
8136   builtin_type_ada_system_address =
8137     lookup_pointer_type (init_type (TYPE_CODE_VOID, 1, 0, "void",
8138                                     (struct objfile *) NULL));
8139   TYPE_NAME (builtin_type_ada_system_address) = "system__address";
8140
8141   add_language (&ada_language_defn);
8142
8143   add_show_from_set
8144     (add_set_cmd ("varsize-limit", class_support, var_uinteger,
8145                   (char *) &varsize_limit,
8146                   "Set maximum bytes in dynamic-sized object.",
8147                   &setlist), &showlist);
8148   varsize_limit = 65536;
8149
8150   add_com ("begin", class_breakpoint, begin_command,
8151            "Start the debugged program, stopping at the beginning of the\n\
8152 main program.  You may specify command-line arguments to give it, as for\n\
8153 the \"run\" command (q.v.).");
8154 }
8155
8156
8157 /* Create a fundamental Ada type using default reasonable for the current
8158    target machine.
8159
8160    Some object/debugging file formats (DWARF version 1, COFF, etc) do not
8161    define fundamental types such as "int" or "double".  Others (stabs or
8162    DWARF version 2, etc) do define fundamental types.  For the formats which
8163    don't provide fundamental types, gdb can create such types using this
8164    function.
8165
8166    FIXME:  Some compilers distinguish explicitly signed integral types
8167    (signed short, signed int, signed long) from "regular" integral types
8168    (short, int, long) in the debugging information.  There is some dis-
8169    agreement as to how useful this feature is.  In particular, gcc does
8170    not support this.  Also, only some debugging formats allow the
8171    distinction to be passed on to a debugger.  For now, we always just
8172    use "short", "int", or "long" as the type name, for both the implicit
8173    and explicitly signed types.  This also makes life easier for the
8174    gdb test suite since we don't have to account for the differences
8175    in output depending upon what the compiler and debugging format
8176    support.  We will probably have to re-examine the issue when gdb
8177    starts taking it's fundamental type information directly from the
8178    debugging information supplied by the compiler.  fnf@cygnus.com */
8179
8180 static struct type *
8181 ada_create_fundamental_type (struct objfile *objfile, int typeid)
8182 {
8183   struct type *type = NULL;
8184
8185   switch (typeid)
8186     {
8187     default:
8188       /* FIXME:  For now, if we are asked to produce a type not in this
8189          language, create the equivalent of a C integer type with the
8190          name "<?type?>".  When all the dust settles from the type
8191          reconstruction work, this should probably become an error. */
8192       type = init_type (TYPE_CODE_INT,
8193                         TARGET_INT_BIT / TARGET_CHAR_BIT,
8194                         0, "<?type?>", objfile);
8195       warning ("internal error: no Ada fundamental type %d", typeid);
8196       break;
8197     case FT_VOID:
8198       type = init_type (TYPE_CODE_VOID,
8199                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
8200                         0, "void", objfile);
8201       break;
8202     case FT_CHAR:
8203       type = init_type (TYPE_CODE_INT,
8204                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
8205                         0, "character", objfile);
8206       break;
8207     case FT_SIGNED_CHAR:
8208       type = init_type (TYPE_CODE_INT,
8209                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
8210                         0, "signed char", objfile);
8211       break;
8212     case FT_UNSIGNED_CHAR:
8213       type = init_type (TYPE_CODE_INT,
8214                         TARGET_CHAR_BIT / TARGET_CHAR_BIT,
8215                         TYPE_FLAG_UNSIGNED, "unsigned char", objfile);
8216       break;
8217     case FT_SHORT:
8218       type = init_type (TYPE_CODE_INT,
8219                         TARGET_SHORT_BIT / TARGET_CHAR_BIT,
8220                         0, "short_integer", objfile);
8221       break;
8222     case FT_SIGNED_SHORT:
8223       type = init_type (TYPE_CODE_INT,
8224                         TARGET_SHORT_BIT / TARGET_CHAR_BIT,
8225                         0, "short_integer", objfile);
8226       break;
8227     case FT_UNSIGNED_SHORT:
8228       type = init_type (TYPE_CODE_INT,
8229                         TARGET_SHORT_BIT / TARGET_CHAR_BIT,
8230                         TYPE_FLAG_UNSIGNED, "unsigned short", objfile);
8231       break;
8232     case FT_INTEGER:
8233       type = init_type (TYPE_CODE_INT,
8234                         TARGET_INT_BIT / TARGET_CHAR_BIT,
8235                         0, "integer", objfile);
8236       break;
8237     case FT_SIGNED_INTEGER:
8238       type = init_type (TYPE_CODE_INT, TARGET_INT_BIT / TARGET_CHAR_BIT, 0, "integer", objfile);        /* FIXME -fnf */
8239       break;
8240     case FT_UNSIGNED_INTEGER:
8241       type = init_type (TYPE_CODE_INT,
8242                         TARGET_INT_BIT / TARGET_CHAR_BIT,
8243                         TYPE_FLAG_UNSIGNED, "unsigned int", objfile);
8244       break;
8245     case FT_LONG:
8246       type = init_type (TYPE_CODE_INT,
8247                         TARGET_LONG_BIT / TARGET_CHAR_BIT,
8248                         0, "long_integer", objfile);
8249       break;
8250     case FT_SIGNED_LONG:
8251       type = init_type (TYPE_CODE_INT,
8252                         TARGET_LONG_BIT / TARGET_CHAR_BIT,
8253                         0, "long_integer", objfile);
8254       break;
8255     case FT_UNSIGNED_LONG:
8256       type = init_type (TYPE_CODE_INT,
8257                         TARGET_LONG_BIT / TARGET_CHAR_BIT,
8258                         TYPE_FLAG_UNSIGNED, "unsigned long", objfile);
8259       break;
8260     case FT_LONG_LONG:
8261       type = init_type (TYPE_CODE_INT,
8262                         TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
8263                         0, "long_long_integer", objfile);
8264       break;
8265     case FT_SIGNED_LONG_LONG:
8266       type = init_type (TYPE_CODE_INT,
8267                         TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
8268                         0, "long_long_integer", objfile);
8269       break;
8270     case FT_UNSIGNED_LONG_LONG:
8271       type = init_type (TYPE_CODE_INT,
8272                         TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
8273                         TYPE_FLAG_UNSIGNED, "unsigned long long", objfile);
8274       break;
8275     case FT_FLOAT:
8276       type = init_type (TYPE_CODE_FLT,
8277                         TARGET_FLOAT_BIT / TARGET_CHAR_BIT,
8278                         0, "float", objfile);
8279       break;
8280     case FT_DBL_PREC_FLOAT:
8281       type = init_type (TYPE_CODE_FLT,
8282                         TARGET_DOUBLE_BIT / TARGET_CHAR_BIT,
8283                         0, "long_float", objfile);
8284       break;
8285     case FT_EXT_PREC_FLOAT:
8286       type = init_type (TYPE_CODE_FLT,
8287                         TARGET_LONG_DOUBLE_BIT / TARGET_CHAR_BIT,
8288                         0, "long_long_float", objfile);
8289       break;
8290     }
8291   return (type);
8292 }
8293
8294 void
8295 ada_dump_symtab (struct symtab *s)
8296 {
8297   int i;
8298   fprintf (stderr, "New symtab: [\n");
8299   fprintf (stderr, "  Name: %s/%s;\n",
8300            s->dirname ? s->dirname : "?", s->filename ? s->filename : "?");
8301   fprintf (stderr, "  Format: %s;\n", s->debugformat);
8302   if (s->linetable != NULL)
8303     {
8304       fprintf (stderr, "  Line table (section %d):\n", s->block_line_section);
8305       for (i = 0; i < s->linetable->nitems; i += 1)
8306         {
8307           struct linetable_entry *e = s->linetable->item + i;
8308           fprintf (stderr, "    %4ld: %8lx\n", (long) e->line, (long) e->pc);
8309         }
8310     }
8311   fprintf (stderr, "]\n");
8312 }