8fccfe930191c2cbf19c4bee41df5776d741bf64
[external/binutils.git] / gdb / valops.c
1 /* Perform non-arithmetic operations on values, for GDB.
2
3    Copyright (C) 1986-2018 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 3 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, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "value.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbcore.h"
27 #include "target.h"
28 #include "demangle.h"
29 #include "language.h"
30 #include "gdbcmd.h"
31 #include "regcache.h"
32 #include "cp-abi.h"
33 #include "block.h"
34 #include "infcall.h"
35 #include "dictionary.h"
36 #include "cp-support.h"
37 #include "target-float.h"
38 #include "tracepoint.h"
39 #include "observer.h"
40 #include "objfiles.h"
41 #include "extension.h"
42 #include "byte-vector.h"
43
44 extern unsigned int overload_debug;
45 /* Local functions.  */
46
47 static int typecmp (int staticp, int varargs, int nargs,
48                     struct field t1[], struct value *t2[]);
49
50 static struct value *search_struct_field (const char *, struct value *, 
51                                           struct type *, int);
52
53 static struct value *search_struct_method (const char *, struct value **,
54                                            struct value **,
55                                            LONGEST, int *, struct type *);
56
57 static int find_oload_champ_namespace (struct value **, int,
58                                        const char *, const char *,
59                                        struct symbol ***,
60                                        struct badness_vector **,
61                                        const int no_adl);
62
63 static
64 int find_oload_champ_namespace_loop (struct value **, int,
65                                      const char *, const char *,
66                                      int, struct symbol ***,
67                                      struct badness_vector **, int *,
68                                      const int no_adl);
69
70 static int find_oload_champ (struct value **, int, int,
71                              struct fn_field *,
72                              const std::vector<xmethod_worker_up> *,
73                              struct symbol **, struct badness_vector **);
74
75 static int oload_method_static_p (struct fn_field *, int);
76
77 enum oload_classification { STANDARD, NON_STANDARD, INCOMPATIBLE };
78
79 static enum
80 oload_classification classify_oload_match (struct badness_vector *,
81                                            int, int);
82
83 static struct value *value_struct_elt_for_reference (struct type *,
84                                                      int, struct type *,
85                                                      const char *,
86                                                      struct type *,
87                                                      int, enum noside);
88
89 static struct value *value_namespace_elt (const struct type *,
90                                           const char *, int , enum noside);
91
92 static struct value *value_maybe_namespace_elt (const struct type *,
93                                                 const char *, int,
94                                                 enum noside);
95
96 static CORE_ADDR allocate_space_in_inferior (int);
97
98 static struct value *cast_into_complex (struct type *, struct value *);
99
100 static void find_method_list (struct value **, const char *,
101                               LONGEST, struct type *, struct fn_field **, int *,
102                               std::vector<xmethod_worker_up> *,
103                               struct type **, LONGEST *);
104
105 #if 0
106 /* Flag for whether we want to abandon failed expression evals by
107    default.  */
108
109 static int auto_abandon = 0;
110 #endif
111
112 int overload_resolution = 0;
113 static void
114 show_overload_resolution (struct ui_file *file, int from_tty,
115                           struct cmd_list_element *c, 
116                           const char *value)
117 {
118   fprintf_filtered (file, _("Overload resolution in evaluating "
119                             "C++ functions is %s.\n"),
120                     value);
121 }
122
123 /* Find the address of function name NAME in the inferior.  If OBJF_P
124    is non-NULL, *OBJF_P will be set to the OBJFILE where the function
125    is defined.  */
126
127 struct value *
128 find_function_in_inferior (const char *name, struct objfile **objf_p)
129 {
130   struct block_symbol sym;
131
132   sym = lookup_symbol (name, 0, VAR_DOMAIN, 0);
133   if (sym.symbol != NULL)
134     {
135       if (SYMBOL_CLASS (sym.symbol) != LOC_BLOCK)
136         {
137           error (_("\"%s\" exists in this program but is not a function."),
138                  name);
139         }
140
141       if (objf_p)
142         *objf_p = symbol_objfile (sym.symbol);
143
144       return value_of_variable (sym.symbol, sym.block);
145     }
146   else
147     {
148       struct bound_minimal_symbol msymbol = 
149         lookup_bound_minimal_symbol (name);
150
151       if (msymbol.minsym != NULL)
152         {
153           struct objfile *objfile = msymbol.objfile;
154           struct gdbarch *gdbarch = get_objfile_arch (objfile);
155
156           struct type *type;
157           CORE_ADDR maddr;
158           type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
159           type = lookup_function_type (type);
160           type = lookup_pointer_type (type);
161           maddr = BMSYMBOL_VALUE_ADDRESS (msymbol);
162
163           if (objf_p)
164             *objf_p = objfile;
165
166           return value_from_pointer (type, maddr);
167         }
168       else
169         {
170           if (!target_has_execution)
171             error (_("evaluation of this expression "
172                      "requires the target program to be active"));
173           else
174             error (_("evaluation of this expression requires the "
175                      "program to have a function \"%s\"."),
176                    name);
177         }
178     }
179 }
180
181 /* Allocate NBYTES of space in the inferior using the inferior's
182    malloc and return a value that is a pointer to the allocated
183    space.  */
184
185 struct value *
186 value_allocate_space_in_inferior (int len)
187 {
188   struct objfile *objf;
189   struct value *val = find_function_in_inferior ("malloc", &objf);
190   struct gdbarch *gdbarch = get_objfile_arch (objf);
191   struct value *blocklen;
192
193   blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
194   val = call_function_by_hand (val, NULL, 1, &blocklen);
195   if (value_logical_not (val))
196     {
197       if (!target_has_execution)
198         error (_("No memory available to program now: "
199                  "you need to start the target first"));
200       else
201         error (_("No memory available to program: call to malloc failed"));
202     }
203   return val;
204 }
205
206 static CORE_ADDR
207 allocate_space_in_inferior (int len)
208 {
209   return value_as_long (value_allocate_space_in_inferior (len));
210 }
211
212 /* Cast struct value VAL to type TYPE and return as a value.
213    Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
214    for this to work.  Typedef to one of the codes is permitted.
215    Returns NULL if the cast is neither an upcast nor a downcast.  */
216
217 static struct value *
218 value_cast_structs (struct type *type, struct value *v2)
219 {
220   struct type *t1;
221   struct type *t2;
222   struct value *v;
223
224   gdb_assert (type != NULL && v2 != NULL);
225
226   t1 = check_typedef (type);
227   t2 = check_typedef (value_type (v2));
228
229   /* Check preconditions.  */
230   gdb_assert ((TYPE_CODE (t1) == TYPE_CODE_STRUCT
231                || TYPE_CODE (t1) == TYPE_CODE_UNION)
232               && !!"Precondition is that type is of STRUCT or UNION kind.");
233   gdb_assert ((TYPE_CODE (t2) == TYPE_CODE_STRUCT
234                || TYPE_CODE (t2) == TYPE_CODE_UNION)
235               && !!"Precondition is that value is of STRUCT or UNION kind");
236
237   if (TYPE_NAME (t1) != NULL
238       && TYPE_NAME (t2) != NULL
239       && !strcmp (TYPE_NAME (t1), TYPE_NAME (t2)))
240     return NULL;
241
242   /* Upcasting: look in the type of the source to see if it contains the
243      type of the target as a superclass.  If so, we'll need to
244      offset the pointer rather than just change its type.  */
245   if (TYPE_NAME (t1) != NULL)
246     {
247       v = search_struct_field (type_name_no_tag (t1),
248                                v2, t2, 1);
249       if (v)
250         return v;
251     }
252
253   /* Downcasting: look in the type of the target to see if it contains the
254      type of the source as a superclass.  If so, we'll need to
255      offset the pointer rather than just change its type.  */
256   if (TYPE_NAME (t2) != NULL)
257     {
258       /* Try downcasting using the run-time type of the value.  */
259       int full, using_enc;
260       LONGEST top;
261       struct type *real_type;
262
263       real_type = value_rtti_type (v2, &full, &top, &using_enc);
264       if (real_type)
265         {
266           v = value_full_object (v2, real_type, full, top, using_enc);
267           v = value_at_lazy (real_type, value_address (v));
268           real_type = value_type (v);
269
270           /* We might be trying to cast to the outermost enclosing
271              type, in which case search_struct_field won't work.  */
272           if (TYPE_NAME (real_type) != NULL
273               && !strcmp (TYPE_NAME (real_type), TYPE_NAME (t1)))
274             return v;
275
276           v = search_struct_field (type_name_no_tag (t2), v, real_type, 1);
277           if (v)
278             return v;
279         }
280
281       /* Try downcasting using information from the destination type
282          T2.  This wouldn't work properly for classes with virtual
283          bases, but those were handled above.  */
284       v = search_struct_field (type_name_no_tag (t2),
285                                value_zero (t1, not_lval), t1, 1);
286       if (v)
287         {
288           /* Downcasting is possible (t1 is superclass of v2).  */
289           CORE_ADDR addr2 = value_address (v2);
290
291           addr2 -= value_address (v) + value_embedded_offset (v);
292           return value_at (type, addr2);
293         }
294     }
295
296   return NULL;
297 }
298
299 /* Cast one pointer or reference type to another.  Both TYPE and
300    the type of ARG2 should be pointer types, or else both should be
301    reference types.  If SUBCLASS_CHECK is non-zero, this will force a
302    check to see whether TYPE is a superclass of ARG2's type.  If
303    SUBCLASS_CHECK is zero, then the subclass check is done only when
304    ARG2 is itself non-zero.  Returns the new pointer or reference.  */
305
306 struct value *
307 value_cast_pointers (struct type *type, struct value *arg2,
308                      int subclass_check)
309 {
310   struct type *type1 = check_typedef (type);
311   struct type *type2 = check_typedef (value_type (arg2));
312   struct type *t1 = check_typedef (TYPE_TARGET_TYPE (type1));
313   struct type *t2 = check_typedef (TYPE_TARGET_TYPE (type2));
314
315   if (TYPE_CODE (t1) == TYPE_CODE_STRUCT
316       && TYPE_CODE (t2) == TYPE_CODE_STRUCT
317       && (subclass_check || !value_logical_not (arg2)))
318     {
319       struct value *v2;
320
321       if (TYPE_IS_REFERENCE (type2))
322         v2 = coerce_ref (arg2);
323       else
324         v2 = value_ind (arg2);
325       gdb_assert (TYPE_CODE (check_typedef (value_type (v2)))
326                   == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
327       v2 = value_cast_structs (t1, v2);
328       /* At this point we have what we can have, un-dereference if needed.  */
329       if (v2)
330         {
331           struct value *v = value_addr (v2);
332
333           deprecated_set_value_type (v, type);
334           return v;
335         }
336     }
337
338   /* No superclass found, just change the pointer type.  */
339   arg2 = value_copy (arg2);
340   deprecated_set_value_type (arg2, type);
341   set_value_enclosing_type (arg2, type);
342   set_value_pointed_to_offset (arg2, 0);        /* pai: chk_val */
343   return arg2;
344 }
345
346 /* Cast value ARG2 to type TYPE and return as a value.
347    More general than a C cast: accepts any two types of the same length,
348    and if ARG2 is an lvalue it can be cast into anything at all.  */
349 /* In C++, casts may change pointer or object representations.  */
350
351 struct value *
352 value_cast (struct type *type, struct value *arg2)
353 {
354   enum type_code code1;
355   enum type_code code2;
356   int scalar;
357   struct type *type2;
358
359   int convert_to_boolean = 0;
360
361   if (value_type (arg2) == type)
362     return arg2;
363
364   /* Check if we are casting struct reference to struct reference.  */
365   if (TYPE_IS_REFERENCE (check_typedef (type)))
366     {
367       /* We dereference type; then we recurse and finally
368          we generate value of the given reference.  Nothing wrong with 
369          that.  */
370       struct type *t1 = check_typedef (type);
371       struct type *dereftype = check_typedef (TYPE_TARGET_TYPE (t1));
372       struct value *val = value_cast (dereftype, arg2);
373
374       return value_ref (val, TYPE_CODE (t1));
375     }
376
377   if (TYPE_IS_REFERENCE (check_typedef (value_type (arg2))))
378     /* We deref the value and then do the cast.  */
379     return value_cast (type, coerce_ref (arg2)); 
380
381   /* Strip typedefs / resolve stubs in order to get at the type's
382      code/length, but remember the original type, to use as the
383      resulting type of the cast, in case it was a typedef.  */
384   struct type *to_type = type;
385
386   type = check_typedef (type);
387   code1 = TYPE_CODE (type);
388   arg2 = coerce_ref (arg2);
389   type2 = check_typedef (value_type (arg2));
390
391   /* You can't cast to a reference type.  See value_cast_pointers
392      instead.  */
393   gdb_assert (!TYPE_IS_REFERENCE (type));
394
395   /* A cast to an undetermined-length array_type, such as 
396      (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
397      where N is sizeof(OBJECT)/sizeof(TYPE).  */
398   if (code1 == TYPE_CODE_ARRAY)
399     {
400       struct type *element_type = TYPE_TARGET_TYPE (type);
401       unsigned element_length = TYPE_LENGTH (check_typedef (element_type));
402
403       if (element_length > 0 && TYPE_ARRAY_UPPER_BOUND_IS_UNDEFINED (type))
404         {
405           struct type *range_type = TYPE_INDEX_TYPE (type);
406           int val_length = TYPE_LENGTH (type2);
407           LONGEST low_bound, high_bound, new_length;
408
409           if (get_discrete_bounds (range_type, &low_bound, &high_bound) < 0)
410             low_bound = 0, high_bound = 0;
411           new_length = val_length / element_length;
412           if (val_length % element_length != 0)
413             warning (_("array element type size does not "
414                        "divide object size in cast"));
415           /* FIXME-type-allocation: need a way to free this type when
416              we are done with it.  */
417           range_type = create_static_range_type ((struct type *) NULL,
418                                                  TYPE_TARGET_TYPE (range_type),
419                                                  low_bound,
420                                                  new_length + low_bound - 1);
421           deprecated_set_value_type (arg2, 
422                                      create_array_type ((struct type *) NULL,
423                                                         element_type, 
424                                                         range_type));
425           return arg2;
426         }
427     }
428
429   if (current_language->c_style_arrays
430       && TYPE_CODE (type2) == TYPE_CODE_ARRAY
431       && !TYPE_VECTOR (type2))
432     arg2 = value_coerce_array (arg2);
433
434   if (TYPE_CODE (type2) == TYPE_CODE_FUNC)
435     arg2 = value_coerce_function (arg2);
436
437   type2 = check_typedef (value_type (arg2));
438   code2 = TYPE_CODE (type2);
439
440   if (code1 == TYPE_CODE_COMPLEX)
441     return cast_into_complex (to_type, arg2);
442   if (code1 == TYPE_CODE_BOOL)
443     {
444       code1 = TYPE_CODE_INT;
445       convert_to_boolean = 1;
446     }
447   if (code1 == TYPE_CODE_CHAR)
448     code1 = TYPE_CODE_INT;
449   if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
450     code2 = TYPE_CODE_INT;
451
452   scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
453             || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
454             || code2 == TYPE_CODE_RANGE);
455
456   if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
457       && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
458       && TYPE_NAME (type) != 0)
459     {
460       struct value *v = value_cast_structs (to_type, arg2);
461
462       if (v)
463         return v;
464     }
465
466   if (is_floating_type (type) && scalar)
467     {
468       if (is_floating_value (arg2))
469         {
470           struct value *v = allocate_value (to_type);
471           target_float_convert (value_contents (arg2), type2,
472                                 value_contents_raw (v), type);
473           return v;
474         }
475
476       /* The only option left is an integral type.  */
477       if (TYPE_UNSIGNED (type2))
478         return value_from_ulongest (to_type, value_as_long (arg2));
479       else
480         return value_from_longest (to_type, value_as_long (arg2));
481     }
482   else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
483             || code1 == TYPE_CODE_RANGE)
484            && (scalar || code2 == TYPE_CODE_PTR
485                || code2 == TYPE_CODE_MEMBERPTR))
486     {
487       LONGEST longest;
488
489       /* When we cast pointers to integers, we mustn't use
490          gdbarch_pointer_to_address to find the address the pointer
491          represents, as value_as_long would.  GDB should evaluate
492          expressions just as the compiler would --- and the compiler
493          sees a cast as a simple reinterpretation of the pointer's
494          bits.  */
495       if (code2 == TYPE_CODE_PTR)
496         longest = extract_unsigned_integer
497                     (value_contents (arg2), TYPE_LENGTH (type2),
498                      gdbarch_byte_order (get_type_arch (type2)));
499       else
500         longest = value_as_long (arg2);
501       return value_from_longest (to_type, convert_to_boolean ?
502                                  (LONGEST) (longest ? 1 : 0) : longest);
503     }
504   else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT  
505                                       || code2 == TYPE_CODE_ENUM 
506                                       || code2 == TYPE_CODE_RANGE))
507     {
508       /* TYPE_LENGTH (type) is the length of a pointer, but we really
509          want the length of an address! -- we are really dealing with
510          addresses (i.e., gdb representations) not pointers (i.e.,
511          target representations) here.
512
513          This allows things like "print *(int *)0x01000234" to work
514          without printing a misleading message -- which would
515          otherwise occur when dealing with a target having two byte
516          pointers and four byte addresses.  */
517
518       int addr_bit = gdbarch_addr_bit (get_type_arch (type2));
519       LONGEST longest = value_as_long (arg2);
520
521       if (addr_bit < sizeof (LONGEST) * HOST_CHAR_BIT)
522         {
523           if (longest >= ((LONGEST) 1 << addr_bit)
524               || longest <= -((LONGEST) 1 << addr_bit))
525             warning (_("value truncated"));
526         }
527       return value_from_longest (to_type, longest);
528     }
529   else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
530            && value_as_long (arg2) == 0)
531     {
532       struct value *result = allocate_value (to_type);
533
534       cplus_make_method_ptr (to_type, value_contents_writeable (result), 0, 0);
535       return result;
536     }
537   else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
538            && value_as_long (arg2) == 0)
539     {
540       /* The Itanium C++ ABI represents NULL pointers to members as
541          minus one, instead of biasing the normal case.  */
542       return value_from_longest (to_type, -1);
543     }
544   else if (code1 == TYPE_CODE_ARRAY && TYPE_VECTOR (type)
545            && code2 == TYPE_CODE_ARRAY && TYPE_VECTOR (type2)
546            && TYPE_LENGTH (type) != TYPE_LENGTH (type2))
547     error (_("Cannot convert between vector values of different sizes"));
548   else if (code1 == TYPE_CODE_ARRAY && TYPE_VECTOR (type) && scalar
549            && TYPE_LENGTH (type) != TYPE_LENGTH (type2))
550     error (_("can only cast scalar to vector of same size"));
551   else if (code1 == TYPE_CODE_VOID)
552     {
553       return value_zero (to_type, not_lval);
554     }
555   else if (TYPE_LENGTH (type) == TYPE_LENGTH (type2))
556     {
557       if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
558         return value_cast_pointers (to_type, arg2, 0);
559
560       arg2 = value_copy (arg2);
561       deprecated_set_value_type (arg2, to_type);
562       set_value_enclosing_type (arg2, to_type);
563       set_value_pointed_to_offset (arg2, 0);    /* pai: chk_val */
564       return arg2;
565     }
566   else if (VALUE_LVAL (arg2) == lval_memory)
567     return value_at_lazy (to_type, value_address (arg2));
568   else
569     {
570       error (_("Invalid cast."));
571       return 0;
572     }
573 }
574
575 /* The C++ reinterpret_cast operator.  */
576
577 struct value *
578 value_reinterpret_cast (struct type *type, struct value *arg)
579 {
580   struct value *result;
581   struct type *real_type = check_typedef (type);
582   struct type *arg_type, *dest_type;
583   int is_ref = 0;
584   enum type_code dest_code, arg_code;
585
586   /* Do reference, function, and array conversion.  */
587   arg = coerce_array (arg);
588
589   /* Attempt to preserve the type the user asked for.  */
590   dest_type = type;
591
592   /* If we are casting to a reference type, transform
593      reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V).  */
594   if (TYPE_IS_REFERENCE (real_type))
595     {
596       is_ref = 1;
597       arg = value_addr (arg);
598       dest_type = lookup_pointer_type (TYPE_TARGET_TYPE (dest_type));
599       real_type = lookup_pointer_type (real_type);
600     }
601
602   arg_type = value_type (arg);
603
604   dest_code = TYPE_CODE (real_type);
605   arg_code = TYPE_CODE (arg_type);
606
607   /* We can convert pointer types, or any pointer type to int, or int
608      type to pointer.  */
609   if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
610       || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
611       || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
612       || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
613       || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
614       || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
615       || (dest_code == arg_code
616           && (dest_code == TYPE_CODE_PTR
617               || dest_code == TYPE_CODE_METHODPTR
618               || dest_code == TYPE_CODE_MEMBERPTR)))
619     result = value_cast (dest_type, arg);
620   else
621     error (_("Invalid reinterpret_cast"));
622
623   if (is_ref)
624     result = value_cast (type, value_ref (value_ind (result),
625                                           TYPE_CODE (type)));
626
627   return result;
628 }
629
630 /* A helper for value_dynamic_cast.  This implements the first of two
631    runtime checks: we iterate over all the base classes of the value's
632    class which are equal to the desired class; if only one of these
633    holds the value, then it is the answer.  */
634
635 static int
636 dynamic_cast_check_1 (struct type *desired_type,
637                       const gdb_byte *valaddr,
638                       LONGEST embedded_offset,
639                       CORE_ADDR address,
640                       struct value *val,
641                       struct type *search_type,
642                       CORE_ADDR arg_addr,
643                       struct type *arg_type,
644                       struct value **result)
645 {
646   int i, result_count = 0;
647
648   for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
649     {
650       LONGEST offset = baseclass_offset (search_type, i, valaddr,
651                                          embedded_offset,
652                                          address, val);
653
654       if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
655         {
656           if (address + embedded_offset + offset >= arg_addr
657               && address + embedded_offset + offset < arg_addr + TYPE_LENGTH (arg_type))
658             {
659               ++result_count;
660               if (!*result)
661                 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
662                                          address + embedded_offset + offset);
663             }
664         }
665       else
666         result_count += dynamic_cast_check_1 (desired_type,
667                                               valaddr,
668                                               embedded_offset + offset,
669                                               address, val,
670                                               TYPE_BASECLASS (search_type, i),
671                                               arg_addr,
672                                               arg_type,
673                                               result);
674     }
675
676   return result_count;
677 }
678
679 /* A helper for value_dynamic_cast.  This implements the second of two
680    runtime checks: we look for a unique public sibling class of the
681    argument's declared class.  */
682
683 static int
684 dynamic_cast_check_2 (struct type *desired_type,
685                       const gdb_byte *valaddr,
686                       LONGEST embedded_offset,
687                       CORE_ADDR address,
688                       struct value *val,
689                       struct type *search_type,
690                       struct value **result)
691 {
692   int i, result_count = 0;
693
694   for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
695     {
696       LONGEST offset;
697
698       if (! BASETYPE_VIA_PUBLIC (search_type, i))
699         continue;
700
701       offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
702                                  address, val);
703       if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
704         {
705           ++result_count;
706           if (*result == NULL)
707             *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
708                                      address + embedded_offset + offset);
709         }
710       else
711         result_count += dynamic_cast_check_2 (desired_type,
712                                               valaddr,
713                                               embedded_offset + offset,
714                                               address, val,
715                                               TYPE_BASECLASS (search_type, i),
716                                               result);
717     }
718
719   return result_count;
720 }
721
722 /* The C++ dynamic_cast operator.  */
723
724 struct value *
725 value_dynamic_cast (struct type *type, struct value *arg)
726 {
727   int full, using_enc;
728   LONGEST top;
729   struct type *resolved_type = check_typedef (type);
730   struct type *arg_type = check_typedef (value_type (arg));
731   struct type *class_type, *rtti_type;
732   struct value *result, *tem, *original_arg = arg;
733   CORE_ADDR addr;
734   int is_ref = TYPE_IS_REFERENCE (resolved_type);
735
736   if (TYPE_CODE (resolved_type) != TYPE_CODE_PTR
737       && !TYPE_IS_REFERENCE (resolved_type))
738     error (_("Argument to dynamic_cast must be a pointer or reference type"));
739   if (TYPE_CODE (TYPE_TARGET_TYPE (resolved_type)) != TYPE_CODE_VOID
740       && TYPE_CODE (TYPE_TARGET_TYPE (resolved_type)) != TYPE_CODE_STRUCT)
741     error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
742
743   class_type = check_typedef (TYPE_TARGET_TYPE (resolved_type));
744   if (TYPE_CODE (resolved_type) == TYPE_CODE_PTR)
745     {
746       if (TYPE_CODE (arg_type) != TYPE_CODE_PTR
747           && ! (TYPE_CODE (arg_type) == TYPE_CODE_INT
748                 && value_as_long (arg) == 0))
749         error (_("Argument to dynamic_cast does not have pointer type"));
750       if (TYPE_CODE (arg_type) == TYPE_CODE_PTR)
751         {
752           arg_type = check_typedef (TYPE_TARGET_TYPE (arg_type));
753           if (TYPE_CODE (arg_type) != TYPE_CODE_STRUCT)
754             error (_("Argument to dynamic_cast does "
755                      "not have pointer to class type"));
756         }
757
758       /* Handle NULL pointers.  */
759       if (value_as_long (arg) == 0)
760         return value_zero (type, not_lval);
761
762       arg = value_ind (arg);
763     }
764   else
765     {
766       if (TYPE_CODE (arg_type) != TYPE_CODE_STRUCT)
767         error (_("Argument to dynamic_cast does not have class type"));
768     }
769
770   /* If the classes are the same, just return the argument.  */
771   if (class_types_same_p (class_type, arg_type))
772     return value_cast (type, arg);
773
774   /* If the target type is a unique base class of the argument's
775      declared type, just cast it.  */
776   if (is_ancestor (class_type, arg_type))
777     {
778       if (is_unique_ancestor (class_type, arg))
779         return value_cast (type, original_arg);
780       error (_("Ambiguous dynamic_cast"));
781     }
782
783   rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
784   if (! rtti_type)
785     error (_("Couldn't determine value's most derived type for dynamic_cast"));
786
787   /* Compute the most derived object's address.  */
788   addr = value_address (arg);
789   if (full)
790     {
791       /* Done.  */
792     }
793   else if (using_enc)
794     addr += top;
795   else
796     addr += top + value_embedded_offset (arg);
797
798   /* dynamic_cast<void *> means to return a pointer to the
799      most-derived object.  */
800   if (TYPE_CODE (resolved_type) == TYPE_CODE_PTR
801       && TYPE_CODE (TYPE_TARGET_TYPE (resolved_type)) == TYPE_CODE_VOID)
802     return value_at_lazy (type, addr);
803
804   tem = value_at (type, addr);
805   type = value_type (tem);
806
807   /* The first dynamic check specified in 5.2.7.  */
808   if (is_public_ancestor (arg_type, TYPE_TARGET_TYPE (resolved_type)))
809     {
810       if (class_types_same_p (rtti_type, TYPE_TARGET_TYPE (resolved_type)))
811         return tem;
812       result = NULL;
813       if (dynamic_cast_check_1 (TYPE_TARGET_TYPE (resolved_type),
814                                 value_contents_for_printing (tem),
815                                 value_embedded_offset (tem),
816                                 value_address (tem), tem,
817                                 rtti_type, addr,
818                                 arg_type,
819                                 &result) == 1)
820         return value_cast (type,
821                            is_ref
822                            ? value_ref (result, TYPE_CODE (resolved_type))
823                            : value_addr (result));
824     }
825
826   /* The second dynamic check specified in 5.2.7.  */
827   result = NULL;
828   if (is_public_ancestor (arg_type, rtti_type)
829       && dynamic_cast_check_2 (TYPE_TARGET_TYPE (resolved_type),
830                                value_contents_for_printing (tem),
831                                value_embedded_offset (tem),
832                                value_address (tem), tem,
833                                rtti_type, &result) == 1)
834     return value_cast (type,
835                        is_ref
836                        ? value_ref (result, TYPE_CODE (resolved_type))
837                        : value_addr (result));
838
839   if (TYPE_CODE (resolved_type) == TYPE_CODE_PTR)
840     return value_zero (type, not_lval);
841
842   error (_("dynamic_cast failed"));
843 }
844
845 /* Create a value of type TYPE that is zero, and return it.  */
846
847 struct value *
848 value_zero (struct type *type, enum lval_type lv)
849 {
850   struct value *val = allocate_value (type);
851
852   VALUE_LVAL (val) = (lv == lval_computed ? not_lval : lv);
853   return val;
854 }
855
856 /* Create a not_lval value of numeric type TYPE that is one, and return it.  */
857
858 struct value *
859 value_one (struct type *type)
860 {
861   struct type *type1 = check_typedef (type);
862   struct value *val;
863
864   if (is_integral_type (type1) || is_floating_type (type1))
865     {
866       val = value_from_longest (type, (LONGEST) 1);
867     }
868   else if (TYPE_CODE (type1) == TYPE_CODE_ARRAY && TYPE_VECTOR (type1))
869     {
870       struct type *eltype = check_typedef (TYPE_TARGET_TYPE (type1));
871       int i;
872       LONGEST low_bound, high_bound;
873       struct value *tmp;
874
875       if (!get_array_bounds (type1, &low_bound, &high_bound))
876         error (_("Could not determine the vector bounds"));
877
878       val = allocate_value (type);
879       for (i = 0; i < high_bound - low_bound + 1; i++)
880         {
881           tmp = value_one (eltype);
882           memcpy (value_contents_writeable (val) + i * TYPE_LENGTH (eltype),
883                   value_contents_all (tmp), TYPE_LENGTH (eltype));
884         }
885     }
886   else
887     {
888       error (_("Not a numeric type."));
889     }
890
891   /* value_one result is never used for assignments to.  */
892   gdb_assert (VALUE_LVAL (val) == not_lval);
893
894   return val;
895 }
896
897 /* Helper function for value_at, value_at_lazy, and value_at_lazy_stack.
898    The type of the created value may differ from the passed type TYPE.
899    Make sure to retrieve the returned values's new type after this call
900    e.g. in case the type is a variable length array.  */
901
902 static struct value *
903 get_value_at (struct type *type, CORE_ADDR addr, int lazy)
904 {
905   struct value *val;
906
907   if (TYPE_CODE (check_typedef (type)) == TYPE_CODE_VOID)
908     error (_("Attempt to dereference a generic pointer."));
909
910   val = value_from_contents_and_address (type, NULL, addr);
911
912   if (!lazy)
913     value_fetch_lazy (val);
914
915   return val;
916 }
917
918 /* Return a value with type TYPE located at ADDR.
919
920    Call value_at only if the data needs to be fetched immediately;
921    if we can be 'lazy' and defer the fetch, perhaps indefinately, call
922    value_at_lazy instead.  value_at_lazy simply records the address of
923    the data and sets the lazy-evaluation-required flag.  The lazy flag
924    is tested in the value_contents macro, which is used if and when
925    the contents are actually required.  The type of the created value
926    may differ from the passed type TYPE.  Make sure to retrieve the
927    returned values's new type after this call e.g. in case the type
928    is a variable length array.
929
930    Note: value_at does *NOT* handle embedded offsets; perform such
931    adjustments before or after calling it.  */
932
933 struct value *
934 value_at (struct type *type, CORE_ADDR addr)
935 {
936   return get_value_at (type, addr, 0);
937 }
938
939 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
940    The type of the created value may differ from the passed type TYPE.
941    Make sure to retrieve the returned values's new type after this call
942    e.g. in case the type is a variable length array.  */
943
944 struct value *
945 value_at_lazy (struct type *type, CORE_ADDR addr)
946 {
947   return get_value_at (type, addr, 1);
948 }
949
950 void
951 read_value_memory (struct value *val, LONGEST bit_offset,
952                    int stack, CORE_ADDR memaddr,
953                    gdb_byte *buffer, size_t length)
954 {
955   ULONGEST xfered_total = 0;
956   struct gdbarch *arch = get_value_arch (val);
957   int unit_size = gdbarch_addressable_memory_unit_size (arch);
958   enum target_object object;
959
960   object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
961
962   while (xfered_total < length)
963     {
964       enum target_xfer_status status;
965       ULONGEST xfered_partial;
966
967       status = target_xfer_partial (current_target.beneath,
968                                     object, NULL,
969                                     buffer + xfered_total * unit_size, NULL,
970                                     memaddr + xfered_total,
971                                     length - xfered_total,
972                                     &xfered_partial);
973
974       if (status == TARGET_XFER_OK)
975         /* nothing */;
976       else if (status == TARGET_XFER_UNAVAILABLE)
977         mark_value_bits_unavailable (val, (xfered_total * HOST_CHAR_BIT
978                                            + bit_offset),
979                                      xfered_partial * HOST_CHAR_BIT);
980       else if (status == TARGET_XFER_EOF)
981         memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
982       else
983         memory_error (status, memaddr + xfered_total);
984
985       xfered_total += xfered_partial;
986       QUIT;
987     }
988 }
989
990 /* Store the contents of FROMVAL into the location of TOVAL.
991    Return a new value with the location of TOVAL and contents of FROMVAL.  */
992
993 struct value *
994 value_assign (struct value *toval, struct value *fromval)
995 {
996   struct type *type;
997   struct value *val;
998   struct frame_id old_frame;
999
1000   if (!deprecated_value_modifiable (toval))
1001     error (_("Left operand of assignment is not a modifiable lvalue."));
1002
1003   toval = coerce_ref (toval);
1004
1005   type = value_type (toval);
1006   if (VALUE_LVAL (toval) != lval_internalvar)
1007     fromval = value_cast (type, fromval);
1008   else
1009     {
1010       /* Coerce arrays and functions to pointers, except for arrays
1011          which only live in GDB's storage.  */
1012       if (!value_must_coerce_to_target (fromval))
1013         fromval = coerce_array (fromval);
1014     }
1015
1016   type = check_typedef (type);
1017
1018   /* Since modifying a register can trash the frame chain, and
1019      modifying memory can trash the frame cache, we save the old frame
1020      and then restore the new frame afterwards.  */
1021   old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1022
1023   switch (VALUE_LVAL (toval))
1024     {
1025     case lval_internalvar:
1026       set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1027       return value_of_internalvar (get_type_arch (type),
1028                                    VALUE_INTERNALVAR (toval));
1029
1030     case lval_internalvar_component:
1031       {
1032         LONGEST offset = value_offset (toval);
1033
1034         /* Are we dealing with a bitfield?
1035
1036            It is important to mention that `value_parent (toval)' is
1037            non-NULL iff `value_bitsize (toval)' is non-zero.  */
1038         if (value_bitsize (toval))
1039           {
1040             /* VALUE_INTERNALVAR below refers to the parent value, while
1041                the offset is relative to this parent value.  */
1042             gdb_assert (value_parent (value_parent (toval)) == NULL);
1043             offset += value_offset (value_parent (toval));
1044           }
1045
1046         set_internalvar_component (VALUE_INTERNALVAR (toval),
1047                                    offset,
1048                                    value_bitpos (toval),
1049                                    value_bitsize (toval),
1050                                    fromval);
1051       }
1052       break;
1053
1054     case lval_memory:
1055       {
1056         const gdb_byte *dest_buffer;
1057         CORE_ADDR changed_addr;
1058         int changed_len;
1059         gdb_byte buffer[sizeof (LONGEST)];
1060
1061         if (value_bitsize (toval))
1062           {
1063             struct value *parent = value_parent (toval);
1064
1065             changed_addr = value_address (parent) + value_offset (toval);
1066             changed_len = (value_bitpos (toval)
1067                            + value_bitsize (toval)
1068                            + HOST_CHAR_BIT - 1)
1069               / HOST_CHAR_BIT;
1070
1071             /* If we can read-modify-write exactly the size of the
1072                containing type (e.g. short or int) then do so.  This
1073                is safer for volatile bitfields mapped to hardware
1074                registers.  */
1075             if (changed_len < TYPE_LENGTH (type)
1076                 && TYPE_LENGTH (type) <= (int) sizeof (LONGEST)
1077                 && ((LONGEST) changed_addr % TYPE_LENGTH (type)) == 0)
1078               changed_len = TYPE_LENGTH (type);
1079
1080             if (changed_len > (int) sizeof (LONGEST))
1081               error (_("Can't handle bitfields which "
1082                        "don't fit in a %d bit word."),
1083                      (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1084
1085             read_memory (changed_addr, buffer, changed_len);
1086             modify_field (type, buffer, value_as_long (fromval),
1087                           value_bitpos (toval), value_bitsize (toval));
1088             dest_buffer = buffer;
1089           }
1090         else
1091           {
1092             changed_addr = value_address (toval);
1093             changed_len = type_length_units (type);
1094             dest_buffer = value_contents (fromval);
1095           }
1096
1097         write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1098       }
1099       break;
1100
1101     case lval_register:
1102       {
1103         struct frame_info *frame;
1104         struct gdbarch *gdbarch;
1105         int value_reg;
1106
1107         /* Figure out which frame this is in currently.
1108         
1109            We use VALUE_FRAME_ID for obtaining the value's frame id instead of
1110            VALUE_NEXT_FRAME_ID due to requiring a frame which may be passed to
1111            put_frame_register_bytes() below.  That function will (eventually)
1112            perform the necessary unwind operation by first obtaining the next
1113            frame.  */
1114         frame = frame_find_by_id (VALUE_FRAME_ID (toval));
1115
1116         value_reg = VALUE_REGNUM (toval);
1117
1118         if (!frame)
1119           error (_("Value being assigned to is no longer active."));
1120
1121         gdbarch = get_frame_arch (frame);
1122
1123         if (value_bitsize (toval))
1124           {
1125             struct value *parent = value_parent (toval);
1126             LONGEST offset = value_offset (parent) + value_offset (toval);
1127             int changed_len;
1128             gdb_byte buffer[sizeof (LONGEST)];
1129             int optim, unavail;
1130
1131             changed_len = (value_bitpos (toval)
1132                            + value_bitsize (toval)
1133                            + HOST_CHAR_BIT - 1)
1134                           / HOST_CHAR_BIT;
1135
1136             if (changed_len > (int) sizeof (LONGEST))
1137               error (_("Can't handle bitfields which "
1138                        "don't fit in a %d bit word."),
1139                      (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1140
1141             if (!get_frame_register_bytes (frame, value_reg, offset,
1142                                            changed_len, buffer,
1143                                            &optim, &unavail))
1144               {
1145                 if (optim)
1146                   throw_error (OPTIMIZED_OUT_ERROR,
1147                                _("value has been optimized out"));
1148                 if (unavail)
1149                   throw_error (NOT_AVAILABLE_ERROR,
1150                                _("value is not available"));
1151               }
1152
1153             modify_field (type, buffer, value_as_long (fromval),
1154                           value_bitpos (toval), value_bitsize (toval));
1155
1156             put_frame_register_bytes (frame, value_reg, offset,
1157                                       changed_len, buffer);
1158           }
1159         else
1160           {
1161             if (gdbarch_convert_register_p (gdbarch, VALUE_REGNUM (toval),
1162                                             type))
1163               {
1164                 /* If TOVAL is a special machine register requiring
1165                    conversion of program values to a special raw
1166                    format.  */
1167                 gdbarch_value_to_register (gdbarch, frame,
1168                                            VALUE_REGNUM (toval), type,
1169                                            value_contents (fromval));
1170               }
1171             else
1172               {
1173                 put_frame_register_bytes (frame, value_reg,
1174                                           value_offset (toval),
1175                                           TYPE_LENGTH (type),
1176                                           value_contents (fromval));
1177               }
1178           }
1179
1180         observer_notify_register_changed (frame, value_reg);
1181         break;
1182       }
1183
1184     case lval_computed:
1185       {
1186         const struct lval_funcs *funcs = value_computed_funcs (toval);
1187
1188         if (funcs->write != NULL)
1189           {
1190             funcs->write (toval, fromval);
1191             break;
1192           }
1193       }
1194       /* Fall through.  */
1195
1196     default:
1197       error (_("Left operand of assignment is not an lvalue."));
1198     }
1199
1200   /* Assigning to the stack pointer, frame pointer, and other
1201      (architecture and calling convention specific) registers may
1202      cause the frame cache and regcache to be out of date.  Assigning to memory
1203      also can.  We just do this on all assignments to registers or
1204      memory, for simplicity's sake; I doubt the slowdown matters.  */
1205   switch (VALUE_LVAL (toval))
1206     {
1207     case lval_memory:
1208     case lval_register:
1209     case lval_computed:
1210
1211       observer_notify_target_changed (&current_target);
1212
1213       /* Having destroyed the frame cache, restore the selected
1214          frame.  */
1215
1216       /* FIXME: cagney/2002-11-02: There has to be a better way of
1217          doing this.  Instead of constantly saving/restoring the
1218          frame.  Why not create a get_selected_frame() function that,
1219          having saved the selected frame's ID can automatically
1220          re-find the previously selected frame automatically.  */
1221
1222       {
1223         struct frame_info *fi = frame_find_by_id (old_frame);
1224
1225         if (fi != NULL)
1226           select_frame (fi);
1227       }
1228
1229       break;
1230     default:
1231       break;
1232     }
1233   
1234   /* If the field does not entirely fill a LONGEST, then zero the sign
1235      bits.  If the field is signed, and is negative, then sign
1236      extend.  */
1237   if ((value_bitsize (toval) > 0)
1238       && (value_bitsize (toval) < 8 * (int) sizeof (LONGEST)))
1239     {
1240       LONGEST fieldval = value_as_long (fromval);
1241       LONGEST valmask = (((ULONGEST) 1) << value_bitsize (toval)) - 1;
1242
1243       fieldval &= valmask;
1244       if (!TYPE_UNSIGNED (type) 
1245           && (fieldval & (valmask ^ (valmask >> 1))))
1246         fieldval |= ~valmask;
1247
1248       fromval = value_from_longest (type, fieldval);
1249     }
1250
1251   /* The return value is a copy of TOVAL so it shares its location
1252      information, but its contents are updated from FROMVAL.  This
1253      implies the returned value is not lazy, even if TOVAL was.  */
1254   val = value_copy (toval);
1255   set_value_lazy (val, 0);
1256   memcpy (value_contents_raw (val), value_contents (fromval),
1257           TYPE_LENGTH (type));
1258
1259   /* We copy over the enclosing type and pointed-to offset from FROMVAL
1260      in the case of pointer types.  For object types, the enclosing type
1261      and embedded offset must *not* be copied: the target object refered
1262      to by TOVAL retains its original dynamic type after assignment.  */
1263   if (TYPE_CODE (type) == TYPE_CODE_PTR)
1264     {
1265       set_value_enclosing_type (val, value_enclosing_type (fromval));
1266       set_value_pointed_to_offset (val, value_pointed_to_offset (fromval));
1267     }
1268
1269   return val;
1270 }
1271
1272 /* Extend a value VAL to COUNT repetitions of its type.  */
1273
1274 struct value *
1275 value_repeat (struct value *arg1, int count)
1276 {
1277   struct value *val;
1278
1279   if (VALUE_LVAL (arg1) != lval_memory)
1280     error (_("Only values in memory can be extended with '@'."));
1281   if (count < 1)
1282     error (_("Invalid number %d of repetitions."), count);
1283
1284   val = allocate_repeat_value (value_enclosing_type (arg1), count);
1285
1286   VALUE_LVAL (val) = lval_memory;
1287   set_value_address (val, value_address (arg1));
1288
1289   read_value_memory (val, 0, value_stack (val), value_address (val),
1290                      value_contents_all_raw (val),
1291                      type_length_units (value_enclosing_type (val)));
1292
1293   return val;
1294 }
1295
1296 struct value *
1297 value_of_variable (struct symbol *var, const struct block *b)
1298 {
1299   struct frame_info *frame = NULL;
1300
1301   if (symbol_read_needs_frame (var))
1302     frame = get_selected_frame (_("No frame selected."));
1303
1304   return read_var_value (var, b, frame);
1305 }
1306
1307 struct value *
1308 address_of_variable (struct symbol *var, const struct block *b)
1309 {
1310   struct type *type = SYMBOL_TYPE (var);
1311   struct value *val;
1312
1313   /* Evaluate it first; if the result is a memory address, we're fine.
1314      Lazy evaluation pays off here.  */
1315
1316   val = value_of_variable (var, b);
1317   type = value_type (val);
1318
1319   if ((VALUE_LVAL (val) == lval_memory && value_lazy (val))
1320       || TYPE_CODE (type) == TYPE_CODE_FUNC)
1321     {
1322       CORE_ADDR addr = value_address (val);
1323
1324       return value_from_pointer (lookup_pointer_type (type), addr);
1325     }
1326
1327   /* Not a memory address; check what the problem was.  */
1328   switch (VALUE_LVAL (val))
1329     {
1330     case lval_register:
1331       {
1332         struct frame_info *frame;
1333         const char *regname;
1334
1335         frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (val));
1336         gdb_assert (frame);
1337
1338         regname = gdbarch_register_name (get_frame_arch (frame),
1339                                          VALUE_REGNUM (val));
1340         gdb_assert (regname && *regname);
1341
1342         error (_("Address requested for identifier "
1343                  "\"%s\" which is in register $%s"),
1344                SYMBOL_PRINT_NAME (var), regname);
1345         break;
1346       }
1347
1348     default:
1349       error (_("Can't take address of \"%s\" which isn't an lvalue."),
1350              SYMBOL_PRINT_NAME (var));
1351       break;
1352     }
1353
1354   return val;
1355 }
1356
1357 /* Return one if VAL does not live in target memory, but should in order
1358    to operate on it.  Otherwise return zero.  */
1359
1360 int
1361 value_must_coerce_to_target (struct value *val)
1362 {
1363   struct type *valtype;
1364
1365   /* The only lval kinds which do not live in target memory.  */
1366   if (VALUE_LVAL (val) != not_lval
1367       && VALUE_LVAL (val) != lval_internalvar
1368       && VALUE_LVAL (val) != lval_xcallable)
1369     return 0;
1370
1371   valtype = check_typedef (value_type (val));
1372
1373   switch (TYPE_CODE (valtype))
1374     {
1375     case TYPE_CODE_ARRAY:
1376       return TYPE_VECTOR (valtype) ? 0 : 1;
1377     case TYPE_CODE_STRING:
1378       return 1;
1379     default:
1380       return 0;
1381     }
1382 }
1383
1384 /* Make sure that VAL lives in target memory if it's supposed to.  For
1385    instance, strings are constructed as character arrays in GDB's
1386    storage, and this function copies them to the target.  */
1387
1388 struct value *
1389 value_coerce_to_target (struct value *val)
1390 {
1391   LONGEST length;
1392   CORE_ADDR addr;
1393
1394   if (!value_must_coerce_to_target (val))
1395     return val;
1396
1397   length = TYPE_LENGTH (check_typedef (value_type (val)));
1398   addr = allocate_space_in_inferior (length);
1399   write_memory (addr, value_contents (val), length);
1400   return value_at_lazy (value_type (val), addr);
1401 }
1402
1403 /* Given a value which is an array, return a value which is a pointer
1404    to its first element, regardless of whether or not the array has a
1405    nonzero lower bound.
1406
1407    FIXME: A previous comment here indicated that this routine should
1408    be substracting the array's lower bound.  It's not clear to me that
1409    this is correct.  Given an array subscripting operation, it would
1410    certainly work to do the adjustment here, essentially computing:
1411
1412    (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1413
1414    However I believe a more appropriate and logical place to account
1415    for the lower bound is to do so in value_subscript, essentially
1416    computing:
1417
1418    (&array[0] + ((index - lowerbound) * sizeof array[0]))
1419
1420    As further evidence consider what would happen with operations
1421    other than array subscripting, where the caller would get back a
1422    value that had an address somewhere before the actual first element
1423    of the array, and the information about the lower bound would be
1424    lost because of the coercion to pointer type.  */
1425
1426 struct value *
1427 value_coerce_array (struct value *arg1)
1428 {
1429   struct type *type = check_typedef (value_type (arg1));
1430
1431   /* If the user tries to do something requiring a pointer with an
1432      array that has not yet been pushed to the target, then this would
1433      be a good time to do so.  */
1434   arg1 = value_coerce_to_target (arg1);
1435
1436   if (VALUE_LVAL (arg1) != lval_memory)
1437     error (_("Attempt to take address of value not located in memory."));
1438
1439   return value_from_pointer (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
1440                              value_address (arg1));
1441 }
1442
1443 /* Given a value which is a function, return a value which is a pointer
1444    to it.  */
1445
1446 struct value *
1447 value_coerce_function (struct value *arg1)
1448 {
1449   struct value *retval;
1450
1451   if (VALUE_LVAL (arg1) != lval_memory)
1452     error (_("Attempt to take address of value not located in memory."));
1453
1454   retval = value_from_pointer (lookup_pointer_type (value_type (arg1)),
1455                                value_address (arg1));
1456   return retval;
1457 }
1458
1459 /* Return a pointer value for the object for which ARG1 is the
1460    contents.  */
1461
1462 struct value *
1463 value_addr (struct value *arg1)
1464 {
1465   struct value *arg2;
1466   struct type *type = check_typedef (value_type (arg1));
1467
1468   if (TYPE_IS_REFERENCE (type))
1469     {
1470       if (value_bits_synthetic_pointer (arg1, value_embedded_offset (arg1),
1471           TARGET_CHAR_BIT * TYPE_LENGTH (type)))
1472         arg1 = coerce_ref (arg1);
1473       else
1474         {
1475           /* Copy the value, but change the type from (T&) to (T*).  We
1476              keep the same location information, which is efficient, and
1477              allows &(&X) to get the location containing the reference.
1478              Do the same to its enclosing type for consistency.  */
1479           struct type *type_ptr
1480             = lookup_pointer_type (TYPE_TARGET_TYPE (type));
1481           struct type *enclosing_type
1482             = check_typedef (value_enclosing_type (arg1));
1483           struct type *enclosing_type_ptr
1484             = lookup_pointer_type (TYPE_TARGET_TYPE (enclosing_type));
1485
1486           arg2 = value_copy (arg1);
1487           deprecated_set_value_type (arg2, type_ptr);
1488           set_value_enclosing_type (arg2, enclosing_type_ptr);
1489
1490           return arg2;
1491         }
1492     }
1493   if (TYPE_CODE (type) == TYPE_CODE_FUNC)
1494     return value_coerce_function (arg1);
1495
1496   /* If this is an array that has not yet been pushed to the target,
1497      then this would be a good time to force it to memory.  */
1498   arg1 = value_coerce_to_target (arg1);
1499
1500   if (VALUE_LVAL (arg1) != lval_memory)
1501     error (_("Attempt to take address of value not located in memory."));
1502
1503   /* Get target memory address.  */
1504   arg2 = value_from_pointer (lookup_pointer_type (value_type (arg1)),
1505                              (value_address (arg1)
1506                               + value_embedded_offset (arg1)));
1507
1508   /* This may be a pointer to a base subobject; so remember the
1509      full derived object's type ...  */
1510   set_value_enclosing_type (arg2,
1511                             lookup_pointer_type (value_enclosing_type (arg1)));
1512   /* ... and also the relative position of the subobject in the full
1513      object.  */
1514   set_value_pointed_to_offset (arg2, value_embedded_offset (arg1));
1515   return arg2;
1516 }
1517
1518 /* Return a reference value for the object for which ARG1 is the
1519    contents.  */
1520
1521 struct value *
1522 value_ref (struct value *arg1, enum type_code refcode)
1523 {
1524   struct value *arg2;
1525   struct type *type = check_typedef (value_type (arg1));
1526
1527   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1528
1529   if ((TYPE_CODE (type) == TYPE_CODE_REF
1530        || TYPE_CODE (type) == TYPE_CODE_RVALUE_REF)
1531       && TYPE_CODE (type) == refcode)
1532     return arg1;
1533
1534   arg2 = value_addr (arg1);
1535   deprecated_set_value_type (arg2, lookup_reference_type (type, refcode));
1536   return arg2;
1537 }
1538
1539 /* Given a value of a pointer type, apply the C unary * operator to
1540    it.  */
1541
1542 struct value *
1543 value_ind (struct value *arg1)
1544 {
1545   struct type *base_type;
1546   struct value *arg2;
1547
1548   arg1 = coerce_array (arg1);
1549
1550   base_type = check_typedef (value_type (arg1));
1551
1552   if (VALUE_LVAL (arg1) == lval_computed)
1553     {
1554       const struct lval_funcs *funcs = value_computed_funcs (arg1);
1555
1556       if (funcs->indirect)
1557         {
1558           struct value *result = funcs->indirect (arg1);
1559
1560           if (result)
1561             return result;
1562         }
1563     }
1564
1565   if (TYPE_CODE (base_type) == TYPE_CODE_PTR)
1566     {
1567       struct type *enc_type;
1568
1569       /* We may be pointing to something embedded in a larger object.
1570          Get the real type of the enclosing object.  */
1571       enc_type = check_typedef (value_enclosing_type (arg1));
1572       enc_type = TYPE_TARGET_TYPE (enc_type);
1573
1574       if (TYPE_CODE (check_typedef (enc_type)) == TYPE_CODE_FUNC
1575           || TYPE_CODE (check_typedef (enc_type)) == TYPE_CODE_METHOD)
1576         /* For functions, go through find_function_addr, which knows
1577            how to handle function descriptors.  */
1578         arg2 = value_at_lazy (enc_type, 
1579                               find_function_addr (arg1, NULL));
1580       else
1581         /* Retrieve the enclosing object pointed to.  */
1582         arg2 = value_at_lazy (enc_type, 
1583                               (value_as_address (arg1)
1584                                - value_pointed_to_offset (arg1)));
1585
1586       enc_type = value_type (arg2);
1587       return readjust_indirect_value_type (arg2, enc_type, base_type, arg1);
1588     }
1589
1590   error (_("Attempt to take contents of a non-pointer value."));
1591   return 0;                     /* For lint -- never reached.  */
1592 }
1593 \f
1594 /* Create a value for an array by allocating space in GDB, copying the
1595    data into that space, and then setting up an array value.
1596
1597    The array bounds are set from LOWBOUND and HIGHBOUND, and the array
1598    is populated from the values passed in ELEMVEC.
1599
1600    The element type of the array is inherited from the type of the
1601    first element, and all elements must have the same size (though we
1602    don't currently enforce any restriction on their types).  */
1603
1604 struct value *
1605 value_array (int lowbound, int highbound, struct value **elemvec)
1606 {
1607   int nelem;
1608   int idx;
1609   ULONGEST typelength;
1610   struct value *val;
1611   struct type *arraytype;
1612
1613   /* Validate that the bounds are reasonable and that each of the
1614      elements have the same size.  */
1615
1616   nelem = highbound - lowbound + 1;
1617   if (nelem <= 0)
1618     {
1619       error (_("bad array bounds (%d, %d)"), lowbound, highbound);
1620     }
1621   typelength = type_length_units (value_enclosing_type (elemvec[0]));
1622   for (idx = 1; idx < nelem; idx++)
1623     {
1624       if (type_length_units (value_enclosing_type (elemvec[idx]))
1625           != typelength)
1626         {
1627           error (_("array elements must all be the same size"));
1628         }
1629     }
1630
1631   arraytype = lookup_array_range_type (value_enclosing_type (elemvec[0]),
1632                                        lowbound, highbound);
1633
1634   if (!current_language->c_style_arrays)
1635     {
1636       val = allocate_value (arraytype);
1637       for (idx = 0; idx < nelem; idx++)
1638         value_contents_copy (val, idx * typelength, elemvec[idx], 0,
1639                              typelength);
1640       return val;
1641     }
1642
1643   /* Allocate space to store the array, and then initialize it by
1644      copying in each element.  */
1645
1646   val = allocate_value (arraytype);
1647   for (idx = 0; idx < nelem; idx++)
1648     value_contents_copy (val, idx * typelength, elemvec[idx], 0, typelength);
1649   return val;
1650 }
1651
1652 struct value *
1653 value_cstring (const char *ptr, ssize_t len, struct type *char_type)
1654 {
1655   struct value *val;
1656   int lowbound = current_language->string_lower_bound;
1657   ssize_t highbound = len / TYPE_LENGTH (char_type);
1658   struct type *stringtype
1659     = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1660
1661   val = allocate_value (stringtype);
1662   memcpy (value_contents_raw (val), ptr, len);
1663   return val;
1664 }
1665
1666 /* Create a value for a string constant by allocating space in the
1667    inferior, copying the data into that space, and returning the
1668    address with type TYPE_CODE_STRING.  PTR points to the string
1669    constant data; LEN is number of characters.
1670
1671    Note that string types are like array of char types with a lower
1672    bound of zero and an upper bound of LEN - 1.  Also note that the
1673    string may contain embedded null bytes.  */
1674
1675 struct value *
1676 value_string (const char *ptr, ssize_t len, struct type *char_type)
1677 {
1678   struct value *val;
1679   int lowbound = current_language->string_lower_bound;
1680   ssize_t highbound = len / TYPE_LENGTH (char_type);
1681   struct type *stringtype
1682     = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1683
1684   val = allocate_value (stringtype);
1685   memcpy (value_contents_raw (val), ptr, len);
1686   return val;
1687 }
1688
1689 \f
1690 /* See if we can pass arguments in T2 to a function which takes
1691    arguments of types T1.  T1 is a list of NARGS arguments, and T2 is
1692    a NULL-terminated vector.  If some arguments need coercion of some
1693    sort, then the coerced values are written into T2.  Return value is
1694    0 if the arguments could be matched, or the position at which they
1695    differ if not.
1696
1697    STATICP is nonzero if the T1 argument list came from a static
1698    member function.  T2 will still include the ``this'' pointer, but
1699    it will be skipped.
1700
1701    For non-static member functions, we ignore the first argument,
1702    which is the type of the instance variable.  This is because we
1703    want to handle calls with objects from derived classes.  This is
1704    not entirely correct: we should actually check to make sure that a
1705    requested operation is type secure, shouldn't we?  FIXME.  */
1706
1707 static int
1708 typecmp (int staticp, int varargs, int nargs,
1709          struct field t1[], struct value *t2[])
1710 {
1711   int i;
1712
1713   if (t2 == 0)
1714     internal_error (__FILE__, __LINE__, 
1715                     _("typecmp: no argument list"));
1716
1717   /* Skip ``this'' argument if applicable.  T2 will always include
1718      THIS.  */
1719   if (staticp)
1720     t2 ++;
1721
1722   for (i = 0;
1723        (i < nargs) && TYPE_CODE (t1[i].type) != TYPE_CODE_VOID;
1724        i++)
1725     {
1726       struct type *tt1, *tt2;
1727
1728       if (!t2[i])
1729         return i + 1;
1730
1731       tt1 = check_typedef (t1[i].type);
1732       tt2 = check_typedef (value_type (t2[i]));
1733
1734       if (TYPE_IS_REFERENCE (tt1)
1735           /* We should be doing hairy argument matching, as below.  */
1736           && (TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (tt1)))
1737               == TYPE_CODE (tt2)))
1738         {
1739           if (TYPE_CODE (tt2) == TYPE_CODE_ARRAY)
1740             t2[i] = value_coerce_array (t2[i]);
1741           else
1742             t2[i] = value_ref (t2[i], TYPE_CODE (tt1));
1743           continue;
1744         }
1745
1746       /* djb - 20000715 - Until the new type structure is in the
1747          place, and we can attempt things like implicit conversions,
1748          we need to do this so you can take something like a map<const
1749          char *>, and properly access map["hello"], because the
1750          argument to [] will be a reference to a pointer to a char,
1751          and the argument will be a pointer to a char.  */
1752       while (TYPE_IS_REFERENCE (tt1) || TYPE_CODE (tt1) == TYPE_CODE_PTR)
1753         {
1754           tt1 = check_typedef( TYPE_TARGET_TYPE(tt1) );
1755         }
1756       while (TYPE_CODE(tt2) == TYPE_CODE_ARRAY
1757              || TYPE_CODE(tt2) == TYPE_CODE_PTR
1758              || TYPE_IS_REFERENCE (tt2))
1759         {
1760           tt2 = check_typedef (TYPE_TARGET_TYPE(tt2));
1761         }
1762       if (TYPE_CODE (tt1) == TYPE_CODE (tt2))
1763         continue;
1764       /* Array to pointer is a `trivial conversion' according to the
1765          ARM.  */
1766
1767       /* We should be doing much hairier argument matching (see
1768          section 13.2 of the ARM), but as a quick kludge, just check
1769          for the same type code.  */
1770       if (TYPE_CODE (t1[i].type) != TYPE_CODE (value_type (t2[i])))
1771         return i + 1;
1772     }
1773   if (varargs || t2[i] == NULL)
1774     return 0;
1775   return i + 1;
1776 }
1777
1778 /* Helper class for do_search_struct_field that updates *RESULT_PTR
1779    and *LAST_BOFFSET, and possibly throws an exception if the field
1780    search has yielded ambiguous results.  */
1781
1782 static void
1783 update_search_result (struct value **result_ptr, struct value *v,
1784                       LONGEST *last_boffset, LONGEST boffset,
1785                       const char *name, struct type *type)
1786 {
1787   if (v != NULL)
1788     {
1789       if (*result_ptr != NULL
1790           /* The result is not ambiguous if all the classes that are
1791              found occupy the same space.  */
1792           && *last_boffset != boffset)
1793         error (_("base class '%s' is ambiguous in type '%s'"),
1794                name, TYPE_SAFE_NAME (type));
1795       *result_ptr = v;
1796       *last_boffset = boffset;
1797     }
1798 }
1799
1800 /* A helper for search_struct_field.  This does all the work; most
1801    arguments are as passed to search_struct_field.  The result is
1802    stored in *RESULT_PTR, which must be initialized to NULL.
1803    OUTERMOST_TYPE is the type of the initial type passed to
1804    search_struct_field; this is used for error reporting when the
1805    lookup is ambiguous.  */
1806
1807 static void
1808 do_search_struct_field (const char *name, struct value *arg1, LONGEST offset,
1809                         struct type *type, int looking_for_baseclass,
1810                         struct value **result_ptr,
1811                         LONGEST *last_boffset,
1812                         struct type *outermost_type)
1813 {
1814   int i;
1815   int nbases;
1816
1817   type = check_typedef (type);
1818   nbases = TYPE_N_BASECLASSES (type);
1819
1820   if (!looking_for_baseclass)
1821     for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
1822       {
1823         const char *t_field_name = TYPE_FIELD_NAME (type, i);
1824
1825         if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
1826           {
1827             struct value *v;
1828
1829             if (field_is_static (&TYPE_FIELD (type, i)))
1830               v = value_static_field (type, i);
1831             else
1832               v = value_primitive_field (arg1, offset, i, type);
1833             *result_ptr = v;
1834             return;
1835           }
1836
1837         if (t_field_name
1838             && t_field_name[0] == '\0')
1839           {
1840             struct type *field_type = TYPE_FIELD_TYPE (type, i);
1841
1842             if (TYPE_CODE (field_type) == TYPE_CODE_UNION
1843                 || TYPE_CODE (field_type) == TYPE_CODE_STRUCT)
1844               {
1845                 /* Look for a match through the fields of an anonymous
1846                    union, or anonymous struct.  C++ provides anonymous
1847                    unions.
1848
1849                    In the GNU Chill (now deleted from GDB)
1850                    implementation of variant record types, each
1851                    <alternative field> has an (anonymous) union type,
1852                    each member of the union represents a <variant
1853                    alternative>.  Each <variant alternative> is
1854                    represented as a struct, with a member for each
1855                    <variant field>.  */
1856
1857                 struct value *v = NULL;
1858                 LONGEST new_offset = offset;
1859
1860                 /* This is pretty gross.  In G++, the offset in an
1861                    anonymous union is relative to the beginning of the
1862                    enclosing struct.  In the GNU Chill (now deleted
1863                    from GDB) implementation of variant records, the
1864                    bitpos is zero in an anonymous union field, so we
1865                    have to add the offset of the union here.  */
1866                 if (TYPE_CODE (field_type) == TYPE_CODE_STRUCT
1867                     || (TYPE_NFIELDS (field_type) > 0
1868                         && TYPE_FIELD_BITPOS (field_type, 0) == 0))
1869                   new_offset += TYPE_FIELD_BITPOS (type, i) / 8;
1870
1871                 do_search_struct_field (name, arg1, new_offset, 
1872                                         field_type,
1873                                         looking_for_baseclass, &v,
1874                                         last_boffset,
1875                                         outermost_type);
1876                 if (v)
1877                   {
1878                     *result_ptr = v;
1879                     return;
1880                   }
1881               }
1882           }
1883       }
1884
1885   for (i = 0; i < nbases; i++)
1886     {
1887       struct value *v = NULL;
1888       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
1889       /* If we are looking for baseclasses, this is what we get when
1890          we hit them.  But it could happen that the base part's member
1891          name is not yet filled in.  */
1892       int found_baseclass = (looking_for_baseclass
1893                              && TYPE_BASECLASS_NAME (type, i) != NULL
1894                              && (strcmp_iw (name, 
1895                                             TYPE_BASECLASS_NAME (type, 
1896                                                                  i)) == 0));
1897       LONGEST boffset = value_embedded_offset (arg1) + offset;
1898
1899       if (BASETYPE_VIA_VIRTUAL (type, i))
1900         {
1901           struct value *v2;
1902
1903           boffset = baseclass_offset (type, i,
1904                                       value_contents_for_printing (arg1),
1905                                       value_embedded_offset (arg1) + offset,
1906                                       value_address (arg1),
1907                                       arg1);
1908
1909           /* The virtual base class pointer might have been clobbered
1910              by the user program.  Make sure that it still points to a
1911              valid memory location.  */
1912
1913           boffset += value_embedded_offset (arg1) + offset;
1914           if (boffset < 0
1915               || boffset >= TYPE_LENGTH (value_enclosing_type (arg1)))
1916             {
1917               CORE_ADDR base_addr;
1918
1919               base_addr = value_address (arg1) + boffset;
1920               v2 = value_at_lazy (basetype, base_addr);
1921               if (target_read_memory (base_addr, 
1922                                       value_contents_raw (v2),
1923                                       TYPE_LENGTH (value_type (v2))) != 0)
1924                 error (_("virtual baseclass botch"));
1925             }
1926           else
1927             {
1928               v2 = value_copy (arg1);
1929               deprecated_set_value_type (v2, basetype);
1930               set_value_embedded_offset (v2, boffset);
1931             }
1932
1933           if (found_baseclass)
1934             v = v2;
1935           else
1936             {
1937               do_search_struct_field (name, v2, 0,
1938                                       TYPE_BASECLASS (type, i),
1939                                       looking_for_baseclass,
1940                                       result_ptr, last_boffset,
1941                                       outermost_type);
1942             }
1943         }
1944       else if (found_baseclass)
1945         v = value_primitive_field (arg1, offset, i, type);
1946       else
1947         {
1948           do_search_struct_field (name, arg1,
1949                                   offset + TYPE_BASECLASS_BITPOS (type, 
1950                                                                   i) / 8,
1951                                   basetype, looking_for_baseclass,
1952                                   result_ptr, last_boffset,
1953                                   outermost_type);
1954         }
1955
1956       update_search_result (result_ptr, v, last_boffset,
1957                             boffset, name, outermost_type);
1958     }
1959 }
1960
1961 /* Helper function used by value_struct_elt to recurse through
1962    baseclasses.  Look for a field NAME in ARG1.  Search in it assuming
1963    it has (class) type TYPE.  If found, return value, else return NULL.
1964
1965    If LOOKING_FOR_BASECLASS, then instead of looking for struct
1966    fields, look for a baseclass named NAME.  */
1967
1968 static struct value *
1969 search_struct_field (const char *name, struct value *arg1,
1970                      struct type *type, int looking_for_baseclass)
1971 {
1972   struct value *result = NULL;
1973   LONGEST boffset = 0;
1974
1975   do_search_struct_field (name, arg1, 0, type, looking_for_baseclass,
1976                           &result, &boffset, type);
1977   return result;
1978 }
1979
1980 /* Helper function used by value_struct_elt to recurse through
1981    baseclasses.  Look for a field NAME in ARG1.  Adjust the address of
1982    ARG1 by OFFSET bytes, and search in it assuming it has (class) type
1983    TYPE.
1984
1985    If found, return value, else if name matched and args not return
1986    (value) -1, else return NULL.  */
1987
1988 static struct value *
1989 search_struct_method (const char *name, struct value **arg1p,
1990                       struct value **args, LONGEST offset,
1991                       int *static_memfuncp, struct type *type)
1992 {
1993   int i;
1994   struct value *v;
1995   int name_matched = 0;
1996   char dem_opname[64];
1997
1998   type = check_typedef (type);
1999   for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2000     {
2001       const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2002
2003       /* FIXME!  May need to check for ARM demangling here.  */
2004       if (startswith (t_field_name, "__") ||
2005           startswith (t_field_name, "op") ||
2006           startswith (t_field_name, "type"))
2007         {
2008           if (cplus_demangle_opname (t_field_name, dem_opname, DMGL_ANSI))
2009             t_field_name = dem_opname;
2010           else if (cplus_demangle_opname (t_field_name, dem_opname, 0))
2011             t_field_name = dem_opname;
2012         }
2013       if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2014         {
2015           int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2016           struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2017
2018           name_matched = 1;
2019           check_stub_method_group (type, i);
2020           if (j > 0 && args == 0)
2021             error (_("cannot resolve overloaded method "
2022                      "`%s': no arguments supplied"), name);
2023           else if (j == 0 && args == 0)
2024             {
2025               v = value_fn_field (arg1p, f, j, type, offset);
2026               if (v != NULL)
2027                 return v;
2028             }
2029           else
2030             while (j >= 0)
2031               {
2032                 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2033                               TYPE_VARARGS (TYPE_FN_FIELD_TYPE (f, j)),
2034                               TYPE_NFIELDS (TYPE_FN_FIELD_TYPE (f, j)),
2035                               TYPE_FN_FIELD_ARGS (f, j), args))
2036                   {
2037                     if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2038                       return value_virtual_fn_field (arg1p, f, j, 
2039                                                      type, offset);
2040                     if (TYPE_FN_FIELD_STATIC_P (f, j) 
2041                         && static_memfuncp)
2042                       *static_memfuncp = 1;
2043                     v = value_fn_field (arg1p, f, j, type, offset);
2044                     if (v != NULL)
2045                       return v;       
2046                   }
2047                 j--;
2048               }
2049         }
2050     }
2051
2052   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2053     {
2054       LONGEST base_offset;
2055       LONGEST this_offset;
2056
2057       if (BASETYPE_VIA_VIRTUAL (type, i))
2058         {
2059           struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2060           struct value *base_val;
2061           const gdb_byte *base_valaddr;
2062
2063           /* The virtual base class pointer might have been
2064              clobbered by the user program.  Make sure that it
2065              still points to a valid memory location.  */
2066
2067           if (offset < 0 || offset >= TYPE_LENGTH (type))
2068             {
2069               CORE_ADDR address;
2070
2071               gdb::byte_vector tmp (TYPE_LENGTH (baseclass));
2072               address = value_address (*arg1p);
2073
2074               if (target_read_memory (address + offset,
2075                                       tmp.data (), TYPE_LENGTH (baseclass)) != 0)
2076                 error (_("virtual baseclass botch"));
2077
2078               base_val = value_from_contents_and_address (baseclass,
2079                                                           tmp.data (),
2080                                                           address + offset);
2081               base_valaddr = value_contents_for_printing (base_val);
2082               this_offset = 0;
2083             }
2084           else
2085             {
2086               base_val = *arg1p;
2087               base_valaddr = value_contents_for_printing (*arg1p);
2088               this_offset = offset;
2089             }
2090
2091           base_offset = baseclass_offset (type, i, base_valaddr,
2092                                           this_offset, value_address (base_val),
2093                                           base_val);
2094         }
2095       else
2096         {
2097           base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2098         }
2099       v = search_struct_method (name, arg1p, args, base_offset + offset,
2100                                 static_memfuncp, TYPE_BASECLASS (type, i));
2101       if (v == (struct value *) - 1)
2102         {
2103           name_matched = 1;
2104         }
2105       else if (v)
2106         {
2107           /* FIXME-bothner:  Why is this commented out?  Why is it here?  */
2108           /* *arg1p = arg1_tmp; */
2109           return v;
2110         }
2111     }
2112   if (name_matched)
2113     return (struct value *) - 1;
2114   else
2115     return NULL;
2116 }
2117
2118 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2119    extract the component named NAME from the ultimate target
2120    structure/union and return it as a value with its appropriate type.
2121    ERR is used in the error message if *ARGP's type is wrong.
2122
2123    C++: ARGS is a list of argument types to aid in the selection of
2124    an appropriate method.  Also, handle derived types.
2125
2126    STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2127    where the truthvalue of whether the function that was resolved was
2128    a static member function or not is stored.
2129
2130    ERR is an error message to be printed in case the field is not
2131    found.  */
2132
2133 struct value *
2134 value_struct_elt (struct value **argp, struct value **args,
2135                   const char *name, int *static_memfuncp, const char *err)
2136 {
2137   struct type *t;
2138   struct value *v;
2139
2140   *argp = coerce_array (*argp);
2141
2142   t = check_typedef (value_type (*argp));
2143
2144   /* Follow pointers until we get to a non-pointer.  */
2145
2146   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_IS_REFERENCE (t))
2147     {
2148       *argp = value_ind (*argp);
2149       /* Don't coerce fn pointer to fn and then back again!  */
2150       if (TYPE_CODE (check_typedef (value_type (*argp))) != TYPE_CODE_FUNC)
2151         *argp = coerce_array (*argp);
2152       t = check_typedef (value_type (*argp));
2153     }
2154
2155   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2156       && TYPE_CODE (t) != TYPE_CODE_UNION)
2157     error (_("Attempt to extract a component of a value that is not a %s."),
2158            err);
2159
2160   /* Assume it's not, unless we see that it is.  */
2161   if (static_memfuncp)
2162     *static_memfuncp = 0;
2163
2164   if (!args)
2165     {
2166       /* if there are no arguments ...do this...  */
2167
2168       /* Try as a field first, because if we succeed, there is less
2169          work to be done.  */
2170       v = search_struct_field (name, *argp, t, 0);
2171       if (v)
2172         return v;
2173
2174       /* C++: If it was not found as a data field, then try to
2175          return it as a pointer to a method.  */
2176       v = search_struct_method (name, argp, args, 0, 
2177                                 static_memfuncp, t);
2178
2179       if (v == (struct value *) - 1)
2180         error (_("Cannot take address of method %s."), name);
2181       else if (v == 0)
2182         {
2183           if (TYPE_NFN_FIELDS (t))
2184             error (_("There is no member or method named %s."), name);
2185           else
2186             error (_("There is no member named %s."), name);
2187         }
2188       return v;
2189     }
2190
2191   v = search_struct_method (name, argp, args, 0, 
2192                             static_memfuncp, t);
2193   
2194   if (v == (struct value *) - 1)
2195     {
2196       error (_("One of the arguments you tried to pass to %s could not "
2197                "be converted to what the function wants."), name);
2198     }
2199   else if (v == 0)
2200     {
2201       /* See if user tried to invoke data as function.  If so, hand it
2202          back.  If it's not callable (i.e., a pointer to function),
2203          gdb should give an error.  */
2204       v = search_struct_field (name, *argp, t, 0);
2205       /* If we found an ordinary field, then it is not a method call.
2206          So, treat it as if it were a static member function.  */
2207       if (v && static_memfuncp)
2208         *static_memfuncp = 1;
2209     }
2210
2211   if (!v)
2212     throw_error (NOT_FOUND_ERROR,
2213                  _("Structure has no component named %s."), name);
2214   return v;
2215 }
2216
2217 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2218    to a structure or union, extract and return its component (field) of
2219    type FTYPE at the specified BITPOS.
2220    Throw an exception on error.  */
2221
2222 struct value *
2223 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2224                          const char *err)
2225 {
2226   struct type *t;
2227   int i;
2228
2229   *argp = coerce_array (*argp);
2230
2231   t = check_typedef (value_type (*argp));
2232
2233   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_IS_REFERENCE (t))
2234     {
2235       *argp = value_ind (*argp);
2236       if (TYPE_CODE (check_typedef (value_type (*argp))) != TYPE_CODE_FUNC)
2237         *argp = coerce_array (*argp);
2238       t = check_typedef (value_type (*argp));
2239     }
2240
2241   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2242       && TYPE_CODE (t) != TYPE_CODE_UNION)
2243     error (_("Attempt to extract a component of a value that is not a %s."),
2244            err);
2245
2246   for (i = TYPE_N_BASECLASSES (t); i < TYPE_NFIELDS (t); i++)
2247     {
2248       if (!field_is_static (&TYPE_FIELD (t, i))
2249           && bitpos == TYPE_FIELD_BITPOS (t, i)
2250           && types_equal (ftype, TYPE_FIELD_TYPE (t, i)))
2251         return value_primitive_field (*argp, 0, i, t);
2252     }
2253
2254   error (_("No field with matching bitpos and type."));
2255
2256   /* Never hit.  */
2257   return NULL;
2258 }
2259
2260 /* Search through the methods of an object (and its bases) to find a
2261    specified method.  Return the pointer to the fn_field list FN_LIST of
2262    overloaded instances defined in the source language.  If available
2263    and matching, a vector of matching xmethods defined in extension
2264    languages are also returned in XM_WORKER_VEC
2265
2266    Helper function for value_find_oload_list.
2267    ARGP is a pointer to a pointer to a value (the object).
2268    METHOD is a string containing the method name.
2269    OFFSET is the offset within the value.
2270    TYPE is the assumed type of the object.
2271    FN_LIST is the pointer to matching overloaded instances defined in
2272       source language.  Since this is a recursive function, *FN_LIST
2273       should be set to NULL when calling this function.
2274    NUM_FNS is the number of overloaded instances.  *NUM_FNS should be set to
2275       0 when calling this function.
2276    XM_WORKER_VEC is the vector of matching xmethod workers.  *XM_WORKER_VEC
2277       should also be set to NULL when calling this function.
2278    BASETYPE is set to the actual type of the subobject where the
2279       method is found.
2280    BOFFSET is the offset of the base subobject where the method is found.  */
2281
2282 static void
2283 find_method_list (struct value **argp, const char *method,
2284                   LONGEST offset, struct type *type,
2285                   struct fn_field **fn_list, int *num_fns,
2286                   std::vector<xmethod_worker_up> *xm_worker_vec,
2287                   struct type **basetype, LONGEST *boffset)
2288 {
2289   int i;
2290   struct fn_field *f = NULL;
2291
2292   gdb_assert (fn_list != NULL && xm_worker_vec != NULL);
2293   type = check_typedef (type);
2294
2295   /* First check in object itself.
2296      This function is called recursively to search through base classes.
2297      If there is a source method match found at some stage, then we need not
2298      look for source methods in consequent recursive calls.  */
2299   if ((*fn_list) == NULL)
2300     {
2301       for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2302         {
2303           /* pai: FIXME What about operators and type conversions?  */
2304           const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2305
2306           if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2307             {
2308               int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2309               f = TYPE_FN_FIELDLIST1 (type, i);
2310               *fn_list = f;
2311
2312               *num_fns = len;
2313               *basetype = type;
2314               *boffset = offset;
2315
2316               /* Resolve any stub methods.  */
2317               check_stub_method_group (type, i);
2318
2319               break;
2320             }
2321         }
2322     }
2323
2324   /* Unlike source methods, xmethods can be accumulated over successive
2325      recursive calls.  In other words, an xmethod named 'm' in a class
2326      will not hide an xmethod named 'm' in its base class(es).  We want
2327      it to be this way because xmethods are after all convenience functions
2328      and hence there is no point restricting them with something like method
2329      hiding.  Moreover, if hiding is done for xmethods as well, then we will
2330      have to provide a mechanism to un-hide (like the 'using' construct).  */
2331   get_matching_xmethod_workers (type, method, xm_worker_vec);
2332
2333   /* If source methods are not found in current class, look for them in the
2334      base classes.  We also have to go through the base classes to gather
2335      extension methods.  */
2336   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2337     {
2338       LONGEST base_offset;
2339
2340       if (BASETYPE_VIA_VIRTUAL (type, i))
2341         {
2342           base_offset = baseclass_offset (type, i,
2343                                           value_contents_for_printing (*argp),
2344                                           value_offset (*argp) + offset,
2345                                           value_address (*argp), *argp);
2346         }
2347       else /* Non-virtual base, simply use bit position from debug
2348               info.  */
2349         {
2350           base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2351         }
2352
2353       find_method_list (argp, method, base_offset + offset,
2354                         TYPE_BASECLASS (type, i), fn_list, num_fns,
2355                         xm_worker_vec, basetype, boffset);
2356     }
2357 }
2358
2359 /* Return the list of overloaded methods of a specified name.  The methods
2360    could be those GDB finds in the binary, or xmethod.  Methods found in
2361    the binary are returned in FN_LIST, and xmethods are returned in
2362    XM_WORKER_VEC.
2363
2364    ARGP is a pointer to a pointer to a value (the object).
2365    METHOD is the method name.
2366    OFFSET is the offset within the value contents.
2367    FN_LIST is the pointer to matching overloaded instances defined in
2368       source language.
2369    NUM_FNS is the number of overloaded instances.
2370    XM_WORKER_VEC is the vector of matching xmethod workers defined in
2371       extension languages.
2372    BASETYPE is set to the type of the base subobject that defines the
2373       method.
2374    BOFFSET is the offset of the base subobject which defines the method.  */
2375
2376 static void
2377 value_find_oload_method_list (struct value **argp, const char *method,
2378                               LONGEST offset, struct fn_field **fn_list,
2379                               int *num_fns,
2380                               std::vector<xmethod_worker_up> *xm_worker_vec,
2381                               struct type **basetype, LONGEST *boffset)
2382 {
2383   struct type *t;
2384
2385   t = check_typedef (value_type (*argp));
2386
2387   /* Code snarfed from value_struct_elt.  */
2388   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_IS_REFERENCE (t))
2389     {
2390       *argp = value_ind (*argp);
2391       /* Don't coerce fn pointer to fn and then back again!  */
2392       if (TYPE_CODE (check_typedef (value_type (*argp))) != TYPE_CODE_FUNC)
2393         *argp = coerce_array (*argp);
2394       t = check_typedef (value_type (*argp));
2395     }
2396
2397   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2398       && TYPE_CODE (t) != TYPE_CODE_UNION)
2399     error (_("Attempt to extract a component of a "
2400              "value that is not a struct or union"));
2401
2402   gdb_assert (fn_list != NULL && xm_worker_vec != NULL);
2403
2404   /* Clear the lists.  */
2405   *fn_list = NULL;
2406   *num_fns = 0;
2407   xm_worker_vec->clear ();
2408
2409   find_method_list (argp, method, 0, t, fn_list, num_fns, xm_worker_vec,
2410                     basetype, boffset);
2411 }
2412
2413 /* Given an array of arguments (ARGS) (which includes an
2414    entry for "this" in the case of C++ methods), the number of
2415    arguments NARGS, the NAME of a function, and whether it's a method or
2416    not (METHOD), find the best function that matches on the argument types
2417    according to the overload resolution rules.
2418
2419    METHOD can be one of three values:
2420      NON_METHOD for non-member functions.
2421      METHOD: for member functions.
2422      BOTH: used for overload resolution of operators where the
2423        candidates are expected to be either member or non member
2424        functions.  In this case the first argument ARGTYPES
2425        (representing 'this') is expected to be a reference to the
2426        target object, and will be dereferenced when attempting the
2427        non-member search.
2428
2429    In the case of class methods, the parameter OBJ is an object value
2430    in which to search for overloaded methods.
2431
2432    In the case of non-method functions, the parameter FSYM is a symbol
2433    corresponding to one of the overloaded functions.
2434
2435    Return value is an integer: 0 -> good match, 10 -> debugger applied
2436    non-standard coercions, 100 -> incompatible.
2437
2438    If a method is being searched for, VALP will hold the value.
2439    If a non-method is being searched for, SYMP will hold the symbol 
2440    for it.
2441
2442    If a method is being searched for, and it is a static method,
2443    then STATICP will point to a non-zero value.
2444
2445    If NO_ADL argument dependent lookup is disabled.  This is used to prevent
2446    ADL overload candidates when performing overload resolution for a fully
2447    qualified name.
2448
2449    If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2450    read while picking the best overload match (it may be all zeroes and thus
2451    not have a vtable pointer), in which case skip virtual function lookup.
2452    This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2453    the result type.
2454
2455    Note: This function does *not* check the value of
2456    overload_resolution.  Caller must check it to see whether overload
2457    resolution is permitted.  */
2458
2459 int
2460 find_overload_match (struct value **args, int nargs,
2461                      const char *name, enum oload_search_type method,
2462                      struct value **objp, struct symbol *fsym,
2463                      struct value **valp, struct symbol **symp, 
2464                      int *staticp, const int no_adl,
2465                      const enum noside noside)
2466 {
2467   struct value *obj = (objp ? *objp : NULL);
2468   struct type *obj_type = obj ? value_type (obj) : NULL;
2469   /* Index of best overloaded function.  */
2470   int func_oload_champ = -1;
2471   int method_oload_champ = -1;
2472   int src_method_oload_champ = -1;
2473   int ext_method_oload_champ = -1;
2474
2475   /* The measure for the current best match.  */
2476   struct badness_vector *method_badness = NULL;
2477   struct badness_vector *func_badness = NULL;
2478   struct badness_vector *ext_method_badness = NULL;
2479   struct badness_vector *src_method_badness = NULL;
2480
2481   struct value *temp = obj;
2482   /* For methods, the list of overloaded methods.  */
2483   struct fn_field *fns_ptr = NULL;
2484   /* For non-methods, the list of overloaded function symbols.  */
2485   struct symbol **oload_syms = NULL;
2486   /* For xmethods, the vector of xmethod workers.  */
2487   std::vector<xmethod_worker_up> xm_worker_vec;
2488   /* Number of overloaded instances being considered.  */
2489   int num_fns = 0;
2490   struct type *basetype = NULL;
2491   LONGEST boffset;
2492
2493   struct cleanup *all_cleanups = make_cleanup (null_cleanup, NULL);
2494
2495   const char *obj_type_name = NULL;
2496   const char *func_name = NULL;
2497   enum oload_classification match_quality;
2498   enum oload_classification method_match_quality = INCOMPATIBLE;
2499   enum oload_classification src_method_match_quality = INCOMPATIBLE;
2500   enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2501   enum oload_classification func_match_quality = INCOMPATIBLE;
2502
2503   /* Get the list of overloaded methods or functions.  */
2504   if (method == METHOD || method == BOTH)
2505     {
2506       gdb_assert (obj);
2507
2508       /* OBJ may be a pointer value rather than the object itself.  */
2509       obj = coerce_ref (obj);
2510       while (TYPE_CODE (check_typedef (value_type (obj))) == TYPE_CODE_PTR)
2511         obj = coerce_ref (value_ind (obj));
2512       obj_type_name = TYPE_NAME (value_type (obj));
2513
2514       /* First check whether this is a data member, e.g. a pointer to
2515          a function.  */
2516       if (TYPE_CODE (check_typedef (value_type (obj))) == TYPE_CODE_STRUCT)
2517         {
2518           *valp = search_struct_field (name, obj,
2519                                        check_typedef (value_type (obj)), 0);
2520           if (*valp)
2521             {
2522               *staticp = 1;
2523               do_cleanups (all_cleanups);
2524               return 0;
2525             }
2526         }
2527
2528       /* Retrieve the list of methods with the name NAME.  */
2529       value_find_oload_method_list (&temp, name, 0, &fns_ptr, &num_fns,
2530                                     &xm_worker_vec, &basetype, &boffset);
2531       /* If this is a method only search, and no methods were found
2532          the search has failed.  */
2533       if (method == METHOD && (!fns_ptr || !num_fns) && xm_worker_vec.empty ())
2534         error (_("Couldn't find method %s%s%s"),
2535                obj_type_name,
2536                (obj_type_name && *obj_type_name) ? "::" : "",
2537                name);
2538       /* If we are dealing with stub method types, they should have
2539          been resolved by find_method_list via
2540          value_find_oload_method_list above.  */
2541       if (fns_ptr)
2542         {
2543           gdb_assert (TYPE_SELF_TYPE (fns_ptr[0].type) != NULL);
2544
2545           src_method_oload_champ = find_oload_champ (args, nargs,
2546                                                      num_fns, fns_ptr, NULL,
2547                                                      NULL, &src_method_badness);
2548
2549           src_method_match_quality = classify_oload_match
2550             (src_method_badness, nargs,
2551              oload_method_static_p (fns_ptr, src_method_oload_champ));
2552
2553           make_cleanup (xfree, src_method_badness);
2554         }
2555
2556       if (!xm_worker_vec.empty ())
2557         {
2558           ext_method_oload_champ = find_oload_champ (args, nargs,
2559                                                      0, NULL, &xm_worker_vec,
2560                                                      NULL, &ext_method_badness);
2561           ext_method_match_quality = classify_oload_match (ext_method_badness,
2562                                                            nargs, 0);
2563           make_cleanup (xfree, ext_method_badness);
2564         }
2565
2566       if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2567         {
2568           switch (compare_badness (ext_method_badness, src_method_badness))
2569             {
2570               case 0: /* Src method and xmethod are equally good.  */
2571                 /* If src method and xmethod are equally good, then
2572                    xmethod should be the winner.  Hence, fall through to the
2573                    case where a xmethod is better than the source
2574                    method, except when the xmethod match quality is
2575                    non-standard.  */
2576                 /* FALLTHROUGH */
2577               case 1: /* Src method and ext method are incompatible.  */
2578                 /* If ext method match is not standard, then let source method
2579                    win.  Otherwise, fallthrough to let xmethod win.  */
2580                 if (ext_method_match_quality != STANDARD)
2581                   {
2582                     method_oload_champ = src_method_oload_champ;
2583                     method_badness = src_method_badness;
2584                     ext_method_oload_champ = -1;
2585                     method_match_quality = src_method_match_quality;
2586                     break;
2587                   }
2588                 /* FALLTHROUGH */
2589               case 2: /* Ext method is champion.  */
2590                 method_oload_champ = ext_method_oload_champ;
2591                 method_badness = ext_method_badness;
2592                 src_method_oload_champ = -1;
2593                 method_match_quality = ext_method_match_quality;
2594                 break;
2595               case 3: /* Src method is champion.  */
2596                 method_oload_champ = src_method_oload_champ;
2597                 method_badness = src_method_badness;
2598                 ext_method_oload_champ = -1;
2599                 method_match_quality = src_method_match_quality;
2600                 break;
2601               default:
2602                 gdb_assert_not_reached ("Unexpected overload comparison "
2603                                         "result");
2604                 break;
2605             }
2606         }
2607       else if (src_method_oload_champ >= 0)
2608         {
2609           method_oload_champ = src_method_oload_champ;
2610           method_badness = src_method_badness;
2611           method_match_quality = src_method_match_quality;
2612         }
2613       else if (ext_method_oload_champ >= 0)
2614         {
2615           method_oload_champ = ext_method_oload_champ;
2616           method_badness = ext_method_badness;
2617           method_match_quality = ext_method_match_quality;
2618         }
2619     }
2620
2621   if (method == NON_METHOD || method == BOTH)
2622     {
2623       const char *qualified_name = NULL;
2624
2625       /* If the overload match is being search for both as a method
2626          and non member function, the first argument must now be
2627          dereferenced.  */
2628       if (method == BOTH)
2629         args[0] = value_ind (args[0]);
2630
2631       if (fsym)
2632         {
2633           qualified_name = SYMBOL_NATURAL_NAME (fsym);
2634
2635           /* If we have a function with a C++ name, try to extract just
2636              the function part.  Do not try this for non-functions (e.g.
2637              function pointers).  */
2638           if (qualified_name
2639               && TYPE_CODE (check_typedef (SYMBOL_TYPE (fsym)))
2640               == TYPE_CODE_FUNC)
2641             {
2642               char *temp;
2643
2644               temp = cp_func_name (qualified_name);
2645
2646               /* If cp_func_name did not remove anything, the name of the
2647                  symbol did not include scope or argument types - it was
2648                  probably a C-style function.  */
2649               if (temp)
2650                 {
2651                   make_cleanup (xfree, temp);
2652                   if (strcmp (temp, qualified_name) == 0)
2653                     func_name = NULL;
2654                   else
2655                     func_name = temp;
2656                 }
2657             }
2658         }
2659       else
2660         {
2661           func_name = name;
2662           qualified_name = name;
2663         }
2664
2665       /* If there was no C++ name, this must be a C-style function or
2666          not a function at all.  Just return the same symbol.  Do the
2667          same if cp_func_name fails for some reason.  */
2668       if (func_name == NULL)
2669         {
2670           *symp = fsym;
2671           do_cleanups (all_cleanups);
2672           return 0;
2673         }
2674
2675       func_oload_champ = find_oload_champ_namespace (args, nargs,
2676                                                      func_name,
2677                                                      qualified_name,
2678                                                      &oload_syms,
2679                                                      &func_badness,
2680                                                      no_adl);
2681
2682       if (func_oload_champ >= 0)
2683         func_match_quality = classify_oload_match (func_badness, nargs, 0);
2684
2685       make_cleanup (xfree, oload_syms);
2686       make_cleanup (xfree, func_badness);
2687     }
2688
2689   /* Did we find a match ?  */
2690   if (method_oload_champ == -1 && func_oload_champ == -1)
2691     throw_error (NOT_FOUND_ERROR,
2692                  _("No symbol \"%s\" in current context."),
2693                  name);
2694
2695   /* If we have found both a method match and a function
2696      match, find out which one is better, and calculate match
2697      quality.  */
2698   if (method_oload_champ >= 0 && func_oload_champ >= 0)
2699     {
2700       switch (compare_badness (func_badness, method_badness))
2701         {
2702           case 0: /* Top two contenders are equally good.  */
2703             /* FIXME: GDB does not support the general ambiguous case.
2704              All candidates should be collected and presented the
2705              user.  */
2706             error (_("Ambiguous overload resolution"));
2707             break;
2708           case 1: /* Incomparable top contenders.  */
2709             /* This is an error incompatible candidates
2710                should not have been proposed.  */
2711             error (_("Internal error: incompatible "
2712                      "overload candidates proposed"));
2713             break;
2714           case 2: /* Function champion.  */
2715             method_oload_champ = -1;
2716             match_quality = func_match_quality;
2717             break;
2718           case 3: /* Method champion.  */
2719             func_oload_champ = -1;
2720             match_quality = method_match_quality;
2721             break;
2722           default:
2723             error (_("Internal error: unexpected overload comparison result"));
2724             break;
2725         }
2726     }
2727   else
2728     {
2729       /* We have either a method match or a function match.  */
2730       if (method_oload_champ >= 0)
2731         match_quality = method_match_quality;
2732       else
2733         match_quality = func_match_quality;
2734     }
2735
2736   if (match_quality == INCOMPATIBLE)
2737     {
2738       if (method == METHOD)
2739         error (_("Cannot resolve method %s%s%s to any overloaded instance"),
2740                obj_type_name,
2741                (obj_type_name && *obj_type_name) ? "::" : "",
2742                name);
2743       else
2744         error (_("Cannot resolve function %s to any overloaded instance"),
2745                func_name);
2746     }
2747   else if (match_quality == NON_STANDARD)
2748     {
2749       if (method == METHOD)
2750         warning (_("Using non-standard conversion to match "
2751                    "method %s%s%s to supplied arguments"),
2752                  obj_type_name,
2753                  (obj_type_name && *obj_type_name) ? "::" : "",
2754                  name);
2755       else
2756         warning (_("Using non-standard conversion to match "
2757                    "function %s to supplied arguments"),
2758                  func_name);
2759     }
2760
2761   if (staticp != NULL)
2762     *staticp = oload_method_static_p (fns_ptr, method_oload_champ);
2763
2764   if (method_oload_champ >= 0)
2765     {
2766       if (src_method_oload_champ >= 0)
2767         {
2768           if (TYPE_FN_FIELD_VIRTUAL_P (fns_ptr, method_oload_champ)
2769               && noside != EVAL_AVOID_SIDE_EFFECTS)
2770             {
2771               *valp = value_virtual_fn_field (&temp, fns_ptr,
2772                                               method_oload_champ, basetype,
2773                                               boffset);
2774             }
2775           else
2776             *valp = value_fn_field (&temp, fns_ptr, method_oload_champ,
2777                                     basetype, boffset);
2778         }
2779       else
2780         *valp = value_from_xmethod
2781           (xm_worker_vec[ext_method_oload_champ]->clone ());
2782     }
2783   else
2784     *symp = oload_syms[func_oload_champ];
2785
2786   if (objp)
2787     {
2788       struct type *temp_type = check_typedef (value_type (temp));
2789       struct type *objtype = check_typedef (obj_type);
2790
2791       if (TYPE_CODE (temp_type) != TYPE_CODE_PTR
2792           && (TYPE_CODE (objtype) == TYPE_CODE_PTR
2793               || TYPE_IS_REFERENCE (objtype)))
2794         {
2795           temp = value_addr (temp);
2796         }
2797       *objp = temp;
2798     }
2799
2800   do_cleanups (all_cleanups);
2801
2802   switch (match_quality)
2803     {
2804     case INCOMPATIBLE:
2805       return 100;
2806     case NON_STANDARD:
2807       return 10;
2808     default:                            /* STANDARD */
2809       return 0;
2810     }
2811 }
2812
2813 /* Find the best overload match, searching for FUNC_NAME in namespaces
2814    contained in QUALIFIED_NAME until it either finds a good match or
2815    runs out of namespaces.  It stores the overloaded functions in
2816    *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV.  The
2817    calling function is responsible for freeing *OLOAD_SYMS and
2818    *OLOAD_CHAMP_BV.  If NO_ADL, argument dependent lookup is not 
2819    performned.  */
2820
2821 static int
2822 find_oload_champ_namespace (struct value **args, int nargs,
2823                             const char *func_name,
2824                             const char *qualified_name,
2825                             struct symbol ***oload_syms,
2826                             struct badness_vector **oload_champ_bv,
2827                             const int no_adl)
2828 {
2829   int oload_champ;
2830
2831   find_oload_champ_namespace_loop (args, nargs,
2832                                    func_name,
2833                                    qualified_name, 0,
2834                                    oload_syms, oload_champ_bv,
2835                                    &oload_champ,
2836                                    no_adl);
2837
2838   return oload_champ;
2839 }
2840
2841 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
2842    how deep we've looked for namespaces, and the champ is stored in
2843    OLOAD_CHAMP.  The return value is 1 if the champ is a good one, 0
2844    if it isn't.  Other arguments are the same as in
2845    find_oload_champ_namespace
2846
2847    It is the caller's responsibility to free *OLOAD_SYMS and
2848    *OLOAD_CHAMP_BV.  */
2849
2850 static int
2851 find_oload_champ_namespace_loop (struct value **args, int nargs,
2852                                  const char *func_name,
2853                                  const char *qualified_name,
2854                                  int namespace_len,
2855                                  struct symbol ***oload_syms,
2856                                  struct badness_vector **oload_champ_bv,
2857                                  int *oload_champ,
2858                                  const int no_adl)
2859 {
2860   int next_namespace_len = namespace_len;
2861   int searched_deeper = 0;
2862   int num_fns = 0;
2863   struct cleanup *old_cleanups;
2864   int new_oload_champ;
2865   struct symbol **new_oload_syms;
2866   struct badness_vector *new_oload_champ_bv;
2867   char *new_namespace;
2868
2869   if (next_namespace_len != 0)
2870     {
2871       gdb_assert (qualified_name[next_namespace_len] == ':');
2872       next_namespace_len +=  2;
2873     }
2874   next_namespace_len +=
2875     cp_find_first_component (qualified_name + next_namespace_len);
2876
2877   /* Initialize these to values that can safely be xfree'd.  */
2878   *oload_syms = NULL;
2879   *oload_champ_bv = NULL;
2880
2881   /* First, see if we have a deeper namespace we can search in.
2882      If we get a good match there, use it.  */
2883
2884   if (qualified_name[next_namespace_len] == ':')
2885     {
2886       searched_deeper = 1;
2887
2888       if (find_oload_champ_namespace_loop (args, nargs,
2889                                            func_name, qualified_name,
2890                                            next_namespace_len,
2891                                            oload_syms, oload_champ_bv,
2892                                            oload_champ, no_adl))
2893         {
2894           return 1;
2895         }
2896     };
2897
2898   /* If we reach here, either we're in the deepest namespace or we
2899      didn't find a good match in a deeper namespace.  But, in the
2900      latter case, we still have a bad match in a deeper namespace;
2901      note that we might not find any match at all in the current
2902      namespace.  (There's always a match in the deepest namespace,
2903      because this overload mechanism only gets called if there's a
2904      function symbol to start off with.)  */
2905
2906   old_cleanups = make_cleanup (xfree, *oload_syms);
2907   make_cleanup (xfree, *oload_champ_bv);
2908   new_namespace = (char *) alloca (namespace_len + 1);
2909   strncpy (new_namespace, qualified_name, namespace_len);
2910   new_namespace[namespace_len] = '\0';
2911   new_oload_syms = make_symbol_overload_list (func_name,
2912                                               new_namespace);
2913
2914   /* If we have reached the deepest level perform argument
2915      determined lookup.  */
2916   if (!searched_deeper && !no_adl)
2917     {
2918       int ix;
2919       struct type **arg_types;
2920
2921       /* Prepare list of argument types for overload resolution.  */
2922       arg_types = (struct type **)
2923         alloca (nargs * (sizeof (struct type *)));
2924       for (ix = 0; ix < nargs; ix++)
2925         arg_types[ix] = value_type (args[ix]);
2926       make_symbol_overload_list_adl (arg_types, nargs, func_name);
2927     }
2928
2929   while (new_oload_syms[num_fns])
2930     ++num_fns;
2931
2932   new_oload_champ = find_oload_champ (args, nargs, num_fns,
2933                                       NULL, NULL, new_oload_syms,
2934                                       &new_oload_champ_bv);
2935
2936   /* Case 1: We found a good match.  Free earlier matches (if any),
2937      and return it.  Case 2: We didn't find a good match, but we're
2938      not the deepest function.  Then go with the bad match that the
2939      deeper function found.  Case 3: We found a bad match, and we're
2940      the deepest function.  Then return what we found, even though
2941      it's a bad match.  */
2942
2943   if (new_oload_champ != -1
2944       && classify_oload_match (new_oload_champ_bv, nargs, 0) == STANDARD)
2945     {
2946       *oload_syms = new_oload_syms;
2947       *oload_champ = new_oload_champ;
2948       *oload_champ_bv = new_oload_champ_bv;
2949       do_cleanups (old_cleanups);
2950       return 1;
2951     }
2952   else if (searched_deeper)
2953     {
2954       xfree (new_oload_syms);
2955       xfree (new_oload_champ_bv);
2956       discard_cleanups (old_cleanups);
2957       return 0;
2958     }
2959   else
2960     {
2961       *oload_syms = new_oload_syms;
2962       *oload_champ = new_oload_champ;
2963       *oload_champ_bv = new_oload_champ_bv;
2964       do_cleanups (old_cleanups);
2965       return 0;
2966     }
2967 }
2968
2969 /* Look for a function to take NARGS args of ARGS.  Find
2970    the best match from among the overloaded methods or functions
2971    given by FNS_PTR or OLOAD_SYMS or XM_WORKER_VEC, respectively.
2972    One, and only one of FNS_PTR, OLOAD_SYMS and XM_WORKER_VEC can be
2973    non-NULL.
2974
2975    If XM_WORKER_VEC is NULL, then the length of the arrays FNS_PTR
2976    or OLOAD_SYMS (whichever is non-NULL) is specified in NUM_FNS.
2977
2978    Return the index of the best match; store an indication of the
2979    quality of the match in OLOAD_CHAMP_BV.
2980
2981    It is the caller's responsibility to free *OLOAD_CHAMP_BV.  */
2982
2983 static int
2984 find_oload_champ (struct value **args, int nargs,
2985                   int num_fns, struct fn_field *fns_ptr,
2986                   const std::vector<xmethod_worker_up> *xm_worker_vec,
2987                   struct symbol **oload_syms,
2988                   struct badness_vector **oload_champ_bv)
2989 {
2990   int ix;
2991   /* A measure of how good an overloaded instance is.  */
2992   struct badness_vector *bv;
2993   /* Index of best overloaded function.  */
2994   int oload_champ = -1;
2995   /* Current ambiguity state for overload resolution.  */
2996   int oload_ambiguous = 0;
2997   /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs.  */
2998
2999   /* A champion can be found among methods alone, or among functions
3000      alone, or in xmethods alone, but not in more than one of these
3001      groups.  */
3002   gdb_assert ((fns_ptr != NULL) + (oload_syms != NULL) + (xm_worker_vec != NULL)
3003               == 1);
3004
3005   *oload_champ_bv = NULL;
3006
3007   int fn_count = xm_worker_vec != NULL ? xm_worker_vec->size () : num_fns;
3008
3009   /* Consider each candidate in turn.  */
3010   for (ix = 0; ix < fn_count; ix++)
3011     {
3012       int jj;
3013       int static_offset = 0;
3014       int nparms;
3015       struct type **parm_types;
3016
3017       if (xm_worker_vec != NULL)
3018         {
3019           xmethod_worker *worker = (*xm_worker_vec)[ix].get ();
3020           parm_types = worker->get_arg_types (&nparms);
3021         }
3022       else
3023         {
3024           if (fns_ptr != NULL)
3025             {
3026               nparms = TYPE_NFIELDS (TYPE_FN_FIELD_TYPE (fns_ptr, ix));
3027               static_offset = oload_method_static_p (fns_ptr, ix);
3028             }
3029           else
3030             nparms = TYPE_NFIELDS (SYMBOL_TYPE (oload_syms[ix]));
3031
3032           parm_types = XNEWVEC (struct type *, nparms);
3033           for (jj = 0; jj < nparms; jj++)
3034             parm_types[jj] = (fns_ptr != NULL
3035                               ? (TYPE_FN_FIELD_ARGS (fns_ptr, ix)[jj].type)
3036                               : TYPE_FIELD_TYPE (SYMBOL_TYPE (oload_syms[ix]),
3037                                                  jj));
3038         }
3039
3040       /* Compare parameter types to supplied argument types.  Skip
3041          THIS for static methods.  */
3042       bv = rank_function (parm_types, nparms, 
3043                           args + static_offset,
3044                           nargs - static_offset);
3045
3046       if (!*oload_champ_bv)
3047         {
3048           *oload_champ_bv = bv;
3049           oload_champ = 0;
3050         }
3051       else /* See whether current candidate is better or worse than
3052               previous best.  */
3053         switch (compare_badness (bv, *oload_champ_bv))
3054           {
3055           case 0:               /* Top two contenders are equally good.  */
3056             oload_ambiguous = 1;
3057             break;
3058           case 1:               /* Incomparable top contenders.  */
3059             oload_ambiguous = 2;
3060             break;
3061           case 2:               /* New champion, record details.  */
3062             *oload_champ_bv = bv;
3063             oload_ambiguous = 0;
3064             oload_champ = ix;
3065             break;
3066           case 3:
3067           default:
3068             break;
3069           }
3070       xfree (parm_types);
3071       if (overload_debug)
3072         {
3073           if (fns_ptr != NULL)
3074             fprintf_filtered (gdb_stderr,
3075                               "Overloaded method instance %s, # of parms %d\n",
3076                               fns_ptr[ix].physname, nparms);
3077           else if (xm_worker_vec != NULL)
3078             fprintf_filtered (gdb_stderr,
3079                               "Xmethod worker, # of parms %d\n",
3080                               nparms);
3081           else
3082             fprintf_filtered (gdb_stderr,
3083                               "Overloaded function instance "
3084                               "%s # of parms %d\n",
3085                               SYMBOL_DEMANGLED_NAME (oload_syms[ix]), 
3086                               nparms);
3087           for (jj = 0; jj < nargs - static_offset; jj++)
3088             fprintf_filtered (gdb_stderr,
3089                               "...Badness @ %d : %d\n", 
3090                               jj, bv->rank[jj].rank);
3091           fprintf_filtered (gdb_stderr, "Overload resolution "
3092                             "champion is %d, ambiguous? %d\n", 
3093                             oload_champ, oload_ambiguous);
3094         }
3095     }
3096
3097   return oload_champ;
3098 }
3099
3100 /* Return 1 if we're looking at a static method, 0 if we're looking at
3101    a non-static method or a function that isn't a method.  */
3102
3103 static int
3104 oload_method_static_p (struct fn_field *fns_ptr, int index)
3105 {
3106   if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3107     return 1;
3108   else
3109     return 0;
3110 }
3111
3112 /* Check how good an overload match OLOAD_CHAMP_BV represents.  */
3113
3114 static enum oload_classification
3115 classify_oload_match (struct badness_vector *oload_champ_bv,
3116                       int nargs,
3117                       int static_offset)
3118 {
3119   int ix;
3120   enum oload_classification worst = STANDARD;
3121
3122   for (ix = 1; ix <= nargs - static_offset; ix++)
3123     {
3124       /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3125          or worse return INCOMPATIBLE.  */
3126       if (compare_ranks (oload_champ_bv->rank[ix],
3127                          INCOMPATIBLE_TYPE_BADNESS) <= 0)
3128         return INCOMPATIBLE;    /* Truly mismatched types.  */
3129       /* Otherwise If this conversion is as bad as
3130          NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD.  */
3131       else if (compare_ranks (oload_champ_bv->rank[ix],
3132                               NS_POINTER_CONVERSION_BADNESS) <= 0)
3133         worst = NON_STANDARD;   /* Non-standard type conversions
3134                                    needed.  */
3135     }
3136
3137   /* If no INCOMPATIBLE classification was found, return the worst one
3138      that was found (if any).  */
3139   return worst;
3140 }
3141
3142 /* C++: return 1 is NAME is a legitimate name for the destructor of
3143    type TYPE.  If TYPE does not have a destructor, or if NAME is
3144    inappropriate for TYPE, an error is signaled.  Parameter TYPE should not yet
3145    have CHECK_TYPEDEF applied, this function will apply it itself.  */
3146
3147 int
3148 destructor_name_p (const char *name, struct type *type)
3149 {
3150   if (name[0] == '~')
3151     {
3152       const char *dname = type_name_no_tag_or_error (type);
3153       const char *cp = strchr (dname, '<');
3154       unsigned int len;
3155
3156       /* Do not compare the template part for template classes.  */
3157       if (cp == NULL)
3158         len = strlen (dname);
3159       else
3160         len = cp - dname;
3161       if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3162         error (_("name of destructor must equal name of class"));
3163       else
3164         return 1;
3165     }
3166   return 0;
3167 }
3168
3169 /* Find an enum constant named NAME in TYPE.  TYPE must be an "enum
3170    class".  If the name is found, return a value representing it;
3171    otherwise throw an exception.  */
3172
3173 static struct value *
3174 enum_constant_from_type (struct type *type, const char *name)
3175 {
3176   int i;
3177   int name_len = strlen (name);
3178
3179   gdb_assert (TYPE_CODE (type) == TYPE_CODE_ENUM
3180               && TYPE_DECLARED_CLASS (type));
3181
3182   for (i = TYPE_N_BASECLASSES (type); i < TYPE_NFIELDS (type); ++i)
3183     {
3184       const char *fname = TYPE_FIELD_NAME (type, i);
3185       int len;
3186
3187       if (TYPE_FIELD_LOC_KIND (type, i) != FIELD_LOC_KIND_ENUMVAL
3188           || fname == NULL)
3189         continue;
3190
3191       /* Look for the trailing "::NAME", since enum class constant
3192          names are qualified here.  */
3193       len = strlen (fname);
3194       if (len + 2 >= name_len
3195           && fname[len - name_len - 2] == ':'
3196           && fname[len - name_len - 1] == ':'
3197           && strcmp (&fname[len - name_len], name) == 0)
3198         return value_from_longest (type, TYPE_FIELD_ENUMVAL (type, i));
3199     }
3200
3201   error (_("no constant named \"%s\" in enum \"%s\""),
3202          name, TYPE_TAG_NAME (type));
3203 }
3204
3205 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3206    return the appropriate member (or the address of the member, if
3207    WANT_ADDRESS).  This function is used to resolve user expressions
3208    of the form "DOMAIN::NAME".  For more details on what happens, see
3209    the comment before value_struct_elt_for_reference.  */
3210
3211 struct value *
3212 value_aggregate_elt (struct type *curtype, const char *name,
3213                      struct type *expect_type, int want_address,
3214                      enum noside noside)
3215 {
3216   switch (TYPE_CODE (curtype))
3217     {
3218     case TYPE_CODE_STRUCT:
3219     case TYPE_CODE_UNION:
3220       return value_struct_elt_for_reference (curtype, 0, curtype, 
3221                                              name, expect_type,
3222                                              want_address, noside);
3223     case TYPE_CODE_NAMESPACE:
3224       return value_namespace_elt (curtype, name, 
3225                                   want_address, noside);
3226
3227     case TYPE_CODE_ENUM:
3228       return enum_constant_from_type (curtype, name);
3229
3230     default:
3231       internal_error (__FILE__, __LINE__,
3232                       _("non-aggregate type in value_aggregate_elt"));
3233     }
3234 }
3235
3236 /* Compares the two method/function types T1 and T2 for "equality" 
3237    with respect to the methods' parameters.  If the types of the
3238    two parameter lists are the same, returns 1; 0 otherwise.  This
3239    comparison may ignore any artificial parameters in T1 if
3240    SKIP_ARTIFICIAL is non-zero.  This function will ALWAYS skip
3241    the first artificial parameter in T1, assumed to be a 'this' pointer.
3242
3243    The type T2 is expected to have come from make_params (in eval.c).  */
3244
3245 static int
3246 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3247 {
3248   int start = 0;
3249
3250   if (TYPE_NFIELDS (t1) > 0 && TYPE_FIELD_ARTIFICIAL (t1, 0))
3251     ++start;
3252
3253   /* If skipping artificial fields, find the first real field
3254      in T1.  */
3255   if (skip_artificial)
3256     {
3257       while (start < TYPE_NFIELDS (t1)
3258              && TYPE_FIELD_ARTIFICIAL (t1, start))
3259         ++start;
3260     }
3261
3262   /* Now compare parameters.  */
3263
3264   /* Special case: a method taking void.  T1 will contain no
3265      non-artificial fields, and T2 will contain TYPE_CODE_VOID.  */
3266   if ((TYPE_NFIELDS (t1) - start) == 0 && TYPE_NFIELDS (t2) == 1
3267       && TYPE_CODE (TYPE_FIELD_TYPE (t2, 0)) == TYPE_CODE_VOID)
3268     return 1;
3269
3270   if ((TYPE_NFIELDS (t1) - start) == TYPE_NFIELDS (t2))
3271     {
3272       int i;
3273
3274       for (i = 0; i < TYPE_NFIELDS (t2); ++i)
3275         {
3276           if (compare_ranks (rank_one_type (TYPE_FIELD_TYPE (t1, start + i),
3277                                             TYPE_FIELD_TYPE (t2, i), NULL),
3278                              EXACT_MATCH_BADNESS) != 0)
3279             return 0;
3280         }
3281
3282       return 1;
3283     }
3284
3285   return 0;
3286 }
3287
3288 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3289    return the address of this member as a "pointer to member" type.
3290    If INTYPE is non-null, then it will be the type of the member we
3291    are looking for.  This will help us resolve "pointers to member
3292    functions".  This function is used to resolve user expressions of
3293    the form "DOMAIN::NAME".  */
3294
3295 static struct value *
3296 value_struct_elt_for_reference (struct type *domain, int offset,
3297                                 struct type *curtype, const char *name,
3298                                 struct type *intype, 
3299                                 int want_address,
3300                                 enum noside noside)
3301 {
3302   struct type *t = curtype;
3303   int i;
3304   struct value *v, *result;
3305
3306   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
3307       && TYPE_CODE (t) != TYPE_CODE_UNION)
3308     error (_("Internal error: non-aggregate type "
3309              "to value_struct_elt_for_reference"));
3310
3311   for (i = TYPE_NFIELDS (t) - 1; i >= TYPE_N_BASECLASSES (t); i--)
3312     {
3313       const char *t_field_name = TYPE_FIELD_NAME (t, i);
3314
3315       if (t_field_name && strcmp (t_field_name, name) == 0)
3316         {
3317           if (field_is_static (&TYPE_FIELD (t, i)))
3318             {
3319               v = value_static_field (t, i);
3320               if (want_address)
3321                 v = value_addr (v);
3322               return v;
3323             }
3324           if (TYPE_FIELD_PACKED (t, i))
3325             error (_("pointers to bitfield members not allowed"));
3326
3327           if (want_address)
3328             return value_from_longest
3329               (lookup_memberptr_type (TYPE_FIELD_TYPE (t, i), domain),
3330                offset + (LONGEST) (TYPE_FIELD_BITPOS (t, i) >> 3));
3331           else if (noside != EVAL_NORMAL)
3332             return allocate_value (TYPE_FIELD_TYPE (t, i));
3333           else
3334             {
3335               /* Try to evaluate NAME as a qualified name with implicit
3336                  this pointer.  In this case, attempt to return the
3337                  equivalent to `this->*(&TYPE::NAME)'.  */
3338               v = value_of_this_silent (current_language);
3339               if (v != NULL)
3340                 {
3341                   struct value *ptr;
3342                   long mem_offset;
3343                   struct type *type, *tmp;
3344
3345                   ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3346                   type = check_typedef (value_type (ptr));
3347                   gdb_assert (type != NULL
3348                               && TYPE_CODE (type) == TYPE_CODE_MEMBERPTR);
3349                   tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3350                   v = value_cast_pointers (tmp, v, 1);
3351                   mem_offset = value_as_long (ptr);
3352                   tmp = lookup_pointer_type (TYPE_TARGET_TYPE (type));
3353                   result = value_from_pointer (tmp,
3354                                                value_as_long (v) + mem_offset);
3355                   return value_ind (result);
3356                 }
3357
3358               error (_("Cannot reference non-static field \"%s\""), name);
3359             }
3360         }
3361     }
3362
3363   /* C++: If it was not found as a data field, then try to return it
3364      as a pointer to a method.  */
3365
3366   /* Perform all necessary dereferencing.  */
3367   while (intype && TYPE_CODE (intype) == TYPE_CODE_PTR)
3368     intype = TYPE_TARGET_TYPE (intype);
3369
3370   for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3371     {
3372       const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3373       char dem_opname[64];
3374
3375       if (startswith (t_field_name, "__") 
3376           || startswith (t_field_name, "op") 
3377           || startswith (t_field_name, "type"))
3378         {
3379           if (cplus_demangle_opname (t_field_name, 
3380                                      dem_opname, DMGL_ANSI))
3381             t_field_name = dem_opname;
3382           else if (cplus_demangle_opname (t_field_name, 
3383                                           dem_opname, 0))
3384             t_field_name = dem_opname;
3385         }
3386       if (t_field_name && strcmp (t_field_name, name) == 0)
3387         {
3388           int j;
3389           int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3390           struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3391
3392           check_stub_method_group (t, i);
3393
3394           if (intype)
3395             {
3396               for (j = 0; j < len; ++j)
3397                 {
3398                   if (TYPE_CONST (intype) != TYPE_FN_FIELD_CONST (f, j))
3399                     continue;
3400                   if (TYPE_VOLATILE (intype) != TYPE_FN_FIELD_VOLATILE (f, j))
3401                     continue;
3402
3403                   if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3404                       || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3405                                              intype, 1))
3406                     break;
3407                 }
3408
3409               if (j == len)
3410                 error (_("no member function matches "
3411                          "that type instantiation"));
3412             }
3413           else
3414             {
3415               int ii;
3416
3417               j = -1;
3418               for (ii = 0; ii < len; ++ii)
3419                 {
3420                   /* Skip artificial methods.  This is necessary if,
3421                      for example, the user wants to "print
3422                      subclass::subclass" with only one user-defined
3423                      constructor.  There is no ambiguity in this case.
3424                      We are careful here to allow artificial methods
3425                      if they are the unique result.  */
3426                   if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3427                     {
3428                       if (j == -1)
3429                         j = ii;
3430                       continue;
3431                     }
3432
3433                   /* Desired method is ambiguous if more than one
3434                      method is defined.  */
3435                   if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3436                     error (_("non-unique member `%s' requires "
3437                              "type instantiation"), name);
3438
3439                   j = ii;
3440                 }
3441
3442               if (j == -1)
3443                 error (_("no matching member function"));
3444             }
3445
3446           if (TYPE_FN_FIELD_STATIC_P (f, j))
3447             {
3448               struct symbol *s = 
3449                 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3450                                0, VAR_DOMAIN, 0).symbol;
3451
3452               if (s == NULL)
3453                 return NULL;
3454
3455               if (want_address)
3456                 return value_addr (read_var_value (s, 0, 0));
3457               else
3458                 return read_var_value (s, 0, 0);
3459             }
3460
3461           if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3462             {
3463               if (want_address)
3464                 {
3465                   result = allocate_value
3466                     (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3467                   cplus_make_method_ptr (value_type (result),
3468                                          value_contents_writeable (result),
3469                                          TYPE_FN_FIELD_VOFFSET (f, j), 1);
3470                 }
3471               else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3472                 return allocate_value (TYPE_FN_FIELD_TYPE (f, j));
3473               else
3474                 error (_("Cannot reference virtual member function \"%s\""),
3475                        name);
3476             }
3477           else
3478             {
3479               struct symbol *s = 
3480                 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3481                                0, VAR_DOMAIN, 0).symbol;
3482
3483               if (s == NULL)
3484                 return NULL;
3485
3486               v = read_var_value (s, 0, 0);
3487               if (!want_address)
3488                 result = v;
3489               else
3490                 {
3491                   result = allocate_value (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3492                   cplus_make_method_ptr (value_type (result),
3493                                          value_contents_writeable (result),
3494                                          value_address (v), 0);
3495                 }
3496             }
3497           return result;
3498         }
3499     }
3500   for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3501     {
3502       struct value *v;
3503       int base_offset;
3504
3505       if (BASETYPE_VIA_VIRTUAL (t, i))
3506         base_offset = 0;
3507       else
3508         base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3509       v = value_struct_elt_for_reference (domain,
3510                                           offset + base_offset,
3511                                           TYPE_BASECLASS (t, i),
3512                                           name, intype, 
3513                                           want_address, noside);
3514       if (v)
3515         return v;
3516     }
3517
3518   /* As a last chance, pretend that CURTYPE is a namespace, and look
3519      it up that way; this (frequently) works for types nested inside
3520      classes.  */
3521
3522   return value_maybe_namespace_elt (curtype, name, 
3523                                     want_address, noside);
3524 }
3525
3526 /* C++: Return the member NAME of the namespace given by the type
3527    CURTYPE.  */
3528
3529 static struct value *
3530 value_namespace_elt (const struct type *curtype,
3531                      const char *name, int want_address,
3532                      enum noside noside)
3533 {
3534   struct value *retval = value_maybe_namespace_elt (curtype, name,
3535                                                     want_address, 
3536                                                     noside);
3537
3538   if (retval == NULL)
3539     error (_("No symbol \"%s\" in namespace \"%s\"."), 
3540            name, TYPE_TAG_NAME (curtype));
3541
3542   return retval;
3543 }
3544
3545 /* A helper function used by value_namespace_elt and
3546    value_struct_elt_for_reference.  It looks up NAME inside the
3547    context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3548    is a class and NAME refers to a type in CURTYPE itself (as opposed
3549    to, say, some base class of CURTYPE).  */
3550
3551 static struct value *
3552 value_maybe_namespace_elt (const struct type *curtype,
3553                            const char *name, int want_address,
3554                            enum noside noside)
3555 {
3556   const char *namespace_name = TYPE_TAG_NAME (curtype);
3557   struct block_symbol sym;
3558   struct value *result;
3559
3560   sym = cp_lookup_symbol_namespace (namespace_name, name,
3561                                     get_selected_block (0), VAR_DOMAIN);
3562
3563   if (sym.symbol == NULL)
3564     return NULL;
3565   else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3566            && (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF))
3567     result = allocate_value (SYMBOL_TYPE (sym.symbol));
3568   else
3569     result = value_of_variable (sym.symbol, sym.block);
3570
3571   if (want_address)
3572     result = value_addr (result);
3573
3574   return result;
3575 }
3576
3577 /* Given a pointer or a reference value V, find its real (RTTI) type.
3578
3579    Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3580    and refer to the values computed for the object pointed to.  */
3581
3582 struct type *
3583 value_rtti_indirect_type (struct value *v, int *full, 
3584                           LONGEST *top, int *using_enc)
3585 {
3586   struct value *target = NULL;
3587   struct type *type, *real_type, *target_type;
3588
3589   type = value_type (v);
3590   type = check_typedef (type);
3591   if (TYPE_IS_REFERENCE (type))
3592     target = coerce_ref (v);
3593   else if (TYPE_CODE (type) == TYPE_CODE_PTR)
3594     {
3595
3596       TRY
3597         {
3598           target = value_ind (v);
3599         }
3600       CATCH (except, RETURN_MASK_ERROR)
3601         {
3602           if (except.error == MEMORY_ERROR)
3603             {
3604               /* value_ind threw a memory error. The pointer is NULL or
3605                  contains an uninitialized value: we can't determine any
3606                  type.  */
3607               return NULL;
3608             }
3609           throw_exception (except);
3610         }
3611       END_CATCH
3612     }
3613   else
3614     return NULL;
3615
3616   real_type = value_rtti_type (target, full, top, using_enc);
3617
3618   if (real_type)
3619     {
3620       /* Copy qualifiers to the referenced object.  */
3621       target_type = value_type (target);
3622       real_type = make_cv_type (TYPE_CONST (target_type),
3623                                 TYPE_VOLATILE (target_type), real_type, NULL);
3624       if (TYPE_IS_REFERENCE (type))
3625         real_type = lookup_reference_type (real_type, TYPE_CODE (type));
3626       else if (TYPE_CODE (type) == TYPE_CODE_PTR)
3627         real_type = lookup_pointer_type (real_type);
3628       else
3629         internal_error (__FILE__, __LINE__, _("Unexpected value type."));
3630
3631       /* Copy qualifiers to the pointer/reference.  */
3632       real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3633                                 real_type, NULL);
3634     }
3635
3636   return real_type;
3637 }
3638
3639 /* Given a value pointed to by ARGP, check its real run-time type, and
3640    if that is different from the enclosing type, create a new value
3641    using the real run-time type as the enclosing type (and of the same
3642    type as ARGP) and return it, with the embedded offset adjusted to
3643    be the correct offset to the enclosed object.  RTYPE is the type,
3644    and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3645    by value_rtti_type().  If these are available, they can be supplied
3646    and a second call to value_rtti_type() is avoided.  (Pass RTYPE ==
3647    NULL if they're not available.  */
3648
3649 struct value *
3650 value_full_object (struct value *argp, 
3651                    struct type *rtype, 
3652                    int xfull, int xtop,
3653                    int xusing_enc)
3654 {
3655   struct type *real_type;
3656   int full = 0;
3657   LONGEST top = -1;
3658   int using_enc = 0;
3659   struct value *new_val;
3660
3661   if (rtype)
3662     {
3663       real_type = rtype;
3664       full = xfull;
3665       top = xtop;
3666       using_enc = xusing_enc;
3667     }
3668   else
3669     real_type = value_rtti_type (argp, &full, &top, &using_enc);
3670
3671   /* If no RTTI data, or if object is already complete, do nothing.  */
3672   if (!real_type || real_type == value_enclosing_type (argp))
3673     return argp;
3674
3675   /* In a destructor we might see a real type that is a superclass of
3676      the object's type.  In this case it is better to leave the object
3677      as-is.  */
3678   if (full
3679       && TYPE_LENGTH (real_type) < TYPE_LENGTH (value_enclosing_type (argp)))
3680     return argp;
3681
3682   /* If we have the full object, but for some reason the enclosing
3683      type is wrong, set it.  */
3684   /* pai: FIXME -- sounds iffy */
3685   if (full)
3686     {
3687       argp = value_copy (argp);
3688       set_value_enclosing_type (argp, real_type);
3689       return argp;
3690     }
3691
3692   /* Check if object is in memory.  */
3693   if (VALUE_LVAL (argp) != lval_memory)
3694     {
3695       warning (_("Couldn't retrieve complete object of RTTI "
3696                  "type %s; object may be in register(s)."), 
3697                TYPE_NAME (real_type));
3698
3699       return argp;
3700     }
3701
3702   /* All other cases -- retrieve the complete object.  */
3703   /* Go back by the computed top_offset from the beginning of the
3704      object, adjusting for the embedded offset of argp if that's what
3705      value_rtti_type used for its computation.  */
3706   new_val = value_at_lazy (real_type, value_address (argp) - top +
3707                            (using_enc ? 0 : value_embedded_offset (argp)));
3708   deprecated_set_value_type (new_val, value_type (argp));
3709   set_value_embedded_offset (new_val, (using_enc
3710                                        ? top + value_embedded_offset (argp)
3711                                        : top));
3712   return new_val;
3713 }
3714
3715
3716 /* Return the value of the local variable, if one exists.  Throw error
3717    otherwise, such as if the request is made in an inappropriate context.  */
3718
3719 struct value *
3720 value_of_this (const struct language_defn *lang)
3721 {
3722   struct block_symbol sym;
3723   const struct block *b;
3724   struct frame_info *frame;
3725
3726   if (!lang->la_name_of_this)
3727     error (_("no `this' in current language"));
3728
3729   frame = get_selected_frame (_("no frame selected"));
3730
3731   b = get_frame_block (frame, NULL);
3732
3733   sym = lookup_language_this (lang, b);
3734   if (sym.symbol == NULL)
3735     error (_("current stack frame does not contain a variable named `%s'"),
3736            lang->la_name_of_this);
3737
3738   return read_var_value (sym.symbol, sym.block, frame);
3739 }
3740
3741 /* Return the value of the local variable, if one exists.  Return NULL
3742    otherwise.  Never throw error.  */
3743
3744 struct value *
3745 value_of_this_silent (const struct language_defn *lang)
3746 {
3747   struct value *ret = NULL;
3748
3749   TRY
3750     {
3751       ret = value_of_this (lang);
3752     }
3753   CATCH (except, RETURN_MASK_ERROR)
3754     {
3755     }
3756   END_CATCH
3757
3758   return ret;
3759 }
3760
3761 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
3762    elements long, starting at LOWBOUND.  The result has the same lower
3763    bound as the original ARRAY.  */
3764
3765 struct value *
3766 value_slice (struct value *array, int lowbound, int length)
3767 {
3768   struct type *slice_range_type, *slice_type, *range_type;
3769   LONGEST lowerbound, upperbound;
3770   struct value *slice;
3771   struct type *array_type;
3772
3773   array_type = check_typedef (value_type (array));
3774   if (TYPE_CODE (array_type) != TYPE_CODE_ARRAY
3775       && TYPE_CODE (array_type) != TYPE_CODE_STRING)
3776     error (_("cannot take slice of non-array"));
3777
3778   range_type = TYPE_INDEX_TYPE (array_type);
3779   if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
3780     error (_("slice from bad array or bitstring"));
3781
3782   if (lowbound < lowerbound || length < 0
3783       || lowbound + length - 1 > upperbound)
3784     error (_("slice out of range"));
3785
3786   /* FIXME-type-allocation: need a way to free this type when we are
3787      done with it.  */
3788   slice_range_type = create_static_range_type ((struct type *) NULL,
3789                                                TYPE_TARGET_TYPE (range_type),
3790                                                lowbound,
3791                                                lowbound + length - 1);
3792
3793   {
3794     struct type *element_type = TYPE_TARGET_TYPE (array_type);
3795     LONGEST offset
3796       = (lowbound - lowerbound) * TYPE_LENGTH (check_typedef (element_type));
3797
3798     slice_type = create_array_type ((struct type *) NULL,
3799                                     element_type,
3800                                     slice_range_type);
3801     TYPE_CODE (slice_type) = TYPE_CODE (array_type);
3802
3803     if (VALUE_LVAL (array) == lval_memory && value_lazy (array))
3804       slice = allocate_value_lazy (slice_type);
3805     else
3806       {
3807         slice = allocate_value (slice_type);
3808         value_contents_copy (slice, 0, array, offset,
3809                              type_length_units (slice_type));
3810       }
3811
3812     set_value_component_location (slice, array);
3813     set_value_offset (slice, value_offset (array) + offset);
3814   }
3815
3816   return slice;
3817 }
3818
3819 /* Create a value for a FORTRAN complex number.  Currently most of the
3820    time values are coerced to COMPLEX*16 (i.e. a complex number
3821    composed of 2 doubles.  This really should be a smarter routine
3822    that figures out precision inteligently as opposed to assuming
3823    doubles.  FIXME: fmb  */
3824
3825 struct value *
3826 value_literal_complex (struct value *arg1, 
3827                        struct value *arg2,
3828                        struct type *type)
3829 {
3830   struct value *val;
3831   struct type *real_type = TYPE_TARGET_TYPE (type);
3832
3833   val = allocate_value (type);
3834   arg1 = value_cast (real_type, arg1);
3835   arg2 = value_cast (real_type, arg2);
3836
3837   memcpy (value_contents_raw (val),
3838           value_contents (arg1), TYPE_LENGTH (real_type));
3839   memcpy (value_contents_raw (val) + TYPE_LENGTH (real_type),
3840           value_contents (arg2), TYPE_LENGTH (real_type));
3841   return val;
3842 }
3843
3844 /* Cast a value into the appropriate complex data type.  */
3845
3846 static struct value *
3847 cast_into_complex (struct type *type, struct value *val)
3848 {
3849   struct type *real_type = TYPE_TARGET_TYPE (type);
3850
3851   if (TYPE_CODE (value_type (val)) == TYPE_CODE_COMPLEX)
3852     {
3853       struct type *val_real_type = TYPE_TARGET_TYPE (value_type (val));
3854       struct value *re_val = allocate_value (val_real_type);
3855       struct value *im_val = allocate_value (val_real_type);
3856
3857       memcpy (value_contents_raw (re_val),
3858               value_contents (val), TYPE_LENGTH (val_real_type));
3859       memcpy (value_contents_raw (im_val),
3860               value_contents (val) + TYPE_LENGTH (val_real_type),
3861               TYPE_LENGTH (val_real_type));
3862
3863       return value_literal_complex (re_val, im_val, type);
3864     }
3865   else if (TYPE_CODE (value_type (val)) == TYPE_CODE_FLT
3866            || TYPE_CODE (value_type (val)) == TYPE_CODE_INT)
3867     return value_literal_complex (val, 
3868                                   value_zero (real_type, not_lval), 
3869                                   type);
3870   else
3871     error (_("cannot cast non-number to complex"));
3872 }
3873
3874 void
3875 _initialize_valops (void)
3876 {
3877   add_setshow_boolean_cmd ("overload-resolution", class_support,
3878                            &overload_resolution, _("\
3879 Set overload resolution in evaluating C++ functions."), _("\
3880 Show overload resolution in evaluating C++ functions."), 
3881                            NULL, NULL,
3882                            show_overload_resolution,
3883                            &setlist, &showlist);
3884   overload_resolution = 1;
3885 }