OSDN Git Service

* cvt.c (convert_lvalue): New fn.
[pf3gnuchains/gcc-fork.git] / gcc / cp / class.c
1 /* Functions related to building classes and their related objects.
2    Copyright (C) 1987, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001  Free Software Foundation, Inc.
4    Contributed by Michael Tiemann (tiemann@cygnus.com)
5
6 This file is part of GNU CC.
7
8 GNU CC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GNU CC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU CC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23
24 /* High-level class interface.  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "tree.h"
29 #include "cp-tree.h"
30 #include "flags.h"
31 #include "rtl.h"
32 #include "output.h"
33 #include "toplev.h"
34 #include "ggc.h"
35 #include "lex.h"
36
37 #include "obstack.h"
38 #define obstack_chunk_alloc xmalloc
39 #define obstack_chunk_free free
40
41 /* The number of nested classes being processed.  If we are not in the
42    scope of any class, this is zero.  */
43
44 int current_class_depth;
45
46 /* In order to deal with nested classes, we keep a stack of classes.
47    The topmost entry is the innermost class, and is the entry at index
48    CURRENT_CLASS_DEPTH  */
49
50 typedef struct class_stack_node {
51   /* The name of the class.  */
52   tree name;
53
54   /* The _TYPE node for the class.  */
55   tree type;
56
57   /* The access specifier pending for new declarations in the scope of
58      this class.  */
59   tree access;
60
61   /* If were defining TYPE, the names used in this class.  */
62   splay_tree names_used;
63 }* class_stack_node_t;
64
65 typedef struct vtbl_init_data_s
66 {
67   /* The base for which we're building initializers.  */
68   tree binfo;
69   /* The type of the most-derived type.  */
70   tree derived;
71   /* The binfo for the dynamic type. This will be TYPE_BINFO (derived),
72      unless ctor_vtbl_p is true.  */
73   tree rtti_binfo;
74   /* The negative-index vtable initializers built up so far.  These
75      are in order from least negative index to most negative index.  */
76   tree inits;
77   /* The last (i.e., most negative) entry in INITS.  */
78   tree* last_init;
79   /* The binfo for the virtual base for which we're building
80      vcall offset initializers.  */
81   tree vbase;
82   /* The functions in vbase for which we have already provided vcall
83      offsets.  */
84   varray_type fns;
85   /* The vtable index of the next vcall or vbase offset.  */
86   tree index;
87   /* Nonzero if we are building the initializer for the primary
88      vtable.  */
89   int primary_vtbl_p;
90   /* Nonzero if we are building the initializer for a construction
91      vtable.  */
92   int ctor_vtbl_p;
93 } vtbl_init_data;
94
95 /* The type of a function passed to walk_subobject_offsets.  */
96 typedef int (*subobject_offset_fn) PARAMS ((tree, tree, splay_tree));
97
98 /* The stack itself.  This is an dynamically resized array.  The
99    number of elements allocated is CURRENT_CLASS_STACK_SIZE.  */
100 static int current_class_stack_size;
101 static class_stack_node_t current_class_stack;
102
103 /* An array of all local classes present in this translation unit, in
104    declaration order.  */
105 varray_type local_classes;
106
107 static tree get_vfield_name PARAMS ((tree));
108 static void finish_struct_anon PARAMS ((tree));
109 static tree build_vbase_pointer PARAMS ((tree, tree));
110 static tree build_vtable_entry PARAMS ((tree, tree, tree));
111 static tree get_vtable_name PARAMS ((tree));
112 static tree get_basefndecls PARAMS ((tree, tree));
113 static int build_primary_vtable PARAMS ((tree, tree));
114 static int build_secondary_vtable PARAMS ((tree, tree));
115 static tree dfs_finish_vtbls PARAMS ((tree, void *));
116 static void finish_vtbls PARAMS ((tree));
117 static void modify_vtable_entry PARAMS ((tree, tree, tree, tree, tree *));
118 static void add_virtual_function PARAMS ((tree *, tree *, int *, tree, tree));
119 static tree delete_duplicate_fields_1 PARAMS ((tree, tree));
120 static void delete_duplicate_fields PARAMS ((tree));
121 static void finish_struct_bits PARAMS ((tree));
122 static int alter_access PARAMS ((tree, tree, tree));
123 static void handle_using_decl PARAMS ((tree, tree));
124 static int strictly_overrides PARAMS ((tree, tree));
125 static void mark_overriders PARAMS ((tree, tree));
126 static void check_for_override PARAMS ((tree, tree));
127 static tree dfs_modify_vtables PARAMS ((tree, void *));
128 static tree modify_all_vtables PARAMS ((tree, int *, tree));
129 static void determine_primary_base PARAMS ((tree, int *));
130 static void finish_struct_methods PARAMS ((tree));
131 static void maybe_warn_about_overly_private_class PARAMS ((tree));
132 static int field_decl_cmp PARAMS ((const tree *, const tree *));
133 static int method_name_cmp PARAMS ((const tree *, const tree *));
134 static tree add_implicitly_declared_members PARAMS ((tree, int, int, int));
135 static tree fixed_type_or_null PARAMS ((tree, int *, int *));
136 static tree resolve_address_of_overloaded_function PARAMS ((tree, tree, int,
137                                                           int, int, tree));
138 static void build_vtable_entry_ref PARAMS ((tree, tree));
139 static tree build_vtbl_initializer PARAMS ((tree, tree, tree, tree, int *));
140 static int count_fields PARAMS ((tree));
141 static int add_fields_to_vec PARAMS ((tree, tree, int));
142 static void check_bitfield_decl PARAMS ((tree));
143 static void check_field_decl PARAMS ((tree, tree, int *, int *, int *, int *));
144 static void check_field_decls PARAMS ((tree, tree *, int *, int *, int *, 
145                                      int *));
146 static bool build_base_field PARAMS ((record_layout_info, tree, int *,
147                                      splay_tree, tree));
148 static bool build_base_fields PARAMS ((record_layout_info, int *,
149                                       splay_tree, tree));
150 static tree build_vbase_pointer_fields PARAMS ((record_layout_info, int *));
151 static tree build_vtbl_or_vbase_field PARAMS ((tree, tree, tree, tree, tree,
152                                                int *));
153 static void check_methods PARAMS ((tree));
154 static void remove_zero_width_bit_fields PARAMS ((tree));
155 static void check_bases PARAMS ((tree, int *, int *, int *));
156 static void check_bases_and_members PARAMS ((tree, int *));
157 static tree create_vtable_ptr PARAMS ((tree, int *, int *, tree *, tree *));
158 static void layout_class_type PARAMS ((tree, int *, int *, tree *, tree *));
159 static void fixup_pending_inline PARAMS ((tree));
160 static void fixup_inline_methods PARAMS ((tree));
161 static void set_primary_base PARAMS ((tree, tree, int *));
162 static void propagate_binfo_offsets PARAMS ((tree, tree, tree));
163 static void layout_virtual_bases PARAMS ((tree, splay_tree));
164 static tree dfs_set_offset_for_unshared_vbases PARAMS ((tree, void *));
165 static void build_vbase_offset_vtbl_entries PARAMS ((tree, vtbl_init_data *));
166 static void add_vcall_offset_vtbl_entries_r PARAMS ((tree, vtbl_init_data *));
167 static void add_vcall_offset_vtbl_entries_1 PARAMS ((tree, vtbl_init_data *));
168 static void build_vcall_offset_vtbl_entries PARAMS ((tree, vtbl_init_data *));
169 static void layout_vtable_decl PARAMS ((tree, int));
170 static tree dfs_find_final_overrider PARAMS ((tree, void *));
171 static tree find_final_overrider PARAMS ((tree, tree, tree));
172 static int make_new_vtable PARAMS ((tree, tree));
173 static int maybe_indent_hierarchy PARAMS ((FILE *, int, int));
174 static void dump_class_hierarchy_r PARAMS ((FILE *, int, tree, tree, int));
175 static void dump_class_hierarchy PARAMS ((tree));
176 static void dump_array PARAMS ((FILE *, tree));
177 static void dump_vtable PARAMS ((tree, tree, tree));
178 static void dump_vtt PARAMS ((tree, tree));
179 static tree build_vtable PARAMS ((tree, tree, tree));
180 static void initialize_vtable PARAMS ((tree, tree));
181 static void initialize_array PARAMS ((tree, tree));
182 static void layout_nonempty_base_or_field PARAMS ((record_layout_info,
183                                                    tree, tree,
184                                                    splay_tree, tree));
185 static unsigned HOST_WIDE_INT end_of_class PARAMS ((tree, int));
186 static bool layout_empty_base PARAMS ((tree, tree, splay_tree, tree));
187 static void accumulate_vtbl_inits PARAMS ((tree, tree, tree, tree, tree));
188 static tree dfs_accumulate_vtbl_inits PARAMS ((tree, tree, tree, tree,
189                                                tree));
190 static void set_vindex PARAMS ((tree, int *));
191 static void build_rtti_vtbl_entries PARAMS ((tree, vtbl_init_data *));
192 static void build_vcall_and_vbase_vtbl_entries PARAMS ((tree, 
193                                                         vtbl_init_data *));
194 static void force_canonical_binfo_r PARAMS ((tree, tree, tree, tree));
195 static void force_canonical_binfo PARAMS ((tree, tree, tree, tree));
196 static tree dfs_unshared_virtual_bases PARAMS ((tree, void *));
197 static void mark_primary_bases PARAMS ((tree));
198 static tree mark_primary_virtual_base PARAMS ((tree, tree, tree));
199 static void clone_constructors_and_destructors PARAMS ((tree));
200 static tree build_clone PARAMS ((tree, tree));
201 static void update_vtable_entry_for_fn PARAMS ((tree, tree, tree, tree *));
202 static tree copy_virtuals PARAMS ((tree));
203 static void build_ctor_vtbl_group PARAMS ((tree, tree));
204 static void build_vtt PARAMS ((tree));
205 static tree *build_vtt_inits PARAMS ((tree, tree, tree *, tree *));
206 static tree dfs_build_secondary_vptr_vtt_inits PARAMS ((tree, void *));
207 static tree dfs_ctor_vtable_bases_queue_p PARAMS ((tree, void *data));
208 static tree dfs_fixup_binfo_vtbls PARAMS ((tree, void *));
209 static tree get_original_base PARAMS ((tree, tree));
210 static tree dfs_get_primary_binfo PARAMS ((tree, void*));
211 static int record_subobject_offset PARAMS ((tree, tree, splay_tree));
212 static int check_subobject_offset PARAMS ((tree, tree, splay_tree));
213 static int walk_subobject_offsets PARAMS ((tree, subobject_offset_fn,
214                                            tree, splay_tree, tree, int));
215 static void record_subobject_offsets PARAMS ((tree, tree, splay_tree, int));
216 static int layout_conflict_p PARAMS ((tree, tree, splay_tree, int));
217 static int splay_tree_compare_integer_csts PARAMS ((splay_tree_key k1,
218                                                     splay_tree_key k2));
219 static void warn_about_ambiguous_direct_bases PARAMS ((tree));
220
221 /* Macros for dfs walking during vtt construction. See
222    dfs_ctor_vtable_bases_queue_p, dfs_build_secondary_vptr_vtt_inits
223    and dfs_fixup_binfo_vtbls.  */
224 #define VTT_TOP_LEVEL_P(node) TREE_UNSIGNED(node)
225 #define VTT_MARKED_BINFO_P(node) TREE_USED(node)
226
227 /* Variables shared between class.c and call.c.  */
228
229 #ifdef GATHER_STATISTICS
230 int n_vtables = 0;
231 int n_vtable_entries = 0;
232 int n_vtable_searches = 0;
233 int n_vtable_elems = 0;
234 int n_convert_harshness = 0;
235 int n_compute_conversion_costs = 0;
236 int n_build_method_call = 0;
237 int n_inner_fields_searched = 0;
238 #endif
239
240 /* Virtual base class layout.  */
241
242 /* Returns a list of virtual base class pointers as a chain of
243    FIELD_DECLS.  */
244
245 static tree
246 build_vbase_pointer_fields (rli, empty_p)
247      record_layout_info rli;
248      int *empty_p;
249 {
250   /* Chain to hold all the new FIELD_DECLs which point at virtual
251      base classes.  */
252   tree rec = rli->t;
253   tree vbase_decls = NULL_TREE;
254   tree binfos = TYPE_BINFO_BASETYPES (rec);
255   int n_baseclasses = CLASSTYPE_N_BASECLASSES (rec);
256   tree decl;
257   int i;
258
259   /* Under the new ABI, there are no vbase pointers in the object.
260      Instead, the offsets are stored in the vtable.  */
261   if (vbase_offsets_in_vtable_p ())
262     return NULL_TREE;
263
264   /* Loop over the baseclasses, adding vbase pointers as needed.  */
265   for (i = 0; i < n_baseclasses; i++)
266     {
267       register tree base_binfo = TREE_VEC_ELT (binfos, i);
268       register tree basetype = BINFO_TYPE (base_binfo);
269
270       if (!COMPLETE_TYPE_P (basetype))
271         /* This error is now reported in xref_tag, thus giving better
272            location information.  */
273         continue;
274
275       /* All basetypes are recorded in the association list of the
276          derived type.  */
277
278       if (TREE_VIA_VIRTUAL (base_binfo))
279         {
280           int j;
281           const char *name;
282
283           /* The offset for a virtual base class is only used in computing
284              virtual function tables and for initializing virtual base
285              pointers.  It is built once `get_vbase_types' is called.  */
286
287           /* If this basetype can come from another vbase pointer
288              without an additional indirection, we will share
289              that pointer.  If an indirection is involved, we
290              make our own pointer.  */
291           for (j = 0; j < n_baseclasses; j++)
292             {
293               tree other_base_binfo = TREE_VEC_ELT (binfos, j);
294               if (! TREE_VIA_VIRTUAL (other_base_binfo)
295                   && binfo_for_vbase (basetype, BINFO_TYPE (other_base_binfo)))
296                 goto got_it;
297             }
298           FORMAT_VBASE_NAME (name, basetype);
299           decl = build_vtbl_or_vbase_field (get_identifier (name), 
300                                             get_identifier (VTABLE_BASE),
301                                             build_pointer_type (basetype),
302                                             rec,
303                                             basetype,
304                                             empty_p);
305           BINFO_VPTR_FIELD (base_binfo) = decl;
306           TREE_CHAIN (decl) = vbase_decls;
307           place_field (rli, decl);
308           vbase_decls = decl;
309           *empty_p = 0;
310
311         got_it:
312           /* The space this decl occupies has already been accounted for.  */
313           ;
314         }
315     }
316
317   return vbase_decls;
318 }
319
320 /* Returns a pointer to the virtual base class of EXP that has the
321    indicated TYPE.  EXP is of class type, not a pointer type.  */
322
323 static tree
324 build_vbase_pointer (exp, type)
325      tree exp, type;
326 {
327   if (vbase_offsets_in_vtable_p ())
328     {
329       tree vbase;
330       tree vbase_ptr;
331
332       /* Find the shared copy of TYPE; that's where the vtable offset
333          is recorded.  */
334       vbase = binfo_for_vbase (type, TREE_TYPE (exp));
335       /* Find the virtual function table pointer.  */
336       vbase_ptr = build_vfield_ref (exp, TREE_TYPE (exp));
337       /* Compute the location where the offset will lie.  */
338       vbase_ptr = build (PLUS_EXPR, 
339                          TREE_TYPE (vbase_ptr),
340                          vbase_ptr,
341                          BINFO_VPTR_FIELD (vbase));
342       vbase_ptr = build1 (NOP_EXPR, 
343                           build_pointer_type (ptrdiff_type_node),
344                           vbase_ptr);
345       /* Add the contents of this location to EXP.  */
346       return build (PLUS_EXPR,
347                     build_pointer_type (type),
348                     build_unary_op (ADDR_EXPR, exp, /*noconvert=*/0),
349                     build1 (INDIRECT_REF, ptrdiff_type_node, vbase_ptr));
350     }
351   else
352     {
353       char *name;
354       FORMAT_VBASE_NAME (name, type);
355       return build_component_ref (exp, get_identifier (name), NULL_TREE, 0);
356     }
357 }
358
359 /* Build multi-level access to EXPR using hierarchy path PATH.
360    CODE is PLUS_EXPR if we are going with the grain,
361    and MINUS_EXPR if we are not (in which case, we cannot traverse
362    virtual baseclass links).
363
364    TYPE is the type we want this path to have on exit.
365
366    NONNULL is non-zero if  we know (for any reason) that EXPR is
367    not, in fact, zero.  */
368
369 tree
370 build_vbase_path (code, type, expr, path, nonnull)
371      enum tree_code code;
372      tree type, expr, path;
373      int nonnull;
374 {
375   register int changed = 0;
376   tree last = NULL_TREE, last_virtual = NULL_TREE;
377   int fixed_type_p;
378   tree null_expr = 0, nonnull_expr;
379   tree basetype;
380   tree offset = integer_zero_node;
381
382   if (BINFO_INHERITANCE_CHAIN (path) == NULL_TREE)
383     return build1 (NOP_EXPR, type, expr);
384
385   /* We could do better if we had additional logic to convert back to the
386      unconverted type (the static type of the complete object), and then
387      convert back to the type we want.  Until that is done, we only optimize
388      if the complete type is the same type as expr has.  */
389   fixed_type_p = resolves_to_fixed_type_p (expr, &nonnull);
390   if (fixed_type_p < 0)
391     /* Virtual base layout is not fixed, even in ctors and dtors. */
392     fixed_type_p = 0;
393
394   if (!fixed_type_p && TREE_SIDE_EFFECTS (expr))
395     expr = save_expr (expr);
396   nonnull_expr = expr;
397
398   path = reverse_path (path);
399
400   basetype = BINFO_TYPE (path);
401
402   while (path)
403     {
404       if (TREE_VIA_VIRTUAL (TREE_VALUE (path)))
405         {
406           last_virtual = BINFO_TYPE (TREE_VALUE (path));
407           if (code == PLUS_EXPR)
408             {
409               changed = ! fixed_type_p;
410
411               if (changed)
412                 {
413                   tree ind;
414
415                   /* We already check for ambiguous things in the caller, just
416                      find a path.  */
417                   if (last)
418                     {
419                       tree binfo = get_binfo (last, TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (nonnull_expr))), 0);
420                       nonnull_expr = convert_pointer_to_real (binfo, nonnull_expr);
421                     }
422                   ind = build_indirect_ref (nonnull_expr, NULL);
423                   nonnull_expr = build_vbase_pointer (ind, last_virtual);
424                   if (nonnull == 0
425                       && TREE_CODE (type) == POINTER_TYPE
426                       && null_expr == NULL_TREE)
427                     {
428                       null_expr = build1 (NOP_EXPR, build_pointer_type (last_virtual), integer_zero_node);
429                       expr = build (COND_EXPR, build_pointer_type (last_virtual),
430                                     build (EQ_EXPR, boolean_type_node, expr,
431                                            integer_zero_node),
432                                     null_expr, nonnull_expr);
433                     }
434                 }
435               /* else we'll figure out the offset below.  */
436
437               /* Happens in the case of parse errors.  */
438               if (nonnull_expr == error_mark_node)
439                 return error_mark_node;
440             }
441           else
442             {
443               cp_error ("cannot cast up from virtual baseclass `%T'",
444                           last_virtual);
445               return error_mark_node;
446             }
447         }
448       last = TREE_VALUE (path);
449       path = TREE_CHAIN (path);
450     }
451   /* LAST is now the last basetype assoc on the path.  */
452
453   /* A pointer to a virtual base member of a non-null object
454      is non-null.  Therefore, we only need to test for zeroness once.
455      Make EXPR the canonical expression to deal with here.  */
456   if (null_expr)
457     {
458       TREE_OPERAND (expr, 2) = nonnull_expr;
459       TREE_TYPE (expr) = TREE_TYPE (TREE_OPERAND (expr, 1))
460         = TREE_TYPE (nonnull_expr);
461     }
462   else
463     expr = nonnull_expr;
464
465   /* If we go through any virtual base pointers, make sure that
466      casts to BASETYPE from the last virtual base class use
467      the right value for BASETYPE.  */
468   if (changed)
469     {
470       tree intype = TREE_TYPE (TREE_TYPE (expr));
471
472       if (TYPE_MAIN_VARIANT (intype) != BINFO_TYPE (last))
473         offset
474           = BINFO_OFFSET (get_binfo (last, TYPE_MAIN_VARIANT (intype), 0));
475     }
476   else
477     offset = BINFO_OFFSET (last);
478
479   if (! integer_zerop (offset))
480     {
481       /* Bash types to make the backend happy.  */
482       offset = cp_convert (type, offset);
483
484       /* If expr might be 0, we need to preserve that zeroness.  */
485       if (nonnull == 0)
486         {
487           if (null_expr)
488             TREE_TYPE (null_expr) = type;
489           else
490             null_expr = build1 (NOP_EXPR, type, integer_zero_node);
491           if (TREE_SIDE_EFFECTS (expr))
492             expr = save_expr (expr);
493
494           return build (COND_EXPR, type,
495                         build (EQ_EXPR, boolean_type_node, expr, integer_zero_node),
496                         null_expr,
497                         build (code, type, expr, offset));
498         }
499       else return build (code, type, expr, offset);
500     }
501
502   /* Cannot change the TREE_TYPE of a NOP_EXPR here, since it may
503      be used multiple times in initialization of multiple inheritance.  */
504   if (null_expr)
505     {
506       TREE_TYPE (expr) = type;
507       return expr;
508     }
509   else
510     return build1 (NOP_EXPR, type, expr);
511 }
512
513 \f
514 /* Virtual function things.  */
515
516 /* We want to give the assembler the vtable identifier as well as
517    the offset to the function pointer.  So we generate
518
519    __asm__ __volatile__ (".vtable_entry %c0, %c1"
520       : : "s"(&class_vtable),
521           "i"((long)&vtbl[idx].pfn - (long)&vtbl[0])); */
522
523 static void
524 build_vtable_entry_ref (basetype, idx)
525      tree basetype, idx;
526 {
527   static char asm_stmt[] = ".vtable_entry %c0, %c1";
528   tree s, i, i2;
529   tree vtable = get_vtbl_decl_for_binfo (TYPE_BINFO (basetype));
530   tree first_fn = TYPE_BINFO_VTABLE (basetype);
531
532   s = build_unary_op (ADDR_EXPR, vtable, 0);
533   s = build_tree_list (build_string (1, "s"), s);
534
535   i = build_array_ref (first_fn, idx);
536   i = build_c_cast (ptrdiff_type_node, build_unary_op (ADDR_EXPR, i, 0));
537   i2 = build_array_ref (vtable, build_int_2 (0,0));
538   i2 = build_c_cast (ptrdiff_type_node, build_unary_op (ADDR_EXPR, i2, 0));
539   i = cp_build_binary_op (MINUS_EXPR, i, i2);
540   i = build_tree_list (build_string (1, "i"), i);
541
542   finish_asm_stmt (ridpointers[RID_VOLATILE],
543                    build_string (sizeof(asm_stmt)-1, asm_stmt),
544                    NULL_TREE, chainon (s, i), NULL_TREE);
545 }
546
547 /* Given an object INSTANCE, return an expression which yields the
548    virtual function vtable element corresponding to INDEX.  There are
549    many special cases for INSTANCE which we take care of here, mainly
550    to avoid creating extra tree nodes when we don't have to.  */
551
552 tree
553 build_vtbl_ref (instance, idx)
554      tree instance, idx;
555 {
556   tree vtbl, aref;
557   tree basetype = TREE_TYPE (instance);
558
559   if (TREE_CODE (basetype) == REFERENCE_TYPE)
560     basetype = TREE_TYPE (basetype);
561
562   if (instance == current_class_ref)
563     vtbl = build_vfield_ref (instance, basetype);
564   else
565     {
566       if (optimize)
567         {
568           /* Try to figure out what a reference refers to, and
569              access its virtual function table directly.  */
570           tree ref = NULL_TREE;
571
572           if (TREE_CODE (instance) == INDIRECT_REF
573               && TREE_CODE (TREE_TYPE (TREE_OPERAND (instance, 0))) == REFERENCE_TYPE)
574             ref = TREE_OPERAND (instance, 0);
575           else if (TREE_CODE (TREE_TYPE (instance)) == REFERENCE_TYPE)
576             ref = instance;
577
578           if (ref && TREE_CODE (ref) == VAR_DECL
579               && DECL_INITIAL (ref))
580             {
581               tree init = DECL_INITIAL (ref);
582
583               while (TREE_CODE (init) == NOP_EXPR
584                      || TREE_CODE (init) == NON_LVALUE_EXPR)
585                 init = TREE_OPERAND (init, 0);
586               if (TREE_CODE (init) == ADDR_EXPR)
587                 {
588                   init = TREE_OPERAND (init, 0);
589                   if (IS_AGGR_TYPE (TREE_TYPE (init))
590                       && (TREE_CODE (init) == PARM_DECL
591                           || TREE_CODE (init) == VAR_DECL))
592                     instance = init;
593                 }
594             }
595         }
596
597       if (IS_AGGR_TYPE (TREE_TYPE (instance))
598           && (TREE_CODE (instance) == RESULT_DECL
599               || TREE_CODE (instance) == PARM_DECL
600               || TREE_CODE (instance) == VAR_DECL))
601         {
602           vtbl = TYPE_BINFO_VTABLE (basetype);
603           /* Knowing the dynamic type of INSTANCE we can easily obtain
604              the correct vtable entry.  In the new ABI, we resolve
605              this back to be in terms of the primary vtable.  */
606           if (TREE_CODE (vtbl) == PLUS_EXPR)
607             {
608               idx = fold (build (PLUS_EXPR,
609                                  TREE_TYPE (idx),
610                                  idx,
611                                  build (EXACT_DIV_EXPR,
612                                         TREE_TYPE (idx),
613                                         TREE_OPERAND (vtbl, 1),
614                                         TYPE_SIZE_UNIT (vtable_entry_type))));
615               vtbl = get_vtbl_decl_for_binfo (TYPE_BINFO (basetype));
616             }
617         }
618       else
619         vtbl = build_vfield_ref (instance, basetype);
620     }
621
622   assemble_external (vtbl);
623
624   if (flag_vtable_gc)
625     build_vtable_entry_ref (basetype, idx);
626
627   aref = build_array_ref (vtbl, idx);
628
629   return aref;
630 }
631
632 /* Given an object INSTANCE, return an expression which yields the
633    virtual function corresponding to INDEX.  There are many special
634    cases for INSTANCE which we take care of here, mainly to avoid
635    creating extra tree nodes when we don't have to.  */
636
637 tree
638 build_vfn_ref (ptr_to_instptr, instance, idx)
639      tree *ptr_to_instptr, instance;
640      tree idx;
641 {
642   tree aref = build_vtbl_ref (instance, idx);
643
644   /* When using thunks, there is no extra delta, and we get the pfn
645      directly.  */
646   if (flag_vtable_thunks)
647     return aref;
648
649   if (ptr_to_instptr)
650     {
651       /* Save the intermediate result in a SAVE_EXPR so we don't have to
652          compute each component of the virtual function pointer twice.  */ 
653       if (TREE_CODE (aref) == INDIRECT_REF)
654         TREE_OPERAND (aref, 0) = save_expr (TREE_OPERAND (aref, 0));
655
656       *ptr_to_instptr
657         = build (PLUS_EXPR, TREE_TYPE (*ptr_to_instptr),
658                  *ptr_to_instptr,
659                  cp_convert (ptrdiff_type_node,
660                              build_component_ref (aref, delta_identifier, NULL_TREE, 0)));
661     }
662
663   return build_component_ref (aref, pfn_identifier, NULL_TREE, 0);
664 }
665
666 /* Return the name of the virtual function table (as an IDENTIFIER_NODE)
667    for the given TYPE.  */
668
669 static tree
670 get_vtable_name (type)
671      tree type;
672 {
673   return mangle_vtbl_for_type (type);
674 }
675
676 /* Return an IDENTIFIER_NODE for the name of the virtual table table
677    for TYPE.  */
678
679 tree
680 get_vtt_name (type)
681      tree type;
682 {
683   return mangle_vtt_for_type (type);
684 }
685
686 /* Create a VAR_DECL for a primary or secondary vtable for CLASS_TYPE.
687    (For a secondary vtable for B-in-D, CLASS_TYPE should be D, not B.)
688    Use NAME for the name of the vtable, and VTABLE_TYPE for its type.  */
689
690 static tree
691 build_vtable (class_type, name, vtable_type)
692      tree class_type;
693      tree name;
694      tree vtable_type;
695 {
696   tree decl;
697
698   decl = build_lang_decl (VAR_DECL, name, vtable_type);
699   /* vtable names are already mangled; give them their DECL_ASSEMBLER_NAME
700      now to avoid confusion in mangle_decl.  */
701   SET_DECL_ASSEMBLER_NAME (decl, name);
702   DECL_CONTEXT (decl) = class_type;
703   DECL_ARTIFICIAL (decl) = 1;
704   TREE_STATIC (decl) = 1;
705   TREE_READONLY (decl) = 1;
706   DECL_VIRTUAL_P (decl) = 1;
707   import_export_vtable (decl, class_type, 0);
708
709   return decl;
710 }
711
712 /* Get the VAR_DECL of the vtable for TYPE. TYPE need not be polymorphic,
713    or even complete.  If this does not exist, create it.  If COMPLETE is
714    non-zero, then complete the definition of it -- that will render it
715    impossible to actually build the vtable, but is useful to get at those
716    which are known to exist in the runtime.  */
717
718 tree 
719 get_vtable_decl (type, complete)
720      tree type;
721      int complete;
722 {
723   tree name = get_vtable_name (type);
724   tree decl = IDENTIFIER_GLOBAL_VALUE (name);
725   
726   if (decl)
727     {
728       my_friendly_assert (TREE_CODE (decl) == VAR_DECL
729                           && DECL_VIRTUAL_P (decl), 20000118);
730       return decl;
731     }
732   
733   decl = build_vtable (type, name, void_type_node);
734   decl = pushdecl_top_level (decl);
735   my_friendly_assert (IDENTIFIER_GLOBAL_VALUE (name) == decl,
736                       20000517);
737   
738   /* At one time the vtable info was grabbed 2 words at a time.  This
739      fails on sparc unless you have 8-byte alignment.  (tiemann) */
740   DECL_ALIGN (decl) = MAX (TYPE_ALIGN (double_type_node),
741                            DECL_ALIGN (decl));
742
743   if (complete)
744     {
745       DECL_EXTERNAL (decl) = 1;
746       cp_finish_decl (decl, NULL_TREE, NULL_TREE, 0);
747     }
748
749   return decl;
750 }
751
752 /* Returns a copy of the BINFO_VIRTUALS list in BINFO.  The
753    BV_VCALL_INDEX for each entry is cleared.  */
754
755 static tree
756 copy_virtuals (binfo)
757      tree binfo;
758 {
759   tree copies;
760   tree t;
761
762   copies = copy_list (BINFO_VIRTUALS (binfo));
763   for (t = copies; t; t = TREE_CHAIN (t))
764     {
765       BV_VCALL_INDEX (t) = NULL_TREE;
766       BV_USE_VCALL_INDEX_P (t) = 0;
767     }
768
769   return copies;
770 }
771
772 /* Build the primary virtual function table for TYPE.  If BINFO is
773    non-NULL, build the vtable starting with the initial approximation
774    that it is the same as the one which is the head of the association
775    list.  Returns a non-zero value if a new vtable is actually
776    created.  */
777
778 static int
779 build_primary_vtable (binfo, type)
780      tree binfo, type;
781 {
782   tree decl;
783   tree virtuals;
784
785   decl = get_vtable_decl (type, /*complete=*/0);
786   
787   if (binfo)
788     {
789       if (BINFO_NEW_VTABLE_MARKED (binfo, type))
790         /* We have already created a vtable for this base, so there's
791            no need to do it again.  */
792         return 0;
793       
794       virtuals = copy_virtuals (binfo);
795       TREE_TYPE (decl) = TREE_TYPE (get_vtbl_decl_for_binfo (binfo));
796       DECL_SIZE (decl) = TYPE_SIZE (TREE_TYPE (decl));
797       DECL_SIZE_UNIT (decl) = TYPE_SIZE_UNIT (TREE_TYPE (decl));
798     }
799   else
800     {
801       my_friendly_assert (TREE_CODE (TREE_TYPE (decl)) == VOID_TYPE,
802                           20000118);
803       virtuals = NULL_TREE;
804     }
805
806 #ifdef GATHER_STATISTICS
807   n_vtables += 1;
808   n_vtable_elems += list_length (virtuals);
809 #endif
810
811   /* Initialize the association list for this type, based
812      on our first approximation.  */
813   TYPE_BINFO_VTABLE (type) = decl;
814   TYPE_BINFO_VIRTUALS (type) = virtuals;
815   SET_BINFO_NEW_VTABLE_MARKED (TYPE_BINFO (type), type);
816   return 1;
817 }
818
819 /* Give TYPE a new virtual function table which is initialized
820    with a skeleton-copy of its original initialization.  The only
821    entry that changes is the `delta' entry, so we can really
822    share a lot of structure.
823
824    FOR_TYPE is the derived type which caused this table to
825    be needed.
826
827    BINFO is the type association which provided TYPE for FOR_TYPE.
828
829    The order in which vtables are built (by calling this function) for
830    an object must remain the same, otherwise a binary incompatibility
831    can result.  */
832
833 static int
834 build_secondary_vtable (binfo, for_type)
835      tree binfo, for_type;
836 {
837   tree basetype;
838   tree orig_decl = BINFO_VTABLE (binfo);
839   tree name;
840   tree new_decl;
841   tree offset;
842   tree path = binfo;
843   char *buf;
844   const char *buf2;
845   char joiner = '_';
846   int i;
847
848 #ifdef JOINER
849   joiner = JOINER;
850 #endif
851
852   if (TREE_VIA_VIRTUAL (binfo))
853     my_friendly_assert (binfo == binfo_for_vbase (BINFO_TYPE (binfo),
854                                                   current_class_type),
855                         170);
856
857   if (BINFO_NEW_VTABLE_MARKED (binfo, current_class_type))
858     /* We already created a vtable for this base.  There's no need to
859        do it again.  */
860     return 0;
861
862   /* Remember that we've created a vtable for this BINFO, so that we
863      don't try to do so again.  */
864   SET_BINFO_NEW_VTABLE_MARKED (binfo, current_class_type);
865   
866   /* Make fresh virtual list, so we can smash it later.  */
867   BINFO_VIRTUALS (binfo) = copy_virtuals (binfo);
868
869   my_friendly_assert (binfo == CANONICAL_BINFO (binfo, for_type), 20010605);
870   offset = BINFO_OFFSET (binfo);
871
872   /* In the new ABI, secondary vtables are laid out as part of the
873      same structure as the primary vtable.  */
874   if (merge_primary_and_secondary_vtables_p ())
875     {
876       BINFO_VTABLE (binfo) = NULL_TREE;
877       return 1;
878     }
879
880   /* Create the declaration for the secondary vtable.  */
881   basetype = TYPE_MAIN_VARIANT (BINFO_TYPE (binfo));
882   buf2 = TYPE_ASSEMBLER_NAME_STRING (basetype);
883   i = TYPE_ASSEMBLER_NAME_LENGTH (basetype) + 1;
884
885   /* We know that the vtable that we are going to create doesn't exist
886      yet in the global namespace, and when we finish, it will be
887      pushed into the global namespace.  In complex MI hierarchies, we
888      have to loop while the name we are thinking of adding is globally
889      defined, adding more name components to the vtable name as we
890      loop, until the name is unique.  This is because in complex MI
891      cases, we might have the same base more than once.  This means
892      that the order in which this function is called for vtables must
893      remain the same, otherwise binary compatibility can be
894      compromised.  */
895
896   while (1)
897     {
898       char *buf1 = (char *) alloca (TYPE_ASSEMBLER_NAME_LENGTH (for_type)
899                                     + 1 + i);
900       char *new_buf2;
901
902       sprintf (buf1, "%s%c%s", TYPE_ASSEMBLER_NAME_STRING (for_type), joiner,
903                buf2);
904       buf = (char *) alloca (strlen (VTABLE_NAME_PREFIX) + strlen (buf1) + 1);
905       sprintf (buf, "%s%s", VTABLE_NAME_PREFIX, buf1);
906       name = get_identifier (buf);
907
908       /* If this name doesn't clash, then we can use it, otherwise
909          we add more to the name until it is unique.  */
910
911       if (! IDENTIFIER_GLOBAL_VALUE (name))
912         break;
913
914       /* Set values for next loop through, if the name isn't unique.  */
915
916       path = BINFO_INHERITANCE_CHAIN (path);
917
918       /* We better not run out of stuff to make it unique.  */
919       my_friendly_assert (path != NULL_TREE, 368);
920
921       basetype = TYPE_MAIN_VARIANT (BINFO_TYPE (path));
922
923       if (for_type == basetype)
924         {
925           /* If we run out of basetypes in the path, we have already
926              found created a vtable with that name before, we now
927              resort to tacking on _%d to distinguish them.  */
928           int j = 2;
929           i = TYPE_ASSEMBLER_NAME_LENGTH (basetype) + 1 + i + 1 + 3;
930           buf1 = (char *) alloca (i);
931           do {
932             sprintf (buf1, "%s%c%s%c%d",
933                      TYPE_ASSEMBLER_NAME_STRING (basetype), joiner,
934                      buf2, joiner, j);
935             buf = (char *) alloca (strlen (VTABLE_NAME_PREFIX)
936                                    + strlen (buf1) + 1);
937             sprintf (buf, "%s%s", VTABLE_NAME_PREFIX, buf1);
938             name = get_identifier (buf);
939
940             /* If this name doesn't clash, then we can use it,
941                otherwise we add something different to the name until
942                it is unique.  */
943           } while (++j <= 999 && IDENTIFIER_GLOBAL_VALUE (name));
944
945           /* Hey, they really like MI don't they?  Increase the 3
946              above to 6, and the 999 to 999999.  :-)  */
947           my_friendly_assert (j <= 999, 369);
948
949           break;
950         }
951
952       i = TYPE_ASSEMBLER_NAME_LENGTH (basetype) + 1 + i;
953       new_buf2 = (char *) alloca (i);
954       sprintf (new_buf2, "%s%c%s",
955                TYPE_ASSEMBLER_NAME_STRING (basetype), joiner, buf2);
956       buf2 = new_buf2;
957     }
958
959   new_decl = build_vtable (for_type, name, TREE_TYPE (orig_decl));
960   DECL_ALIGN (new_decl) = DECL_ALIGN (orig_decl);
961   DECL_USER_ALIGN (new_decl) = DECL_USER_ALIGN (orig_decl);
962   BINFO_VTABLE (binfo) = pushdecl_top_level (new_decl);
963
964 #ifdef GATHER_STATISTICS
965   n_vtables += 1;
966   n_vtable_elems += list_length (BINFO_VIRTUALS (binfo));
967 #endif
968
969   return 1;
970 }
971
972 /* Create a new vtable for BINFO which is the hierarchy dominated by
973    T.  */
974
975 static int
976 make_new_vtable (t, binfo)
977      tree t;
978      tree binfo;
979 {
980   if (binfo == TYPE_BINFO (t))
981     /* In this case, it is *type*'s vtable we are modifying.  We start
982        with the approximation that its vtable is that of the
983        immediate base class.  */
984     /* ??? This actually passes TYPE_BINFO (t), not the primary base binfo,
985        since we've updated DECL_CONTEXT (TYPE_VFIELD (t)) by now.  */
986     return build_primary_vtable (TYPE_BINFO (DECL_CONTEXT (TYPE_VFIELD (t))),
987                                  t);
988   else
989     /* This is our very own copy of `basetype' to play with.  Later,
990        we will fill in all the virtual functions that override the
991        virtual functions in these base classes which are not defined
992        by the current type.  */
993     return build_secondary_vtable (binfo, t);
994 }
995
996 /* Make *VIRTUALS, an entry on the BINFO_VIRTUALS list for BINFO
997    (which is in the hierarchy dominated by T) list FNDECL as its
998    BV_FN.  DELTA is the required constant adjustment from the `this'
999    pointer where the vtable entry appears to the `this' required when
1000    the function is actually called.  */
1001
1002 static void
1003 modify_vtable_entry (t, binfo, fndecl, delta, virtuals)
1004      tree t;
1005      tree binfo;
1006      tree fndecl;
1007      tree delta;
1008      tree *virtuals;
1009 {
1010   tree v;
1011
1012   v = *virtuals;
1013
1014   if (fndecl != BV_FN (v)
1015       || !tree_int_cst_equal (delta, BV_DELTA (v)))
1016     {
1017       tree base_fndecl;
1018
1019       /* We need a new vtable for BINFO.  */
1020       if (make_new_vtable (t, binfo))
1021         {
1022           /* If we really did make a new vtable, we also made a copy
1023              of the BINFO_VIRTUALS list.  Now, we have to find the
1024              corresponding entry in that list.  */
1025           *virtuals = BINFO_VIRTUALS (binfo);
1026           while (BV_FN (*virtuals) != BV_FN (v))
1027             *virtuals = TREE_CHAIN (*virtuals);
1028           v = *virtuals;
1029         }
1030
1031       base_fndecl = BV_FN (v);
1032       BV_DELTA (v) = delta;
1033       BV_VCALL_INDEX (v) = NULL_TREE;
1034       BV_FN (v) = fndecl;
1035
1036       /* Now assign virtual dispatch information, if unset.  We can
1037          dispatch this through any overridden base function.
1038
1039          FIXME this can choose a secondary vtable if the primary is not
1040          also lexically first, leading to useless conversions.
1041          In the V3 ABI, there's no reason for DECL_VIRTUAL_CONTEXT to
1042          ever be different from DECL_CONTEXT.  */
1043       if (TREE_CODE (DECL_VINDEX (fndecl)) != INTEGER_CST)
1044         {
1045           DECL_VINDEX (fndecl) = DECL_VINDEX (base_fndecl);
1046           DECL_VIRTUAL_CONTEXT (fndecl) = DECL_VIRTUAL_CONTEXT (base_fndecl);
1047         }
1048     }
1049 }
1050
1051 /* Set DECL_VINDEX for DECL.  VINDEX_P is the number of virtual
1052    functions present in the vtable so far.  */
1053
1054 static void
1055 set_vindex (decl, vfuns_p)
1056      tree decl;
1057      int *vfuns_p;
1058 {
1059   int vindex;
1060
1061   vindex = (*vfuns_p)++;
1062   DECL_VINDEX (decl) = build_shared_int_cst (vindex);
1063 }
1064
1065 /* Add a virtual function to all the appropriate vtables for the class
1066    T.  DECL_VINDEX(X) should be error_mark_node, if we want to
1067    allocate a new slot in our table.  If it is error_mark_node, we
1068    know that no other function from another vtable is overridden by X.
1069    VFUNS_P keeps track of how many virtuals there are in our
1070    main vtable for the type, and we build upon the NEW_VIRTUALS list
1071    and return it.  */
1072
1073 static void
1074 add_virtual_function (new_virtuals_p, overridden_virtuals_p,
1075                       vfuns_p, fndecl, t)
1076      tree *new_virtuals_p;
1077      tree *overridden_virtuals_p;
1078      int *vfuns_p;
1079      tree fndecl;
1080      tree t; /* Structure type.  */
1081 {
1082   tree new_virtual;
1083
1084   /* If this function doesn't override anything from a base class, we
1085      can just assign it a new DECL_VINDEX now.  Otherwise, if it does
1086      override something, we keep it around and assign its DECL_VINDEX
1087      later, in modify_all_vtables.  */
1088   if (TREE_CODE (DECL_VINDEX (fndecl)) == INTEGER_CST)
1089     /* We've already dealt with this function.  */
1090     return;
1091
1092   new_virtual = make_node (TREE_LIST);
1093   BV_FN (new_virtual) = fndecl;
1094   BV_DELTA (new_virtual) = integer_zero_node;
1095
1096   if (DECL_VINDEX (fndecl) == error_mark_node)
1097     {
1098       /* FNDECL is a new virtual function; it doesn't override any
1099          virtual function in a base class.  */
1100
1101       /* We remember that this was the base sub-object for rtti.  */
1102       CLASSTYPE_RTTI (t) = t;
1103
1104       /* Now assign virtual dispatch information.  */
1105       set_vindex (fndecl, vfuns_p);
1106       DECL_VIRTUAL_CONTEXT (fndecl) = t;
1107
1108       /* Save the state we've computed on the NEW_VIRTUALS list.  */
1109       TREE_CHAIN (new_virtual) = *new_virtuals_p;
1110       *new_virtuals_p = new_virtual;
1111     }
1112   else
1113     {
1114       /* FNDECL overrides a function from a base class.  */
1115       TREE_CHAIN (new_virtual) = *overridden_virtuals_p;
1116       *overridden_virtuals_p = new_virtual;
1117     }
1118 }
1119 \f
1120 /* Add method METHOD to class TYPE.  If ERROR_P is true, we are adding
1121    the method after the class has already been defined because a
1122    declaration for it was seen.  (Even though that is erroneous, we
1123    add the method for improved error recovery.)  */
1124
1125 void
1126 add_method (type, method, error_p)
1127      tree type;
1128      tree method;
1129      int error_p;
1130 {
1131   int using = (DECL_CONTEXT (method) != type);
1132   int len;
1133   int slot;
1134   tree method_vec;
1135
1136   if (!CLASSTYPE_METHOD_VEC (type))
1137     /* Make a new method vector.  We start with 8 entries.  We must
1138        allocate at least two (for constructors and destructors), and
1139        we're going to end up with an assignment operator at some point
1140        as well.
1141        
1142        We could use a TREE_LIST for now, and convert it to a TREE_VEC
1143        in finish_struct, but we would probably waste more memory
1144        making the links in the list than we would by over-allocating
1145        the size of the vector here.  Furthermore, we would complicate
1146        all the code that expects this to be a vector.  */
1147     CLASSTYPE_METHOD_VEC (type) = make_tree_vec (8);
1148
1149   method_vec = CLASSTYPE_METHOD_VEC (type);
1150   len = TREE_VEC_LENGTH (method_vec);
1151
1152   /* Constructors and destructors go in special slots.  */
1153   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (method))
1154     slot = CLASSTYPE_CONSTRUCTOR_SLOT;
1155   else if (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (method))
1156     slot = CLASSTYPE_DESTRUCTOR_SLOT;
1157   else
1158     {
1159       /* See if we already have an entry with this name.  */
1160       for (slot = CLASSTYPE_FIRST_CONVERSION_SLOT; slot < len; ++slot)
1161         if (!TREE_VEC_ELT (method_vec, slot)
1162             || (DECL_NAME (OVL_CURRENT (TREE_VEC_ELT (method_vec, 
1163                                                       slot))) 
1164                 == DECL_NAME (method)))
1165           break;
1166                 
1167       if (slot == len)
1168         {
1169           /* We need a bigger method vector.  */
1170           int new_len;
1171           tree new_vec;
1172
1173           /* In the non-error case, we are processing a class
1174              definition.  Double the size of the vector to give room
1175              for new methods.  */
1176           if (!error_p)
1177             new_len = 2 * len;
1178           /* In the error case, the vector is already complete.  We
1179              don't expect many errors, and the rest of the front-end
1180              will get confused if there are empty slots in the vector.  */
1181           else
1182             new_len = len + 1;
1183
1184           new_vec = make_tree_vec (new_len);
1185           memcpy (&TREE_VEC_ELT (new_vec, 0), &TREE_VEC_ELT (method_vec, 0),
1186                   len * sizeof (tree));
1187           len = new_len;
1188           method_vec = CLASSTYPE_METHOD_VEC (type) = new_vec;
1189         }
1190
1191       if (DECL_CONV_FN_P (method) && !TREE_VEC_ELT (method_vec, slot))
1192         {
1193           /* Type conversion operators have to come before ordinary
1194              methods; add_conversions depends on this to speed up
1195              looking for conversion operators.  So, if necessary, we
1196              slide some of the vector elements up.  In theory, this
1197              makes this algorithm O(N^2) but we don't expect many
1198              conversion operators.  */
1199           for (slot = 2; slot < len; ++slot)
1200             {
1201               tree fn = TREE_VEC_ELT (method_vec, slot);
1202   
1203               if (!fn)
1204                 /* There are no more entries in the vector, so we
1205                    can insert the new conversion operator here.  */
1206                 break;
1207                   
1208               if (!DECL_CONV_FN_P (OVL_CURRENT (fn)))
1209                 /* We can insert the new function right at the
1210                    SLOTth position.  */
1211                 break;
1212             }
1213   
1214           if (!TREE_VEC_ELT (method_vec, slot))
1215             /* There is nothing in the Ith slot, so we can avoid
1216                moving anything.  */
1217                 ; 
1218           else
1219             {
1220               /* We know the last slot in the vector is empty
1221                  because we know that at this point there's room
1222                  for a new function.  */
1223               memmove (&TREE_VEC_ELT (method_vec, slot + 1),
1224                        &TREE_VEC_ELT (method_vec, slot),
1225                        (len - slot - 1) * sizeof (tree));
1226               TREE_VEC_ELT (method_vec, slot) = NULL_TREE;
1227             }
1228         }
1229     }
1230       
1231   if (template_class_depth (type))
1232     /* TYPE is a template class.  Don't issue any errors now; wait
1233        until instantiation time to complain.  */
1234     ;
1235   else
1236     {
1237       tree fns;
1238
1239       /* Check to see if we've already got this method.  */
1240       for (fns = TREE_VEC_ELT (method_vec, slot);
1241            fns;
1242            fns = OVL_NEXT (fns))
1243         {
1244           tree fn = OVL_CURRENT (fns);
1245                  
1246           if (TREE_CODE (fn) != TREE_CODE (method))
1247             continue;
1248
1249           if (TREE_CODE (method) != TEMPLATE_DECL)
1250             {
1251               /* [over.load] Member function declarations with the
1252                  same name and the same parameter types cannot be
1253                  overloaded if any of them is a static member
1254                  function declaration.  */
1255               if ((DECL_STATIC_FUNCTION_P (fn)
1256                    != DECL_STATIC_FUNCTION_P (method))
1257                   || using)
1258                 {
1259                   tree parms1 = TYPE_ARG_TYPES (TREE_TYPE (fn));
1260                   tree parms2 = TYPE_ARG_TYPES (TREE_TYPE (method));
1261
1262                   if (! DECL_STATIC_FUNCTION_P (fn))
1263                     parms1 = TREE_CHAIN (parms1);
1264                   if (! DECL_STATIC_FUNCTION_P (method))
1265                     parms2 = TREE_CHAIN (parms2);
1266
1267                   if (compparms (parms1, parms2))
1268                     {
1269                       if (using)
1270                         /* Defer to the local function.  */
1271                         return;
1272                       else
1273                         cp_error ("`%#D' and `%#D' cannot be overloaded",
1274                                   fn, method);
1275                     }
1276                 }
1277             }
1278
1279           if (!decls_match (fn, method))
1280             continue;
1281
1282           /* There has already been a declaration of this method
1283              or member template.  */
1284           cp_error_at ("`%D' has already been declared in `%T'", 
1285                        method, type);
1286
1287           /* We don't call duplicate_decls here to merge the
1288              declarations because that will confuse things if the
1289              methods have inline definitions.  In particular, we
1290              will crash while processing the definitions.  */
1291           return;
1292         }
1293     }
1294
1295   /* Actually insert the new method.  */
1296   TREE_VEC_ELT (method_vec, slot) 
1297     = build_overload (method, TREE_VEC_ELT (method_vec, slot));
1298
1299       /* Add the new binding.  */ 
1300   if (!DECL_CONSTRUCTOR_P (method)
1301       && !DECL_DESTRUCTOR_P (method))
1302     push_class_level_binding (DECL_NAME (method),
1303                               TREE_VEC_ELT (method_vec, slot));
1304 }
1305
1306 /* Subroutines of finish_struct.  */
1307
1308 /* Look through the list of fields for this struct, deleting
1309    duplicates as we go.  This must be recursive to handle
1310    anonymous unions.
1311
1312    FIELD is the field which may not appear anywhere in FIELDS.
1313    FIELD_PTR, if non-null, is the starting point at which
1314    chained deletions may take place.
1315    The value returned is the first acceptable entry found
1316    in FIELDS.
1317
1318    Note that anonymous fields which are not of UNION_TYPE are
1319    not duplicates, they are just anonymous fields.  This happens
1320    when we have unnamed bitfields, for example.  */
1321
1322 static tree
1323 delete_duplicate_fields_1 (field, fields)
1324      tree field, fields;
1325 {
1326   tree x;
1327   tree prev = 0;
1328   if (DECL_NAME (field) == 0)
1329     {
1330       if (! ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1331         return fields;
1332
1333       for (x = TYPE_FIELDS (TREE_TYPE (field)); x; x = TREE_CHAIN (x))
1334         fields = delete_duplicate_fields_1 (x, fields);
1335       return fields;
1336     }
1337   else
1338     {
1339       for (x = fields; x; prev = x, x = TREE_CHAIN (x))
1340         {
1341           if (DECL_NAME (x) == 0)
1342             {
1343               if (! ANON_AGGR_TYPE_P (TREE_TYPE (x)))
1344                 continue;
1345               TYPE_FIELDS (TREE_TYPE (x))
1346                 = delete_duplicate_fields_1 (field, TYPE_FIELDS (TREE_TYPE (x)));
1347               if (TYPE_FIELDS (TREE_TYPE (x)) == 0)
1348                 {
1349                   if (prev == 0)
1350                     fields = TREE_CHAIN (fields);
1351                   else
1352                     TREE_CHAIN (prev) = TREE_CHAIN (x);
1353                 }
1354             }
1355           else if (TREE_CODE (field) == USING_DECL)
1356             /* A using declaration may is allowed to appear more than
1357                once.  We'll prune these from the field list later, and
1358                handle_using_decl will complain about invalid multiple
1359                uses.  */
1360             ;
1361           else if (DECL_NAME (field) == DECL_NAME (x))
1362             {
1363               if (TREE_CODE (field) == CONST_DECL
1364                   && TREE_CODE (x) == CONST_DECL)
1365                 cp_error_at ("duplicate enum value `%D'", x);
1366               else if (TREE_CODE (field) == CONST_DECL
1367                        || TREE_CODE (x) == CONST_DECL)
1368                 cp_error_at ("duplicate field `%D' (as enum and non-enum)",
1369                              x);
1370               else if (DECL_DECLARES_TYPE_P (field)
1371                        && DECL_DECLARES_TYPE_P (x))
1372                 {
1373                   if (same_type_p (TREE_TYPE (field), TREE_TYPE (x)))
1374                     continue;
1375                   cp_error_at ("duplicate nested type `%D'", x);
1376                 }
1377               else if (DECL_DECLARES_TYPE_P (field)
1378                        || DECL_DECLARES_TYPE_P (x))
1379                 {
1380                   /* Hide tag decls.  */
1381                   if ((TREE_CODE (field) == TYPE_DECL
1382                        && DECL_ARTIFICIAL (field))
1383                       || (TREE_CODE (x) == TYPE_DECL
1384                           && DECL_ARTIFICIAL (x)))
1385                     continue;
1386                   cp_error_at ("duplicate field `%D' (as type and non-type)",
1387                                x);
1388                 }
1389               else
1390                 cp_error_at ("duplicate member `%D'", x);
1391               if (prev == 0)
1392                 fields = TREE_CHAIN (fields);
1393               else
1394                 TREE_CHAIN (prev) = TREE_CHAIN (x);
1395             }
1396         }
1397     }
1398   return fields;
1399 }
1400
1401 static void
1402 delete_duplicate_fields (fields)
1403      tree fields;
1404 {
1405   tree x;
1406   for (x = fields; x && TREE_CHAIN (x); x = TREE_CHAIN (x))
1407     TREE_CHAIN (x) = delete_duplicate_fields_1 (x, TREE_CHAIN (x));
1408 }
1409
1410 /* Change the access of FDECL to ACCESS in T.  Return 1 if change was
1411    legit, otherwise return 0.  */
1412
1413 static int
1414 alter_access (t, fdecl, access)
1415      tree t;
1416      tree fdecl;
1417      tree access;
1418 {
1419   tree elem;
1420
1421   if (!DECL_LANG_SPECIFIC (fdecl))
1422     retrofit_lang_decl (fdecl);
1423
1424   if (DECL_DISCRIMINATOR_P (fdecl))
1425     abort ();
1426
1427   elem = purpose_member (t, DECL_ACCESS (fdecl));
1428   if (elem)
1429     {
1430       if (TREE_VALUE (elem) != access)
1431         {
1432           if (TREE_CODE (TREE_TYPE (fdecl)) == FUNCTION_DECL)
1433             cp_error_at ("conflicting access specifications for method `%D', ignored", TREE_TYPE (fdecl));
1434           else
1435             error ("conflicting access specifications for field `%s', ignored",
1436                    IDENTIFIER_POINTER (DECL_NAME (fdecl)));
1437         }
1438       else
1439         {
1440           /* They're changing the access to the same thing they changed
1441              it to before.  That's OK.  */
1442           ;
1443         }
1444     }
1445   else
1446     {
1447       enforce_access (t, fdecl);
1448       DECL_ACCESS (fdecl) = tree_cons (t, access, DECL_ACCESS (fdecl));
1449       return 1;
1450     }
1451   return 0;
1452 }
1453
1454 /* Process the USING_DECL, which is a member of T.  */
1455
1456 static void
1457 handle_using_decl (using_decl, t)
1458      tree using_decl;
1459      tree t;
1460 {
1461   tree ctype = DECL_INITIAL (using_decl);
1462   tree name = DECL_NAME (using_decl);
1463   tree access
1464     = TREE_PRIVATE (using_decl) ? access_private_node
1465     : TREE_PROTECTED (using_decl) ? access_protected_node
1466     : access_public_node;
1467   tree fdecl, binfo;
1468   tree flist = NULL_TREE;
1469   tree old_value;
1470
1471   binfo = binfo_or_else (ctype, t);
1472   if (! binfo)
1473     return;
1474   
1475   if (name == constructor_name (ctype)
1476       || name == constructor_name_full (ctype))
1477     {
1478       cp_error_at ("`%D' names constructor", using_decl);
1479       return;
1480     }
1481   if (name == constructor_name (t)
1482       || name == constructor_name_full (t))
1483     {
1484       cp_error_at ("`%D' invalid in `%T'", using_decl, t);
1485       return;
1486     }
1487
1488   fdecl = lookup_member (binfo, name, 0, 0);
1489   
1490   if (!fdecl)
1491     {
1492       cp_error_at ("no members matching `%D' in `%#T'", using_decl, ctype);
1493       return;
1494     }
1495
1496   if (BASELINK_P (fdecl))
1497     /* Ignore base type this came from. */
1498     fdecl = TREE_VALUE (fdecl);
1499
1500   old_value = IDENTIFIER_CLASS_VALUE (name);
1501   if (old_value)
1502     {
1503       if (is_overloaded_fn (old_value))
1504         old_value = OVL_CURRENT (old_value);
1505
1506       if (DECL_P (old_value) && DECL_CONTEXT (old_value) == t)
1507         /* OK */;
1508       else
1509         old_value = NULL_TREE;
1510     }
1511
1512   if (is_overloaded_fn (fdecl))
1513     flist = fdecl;
1514
1515   if (! old_value)
1516     ;
1517   else if (is_overloaded_fn (old_value))
1518     {
1519       if (flist)
1520         /* It's OK to use functions from a base when there are functions with
1521            the same name already present in the current class.  */;
1522       else
1523         {
1524           cp_error_at ("`%D' invalid in `%#T'", using_decl, t);
1525           cp_error_at ("  because of local method `%#D' with same name",
1526                        OVL_CURRENT (old_value));
1527           return;
1528         }
1529     }
1530   else if (!DECL_ARTIFICIAL (old_value))
1531     {
1532       cp_error_at ("`%D' invalid in `%#T'", using_decl, t);
1533       cp_error_at ("  because of local member `%#D' with same name", old_value);
1534       return;
1535     }
1536   
1537   /* Make type T see field decl FDECL with access ACCESS.*/
1538   if (flist)
1539     for (; flist; flist = OVL_NEXT (flist))
1540       {
1541         add_method (t, OVL_CURRENT (flist), /*error_p=*/0);
1542         alter_access (t, OVL_CURRENT (flist), access);
1543       }
1544   else
1545     alter_access (t, fdecl, access);
1546 }
1547 \f
1548 /* Run through the base clases of T, updating
1549    CANT_HAVE_DEFAULT_CTOR_P, CANT_HAVE_CONST_CTOR_P, and
1550    NO_CONST_ASN_REF_P.  Also set flag bits in T based on properties of
1551    the bases.  */
1552
1553 static void
1554 check_bases (t, cant_have_default_ctor_p, cant_have_const_ctor_p,
1555              no_const_asn_ref_p)
1556      tree t;
1557      int *cant_have_default_ctor_p;
1558      int *cant_have_const_ctor_p;
1559      int *no_const_asn_ref_p;
1560 {
1561   int n_baseclasses;
1562   int i;
1563   int seen_non_virtual_nearly_empty_base_p;
1564   tree binfos;
1565
1566   binfos = TYPE_BINFO_BASETYPES (t);
1567   n_baseclasses = CLASSTYPE_N_BASECLASSES (t);
1568   seen_non_virtual_nearly_empty_base_p = 0;
1569
1570   /* An aggregate cannot have baseclasses.  */
1571   CLASSTYPE_NON_AGGREGATE (t) |= (n_baseclasses != 0);
1572
1573   for (i = 0; i < n_baseclasses; ++i) 
1574     {
1575       tree base_binfo;
1576       tree basetype;
1577
1578       /* Figure out what base we're looking at.  */
1579       base_binfo = TREE_VEC_ELT (binfos, i);
1580       basetype = TREE_TYPE (base_binfo);
1581
1582       /* If the type of basetype is incomplete, then we already
1583          complained about that fact (and we should have fixed it up as
1584          well).  */
1585       if (!COMPLETE_TYPE_P (basetype))
1586         {
1587           int j;
1588           /* The base type is of incomplete type.  It is
1589              probably best to pretend that it does not
1590              exist.  */
1591           if (i == n_baseclasses-1)
1592             TREE_VEC_ELT (binfos, i) = NULL_TREE;
1593           TREE_VEC_LENGTH (binfos) -= 1;
1594           n_baseclasses -= 1;
1595           for (j = i; j+1 < n_baseclasses; j++)
1596             TREE_VEC_ELT (binfos, j) = TREE_VEC_ELT (binfos, j+1);
1597           continue;
1598         }
1599
1600       /* Effective C++ rule 14.  We only need to check TYPE_POLYMORPHIC_P
1601          here because the case of virtual functions but non-virtual
1602          dtor is handled in finish_struct_1.  */
1603       if (warn_ecpp && ! TYPE_POLYMORPHIC_P (basetype)
1604           && TYPE_HAS_DESTRUCTOR (basetype))
1605         cp_warning ("base class `%#T' has a non-virtual destructor",
1606                     basetype);
1607
1608       /* If the base class doesn't have copy constructors or
1609          assignment operators that take const references, then the
1610          derived class cannot have such a member automatically
1611          generated.  */
1612       if (! TYPE_HAS_CONST_INIT_REF (basetype))
1613         *cant_have_const_ctor_p = 1;
1614       if (TYPE_HAS_ASSIGN_REF (basetype)
1615           && !TYPE_HAS_CONST_ASSIGN_REF (basetype))
1616         *no_const_asn_ref_p = 1;
1617       /* Similarly, if the base class doesn't have a default
1618          constructor, then the derived class won't have an
1619          automatically generated default constructor.  */
1620       if (TYPE_HAS_CONSTRUCTOR (basetype)
1621           && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype))
1622         {
1623           *cant_have_default_ctor_p = 1;
1624           if (! TYPE_HAS_CONSTRUCTOR (t))
1625             cp_pedwarn ("base `%T' with only non-default constructor in class without a constructor",
1626                         basetype);
1627         }
1628
1629       if (TREE_VIA_VIRTUAL (base_binfo))
1630         /* A virtual base does not effect nearly emptiness. */
1631         ;
1632       else if (CLASSTYPE_NEARLY_EMPTY_P (basetype))
1633         {
1634           if (seen_non_virtual_nearly_empty_base_p)
1635             /* And if there is more than one nearly empty base, then the
1636                derived class is not nearly empty either.  */
1637             CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
1638           else
1639             /* Remember we've seen one. */
1640             seen_non_virtual_nearly_empty_base_p = 1;
1641         }
1642       else if (!is_empty_class (basetype))
1643         /* If the base class is not empty or nearly empty, then this
1644            class cannot be nearly empty.  */
1645         CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
1646
1647       /* A lot of properties from the bases also apply to the derived
1648          class.  */
1649       TYPE_NEEDS_CONSTRUCTING (t) |= TYPE_NEEDS_CONSTRUCTING (basetype);
1650       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) 
1651         |= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (basetype);
1652       TYPE_HAS_COMPLEX_ASSIGN_REF (t) 
1653         |= TYPE_HAS_COMPLEX_ASSIGN_REF (basetype);
1654       TYPE_HAS_COMPLEX_INIT_REF (t) |= TYPE_HAS_COMPLEX_INIT_REF (basetype);
1655       TYPE_OVERLOADS_CALL_EXPR (t) |= TYPE_OVERLOADS_CALL_EXPR (basetype);
1656       TYPE_OVERLOADS_ARRAY_REF (t) |= TYPE_OVERLOADS_ARRAY_REF (basetype);
1657       TYPE_OVERLOADS_ARROW (t) |= TYPE_OVERLOADS_ARROW (basetype);
1658       TYPE_POLYMORPHIC_P (t) |= TYPE_POLYMORPHIC_P (basetype);
1659     }
1660 }
1661
1662 /* Binfo FROM is within a virtual heirarchy which is being reseated to
1663    TO. Move primary information from FROM to TO, and recursively traverse
1664    into FROM's bases. The heirarchy is dominated by TYPE.  MAPPINGS is an
1665    assoc list of binfos that have already been reseated.  */
1666
1667 static void
1668 force_canonical_binfo_r (to, from, type, mappings)
1669      tree to;
1670      tree from;
1671      tree type;
1672      tree mappings;
1673 {
1674   int i, n_baseclasses = BINFO_N_BASETYPES (from);
1675   
1676   BINFO_INDIRECT_PRIMARY_P (to)
1677           = BINFO_INDIRECT_PRIMARY_P (from);
1678   BINFO_INDIRECT_PRIMARY_P (from) = 0;
1679   BINFO_UNSHARED_MARKED (to) = BINFO_UNSHARED_MARKED (from);
1680   BINFO_UNSHARED_MARKED (from) = 0;
1681   BINFO_LOST_PRIMARY_P (to) = BINFO_LOST_PRIMARY_P (from);
1682   BINFO_LOST_PRIMARY_P (from) = 0;
1683   if (BINFO_PRIMARY_P (from))
1684     {
1685       tree primary = BINFO_PRIMARY_BASE_OF (from);
1686       tree assoc;
1687       
1688       /* We might have just moved the primary base too, see if it's on our
1689          mappings.  */
1690       assoc = purpose_member (primary, mappings);
1691       if (assoc)
1692         primary = TREE_VALUE (assoc);
1693       BINFO_PRIMARY_BASE_OF (to) = primary;
1694       BINFO_PRIMARY_BASE_OF (from) = NULL_TREE;
1695     }
1696   my_friendly_assert (same_type_p (BINFO_TYPE (to), BINFO_TYPE (from)),
1697                       20010104);
1698   mappings = tree_cons (from, to, mappings);
1699   for (i = 0; i != n_baseclasses; i++)
1700     {
1701       tree from_binfo = BINFO_BASETYPE (from, i);
1702       tree to_binfo = BINFO_BASETYPE (to, i);
1703       
1704       if (TREE_VIA_VIRTUAL (from_binfo))
1705         {
1706           if (BINFO_PRIMARY_P (from_binfo) &&
1707               purpose_member (BINFO_PRIMARY_BASE_OF (from_binfo), mappings))
1708             /* This base is a primary of some binfo we have already
1709                reseated. We must reseat this one too.  */
1710             force_canonical_binfo (to_binfo, from_binfo, type, mappings);
1711         }
1712       else
1713         force_canonical_binfo_r (to_binfo, from_binfo, type, mappings);
1714     }
1715 }
1716
1717 /* FROM is the canonical binfo for a virtual base. It is being reseated to
1718    make TO the canonical binfo, within the heirarchy dominated by TYPE.
1719    MAPPINGS is an assoc list of binfos that have already been reseated.
1720    Adjust any non-virtual bases within FROM, and also move any virtual bases
1721    which are canonical.  This complication arises because selecting primary
1722    bases walks in inheritance graph order, but we don't share binfos for
1723    virtual bases, hence we can fill in the primaries for a virtual base,
1724    and then discover that a later base requires the virtual as its
1725    primary.  */
1726
1727 static void
1728 force_canonical_binfo (to, from, type, mappings)
1729      tree to;
1730      tree from;
1731      tree type;
1732      tree mappings;
1733 {
1734   tree assoc = purpose_member (BINFO_TYPE (to),
1735                                CLASSTYPE_VBASECLASSES (type));
1736   TREE_VALUE (assoc) = to;
1737   force_canonical_binfo_r (to, from, type, mappings);
1738 }
1739
1740 /* Make BASE_BINFO the primary virtual base of BINFO within the hierarchy
1741    dominated by TYPE. Returns BASE_BINFO, if it can be made so, NULL
1742    otherwise (because something else has already made it primary).  */
1743
1744 static tree
1745 mark_primary_virtual_base (binfo, base_binfo, type)
1746      tree binfo;
1747      tree base_binfo;
1748      tree type;
1749 {
1750   tree shared_binfo = binfo_for_vbase (BINFO_TYPE (base_binfo), type);
1751   tree delta;
1752
1753   if (BINFO_PRIMARY_P (shared_binfo))
1754     {
1755       /* It's already allocated in the hierarchy. BINFO won't have a
1756          primary base in this hierachy, even though the complete object
1757          BINFO is for, would do.  */
1758       BINFO_LOST_PRIMARY_P (binfo) = 1;
1759       
1760       return NULL_TREE;
1761     }
1762      
1763   /* We need to make sure that the assoc list
1764      CLASSTYPE_VBASECLASSES of TYPE, indicates this particular
1765      primary BINFO for the virtual base, as this is the one
1766      that'll really exist.  */
1767   if (base_binfo != shared_binfo)
1768     force_canonical_binfo (base_binfo, shared_binfo, type, NULL);
1769
1770   delta = size_diffop (BINFO_OFFSET (binfo), BINFO_OFFSET (base_binfo));
1771   if (!integer_zerop (delta))
1772     {
1773       propagate_binfo_offsets (base_binfo, delta, type);
1774       BINFO_OFFSET (base_binfo) = BINFO_OFFSET (binfo);
1775     }
1776   return base_binfo;
1777 }
1778
1779 /* If BINFO is an unmarked virtual binfo for a class with a primary virtual
1780    base, then BINFO has no primary base in this graph.  Called from
1781    mark_primary_bases.  DATA is the most derived type. */
1782
1783 static tree dfs_unshared_virtual_bases (binfo, data)
1784      tree binfo;
1785      void *data;
1786 {
1787   tree t = (tree) data;
1788   
1789   if (!BINFO_UNSHARED_MARKED (binfo)
1790       && CLASSTYPE_HAS_PRIMARY_BASE_P (BINFO_TYPE (binfo)))
1791     {
1792       /* This morally virtual base has a primary base when it
1793          is a complete object. We need to locate the shared instance
1794          of this binfo in the type dominated by T. We duplicate the
1795          primary base information from there to here.  */
1796       tree vbase;
1797       tree unshared_base;
1798       
1799       for (vbase = binfo; !TREE_VIA_VIRTUAL (vbase);
1800            vbase = BINFO_INHERITANCE_CHAIN (vbase))
1801         continue;
1802       unshared_base = get_original_base (binfo,
1803                                          binfo_for_vbase (BINFO_TYPE (vbase),
1804                                                           t));
1805       my_friendly_assert (unshared_base != binfo, 20010612);
1806       BINFO_LOST_PRIMARY_P (binfo) = BINFO_LOST_PRIMARY_P (unshared_base);
1807       if (!BINFO_LOST_PRIMARY_P (binfo))
1808               BINFO_PRIMARY_BASE_OF (get_primary_binfo (binfo)) = binfo;
1809     }
1810   
1811   if (binfo != TYPE_BINFO (t))
1812     /* The vtable fields will have been copied when duplicating the
1813        base binfos. That information is bogus, make sure we don't try
1814        and use it. */
1815     BINFO_VTABLE (binfo) = NULL_TREE;
1816   
1817   BINFO_UNSHARED_MARKED (binfo) = 0;
1818   return NULL;
1819 }
1820
1821 /* Set BINFO_PRIMARY_BASE_OF for all binfos in the hierarchy
1822    dominated by TYPE that are primary bases.  */
1823
1824 static void
1825 mark_primary_bases (type)
1826      tree type;
1827 {
1828   tree binfo;
1829   
1830   /* Walk the bases in inheritance graph order.  */
1831   for (binfo = TYPE_BINFO (type); binfo; binfo = TREE_CHAIN (binfo))
1832     {
1833       tree base_binfo;
1834       
1835       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (BINFO_TYPE (binfo)))
1836         /* Not a dynamic base. */
1837         continue;
1838
1839       base_binfo = get_primary_binfo (binfo);
1840
1841       if (TREE_VIA_VIRTUAL (base_binfo))
1842         base_binfo = mark_primary_virtual_base (binfo, base_binfo, type);
1843
1844       if (base_binfo)
1845         BINFO_PRIMARY_BASE_OF (base_binfo) = binfo;
1846       
1847       BINFO_UNSHARED_MARKED (binfo) = 1;
1848     }
1849   /* There could remain unshared morally virtual bases which were not visited
1850      in the inheritance graph walk. These bases will have lost their
1851      virtual primary base (should they have one). We must now find them. */
1852   dfs_walk (TYPE_BINFO (type), dfs_unshared_virtual_bases, NULL, type);
1853 }
1854
1855 /* Make the BINFO the primary base of T.  */
1856
1857 static void
1858 set_primary_base (t, binfo, vfuns_p)
1859      tree t;
1860      tree binfo;
1861      int *vfuns_p;
1862 {
1863   tree basetype;
1864
1865   CLASSTYPE_PRIMARY_BINFO (t) = binfo;
1866   basetype = BINFO_TYPE (binfo);
1867   TYPE_BINFO_VTABLE (t) = TYPE_BINFO_VTABLE (basetype);
1868   TYPE_BINFO_VIRTUALS (t) = TYPE_BINFO_VIRTUALS (basetype);
1869   TYPE_VFIELD (t) = TYPE_VFIELD (basetype);
1870   CLASSTYPE_RTTI (t) = CLASSTYPE_RTTI (basetype);
1871   *vfuns_p = CLASSTYPE_VSIZE (basetype);
1872 }
1873
1874 /* Determine the primary class for T.  */
1875
1876 static void
1877 determine_primary_base (t, vfuns_p)
1878      tree t;
1879      int *vfuns_p;
1880 {
1881   int i, n_baseclasses = CLASSTYPE_N_BASECLASSES (t);
1882   tree vbases;
1883   tree type_binfo;
1884
1885   /* If there are no baseclasses, there is certainly no primary base.  */
1886   if (n_baseclasses == 0)
1887     return;
1888
1889   type_binfo = TYPE_BINFO (t);
1890
1891   for (i = 0; i < n_baseclasses; i++)
1892     {
1893       tree base_binfo = BINFO_BASETYPE (type_binfo, i);
1894       tree basetype = BINFO_TYPE (base_binfo);
1895
1896       if (TYPE_CONTAINS_VPTR_P (basetype))
1897         {
1898           /* Even a virtual baseclass can contain our RTTI
1899              information.  But, we prefer a non-virtual polymorphic
1900              baseclass.  */
1901           if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
1902             CLASSTYPE_RTTI (t) = CLASSTYPE_RTTI (basetype);
1903
1904           /* A virtual baseclass can't be the primary base under the
1905              old ABI.  And under the new ABI we still prefer a
1906              non-virtual base.  */
1907           if (TREE_VIA_VIRTUAL (base_binfo))
1908             continue;
1909
1910           if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
1911             {
1912               set_primary_base (t, base_binfo, vfuns_p);
1913               CLASSTYPE_VFIELDS (t) = copy_list (CLASSTYPE_VFIELDS (basetype));
1914             }
1915           else
1916             {
1917               tree vfields;
1918
1919               /* Only add unique vfields, and flatten them out as we go.  */
1920               for (vfields = CLASSTYPE_VFIELDS (basetype);
1921                    vfields;
1922                    vfields = TREE_CHAIN (vfields))
1923                 if (VF_BINFO_VALUE (vfields) == NULL_TREE
1924                     || ! TREE_VIA_VIRTUAL (VF_BINFO_VALUE (vfields)))
1925                   CLASSTYPE_VFIELDS (t) 
1926                     = tree_cons (base_binfo, 
1927                                  VF_BASETYPE_VALUE (vfields),
1928                                  CLASSTYPE_VFIELDS (t));
1929             }
1930         }
1931     }
1932
1933   if (!TYPE_VFIELD (t))
1934     CLASSTYPE_PRIMARY_BINFO (t) = NULL_TREE;
1935
1936   /* Find the indirect primary bases - those virtual bases which are primary
1937      bases of something else in this hierarchy.  */
1938   for (vbases = CLASSTYPE_VBASECLASSES (t);
1939        vbases;
1940        vbases = TREE_CHAIN (vbases)) 
1941     {
1942       tree vbase_binfo = TREE_VALUE (vbases);
1943
1944       /* See if this virtual base is an indirect primary base.  To be so,
1945          it must be a primary base within the hierarchy of one of our
1946          direct bases.  */
1947       for (i = 0; i < n_baseclasses; ++i) 
1948         {
1949           tree basetype = TYPE_BINFO_BASETYPE (t, i);
1950           tree v;
1951
1952           for (v = CLASSTYPE_VBASECLASSES (basetype); 
1953                v; 
1954                v = TREE_CHAIN (v))
1955             {
1956               tree base_vbase = TREE_VALUE (v);
1957               
1958               if (BINFO_PRIMARY_P (base_vbase)
1959                   && same_type_p (BINFO_TYPE (base_vbase),
1960                                   BINFO_TYPE (vbase_binfo)))
1961                 {
1962                   BINFO_INDIRECT_PRIMARY_P (vbase_binfo) = 1;
1963                   break;
1964                 }
1965             }
1966
1967           /* If we've discovered that this virtual base is an indirect
1968              primary base, then we can move on to the next virtual
1969              base.  */
1970           if (BINFO_INDIRECT_PRIMARY_P (vbase_binfo))
1971             break;
1972         }
1973     }
1974
1975   /* The new ABI allows for the use of a "nearly-empty" virtual base
1976      class as the primary base class if no non-virtual polymorphic
1977      base can be found.  */
1978   if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
1979     {
1980       /* If not NULL, this is the best primary base candidate we have
1981          found so far.  */
1982       tree candidate = NULL_TREE;
1983       tree base_binfo;
1984
1985       /* Loop over the baseclasses.  */
1986       for (base_binfo = TYPE_BINFO (t);
1987            base_binfo;
1988            base_binfo = TREE_CHAIN (base_binfo))
1989         {
1990           tree basetype = BINFO_TYPE (base_binfo);
1991
1992           if (TREE_VIA_VIRTUAL (base_binfo) 
1993               && CLASSTYPE_NEARLY_EMPTY_P (basetype))
1994             {
1995               /* If this is not an indirect primary base, then it's
1996                  definitely our primary base.  */
1997               if (!BINFO_INDIRECT_PRIMARY_P (base_binfo))
1998                 {
1999                   candidate = base_binfo;
2000                   break;
2001                 }
2002
2003               /* If this is an indirect primary base, it still could be
2004                  our primary base -- unless we later find there's another
2005                  nearly-empty virtual base that isn't an indirect
2006                  primary base.  */
2007               if (!candidate)
2008                 candidate = base_binfo;
2009             }
2010         }
2011
2012       /* If we've got a primary base, use it.  */
2013       if (candidate)
2014         {
2015           set_primary_base (t, candidate, vfuns_p);
2016           CLASSTYPE_VFIELDS (t) 
2017             = copy_list (CLASSTYPE_VFIELDS (BINFO_TYPE (candidate)));
2018         }       
2019     }
2020
2021   /* Mark the primary base classes at this point.  */
2022   mark_primary_bases (t);
2023 }
2024 \f
2025 /* Set memoizing fields and bits of T (and its variants) for later
2026    use.  */
2027
2028 static void
2029 finish_struct_bits (t)
2030      tree t;
2031 {
2032   int i, n_baseclasses = CLASSTYPE_N_BASECLASSES (t);
2033
2034   /* Fix up variants (if any).  */
2035   tree variants = TYPE_NEXT_VARIANT (t);
2036   while (variants)
2037     {
2038       /* These fields are in the _TYPE part of the node, not in
2039          the TYPE_LANG_SPECIFIC component, so they are not shared.  */
2040       TYPE_HAS_CONSTRUCTOR (variants) = TYPE_HAS_CONSTRUCTOR (t);
2041       TYPE_HAS_DESTRUCTOR (variants) = TYPE_HAS_DESTRUCTOR (t);
2042       TYPE_NEEDS_CONSTRUCTING (variants) = TYPE_NEEDS_CONSTRUCTING (t);
2043       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (variants) 
2044         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t);
2045
2046       TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (variants) 
2047         = TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (t);
2048       TYPE_POLYMORPHIC_P (variants) = TYPE_POLYMORPHIC_P (t);
2049       TYPE_USES_VIRTUAL_BASECLASSES (variants) = TYPE_USES_VIRTUAL_BASECLASSES (t);
2050       /* Copy whatever these are holding today.  */
2051       TYPE_MIN_VALUE (variants) = TYPE_MIN_VALUE (t);
2052       TYPE_MAX_VALUE (variants) = TYPE_MAX_VALUE (t);
2053       TYPE_FIELDS (variants) = TYPE_FIELDS (t);
2054       TYPE_SIZE (variants) = TYPE_SIZE (t);
2055       TYPE_SIZE_UNIT (variants) = TYPE_SIZE_UNIT (t);
2056       variants = TYPE_NEXT_VARIANT (variants);
2057     }
2058
2059   if (n_baseclasses && TYPE_POLYMORPHIC_P (t))
2060     /* For a class w/o baseclasses, `finish_struct' has set
2061        CLASS_TYPE_ABSTRACT_VIRTUALS correctly (by
2062        definition). Similarly for a class whose base classes do not
2063        have vtables. When neither of these is true, we might have
2064        removed abstract virtuals (by providing a definition), added
2065        some (by declaring new ones), or redeclared ones from a base
2066        class. We need to recalculate what's really an abstract virtual
2067        at this point (by looking in the vtables).  */
2068       get_pure_virtuals (t);
2069
2070   if (n_baseclasses)
2071     {
2072       /* Notice whether this class has type conversion functions defined.  */
2073       tree binfo = TYPE_BINFO (t);
2074       tree binfos = BINFO_BASETYPES (binfo);
2075       tree basetype;
2076
2077       for (i = n_baseclasses-1; i >= 0; i--)
2078         {
2079           basetype = BINFO_TYPE (TREE_VEC_ELT (binfos, i));
2080
2081           TYPE_HAS_CONVERSION (t) |= TYPE_HAS_CONVERSION (basetype);
2082         }
2083     }
2084
2085   /* If this type has a copy constructor, force its mode to be BLKmode, and
2086      force its TREE_ADDRESSABLE bit to be nonzero.  This will cause it to
2087      be passed by invisible reference and prevent it from being returned in
2088      a register.
2089
2090      Also do this if the class has BLKmode but can still be returned in
2091      registers, since function_cannot_inline_p won't let us inline
2092      functions returning such a type.  This affects the HP-PA.  */
2093   if (! TYPE_HAS_TRIVIAL_INIT_REF (t)
2094       || (TYPE_MODE (t) == BLKmode && ! aggregate_value_p (t)
2095           && CLASSTYPE_NON_AGGREGATE (t)))
2096     {
2097       tree variants;
2098       DECL_MODE (TYPE_MAIN_DECL (t)) = BLKmode;
2099       for (variants = t; variants; variants = TYPE_NEXT_VARIANT (variants))
2100         {
2101           TYPE_MODE (variants) = BLKmode;
2102           TREE_ADDRESSABLE (variants) = 1;
2103         }
2104     }
2105 }
2106
2107 /* Issue warnings about T having private constructors, but no friends,
2108    and so forth.  
2109
2110    HAS_NONPRIVATE_METHOD is nonzero if T has any non-private methods or
2111    static members.  HAS_NONPRIVATE_STATIC_FN is nonzero if T has any
2112    non-private static member functions.  */
2113
2114 static void
2115 maybe_warn_about_overly_private_class (t)
2116      tree t;
2117 {
2118   int has_member_fn = 0;
2119   int has_nonprivate_method = 0;
2120   tree fn;
2121
2122   if (!warn_ctor_dtor_privacy
2123       /* If the class has friends, those entities might create and
2124          access instances, so we should not warn.  */
2125       || (CLASSTYPE_FRIEND_CLASSES (t)
2126           || DECL_FRIENDLIST (TYPE_MAIN_DECL (t)))
2127       /* We will have warned when the template was declared; there's
2128          no need to warn on every instantiation.  */
2129       || CLASSTYPE_TEMPLATE_INSTANTIATION (t))
2130     /* There's no reason to even consider warning about this 
2131        class.  */
2132     return;
2133     
2134   /* We only issue one warning, if more than one applies, because
2135      otherwise, on code like:
2136
2137      class A {
2138        // Oops - forgot `public:'
2139        A();
2140        A(const A&);
2141        ~A();
2142      };
2143
2144      we warn several times about essentially the same problem.  */
2145
2146   /* Check to see if all (non-constructor, non-destructor) member
2147      functions are private.  (Since there are no friends or
2148      non-private statics, we can't ever call any of the private member
2149      functions.)  */
2150   for (fn = TYPE_METHODS (t); fn; fn = TREE_CHAIN (fn))
2151     /* We're not interested in compiler-generated methods; they don't
2152        provide any way to call private members.  */
2153     if (!DECL_ARTIFICIAL (fn)) 
2154       {
2155         if (!TREE_PRIVATE (fn))
2156           {
2157             if (DECL_STATIC_FUNCTION_P (fn)) 
2158               /* A non-private static member function is just like a
2159                  friend; it can create and invoke private member
2160                  functions, and be accessed without a class
2161                  instance.  */
2162               return;
2163                 
2164             has_nonprivate_method = 1;
2165             break;
2166           }
2167         else if (!DECL_CONSTRUCTOR_P (fn) && !DECL_DESTRUCTOR_P (fn))
2168           has_member_fn = 1;
2169       } 
2170
2171   if (!has_nonprivate_method && has_member_fn) 
2172     {
2173       /* There are no non-private methods, and there's at least one
2174          private member function that isn't a constructor or
2175          destructor.  (If all the private members are
2176          constructors/destructors we want to use the code below that
2177          issues error messages specifically referring to
2178          constructors/destructors.)  */
2179       int i;
2180       tree binfos = BINFO_BASETYPES (TYPE_BINFO (t));
2181       for (i = 0; i < CLASSTYPE_N_BASECLASSES (t); i++)
2182         if (TREE_VIA_PUBLIC (TREE_VEC_ELT (binfos, i))
2183             || TREE_VIA_PROTECTED (TREE_VEC_ELT (binfos, i)))
2184           {
2185             has_nonprivate_method = 1;
2186             break;
2187           }
2188       if (!has_nonprivate_method) 
2189         {
2190           cp_warning ("all member functions in class `%T' are private", t);
2191           return;
2192         }
2193     }
2194
2195   /* Even if some of the member functions are non-private, the class
2196      won't be useful for much if all the constructors or destructors
2197      are private: such an object can never be created or destroyed.  */
2198   if (TYPE_HAS_DESTRUCTOR (t))
2199     {
2200       tree dtor = TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (t), 1);
2201
2202       if (TREE_PRIVATE (dtor))
2203         {
2204           cp_warning ("`%#T' only defines a private destructor and has no friends",
2205                       t);
2206           return;
2207         }
2208     }
2209
2210   if (TYPE_HAS_CONSTRUCTOR (t))
2211     {
2212       int nonprivate_ctor = 0;
2213           
2214       /* If a non-template class does not define a copy
2215          constructor, one is defined for it, enabling it to avoid
2216          this warning.  For a template class, this does not
2217          happen, and so we would normally get a warning on:
2218
2219            template <class T> class C { private: C(); };  
2220           
2221          To avoid this asymmetry, we check TYPE_HAS_INIT_REF.  All
2222          complete non-template or fully instantiated classes have this
2223          flag set.  */
2224       if (!TYPE_HAS_INIT_REF (t))
2225         nonprivate_ctor = 1;
2226       else 
2227         for (fn = TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (t), 0);
2228              fn;
2229              fn = OVL_NEXT (fn)) 
2230           {
2231             tree ctor = OVL_CURRENT (fn);
2232             /* Ideally, we wouldn't count copy constructors (or, in
2233                fact, any constructor that takes an argument of the
2234                class type as a parameter) because such things cannot
2235                be used to construct an instance of the class unless
2236                you already have one.  But, for now at least, we're
2237                more generous.  */
2238             if (! TREE_PRIVATE (ctor))
2239               {
2240                 nonprivate_ctor = 1;
2241                 break;
2242               }
2243           }
2244
2245       if (nonprivate_ctor == 0)
2246         {
2247           cp_warning ("`%#T' only defines private constructors and has no friends",
2248                       t);
2249           return;
2250         }
2251     }
2252 }
2253
2254 /* Function to help qsort sort FIELD_DECLs by name order.  */
2255
2256 static int
2257 field_decl_cmp (x, y)
2258      const tree *x, *y;
2259 {
2260   if (DECL_NAME (*x) == DECL_NAME (*y))
2261     /* A nontype is "greater" than a type.  */
2262     return DECL_DECLARES_TYPE_P (*y) - DECL_DECLARES_TYPE_P (*x);
2263   if (DECL_NAME (*x) == NULL_TREE)
2264     return -1;
2265   if (DECL_NAME (*y) == NULL_TREE)
2266     return 1;
2267   if (DECL_NAME (*x) < DECL_NAME (*y))
2268     return -1;
2269   return 1;
2270 }
2271
2272 /* Comparison function to compare two TYPE_METHOD_VEC entries by name.  */
2273
2274 static int
2275 method_name_cmp (m1, m2)
2276      const tree *m1, *m2;
2277 {
2278   if (*m1 == NULL_TREE && *m2 == NULL_TREE)
2279     return 0;
2280   if (*m1 == NULL_TREE)
2281     return -1;
2282   if (*m2 == NULL_TREE)
2283     return 1;
2284   if (DECL_NAME (OVL_CURRENT (*m1)) < DECL_NAME (OVL_CURRENT (*m2)))
2285     return -1;
2286   return 1;
2287 }
2288
2289 /* Warn about duplicate methods in fn_fields.  Also compact method
2290    lists so that lookup can be made faster.
2291
2292    Data Structure: List of method lists.  The outer list is a
2293    TREE_LIST, whose TREE_PURPOSE field is the field name and the
2294    TREE_VALUE is the DECL_CHAIN of the FUNCTION_DECLs.  TREE_CHAIN
2295    links the entire list of methods for TYPE_METHODS.  Friends are
2296    chained in the same way as member functions (? TREE_CHAIN or
2297    DECL_CHAIN), but they live in the TREE_TYPE field of the outer
2298    list.  That allows them to be quickly deleted, and requires no
2299    extra storage.
2300
2301    Sort methods that are not special (i.e., constructors, destructors,
2302    and type conversion operators) so that we can find them faster in
2303    search.  */
2304
2305 static void
2306 finish_struct_methods (t)
2307      tree t;
2308 {
2309   tree fn_fields;
2310   tree method_vec;
2311   int slot, len;
2312
2313   if (!TYPE_METHODS (t))
2314     {
2315       /* Clear these for safety; perhaps some parsing error could set
2316          these incorrectly.  */
2317       TYPE_HAS_CONSTRUCTOR (t) = 0;
2318       TYPE_HAS_DESTRUCTOR (t) = 0;
2319       CLASSTYPE_METHOD_VEC (t) = NULL_TREE;
2320       return;
2321     }
2322
2323   method_vec = CLASSTYPE_METHOD_VEC (t);
2324   my_friendly_assert (method_vec != NULL_TREE, 19991215);
2325   len = TREE_VEC_LENGTH (method_vec);
2326
2327   /* First fill in entry 0 with the constructors, entry 1 with destructors,
2328      and the next few with type conversion operators (if any).  */
2329   for (fn_fields = TYPE_METHODS (t); fn_fields; 
2330        fn_fields = TREE_CHAIN (fn_fields))
2331     /* Clear out this flag.  */
2332     DECL_IN_AGGR_P (fn_fields) = 0;
2333
2334   if (TYPE_HAS_DESTRUCTOR (t) && !CLASSTYPE_DESTRUCTORS (t))
2335     /* We thought there was a destructor, but there wasn't.  Some
2336        parse errors cause this anomalous situation.  */
2337     TYPE_HAS_DESTRUCTOR (t) = 0;
2338     
2339   /* Issue warnings about private constructors and such.  If there are
2340      no methods, then some public defaults are generated.  */
2341   maybe_warn_about_overly_private_class (t);
2342
2343   /* Now sort the methods.  */
2344   while (len > 2 && TREE_VEC_ELT (method_vec, len-1) == NULL_TREE)
2345     len--;
2346   TREE_VEC_LENGTH (method_vec) = len;
2347
2348   /* The type conversion ops have to live at the front of the vec, so we
2349      can't sort them.  */
2350   for (slot = 2; slot < len; ++slot)
2351     {
2352       tree fn = TREE_VEC_ELT (method_vec, slot);
2353   
2354       if (!DECL_CONV_FN_P (OVL_CURRENT (fn)))
2355         break;
2356     }
2357   if (len - slot > 1)
2358     qsort (&TREE_VEC_ELT (method_vec, slot), len-slot, sizeof (tree),
2359            (int (*)(const void *, const void *))method_name_cmp);
2360 }
2361
2362 /* Emit error when a duplicate definition of a type is seen.  Patch up.  */
2363
2364 void
2365 duplicate_tag_error (t)
2366      tree t;
2367 {
2368   cp_error ("redefinition of `%#T'", t);
2369   cp_error_at ("previous definition of `%#T'", t);
2370
2371   /* Pretend we haven't defined this type.  */
2372
2373   /* All of the component_decl's were TREE_CHAINed together in the parser.
2374      finish_struct_methods walks these chains and assembles all methods with
2375      the same base name into DECL_CHAINs. Now we don't need the parser chains
2376      anymore, so we unravel them.  */
2377
2378   /* This used to be in finish_struct, but it turns out that the
2379      TREE_CHAIN is used by dbxout_type_methods and perhaps some other
2380      things...  */
2381   if (CLASSTYPE_METHOD_VEC (t)) 
2382     {
2383       tree method_vec = CLASSTYPE_METHOD_VEC (t);
2384       int i, len  = TREE_VEC_LENGTH (method_vec);
2385       for (i = 0; i < len; i++)
2386         {
2387           tree unchain = TREE_VEC_ELT (method_vec, i);
2388           while (unchain != NULL_TREE) 
2389             {
2390               TREE_CHAIN (OVL_CURRENT (unchain)) = NULL_TREE;
2391               unchain = OVL_NEXT (unchain);
2392             }
2393         }
2394     }
2395
2396   if (TYPE_LANG_SPECIFIC (t))
2397     {
2398       tree binfo = TYPE_BINFO (t);
2399       int interface_only = CLASSTYPE_INTERFACE_ONLY (t);
2400       int interface_unknown = CLASSTYPE_INTERFACE_UNKNOWN (t);
2401       tree template_info = CLASSTYPE_TEMPLATE_INFO (t);
2402       int use_template = CLASSTYPE_USE_TEMPLATE (t);
2403
2404       memset ((char *) TYPE_LANG_SPECIFIC (t), 0, sizeof (struct lang_type));
2405       BINFO_BASETYPES(binfo) = NULL_TREE;
2406
2407       TYPE_BINFO (t) = binfo;
2408       CLASSTYPE_INTERFACE_ONLY (t) = interface_only;
2409       SET_CLASSTYPE_INTERFACE_UNKNOWN_X (t, interface_unknown);
2410       TYPE_REDEFINED (t) = 1;
2411       CLASSTYPE_TEMPLATE_INFO (t) = template_info;
2412       CLASSTYPE_USE_TEMPLATE (t) = use_template;
2413     }
2414   TYPE_SIZE (t) = NULL_TREE;
2415   TYPE_MODE (t) = VOIDmode;
2416   TYPE_FIELDS (t) = NULL_TREE;
2417   TYPE_METHODS (t) = NULL_TREE;
2418   TYPE_VFIELD (t) = NULL_TREE;
2419   TYPE_CONTEXT (t) = NULL_TREE;
2420   TYPE_NONCOPIED_PARTS (t) = NULL_TREE;
2421   
2422   /* Clear TYPE_LANG_FLAGS -- those in TYPE_LANG_SPECIFIC are cleared above.  */
2423   TYPE_LANG_FLAG_0 (t) = 0;
2424   TYPE_LANG_FLAG_1 (t) = 0;
2425   TYPE_LANG_FLAG_2 (t) = 0;
2426   TYPE_LANG_FLAG_3 (t) = 0;
2427   TYPE_LANG_FLAG_4 (t) = 0;
2428   TYPE_LANG_FLAG_5 (t) = 0;
2429   TYPE_LANG_FLAG_6 (t) = 0;
2430   /* But not this one.  */
2431   SET_IS_AGGR_TYPE (t, 1);
2432 }
2433
2434 /* Make BINFO's vtable have N entries, including RTTI entries,
2435    vbase and vcall offsets, etc.  Set its type and call the backend
2436    to lay it out.  */
2437
2438 static void
2439 layout_vtable_decl (binfo, n)
2440      tree binfo;
2441      int n;
2442 {
2443   tree atype;
2444   tree vtable;
2445
2446   atype = build_cplus_array_type (vtable_entry_type, 
2447                                   build_index_type (size_int (n - 1)));
2448   layout_type (atype);
2449
2450   /* We may have to grow the vtable.  */
2451   vtable = get_vtbl_decl_for_binfo (binfo);
2452   if (!same_type_p (TREE_TYPE (vtable), atype))
2453     {
2454       TREE_TYPE (vtable) = atype;
2455       DECL_SIZE (vtable) = DECL_SIZE_UNIT (vtable) = NULL_TREE;
2456       layout_decl (vtable, 0);
2457
2458       /* At one time the vtable info was grabbed 2 words at a time.  This
2459          fails on Sparc unless you have 8-byte alignment.  */
2460       DECL_ALIGN (vtable) = MAX (TYPE_ALIGN (double_type_node),
2461                                  DECL_ALIGN (vtable));
2462     }
2463 }
2464
2465 /* True iff FNDECL and BASE_FNDECL (both non-static member functions)
2466    have the same signature.  */
2467
2468 int
2469 same_signature_p (fndecl, base_fndecl)
2470      tree fndecl, base_fndecl;
2471 {
2472   /* One destructor overrides another if they are the same kind of
2473      destructor.  */
2474   if (DECL_DESTRUCTOR_P (base_fndecl) && DECL_DESTRUCTOR_P (fndecl)
2475       && special_function_p (base_fndecl) == special_function_p (fndecl))
2476     return 1;
2477   /* But a non-destructor never overrides a destructor, nor vice
2478      versa, nor do different kinds of destructors override
2479      one-another.  For example, a complete object destructor does not
2480      override a deleting destructor.  */
2481   if (DECL_DESTRUCTOR_P (base_fndecl) || DECL_DESTRUCTOR_P (fndecl))
2482     return 0;
2483
2484   if (DECL_NAME (fndecl) == DECL_NAME (base_fndecl))
2485     {
2486       tree types, base_types;
2487       types = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
2488       base_types = TYPE_ARG_TYPES (TREE_TYPE (base_fndecl));
2489       if ((TYPE_QUALS (TREE_TYPE (TREE_VALUE (base_types)))
2490            == TYPE_QUALS (TREE_TYPE (TREE_VALUE (types))))
2491           && compparms (TREE_CHAIN (base_types), TREE_CHAIN (types)))
2492         return 1;
2493     }
2494   return 0;
2495 }
2496
2497 typedef struct find_final_overrider_data_s {
2498   /* The function for which we are trying to find a final overrider.  */
2499   tree fn;
2500   /* The base class in which the function was declared.  */
2501   tree declaring_base;
2502   /* The most derived class in the hierarchy.  */
2503   tree most_derived_type;
2504   /* The final overriding function.  */
2505   tree overriding_fn;
2506   /* The functions that we thought might be final overriders, but
2507      aren't.  */
2508   tree candidates;
2509   /* The BINFO for the class in which the final overriding function
2510      appears.  */
2511   tree overriding_base;
2512 } find_final_overrider_data;
2513
2514 /* Called from find_final_overrider via dfs_walk.  */
2515
2516 static tree
2517 dfs_find_final_overrider (binfo, data)
2518      tree binfo;
2519      void *data;
2520 {
2521   find_final_overrider_data *ffod = (find_final_overrider_data *) data;
2522
2523   if (same_type_p (BINFO_TYPE (binfo), 
2524                    BINFO_TYPE (ffod->declaring_base))
2525       && tree_int_cst_equal (BINFO_OFFSET (binfo),
2526                              BINFO_OFFSET (ffod->declaring_base)))
2527     {
2528       tree path;
2529       tree method;
2530
2531       /* We haven't found an overrider yet.  */
2532       method = NULL_TREE;
2533       /* We've found a path to the declaring base.  Walk down the path
2534          looking for an overrider for FN.  */
2535       for (path = reverse_path (binfo);
2536            path; 
2537            path = TREE_CHAIN (path))
2538         {
2539           method = look_for_overrides_here (BINFO_TYPE (TREE_VALUE (path)),
2540                                             ffod->fn);
2541           if (method)
2542             break;
2543         }
2544
2545       /* If we found an overrider, record the overriding function, and
2546          the base from which it came.  */
2547       if (path)
2548         {
2549           tree base;
2550
2551           /* Assume the path is non-virtual.  See if there are any
2552              virtual bases from (but not including) the overrider up
2553              to and including the base where the function is
2554              defined. */
2555           for (base = TREE_CHAIN (path); base; base = TREE_CHAIN (base))
2556             if (TREE_VIA_VIRTUAL (TREE_VALUE (base)))
2557               {
2558                 base = ffod->declaring_base;
2559                 break;
2560               }
2561
2562           /* If we didn't already have an overrider, or any
2563              candidates, then this function is the best candidate so
2564              far.  */
2565           if (!ffod->overriding_fn && !ffod->candidates)
2566             {
2567               ffod->overriding_fn = method;
2568               ffod->overriding_base = TREE_VALUE (path);
2569             }
2570           else if (ffod->overriding_fn)
2571             {
2572               /* We had a best overrider; let's see how this compares.  */
2573
2574               if (ffod->overriding_fn == method
2575                   && (tree_int_cst_equal 
2576                       (BINFO_OFFSET (TREE_VALUE (path)),
2577                        BINFO_OFFSET (ffod->overriding_base))))
2578                 /* We found the same overrider we already have, and in the
2579                    same place; it's still the best.  */;
2580               else if (strictly_overrides (ffod->overriding_fn, method))
2581                 /* The old function overrides this function; it's still the
2582                    best.  */;
2583               else if (strictly_overrides (method, ffod->overriding_fn))
2584                 {
2585                   /* The new function overrides the old; it's now the
2586                      best.  */
2587                   ffod->overriding_fn = method;
2588                   ffod->overriding_base = TREE_VALUE (path);
2589                 }
2590               else
2591                 {
2592                   /* Ambiguous.  */
2593                   ffod->candidates 
2594                     = build_tree_list (NULL_TREE,
2595                                        ffod->overriding_fn);
2596                   if (method != ffod->overriding_fn)
2597                     ffod->candidates 
2598                       = tree_cons (NULL_TREE, method, ffod->candidates);
2599                   ffod->overriding_fn = NULL_TREE;
2600                   ffod->overriding_base = NULL_TREE;
2601                 }
2602             }
2603           else
2604             {
2605               /* We had a list of ambiguous overrides; let's see how this
2606                  new one compares.  */
2607
2608               tree candidates;
2609               bool incomparable = false;
2610
2611               /* If there were previous candidates, and this function
2612                  overrides all of them, then it is the new best
2613                  candidate.  */
2614               for (candidates = ffod->candidates;
2615                    candidates;
2616                    candidates = TREE_CHAIN (candidates))
2617                 {
2618                   /* If the candidate overrides the METHOD, then we
2619                      needn't worry about it any further.  */
2620                   if (strictly_overrides (TREE_VALUE (candidates),
2621                                           method))
2622                     {
2623                       method = NULL_TREE;
2624                       break;
2625                     }
2626
2627                   /* If the METHOD doesn't override the candidate,
2628                      then it is incomporable.  */
2629                   if (!strictly_overrides (method,
2630                                            TREE_VALUE (candidates)))
2631                     incomparable = true;
2632                 }
2633
2634               /* If METHOD overrode all the candidates, then it is the
2635                  new best candidate.  */
2636               if (!candidates && !incomparable)
2637                 {
2638                   ffod->overriding_fn = method;
2639                   ffod->overriding_base = TREE_VALUE (path);
2640                   ffod->candidates = NULL_TREE;
2641                 }
2642               /* If METHOD didn't override all the candidates, then it
2643                  is another candidate.  */
2644               else if (method && incomparable)
2645                 ffod->candidates 
2646                   = tree_cons (NULL_TREE, method, ffod->candidates);
2647             }
2648         }
2649     }
2650
2651   return NULL_TREE;
2652 }
2653
2654 /* Returns a TREE_LIST whose TREE_PURPOSE is the final overrider for
2655    FN and whose TREE_VALUE is the binfo for the base where the
2656    overriding occurs.  BINFO (in the hierarchy dominated by T) is the
2657    base object in which FN is declared.  */
2658
2659 static tree
2660 find_final_overrider (t, binfo, fn)
2661      tree t;
2662      tree binfo;
2663      tree fn;
2664 {
2665   find_final_overrider_data ffod;
2666
2667   /* Getting this right is a little tricky.  This is legal:
2668
2669        struct S { virtual void f (); };
2670        struct T { virtual void f (); };
2671        struct U : public S, public T { };
2672
2673      even though calling `f' in `U' is ambiguous.  But, 
2674
2675        struct R { virtual void f(); };
2676        struct S : virtual public R { virtual void f (); };
2677        struct T : virtual public R { virtual void f (); };
2678        struct U : public S, public T { };
2679
2680      is not -- there's no way to decide whether to put `S::f' or
2681      `T::f' in the vtable for `R'.  
2682      
2683      The solution is to look at all paths to BINFO.  If we find
2684      different overriders along any two, then there is a problem.  */
2685   ffod.fn = fn;
2686   ffod.declaring_base = binfo;
2687   ffod.most_derived_type = t;
2688   ffod.overriding_fn = NULL_TREE;
2689   ffod.overriding_base = NULL_TREE;
2690   ffod.candidates = NULL_TREE;
2691
2692   dfs_walk (TYPE_BINFO (t),
2693             dfs_find_final_overrider,
2694             NULL,
2695             &ffod);
2696
2697   /* If there was no winner, issue an error message.  */
2698   if (!ffod.overriding_fn)
2699     {
2700       cp_error ("no unique final overrider for `%D' in `%T'", fn, t);
2701       return error_mark_node;
2702     }
2703
2704   return build_tree_list (ffod.overriding_fn, ffod.overriding_base);
2705 }
2706
2707 /* Returns the function from the BINFO_VIRTUALS entry in T which matches
2708    the signature of FUNCTION_DECL FN, or NULL_TREE if none.  In other words,
2709    the function that the slot in T's primary vtable points to.  */
2710
2711 static tree get_matching_virtual PARAMS ((tree, tree));
2712 static tree
2713 get_matching_virtual (t, fn)
2714      tree t, fn;
2715 {
2716   tree f;
2717
2718   for (f = BINFO_VIRTUALS (TYPE_BINFO (t)); f; f = TREE_CHAIN (f))
2719     if (same_signature_p (BV_FN (f), fn))
2720       return BV_FN (f);
2721   return NULL_TREE;
2722 }
2723
2724 /* Update an entry in the vtable for BINFO, which is in the hierarchy
2725    dominated by T.  FN has been overriden in BINFO; VIRTUALS points to the
2726    corresponding position in the BINFO_VIRTUALS list.  */
2727
2728 static void
2729 update_vtable_entry_for_fn (t, binfo, fn, virtuals)
2730      tree t;
2731      tree binfo;
2732      tree fn;
2733      tree *virtuals;
2734 {
2735   tree b;
2736   tree overrider;
2737   tree delta;
2738   tree virtual_base;
2739   tree first_defn;
2740
2741   /* Find the nearest primary base (possibly binfo itself) which defines
2742      this function; this is the class the caller will convert to when
2743      calling FN through BINFO.  */
2744   for (b = binfo; ; b = get_primary_binfo (b))
2745     {
2746       if (look_for_overrides_here (BINFO_TYPE (b), fn))
2747         break;
2748     }
2749   first_defn = b;
2750
2751   /* Find the final overrider.  */
2752   overrider = find_final_overrider (t, b, fn);
2753   if (overrider == error_mark_node)
2754     return;
2755
2756   /* Assume that we will produce a thunk that convert all the way to
2757      the final overrider, and not to an intermediate virtual base.  */
2758   virtual_base = NULL_TREE;
2759
2760   /* Under the new ABI, we will convert to an intermediate virtual
2761      base first, and then use the vcall offset located there to finish
2762      the conversion.  */
2763   while (b)
2764     {
2765       /* If we find the final overrider, then we can stop
2766          walking.  */
2767       if (same_type_p (BINFO_TYPE (b), 
2768                        BINFO_TYPE (TREE_VALUE (overrider))))
2769         break;
2770
2771       /* If we find a virtual base, and we haven't yet found the
2772          overrider, then there is a virtual base between the
2773          declaring base (first_defn) and the final overrider.  */
2774       if (!virtual_base && TREE_VIA_VIRTUAL (b))
2775         virtual_base = b;
2776
2777       b = BINFO_INHERITANCE_CHAIN (b);
2778     }
2779
2780   /* Compute the constant adjustment to the `this' pointer.  The
2781      `this' pointer, when this function is called, will point at BINFO
2782      (or one of its primary bases, which are at the same offset).  */
2783
2784   if (virtual_base)
2785     /* The `this' pointer needs to be adjusted to the nearest virtual
2786        base.  */
2787     delta = size_diffop (BINFO_OFFSET (virtual_base),
2788                          BINFO_OFFSET (binfo));
2789   else
2790     {
2791       /* The `this' pointer needs to be adjusted from pointing to
2792          BINFO to pointing at the base where the final overrider
2793          appears.  */
2794       delta = size_diffop (BINFO_OFFSET (TREE_VALUE (overrider)),
2795                            BINFO_OFFSET (binfo));
2796
2797       if (! integer_zerop (delta))
2798         {
2799           /* We'll need a thunk.  But if we have a (perhaps formerly)
2800              primary virtual base, we have a vcall slot for this function,
2801              so we can use it rather than create a non-virtual thunk.  */
2802
2803           b = get_primary_binfo (first_defn);
2804           for (; b; b = get_primary_binfo (b))
2805             {
2806               tree f = get_matching_virtual (BINFO_TYPE (b), fn);
2807               if (!f)
2808                 /* b doesn't have this function; no suitable vbase.  */
2809                 break;
2810               if (TREE_VIA_VIRTUAL (b))
2811                 {
2812                   /* Found one; we can treat ourselves as a virtual base.  */
2813                   virtual_base = binfo;
2814                   delta = size_zero_node;
2815                   break;
2816                 }
2817             }
2818         }
2819     }
2820
2821   modify_vtable_entry (t, 
2822                        binfo, 
2823                        TREE_PURPOSE (overrider),
2824                        delta,
2825                        virtuals);
2826
2827   if (virtual_base)
2828     BV_USE_VCALL_INDEX_P (*virtuals) = 1;
2829 }
2830
2831 /* Called from modify_all_vtables via dfs_walk.  */
2832
2833 static tree
2834 dfs_modify_vtables (binfo, data)
2835      tree binfo;
2836      void *data;
2837 {
2838   if (/* There's no need to modify the vtable for a non-virtual
2839          primary base; we're not going to use that vtable anyhow.
2840          We do still need to do this for virtual primary bases, as they
2841          could become non-primary in a construction vtable.  */
2842       (!BINFO_PRIMARY_P (binfo) || TREE_VIA_VIRTUAL (binfo))
2843       /* Similarly, a base without a vtable needs no modification.  */
2844       && CLASSTYPE_VFIELDS (BINFO_TYPE (binfo)))
2845     {
2846       tree t;
2847       tree virtuals;
2848       tree old_virtuals;
2849
2850       t = (tree) data;
2851
2852       /* If we're supporting RTTI then we always need a new vtable to
2853          point to the RTTI information.  Under the new ABI we may need
2854          a new vtable to contain vcall and vbase offsets.  */
2855       make_new_vtable (t, binfo);
2856       
2857       /* Now, go through each of the virtual functions in the virtual
2858          function table for BINFO.  Find the final overrider, and
2859          update the BINFO_VIRTUALS list appropriately.  */
2860       for (virtuals = BINFO_VIRTUALS (binfo),
2861              old_virtuals = BINFO_VIRTUALS (TYPE_BINFO (BINFO_TYPE (binfo)));
2862            virtuals;
2863            virtuals = TREE_CHAIN (virtuals),
2864              old_virtuals = TREE_CHAIN (old_virtuals))
2865         update_vtable_entry_for_fn (t, 
2866                                     binfo, 
2867                                     BV_FN (old_virtuals),
2868                                     &virtuals);
2869     }
2870
2871   SET_BINFO_MARKED (binfo);
2872
2873   return NULL_TREE;
2874 }
2875
2876 /* Update all of the primary and secondary vtables for T.  Create new
2877    vtables as required, and initialize their RTTI information.  Each
2878    of the functions in OVERRIDDEN_VIRTUALS overrides a virtual
2879    function from a base class; find and modify the appropriate entries
2880    to point to the overriding functions.  Returns a list, in
2881    declaration order, of the functions that are overridden in this
2882    class, but do not appear in the primary base class vtable, and
2883    which should therefore be appended to the end of the vtable for T.  */
2884
2885 static tree
2886 modify_all_vtables (t, vfuns_p, overridden_virtuals)
2887      tree t;
2888      int *vfuns_p;
2889      tree overridden_virtuals;
2890 {
2891   tree binfo;
2892
2893   binfo = TYPE_BINFO (t);
2894
2895   /* Update all of the vtables.  */
2896   dfs_walk (binfo, 
2897             dfs_modify_vtables, 
2898             dfs_unmarked_real_bases_queue_p,
2899             t);
2900   dfs_walk (binfo, dfs_unmark, dfs_marked_real_bases_queue_p, t);
2901
2902   /* If we should include overriding functions for secondary vtables
2903      in our primary vtable, add them now.  */
2904   if (all_overridden_vfuns_in_vtables_p ())
2905     {
2906       tree *fnsp = &overridden_virtuals;
2907
2908       while (*fnsp)
2909         {
2910           tree fn = TREE_VALUE (*fnsp);
2911
2912           if (!BINFO_VIRTUALS (binfo)
2913               || !value_member (fn, BINFO_VIRTUALS (binfo)))
2914             {
2915               /* Set the vtable index.  */
2916               set_vindex (fn, vfuns_p);
2917               /* We don't need to convert to a base class when calling
2918                  this function.  */
2919               DECL_VIRTUAL_CONTEXT (fn) = t;
2920
2921               /* We don't need to adjust the `this' pointer when
2922                  calling this function.  */
2923               BV_DELTA (*fnsp) = integer_zero_node;
2924               BV_VCALL_INDEX (*fnsp) = NULL_TREE;
2925
2926               /* This is an overridden function not already in our
2927                  vtable.  Keep it.  */
2928               fnsp = &TREE_CHAIN (*fnsp);
2929             }
2930           else
2931             /* We've already got an entry for this function.  Skip
2932                it.  */
2933             *fnsp = TREE_CHAIN (*fnsp);
2934         }
2935     }
2936   else
2937     overridden_virtuals = NULL_TREE;
2938
2939   return overridden_virtuals;
2940 }
2941
2942 /* Here, we already know that they match in every respect.
2943    All we have to check is where they had their declarations.  */
2944
2945 static int 
2946 strictly_overrides (fndecl1, fndecl2)
2947      tree fndecl1, fndecl2;
2948 {
2949   int distance = get_base_distance (DECL_CONTEXT (fndecl2),
2950                                     DECL_CONTEXT (fndecl1),
2951                                     0, (tree *)0);
2952   if (distance == -2 || distance > 0)
2953     return 1;
2954   return 0;
2955 }
2956
2957 /* Get the base virtual function declarations in T that are either
2958    overridden or hidden by FNDECL as a list.  We set TREE_PURPOSE with
2959    the overrider/hider.  */
2960
2961 static tree
2962 get_basefndecls (fndecl, t)
2963      tree fndecl, t;
2964 {
2965   tree methods = TYPE_METHODS (t);
2966   tree base_fndecls = NULL_TREE;
2967   tree binfos = BINFO_BASETYPES (TYPE_BINFO (t));
2968   int i, n_baseclasses = binfos ? TREE_VEC_LENGTH (binfos) : 0;
2969
2970   while (methods)
2971     {
2972       if (TREE_CODE (methods) == FUNCTION_DECL
2973           && DECL_VINDEX (methods) != NULL_TREE
2974           && DECL_NAME (fndecl) == DECL_NAME (methods))
2975         base_fndecls = tree_cons (fndecl, methods, base_fndecls);
2976
2977       methods = TREE_CHAIN (methods);
2978     }
2979
2980   if (base_fndecls)
2981     return base_fndecls;
2982
2983   for (i = 0; i < n_baseclasses; i++)
2984     {
2985       tree base_binfo = TREE_VEC_ELT (binfos, i);
2986       tree basetype = BINFO_TYPE (base_binfo);
2987
2988       base_fndecls = chainon (get_basefndecls (fndecl, basetype),
2989                               base_fndecls);
2990     }
2991
2992   return base_fndecls;
2993 }
2994
2995 /* Mark the functions that have been hidden with their overriders.
2996    Since we start out with all functions already marked with a hider,
2997    no need to mark functions that are just hidden.
2998
2999    Subroutine of warn_hidden.  */
3000
3001 static void
3002 mark_overriders (fndecl, base_fndecls)
3003      tree fndecl, base_fndecls;
3004 {
3005   for (; base_fndecls; base_fndecls = TREE_CHAIN (base_fndecls))
3006     if (same_signature_p (fndecl, TREE_VALUE (base_fndecls)))
3007       TREE_PURPOSE (base_fndecls) = fndecl;
3008 }
3009
3010 /* If this declaration supersedes the declaration of
3011    a method declared virtual in the base class, then
3012    mark this field as being virtual as well.  */
3013
3014 static void
3015 check_for_override (decl, ctype)
3016      tree decl, ctype;
3017 {
3018   if (TREE_CODE (decl) == TEMPLATE_DECL)
3019     /* In [temp.mem] we have:
3020
3021          A specialization of a member function template does not
3022          override a virtual function from a base class.  */
3023     return;
3024   if ((DECL_DESTRUCTOR_P (decl)
3025        || IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)))
3026       && look_for_overrides (ctype, decl)
3027       && !DECL_STATIC_FUNCTION_P (decl))
3028     {
3029       /* Set DECL_VINDEX to a value that is neither an
3030          INTEGER_CST nor the error_mark_node so that
3031          add_virtual_function will realize this is an
3032          overriding function.  */
3033       DECL_VINDEX (decl) = decl;
3034     }
3035   if (DECL_VIRTUAL_P (decl))
3036     {
3037       if (DECL_VINDEX (decl) == NULL_TREE)
3038         DECL_VINDEX (decl) = error_mark_node;
3039       IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = 1;
3040     }
3041 }
3042
3043 /* Warn about hidden virtual functions that are not overridden in t.
3044    We know that constructors and destructors don't apply.  */
3045
3046 void
3047 warn_hidden (t)
3048      tree t;
3049 {
3050   tree method_vec = CLASSTYPE_METHOD_VEC (t);
3051   int n_methods = method_vec ? TREE_VEC_LENGTH (method_vec) : 0;
3052   int i;
3053
3054   /* We go through each separately named virtual function.  */
3055   for (i = 2; i < n_methods && TREE_VEC_ELT (method_vec, i); ++i)
3056     {
3057       tree fns = TREE_VEC_ELT (method_vec, i);
3058       tree fndecl = NULL_TREE;
3059
3060       tree base_fndecls = NULL_TREE;
3061       tree binfos = BINFO_BASETYPES (TYPE_BINFO (t));
3062       int i, n_baseclasses = binfos ? TREE_VEC_LENGTH (binfos) : 0;
3063
3064       /* First see if we have any virtual functions in this batch.  */
3065       for (; fns; fns = OVL_NEXT (fns))
3066         {
3067           fndecl = OVL_CURRENT (fns);
3068           if (DECL_VINDEX (fndecl))
3069             break;
3070         }
3071
3072       if (fns == NULL_TREE)
3073         continue;
3074
3075       /* First we get a list of all possible functions that might be
3076          hidden from each base class.  */
3077       for (i = 0; i < n_baseclasses; i++)
3078         {
3079           tree base_binfo = TREE_VEC_ELT (binfos, i);
3080           tree basetype = BINFO_TYPE (base_binfo);
3081
3082           base_fndecls = chainon (get_basefndecls (fndecl, basetype),
3083                                   base_fndecls);
3084         }
3085
3086       fns = OVL_NEXT (fns);
3087
3088       /* ...then mark up all the base functions with overriders, preferring
3089          overriders to hiders.  */
3090       if (base_fndecls)
3091         for (; fns; fns = OVL_NEXT (fns))
3092           {
3093             fndecl = OVL_CURRENT (fns);
3094             if (DECL_VINDEX (fndecl))
3095               mark_overriders (fndecl, base_fndecls);
3096           }
3097
3098       /* Now give a warning for all base functions without overriders,
3099          as they are hidden.  */
3100       for (; base_fndecls; base_fndecls = TREE_CHAIN (base_fndecls))
3101         if (!same_signature_p (TREE_PURPOSE (base_fndecls),
3102                                TREE_VALUE (base_fndecls)))
3103           {
3104             /* Here we know it is a hider, and no overrider exists.  */
3105             cp_warning_at ("`%D' was hidden", TREE_VALUE (base_fndecls));
3106             cp_warning_at ("  by `%D'", TREE_PURPOSE (base_fndecls));
3107           }
3108     }
3109 }
3110
3111 /* Check for things that are invalid.  There are probably plenty of other
3112    things we should check for also.  */
3113
3114 static void
3115 finish_struct_anon (t)
3116      tree t;
3117 {
3118   tree field;
3119
3120   for (field = TYPE_FIELDS (t); field; field = TREE_CHAIN (field))
3121     {
3122       if (TREE_STATIC (field))
3123         continue;
3124       if (TREE_CODE (field) != FIELD_DECL)
3125         continue;
3126
3127       if (DECL_NAME (field) == NULL_TREE
3128           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
3129         {
3130           tree elt = TYPE_FIELDS (TREE_TYPE (field));
3131           for (; elt; elt = TREE_CHAIN (elt))
3132             {
3133               if (DECL_ARTIFICIAL (elt))
3134                 continue;
3135
3136               if (DECL_NAME (elt) == constructor_name (t))
3137                 cp_pedwarn_at ("ISO C++ forbids member `%D' with same name as enclosing class",
3138                                elt);
3139
3140               if (TREE_CODE (elt) != FIELD_DECL)
3141                 {
3142                   cp_pedwarn_at ("`%#D' invalid; an anonymous union can only have non-static data members",
3143                                  elt);
3144                   continue;
3145                 }
3146
3147               if (TREE_PRIVATE (elt))
3148                 cp_pedwarn_at ("private member `%#D' in anonymous union",
3149                                elt);
3150               else if (TREE_PROTECTED (elt))
3151                 cp_pedwarn_at ("protected member `%#D' in anonymous union",
3152                                elt);
3153
3154               TREE_PRIVATE (elt) = TREE_PRIVATE (field);
3155               TREE_PROTECTED (elt) = TREE_PROTECTED (field);
3156             }
3157         }
3158     }
3159 }
3160
3161 /* Create default constructors, assignment operators, and so forth for
3162    the type indicated by T, if they are needed.
3163    CANT_HAVE_DEFAULT_CTOR, CANT_HAVE_CONST_CTOR, and
3164    CANT_HAVE_CONST_ASSIGNMENT are nonzero if, for whatever reason, the
3165    class cannot have a default constructor, copy constructor taking a
3166    const reference argument, or an assignment operator taking a const
3167    reference, respectively.  If a virtual destructor is created, its
3168    DECL is returned; otherwise the return value is NULL_TREE.  */
3169
3170 static tree
3171 add_implicitly_declared_members (t, cant_have_default_ctor,
3172                                  cant_have_const_cctor,
3173                                  cant_have_const_assignment)
3174      tree t;
3175      int cant_have_default_ctor;
3176      int cant_have_const_cctor;
3177      int cant_have_const_assignment;
3178 {
3179   tree default_fn;
3180   tree implicit_fns = NULL_TREE;
3181   tree virtual_dtor = NULL_TREE;
3182   tree *f;
3183
3184   /* Destructor.  */
3185   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) && !TYPE_HAS_DESTRUCTOR (t))
3186     {
3187       default_fn = implicitly_declare_fn (sfk_destructor, t, /*const_p=*/0);
3188       check_for_override (default_fn, t);
3189
3190       /* If we couldn't make it work, then pretend we didn't need it.  */
3191       if (default_fn == void_type_node)
3192         TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) = 0;
3193       else
3194         {
3195           TREE_CHAIN (default_fn) = implicit_fns;
3196           implicit_fns = default_fn;
3197
3198           if (DECL_VINDEX (default_fn))
3199             virtual_dtor = default_fn;
3200         }
3201     }
3202   else
3203     /* Any non-implicit destructor is non-trivial.  */
3204     TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) |= TYPE_HAS_DESTRUCTOR (t);
3205
3206   /* Default constructor.  */
3207   if (! TYPE_HAS_CONSTRUCTOR (t) && ! cant_have_default_ctor)
3208     {
3209       default_fn = implicitly_declare_fn (sfk_constructor, t, /*const_p=*/0);
3210       TREE_CHAIN (default_fn) = implicit_fns;
3211       implicit_fns = default_fn;
3212     }
3213
3214   /* Copy constructor.  */
3215   if (! TYPE_HAS_INIT_REF (t) && ! TYPE_FOR_JAVA (t))
3216     {
3217       /* ARM 12.18: You get either X(X&) or X(const X&), but
3218          not both.  --Chip  */
3219       default_fn 
3220         = implicitly_declare_fn (sfk_copy_constructor, t,
3221                                  /*const_p=*/!cant_have_const_cctor);
3222       TREE_CHAIN (default_fn) = implicit_fns;
3223       implicit_fns = default_fn;
3224     }
3225
3226   /* Assignment operator.  */
3227   if (! TYPE_HAS_ASSIGN_REF (t) && ! TYPE_FOR_JAVA (t))
3228     {
3229       default_fn 
3230         = implicitly_declare_fn (sfk_assignment_operator, t,
3231                                  /*const_p=*/!cant_have_const_assignment);
3232       TREE_CHAIN (default_fn) = implicit_fns;
3233       implicit_fns = default_fn;
3234     }
3235
3236   /* Now, hook all of the new functions on to TYPE_METHODS,
3237      and add them to the CLASSTYPE_METHOD_VEC.  */
3238   for (f = &implicit_fns; *f; f = &TREE_CHAIN (*f))
3239     add_method (t, *f, /*error_p=*/0);
3240   *f = TYPE_METHODS (t);
3241   TYPE_METHODS (t) = implicit_fns;
3242
3243   return virtual_dtor;
3244 }
3245
3246 /* Subroutine of finish_struct_1.  Recursively count the number of fields
3247    in TYPE, including anonymous union members.  */
3248
3249 static int
3250 count_fields (fields)
3251      tree fields;
3252 {
3253   tree x;
3254   int n_fields = 0;
3255   for (x = fields; x; x = TREE_CHAIN (x))
3256     {
3257       if (TREE_CODE (x) == FIELD_DECL && ANON_AGGR_TYPE_P (TREE_TYPE (x)))
3258         n_fields += count_fields (TYPE_FIELDS (TREE_TYPE (x)));
3259       else
3260         n_fields += 1;
3261     }
3262   return n_fields;
3263 }
3264
3265 /* Subroutine of finish_struct_1.  Recursively add all the fields in the
3266    TREE_LIST FIELDS to the TREE_VEC FIELD_VEC, starting at offset IDX.  */
3267
3268 static int
3269 add_fields_to_vec (fields, field_vec, idx)
3270      tree fields, field_vec;
3271      int idx;
3272 {
3273   tree x;
3274   for (x = fields; x; x = TREE_CHAIN (x))
3275     {
3276       if (TREE_CODE (x) == FIELD_DECL && ANON_AGGR_TYPE_P (TREE_TYPE (x)))
3277         idx = add_fields_to_vec (TYPE_FIELDS (TREE_TYPE (x)), field_vec, idx);
3278       else
3279         TREE_VEC_ELT (field_vec, idx++) = x;
3280     }
3281   return idx;
3282 }
3283
3284 /* FIELD is a bit-field.  We are finishing the processing for its
3285    enclosing type.  Issue any appropriate messages and set appropriate
3286    flags.  */
3287
3288 static void
3289 check_bitfield_decl (field)
3290      tree field;
3291 {
3292   tree type = TREE_TYPE (field);
3293   tree w = NULL_TREE;
3294
3295   /* Detect invalid bit-field type.  */
3296   if (DECL_INITIAL (field)
3297       && ! INTEGRAL_TYPE_P (TREE_TYPE (field)))
3298     {
3299       cp_error_at ("bit-field `%#D' with non-integral type", field);
3300       w = error_mark_node;
3301     }
3302
3303   /* Detect and ignore out of range field width.  */
3304   if (DECL_INITIAL (field))
3305     {
3306       w = DECL_INITIAL (field);
3307
3308       /* Avoid the non_lvalue wrapper added by fold for PLUS_EXPRs.  */
3309       STRIP_NOPS (w);
3310
3311       /* detect invalid field size.  */
3312       if (TREE_CODE (w) == CONST_DECL)
3313         w = DECL_INITIAL (w);
3314       else
3315         w = decl_constant_value (w);
3316
3317       if (TREE_CODE (w) != INTEGER_CST)
3318         {
3319           cp_error_at ("bit-field `%D' width not an integer constant",
3320                        field);
3321           w = error_mark_node;
3322         }
3323       else if (tree_int_cst_sgn (w) < 0)
3324         {
3325           cp_error_at ("negative width in bit-field `%D'", field);
3326           w = error_mark_node;
3327         }
3328       else if (integer_zerop (w) && DECL_NAME (field) != 0)
3329         {
3330           cp_error_at ("zero width for bit-field `%D'", field);
3331           w = error_mark_node;
3332         }
3333       else if (compare_tree_int (w, TYPE_PRECISION (type)) > 0
3334                && TREE_CODE (type) != ENUMERAL_TYPE
3335                && TREE_CODE (type) != BOOLEAN_TYPE)
3336         cp_warning_at ("width of `%D' exceeds its type", field);
3337       else if (TREE_CODE (type) == ENUMERAL_TYPE
3338                && (0 > compare_tree_int (w,
3339                                          min_precision (TYPE_MIN_VALUE (type),
3340                                                         TREE_UNSIGNED (type)))
3341                    ||  0 > compare_tree_int (w,
3342                                              min_precision
3343                                              (TYPE_MAX_VALUE (type),
3344                                               TREE_UNSIGNED (type)))))
3345         cp_warning_at ("`%D' is too small to hold all values of `%#T'",
3346                        field, type);
3347     }
3348   
3349   /* Remove the bit-field width indicator so that the rest of the
3350      compiler does not treat that value as an initializer.  */
3351   DECL_INITIAL (field) = NULL_TREE;
3352
3353   if (w != error_mark_node)
3354     {
3355       DECL_SIZE (field) = convert (bitsizetype, w);
3356       DECL_BIT_FIELD (field) = 1;
3357
3358       if (integer_zerop (w))
3359         {
3360 #ifdef EMPTY_FIELD_BOUNDARY
3361           DECL_ALIGN (field) = MAX (DECL_ALIGN (field), 
3362                                     EMPTY_FIELD_BOUNDARY);
3363 #endif
3364 #ifdef PCC_BITFIELD_TYPE_MATTERS
3365           if (PCC_BITFIELD_TYPE_MATTERS)
3366             {
3367               DECL_ALIGN (field) = MAX (DECL_ALIGN (field), 
3368                                         TYPE_ALIGN (type));
3369               DECL_USER_ALIGN (field) |= TYPE_USER_ALIGN (type);
3370             }
3371 #endif
3372         }
3373     }
3374   else
3375     {
3376       /* Non-bit-fields are aligned for their type.  */
3377       DECL_BIT_FIELD (field) = 0;
3378       CLEAR_DECL_C_BIT_FIELD (field);
3379       DECL_ALIGN (field) = MAX (DECL_ALIGN (field), TYPE_ALIGN (type));
3380       DECL_USER_ALIGN (field) |= TYPE_USER_ALIGN (type);
3381     }
3382 }
3383
3384 /* FIELD is a non bit-field.  We are finishing the processing for its
3385    enclosing type T.  Issue any appropriate messages and set appropriate
3386    flags.  */
3387
3388 static void
3389 check_field_decl (field, t, cant_have_const_ctor,
3390                   cant_have_default_ctor, no_const_asn_ref,
3391                   any_default_members)
3392      tree field;
3393      tree t;
3394      int *cant_have_const_ctor;
3395      int *cant_have_default_ctor;
3396      int *no_const_asn_ref;
3397      int *any_default_members;
3398 {
3399   tree type = strip_array_types (TREE_TYPE (field));
3400
3401   /* An anonymous union cannot contain any fields which would change
3402      the settings of CANT_HAVE_CONST_CTOR and friends.  */
3403   if (ANON_UNION_TYPE_P (type))
3404     ;
3405   /* And, we don't set TYPE_HAS_CONST_INIT_REF, etc., for anonymous
3406      structs.  So, we recurse through their fields here.  */
3407   else if (ANON_AGGR_TYPE_P (type))
3408     {
3409       tree fields;
3410
3411       for (fields = TYPE_FIELDS (type); fields; fields = TREE_CHAIN (fields))
3412         if (TREE_CODE (fields) == FIELD_DECL && !DECL_C_BIT_FIELD (field))
3413           check_field_decl (fields, t, cant_have_const_ctor,
3414                             cant_have_default_ctor, no_const_asn_ref,
3415                             any_default_members);
3416     }
3417   /* Check members with class type for constructors, destructors,
3418      etc.  */
3419   else if (CLASS_TYPE_P (type))
3420     {
3421       /* Never let anything with uninheritable virtuals
3422          make it through without complaint.  */
3423       abstract_virtuals_error (field, type);
3424                       
3425       if (TREE_CODE (t) == UNION_TYPE)
3426         {
3427           if (TYPE_NEEDS_CONSTRUCTING (type))
3428             cp_error_at ("member `%#D' with constructor not allowed in union",
3429                          field);
3430           if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3431             cp_error_at ("member `%#D' with destructor not allowed in union",
3432                          field);
3433           if (TYPE_HAS_COMPLEX_ASSIGN_REF (type))
3434             cp_error_at ("member `%#D' with copy assignment operator not allowed in union",
3435                          field);
3436         }
3437       else
3438         {
3439           TYPE_NEEDS_CONSTRUCTING (t) |= TYPE_NEEDS_CONSTRUCTING (type);
3440           TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) 
3441             |= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type);
3442           TYPE_HAS_COMPLEX_ASSIGN_REF (t) |= TYPE_HAS_COMPLEX_ASSIGN_REF (type);
3443           TYPE_HAS_COMPLEX_INIT_REF (t) |= TYPE_HAS_COMPLEX_INIT_REF (type);
3444         }
3445
3446       if (!TYPE_HAS_CONST_INIT_REF (type))
3447         *cant_have_const_ctor = 1;
3448
3449       if (!TYPE_HAS_CONST_ASSIGN_REF (type))
3450         *no_const_asn_ref = 1;
3451
3452       if (TYPE_HAS_CONSTRUCTOR (type)
3453           && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
3454         *cant_have_default_ctor = 1;
3455     }
3456   if (DECL_INITIAL (field) != NULL_TREE)
3457     {
3458       /* `build_class_init_list' does not recognize
3459          non-FIELD_DECLs.  */
3460       if (TREE_CODE (t) == UNION_TYPE && any_default_members != 0)
3461         cp_error_at ("multiple fields in union `%T' initialized");
3462       *any_default_members = 1;
3463     }
3464
3465   /* Non-bit-fields are aligned for their type, except packed fields
3466      which require only BITS_PER_UNIT alignment.  */
3467   DECL_ALIGN (field) = MAX (DECL_ALIGN (field), 
3468                             (DECL_PACKED (field) 
3469                              ? BITS_PER_UNIT
3470                              : TYPE_ALIGN (TREE_TYPE (field))));
3471   if (! DECL_PACKED (field))
3472     DECL_USER_ALIGN (field) |= TYPE_USER_ALIGN (TREE_TYPE (field));
3473 }
3474
3475 /* Check the data members (both static and non-static), class-scoped
3476    typedefs, etc., appearing in the declaration of T.  Issue
3477    appropriate diagnostics.  Sets ACCESS_DECLS to a list (in
3478    declaration order) of access declarations; each TREE_VALUE in this
3479    list is a USING_DECL.
3480
3481    In addition, set the following flags:
3482
3483      EMPTY_P
3484        The class is empty, i.e., contains no non-static data members.
3485
3486      CANT_HAVE_DEFAULT_CTOR_P
3487        This class cannot have an implicitly generated default
3488        constructor.
3489
3490      CANT_HAVE_CONST_CTOR_P
3491        This class cannot have an implicitly generated copy constructor
3492        taking a const reference.
3493
3494      CANT_HAVE_CONST_ASN_REF
3495        This class cannot have an implicitly generated assignment
3496        operator taking a const reference.
3497
3498    All of these flags should be initialized before calling this
3499    function.
3500
3501    Returns a pointer to the end of the TYPE_FIELDs chain; additional
3502    fields can be added by adding to this chain.  */
3503
3504 static void
3505 check_field_decls (t, access_decls, empty_p, 
3506                    cant_have_default_ctor_p, cant_have_const_ctor_p,
3507                    no_const_asn_ref_p)
3508      tree t;
3509      tree *access_decls;
3510      int *empty_p;
3511      int *cant_have_default_ctor_p;
3512      int *cant_have_const_ctor_p;
3513      int *no_const_asn_ref_p;
3514 {
3515   tree *field;
3516   tree *next;
3517   int has_pointers;
3518   int any_default_members;
3519
3520   /* First, delete any duplicate fields.  */
3521   delete_duplicate_fields (TYPE_FIELDS (t));
3522
3523   /* Assume there are no access declarations.  */
3524   *access_decls = NULL_TREE;
3525   /* Assume this class has no pointer members.  */
3526   has_pointers = 0;
3527   /* Assume none of the members of this class have default
3528      initializations.  */
3529   any_default_members = 0;
3530
3531   for (field = &TYPE_FIELDS (t); *field; field = next)
3532     {
3533       tree x = *field;
3534       tree type = TREE_TYPE (x);
3535
3536       GNU_xref_member (current_class_name, x);
3537
3538       next = &TREE_CHAIN (x);
3539
3540       if (TREE_CODE (x) == FIELD_DECL)
3541         {
3542           DECL_PACKED (x) |= TYPE_PACKED (t);
3543
3544           if (DECL_C_BIT_FIELD (x) && integer_zerop (DECL_INITIAL (x)))
3545             /* We don't treat zero-width bitfields as making a class
3546                non-empty.  */
3547             ;
3548           else
3549             {
3550               /* The class is non-empty.  */
3551               *empty_p = 0;
3552               /* The class is not even nearly empty.  */
3553               CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
3554             }
3555         }
3556
3557       if (TREE_CODE (x) == USING_DECL)
3558         {
3559           /* Prune the access declaration from the list of fields.  */
3560           *field = TREE_CHAIN (x);
3561
3562           /* Save the access declarations for our caller.  */
3563           *access_decls = tree_cons (NULL_TREE, x, *access_decls);
3564
3565           /* Since we've reset *FIELD there's no reason to skip to the
3566              next field.  */
3567           next = field;
3568           continue;
3569         }
3570
3571       if (TREE_CODE (x) == TYPE_DECL
3572           || TREE_CODE (x) == TEMPLATE_DECL)
3573         continue;
3574
3575       /* If we've gotten this far, it's a data member, possibly static,
3576          or an enumerator.  */
3577
3578       DECL_CONTEXT (x) = t;
3579
3580       /* ``A local class cannot have static data members.'' ARM 9.4 */
3581       if (current_function_decl && TREE_STATIC (x))
3582         cp_error_at ("field `%D' in local class cannot be static", x);
3583
3584       /* Perform error checking that did not get done in
3585          grokdeclarator.  */
3586       if (TREE_CODE (type) == FUNCTION_TYPE)
3587         {
3588           cp_error_at ("field `%D' invalidly declared function type",
3589                        x);
3590           type = build_pointer_type (type);
3591           TREE_TYPE (x) = type;
3592         }
3593       else if (TREE_CODE (type) == METHOD_TYPE)
3594         {
3595           cp_error_at ("field `%D' invalidly declared method type", x);
3596           type = build_pointer_type (type);
3597           TREE_TYPE (x) = type;
3598         }
3599       else if (TREE_CODE (type) == OFFSET_TYPE)
3600         {
3601           cp_error_at ("field `%D' invalidly declared offset type", x);
3602           type = build_pointer_type (type);
3603           TREE_TYPE (x) = type;
3604         }
3605
3606       if (type == error_mark_node)
3607         continue;
3608           
3609       /* When this goes into scope, it will be a non-local reference.  */
3610       DECL_NONLOCAL (x) = 1;
3611
3612       if (TREE_CODE (x) == CONST_DECL)
3613         continue;
3614
3615       if (TREE_CODE (x) == VAR_DECL)
3616         {
3617           if (TREE_CODE (t) == UNION_TYPE)
3618             /* Unions cannot have static members.  */
3619             cp_error_at ("field `%D' declared static in union", x);
3620               
3621           continue;
3622         }
3623
3624       /* Now it can only be a FIELD_DECL.  */
3625
3626       if (TREE_PRIVATE (x) || TREE_PROTECTED (x))
3627         CLASSTYPE_NON_AGGREGATE (t) = 1;
3628
3629       /* If this is of reference type, check if it needs an init.
3630          Also do a little ANSI jig if necessary.  */
3631       if (TREE_CODE (type) == REFERENCE_TYPE)
3632         {
3633           CLASSTYPE_NON_POD_P (t) = 1;
3634           if (DECL_INITIAL (x) == NULL_TREE)
3635             CLASSTYPE_REF_FIELDS_NEED_INIT (t) = 1;
3636
3637           /* ARM $12.6.2: [A member initializer list] (or, for an
3638              aggregate, initialization by a brace-enclosed list) is the
3639              only way to initialize nonstatic const and reference
3640              members.  */
3641           *cant_have_default_ctor_p = 1;
3642           TYPE_HAS_COMPLEX_ASSIGN_REF (t) = 1;
3643
3644           if (! TYPE_HAS_CONSTRUCTOR (t) && extra_warnings)
3645             cp_warning_at ("non-static reference `%#D' in class without a constructor", x);
3646         }
3647
3648       type = strip_array_types (type);
3649       
3650       if (TREE_CODE (type) == POINTER_TYPE)
3651         has_pointers = 1;
3652
3653       if (DECL_MUTABLE_P (x) || TYPE_HAS_MUTABLE_P (type))
3654         CLASSTYPE_HAS_MUTABLE (t) = 1;
3655
3656       if (! pod_type_p (type))
3657         /* DR 148 now allows pointers to members (which are POD themselves),
3658            to be allowed in POD structs.  */
3659         CLASSTYPE_NON_POD_P (t) = 1;
3660
3661       /* If any field is const, the structure type is pseudo-const.  */
3662       if (CP_TYPE_CONST_P (type))
3663         {
3664           C_TYPE_FIELDS_READONLY (t) = 1;
3665           if (DECL_INITIAL (x) == NULL_TREE)
3666             CLASSTYPE_READONLY_FIELDS_NEED_INIT (t) = 1;
3667
3668           /* ARM $12.6.2: [A member initializer list] (or, for an
3669              aggregate, initialization by a brace-enclosed list) is the
3670              only way to initialize nonstatic const and reference
3671              members.  */
3672           *cant_have_default_ctor_p = 1;
3673           TYPE_HAS_COMPLEX_ASSIGN_REF (t) = 1;
3674
3675           if (! TYPE_HAS_CONSTRUCTOR (t) && extra_warnings)
3676             cp_warning_at ("non-static const member `%#D' in class without a constructor", x);
3677         }
3678       /* A field that is pseudo-const makes the structure likewise.  */
3679       else if (IS_AGGR_TYPE (type))
3680         {
3681           C_TYPE_FIELDS_READONLY (t) |= C_TYPE_FIELDS_READONLY (type);
3682           CLASSTYPE_READONLY_FIELDS_NEED_INIT (t) 
3683             |= CLASSTYPE_READONLY_FIELDS_NEED_INIT (type);
3684         }
3685
3686       /* Core issue 80: A nonstatic data member is required to have a
3687          different name from the class iff the class has a
3688          user-defined constructor.  */
3689       if (DECL_NAME (x) == constructor_name (t)
3690           && TYPE_HAS_CONSTRUCTOR (t))
3691         cp_pedwarn_at ("field `%#D' with same name as class", x);
3692
3693       /* We set DECL_C_BIT_FIELD in grokbitfield.
3694          If the type and width are valid, we'll also set DECL_BIT_FIELD.  */
3695       if (DECL_C_BIT_FIELD (x))
3696         check_bitfield_decl (x);
3697       else
3698         check_field_decl (x, t,
3699                           cant_have_const_ctor_p,
3700                           cant_have_default_ctor_p, 
3701                           no_const_asn_ref_p,
3702                           &any_default_members);
3703     }
3704
3705   /* Effective C++ rule 11.  */
3706   if (has_pointers && warn_ecpp && TYPE_HAS_CONSTRUCTOR (t)
3707       && ! (TYPE_HAS_INIT_REF (t) && TYPE_HAS_ASSIGN_REF (t)))
3708     {
3709       cp_warning ("`%#T' has pointer data members", t);
3710       
3711       if (! TYPE_HAS_INIT_REF (t))
3712         {
3713           cp_warning ("  but does not override `%T(const %T&)'", t, t);
3714           if (! TYPE_HAS_ASSIGN_REF (t))
3715             cp_warning ("  or `operator=(const %T&)'", t);
3716         }
3717       else if (! TYPE_HAS_ASSIGN_REF (t))
3718         cp_warning ("  but does not override `operator=(const %T&)'", t);
3719     }
3720
3721
3722   /* Check anonymous struct/anonymous union fields.  */
3723   finish_struct_anon (t);
3724
3725   /* We've built up the list of access declarations in reverse order.
3726      Fix that now.  */
3727   *access_decls = nreverse (*access_decls);
3728 }
3729
3730 /* Return a FIELD_DECL for a pointer-to-virtual-table or
3731    pointer-to-virtual-base.  The NAME, ASSEMBLER_NAME, and TYPE of the
3732    field are as indicated.  The CLASS_TYPE in which this field occurs
3733    is also indicated.  FCONTEXT is the type that is needed for the debug
3734    info output routines.  *EMPTY_P is set to a non-zero value by this
3735    function to indicate that a class containing this field is
3736    non-empty.  */
3737
3738 static tree
3739 build_vtbl_or_vbase_field (name, assembler_name, type, class_type, fcontext,
3740                            empty_p)
3741      tree name;
3742      tree assembler_name;
3743      tree type;
3744      tree class_type;
3745      tree fcontext;
3746      int *empty_p;
3747 {
3748   tree field;
3749
3750   /* This class is non-empty.  */
3751   *empty_p = 0;
3752
3753   /* Build the FIELD_DECL.  */
3754   field = build_decl (FIELD_DECL, name, type);
3755   SET_DECL_ASSEMBLER_NAME (field, assembler_name);
3756   DECL_VIRTUAL_P (field) = 1;
3757   DECL_ARTIFICIAL (field) = 1;
3758   DECL_FIELD_CONTEXT (field) = class_type;
3759   DECL_FCONTEXT (field) = fcontext;
3760   DECL_ALIGN (field) = TYPE_ALIGN (type);
3761   DECL_USER_ALIGN (field) = TYPE_USER_ALIGN (type);
3762
3763   /* Return it.  */
3764   return field;
3765 }
3766
3767 /* If TYPE is an empty class type, records its OFFSET in the table of
3768    OFFSETS.  */
3769
3770 static int
3771 record_subobject_offset (type, offset, offsets)
3772      tree type;
3773      tree offset;
3774      splay_tree offsets;
3775 {
3776   splay_tree_node n;
3777
3778   if (!is_empty_class (type))
3779     return 0;
3780
3781   /* Record the location of this empty object in OFFSETS.  */
3782   n = splay_tree_lookup (offsets, (splay_tree_key) offset);
3783   if (!n)
3784     n = splay_tree_insert (offsets, 
3785                            (splay_tree_key) offset,
3786                            (splay_tree_value) NULL_TREE);
3787   n->value = ((splay_tree_value) 
3788               tree_cons (NULL_TREE,
3789                          type,
3790                          (tree) n->value));
3791
3792   return 0;
3793 }
3794
3795 /* Returns non-zero if TYPE is an empty class type and there is
3796    already an entry in OFFSETS for the same TYPE as the same OFFSET.  */
3797
3798 static int
3799 check_subobject_offset (type, offset, offsets)
3800      tree type;
3801      tree offset;
3802      splay_tree offsets;
3803 {
3804   splay_tree_node n;
3805   tree t;
3806
3807   if (!is_empty_class (type))
3808     return 0;
3809
3810   /* Record the location of this empty object in OFFSETS.  */
3811   n = splay_tree_lookup (offsets, (splay_tree_key) offset);
3812   if (!n)
3813     return 0;
3814
3815   for (t = (tree) n->value; t; t = TREE_CHAIN (t))
3816     if (same_type_p (TREE_VALUE (t), type))
3817       return 1;
3818
3819   return 0;
3820 }
3821
3822 /* Walk through all the subobjects of TYPE (located at OFFSET).  Call
3823    F for every subobject, passing it the type, offset, and table of
3824    OFFSETS.  If VBASES_P is non-zero, then even virtual non-primary
3825    bases should be traversed; otherwise, they are ignored.  
3826
3827    If MAX_OFFSET is non-NULL, then subobjects with an offset greater
3828    than MAX_OFFSET will not be walked.
3829
3830    If F returns a non-zero value, the traversal ceases, and that value
3831    is returned.  Otherwise, returns zero.  */
3832
3833 static int
3834 walk_subobject_offsets (type, f, offset, offsets, max_offset, vbases_p)
3835      tree type;
3836      subobject_offset_fn f;
3837      tree offset;
3838      splay_tree offsets;
3839      tree max_offset;
3840      int vbases_p;
3841 {
3842   int r = 0;
3843
3844   /* If this OFFSET is bigger than the MAX_OFFSET, then we should
3845      stop.  */
3846   if (max_offset && INT_CST_LT (max_offset, offset))
3847     return 0;
3848
3849   if (CLASS_TYPE_P (type))
3850     {
3851       tree field;
3852       int i;
3853
3854       /* Record the location of TYPE.  */
3855       r = (*f) (type, offset, offsets);
3856       if (r)
3857         return r;
3858
3859       /* Iterate through the direct base classes of TYPE.  */
3860       for (i = 0; i < CLASSTYPE_N_BASECLASSES (type); ++i)
3861         {
3862           tree binfo = BINFO_BASETYPE (TYPE_BINFO (type), i);
3863
3864           if (!vbases_p 
3865               && TREE_VIA_VIRTUAL (binfo) 
3866               && !BINFO_PRIMARY_P (binfo))
3867             continue;
3868
3869           r = walk_subobject_offsets (BINFO_TYPE (binfo),
3870                                       f,
3871                                       size_binop (PLUS_EXPR,
3872                                                   offset,
3873                                                   BINFO_OFFSET (binfo)),
3874                                       offsets,
3875                                       max_offset,
3876                                       vbases_p);
3877           if (r)
3878             return r;
3879         }
3880
3881       /* Iterate through the fields of TYPE.  */
3882       for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3883         if (TREE_CODE (field) == FIELD_DECL)
3884           {
3885             r = walk_subobject_offsets (TREE_TYPE (field),
3886                                         f,
3887                                         size_binop (PLUS_EXPR,
3888                                                     offset,
3889                                                     DECL_FIELD_OFFSET (field)),
3890                                         offsets,
3891                                         max_offset,
3892                                         /*vbases_p=*/1);
3893             if (r)
3894               return r;
3895           }
3896     }
3897   else if (TREE_CODE (type) == ARRAY_TYPE)
3898     {
3899       tree domain = TYPE_DOMAIN (type);
3900       tree index;
3901
3902       /* Step through each of the elements in the array.  */
3903       for (index = size_zero_node; 
3904            INT_CST_LT (index, TYPE_MAX_VALUE (domain));
3905            index = size_binop (PLUS_EXPR, index, size_one_node))
3906         {
3907           r = walk_subobject_offsets (TREE_TYPE (type),
3908                                       f,
3909                                       offset,
3910                                       offsets,
3911                                       max_offset,
3912                                       /*vbases_p=*/1);
3913           if (r)
3914             return r;
3915           offset = size_binop (PLUS_EXPR, offset, 
3916                                TYPE_SIZE_UNIT (TREE_TYPE (type)));
3917           /* If this new OFFSET is bigger than the MAX_OFFSET, then
3918              there's no point in iterating through the remaining
3919              elements of the array.  */
3920           if (max_offset && INT_CST_LT (max_offset, offset))
3921             break;
3922         }
3923     }
3924
3925   return 0;
3926 }
3927
3928 /* Record all of the empty subobjects of TYPE (located at OFFSET) in
3929    OFFSETS.  If VBASES_P is non-zero, virtual bases of TYPE are
3930    examined.  */
3931
3932 static void
3933 record_subobject_offsets (type, offset, offsets, vbases_p)
3934      tree type;
3935      tree offset;
3936      splay_tree offsets;
3937      int vbases_p;
3938 {
3939   walk_subobject_offsets (type, record_subobject_offset, offset,
3940                           offsets, /*max_offset=*/NULL_TREE, vbases_p);
3941 }
3942
3943 /* Returns non-zero if any of the empty subobjects of TYPE (located at
3944    OFFSET) conflict with entries in OFFSETS.  If VBASES_P is non-zero,
3945    virtual bases of TYPE are examined.  */
3946
3947 static int
3948 layout_conflict_p (type, offset, offsets, vbases_p)
3949      tree type;
3950      tree offset;
3951      splay_tree offsets;
3952      int vbases_p;
3953 {
3954   splay_tree_node max_node;
3955
3956   /* Get the node in OFFSETS that indicates the maximum offset where
3957      an empty subobject is located.  */
3958   max_node = splay_tree_max (offsets);
3959   /* If there aren't any empty subobjects, then there's no point in
3960      performing this check.  */
3961   if (!max_node)
3962     return 0;
3963
3964   return walk_subobject_offsets (type, check_subobject_offset, offset,
3965                                  offsets, (tree) (max_node->key),
3966                                  vbases_p);
3967 }
3968
3969 /* DECL is a FIELD_DECL corresponding either to a base subobject of a
3970    non-static data member of the type indicated by RLI.  BINFO is the
3971    binfo corresponding to the base subobject, OFFSETS maps offsets to
3972    types already located at those offsets.  T is the most derived
3973    type.  This function determines the position of the DECL.  */
3974
3975 static void
3976 layout_nonempty_base_or_field (rli, decl, binfo, offsets, t)
3977      record_layout_info rli;
3978      tree decl;
3979      tree binfo;
3980      splay_tree offsets;
3981      tree t;
3982 {
3983   tree offset = NULL_TREE;
3984   tree type = TREE_TYPE (decl);
3985   /* If we are laying out a base class, rather than a field, then
3986      DECL_ARTIFICIAL will be set on the FIELD_DECL.  */
3987   int field_p = !DECL_ARTIFICIAL (decl);
3988
3989   /* Try to place the field.  It may take more than one try if we have
3990      a hard time placing the field without putting two objects of the
3991      same type at the same address.  */
3992   while (1)
3993     {
3994       struct record_layout_info_s old_rli = *rli;
3995
3996       /* Place this field.  */
3997       place_field (rli, decl);
3998       offset = byte_position (decl);
3999  
4000       /* We have to check to see whether or not there is already
4001          something of the same type at the offset we're about to use.
4002          For example:
4003          
4004          struct S {};
4005          struct T : public S { int i; };
4006          struct U : public S, public T {};
4007          
4008          Here, we put S at offset zero in U.  Then, we can't put T at
4009          offset zero -- its S component would be at the same address
4010          as the S we already allocated.  So, we have to skip ahead.
4011          Since all data members, including those whose type is an
4012          empty class, have non-zero size, any overlap can happen only
4013          with a direct or indirect base-class -- it can't happen with
4014          a data member.  */
4015       if (layout_conflict_p (TREE_TYPE (decl),
4016                              offset,
4017                              offsets, 
4018                              field_p))
4019         {
4020           /* Strip off the size allocated to this field.  That puts us
4021              at the first place we could have put the field with
4022              proper alignment.  */
4023           *rli = old_rli;
4024
4025           /* Bump up by the alignment required for the type.  */
4026           rli->bitpos
4027             = size_binop (PLUS_EXPR, rli->bitpos, 
4028                           bitsize_int (binfo 
4029                                        ? CLASSTYPE_ALIGN (type)
4030                                        : TYPE_ALIGN (type)));
4031           normalize_rli (rli);
4032         }
4033       else
4034         /* There was no conflict.  We're done laying out this field.  */
4035         break;
4036     }
4037
4038   /* Now that we know where it will be placed, update its
4039      BINFO_OFFSET.  */
4040   if (binfo && CLASS_TYPE_P (BINFO_TYPE (binfo)))
4041     propagate_binfo_offsets (binfo, 
4042                              convert (ssizetype, offset), t);
4043 }
4044
4045 /* Layout the empty base BINFO.  EOC indicates the byte currently just
4046    past the end of the class, and should be correctly aligned for a
4047    class of the type indicated by BINFO; OFFSETS gives the offsets of
4048    the empty bases allocated so far. T is the most derived
4049    type.  Return non-zero iff we added it at the end. */
4050
4051 static bool
4052 layout_empty_base (binfo, eoc, offsets, t)
4053      tree binfo;
4054      tree eoc;
4055      splay_tree offsets;
4056      tree t;
4057 {
4058   tree alignment;
4059   tree basetype = BINFO_TYPE (binfo);
4060   bool atend = false;
4061   
4062   /* This routine should only be used for empty classes.  */
4063   my_friendly_assert (is_empty_class (basetype), 20000321);
4064   alignment = ssize_int (CLASSTYPE_ALIGN_UNIT (basetype));
4065
4066   /* This is an empty base class.  We first try to put it at offset
4067      zero.  */
4068   if (layout_conflict_p (BINFO_TYPE (binfo),
4069                          BINFO_OFFSET (binfo),
4070                          offsets, 
4071                          /*vbases_p=*/0))
4072     {
4073       /* That didn't work.  Now, we move forward from the next
4074          available spot in the class.  */
4075       atend = true;
4076       propagate_binfo_offsets (binfo, convert (ssizetype, eoc), t);
4077       while (1) 
4078         {
4079           if (!layout_conflict_p (BINFO_TYPE (binfo),
4080                                   BINFO_OFFSET (binfo), 
4081                                   offsets,
4082                                   /*vbases_p=*/0))
4083             /* We finally found a spot where there's no overlap.  */
4084             break;
4085
4086           /* There's overlap here, too.  Bump along to the next spot.  */
4087           propagate_binfo_offsets (binfo, alignment, t);
4088         }
4089     }
4090   return atend;
4091 }
4092
4093 /* Build a FIELD_DECL for the base given by BINFO in the class
4094    indicated by RLI.  If the new object is non-empty, clear *EMPTY_P.
4095    *BASE_ALIGN is a running maximum of the alignments of any base
4096    class.  OFFSETS gives the location of empty base subobjects.  T is
4097    the most derived type.  Return non-zero if the new object cannot be
4098    nearly-empty. */
4099
4100 static bool
4101 build_base_field (rli, binfo, empty_p, offsets, t)
4102      record_layout_info rli;
4103      tree binfo;
4104      int *empty_p;
4105      splay_tree offsets;
4106      tree t;
4107 {
4108   tree basetype = BINFO_TYPE (binfo);
4109   tree decl;
4110   bool atend = false;
4111
4112   if (!COMPLETE_TYPE_P (basetype))
4113     /* This error is now reported in xref_tag, thus giving better
4114        location information.  */
4115     return atend;
4116   
4117   decl = build_decl (FIELD_DECL, NULL_TREE, basetype);
4118   DECL_ARTIFICIAL (decl) = 1;
4119   DECL_FIELD_CONTEXT (decl) = rli->t;
4120   DECL_SIZE (decl) = CLASSTYPE_SIZE (basetype);
4121   DECL_SIZE_UNIT (decl) = CLASSTYPE_SIZE_UNIT (basetype);
4122   DECL_ALIGN (decl) = CLASSTYPE_ALIGN (basetype);
4123   DECL_USER_ALIGN (decl) = CLASSTYPE_USER_ALIGN (basetype);
4124   
4125   if (!integer_zerop (DECL_SIZE (decl)))
4126     {
4127       /* The containing class is non-empty because it has a non-empty
4128          base class.  */
4129       *empty_p = 0;
4130
4131       /* Try to place the field.  It may take more than one try if we
4132          have a hard time placing the field without putting two
4133          objects of the same type at the same address.  */
4134       layout_nonempty_base_or_field (rli, decl, binfo, offsets, t);
4135     }
4136   else
4137     {
4138       unsigned HOST_WIDE_INT eoc;
4139
4140       /* On some platforms (ARM), even empty classes will not be
4141          byte-aligned.  */
4142       eoc = tree_low_cst (rli_size_unit_so_far (rli), 0);
4143       eoc = CEIL (eoc, DECL_ALIGN_UNIT (decl)) * DECL_ALIGN_UNIT (decl);
4144       atend |= layout_empty_base (binfo, size_int (eoc), offsets, t);
4145     }
4146
4147   /* Record the offsets of BINFO and its base subobjects.  */
4148   record_subobject_offsets (BINFO_TYPE (binfo), 
4149                             BINFO_OFFSET (binfo),
4150                             offsets, 
4151                             /*vbases_p=*/0);
4152   return atend;
4153 }
4154
4155 /* Layout all of the non-virtual base classes.  Record empty
4156    subobjects in OFFSETS.  T is the most derived type.  Return
4157    non-zero if the type cannot be nearly empty.  */
4158
4159 static bool
4160 build_base_fields (rli, empty_p, offsets, t)
4161      record_layout_info rli;
4162      int *empty_p;
4163      splay_tree offsets;
4164      tree t;
4165 {
4166   /* Chain to hold all the new FIELD_DECLs which stand in for base class
4167      subobjects.  */
4168   tree rec = rli->t;
4169   int n_baseclasses = CLASSTYPE_N_BASECLASSES (rec);
4170   int i;
4171   bool atend = 0;
4172
4173   /* Under the new ABI, the primary base class is always allocated
4174      first.  */
4175   if (CLASSTYPE_HAS_PRIMARY_BASE_P (rec))
4176     build_base_field (rli, CLASSTYPE_PRIMARY_BINFO (rec), 
4177                       empty_p, offsets, t);
4178
4179   /* Now allocate the rest of the bases.  */
4180   for (i = 0; i < n_baseclasses; ++i)
4181     {
4182       tree base_binfo;
4183
4184       base_binfo = BINFO_BASETYPE (TYPE_BINFO (rec), i);
4185
4186       /* Under the new ABI, the primary base was already allocated
4187          above, so we don't need to allocate it again here.  */
4188       if (base_binfo == CLASSTYPE_PRIMARY_BINFO (rec))
4189         continue;
4190
4191       /* A primary virtual base class is allocated just like any other
4192          base class, but a non-primary virtual base is allocated
4193          later, in layout_virtual_bases.  */
4194       if (TREE_VIA_VIRTUAL (base_binfo) 
4195           && !BINFO_PRIMARY_P (base_binfo))
4196         continue;
4197
4198       atend |= build_base_field (rli, base_binfo, empty_p, offsets, t);
4199     }
4200   return atend;
4201 }
4202
4203 /* Go through the TYPE_METHODS of T issuing any appropriate
4204    diagnostics, figuring out which methods override which other
4205    methods, and so forth.  */
4206
4207 static void
4208 check_methods (t)
4209      tree t;
4210 {
4211   tree x;
4212   int seen_one_arg_array_delete_p = 0;
4213
4214   for (x = TYPE_METHODS (t); x; x = TREE_CHAIN (x))
4215     {
4216       GNU_xref_member (current_class_name, x);
4217
4218       /* If this was an evil function, don't keep it in class.  */
4219       if (DECL_ASSEMBLER_NAME_SET_P (x) 
4220           && IDENTIFIER_ERROR_LOCUS (DECL_ASSEMBLER_NAME (x)))
4221         continue;
4222
4223       check_for_override (x, t);
4224       if (DECL_PURE_VIRTUAL_P (x) && ! DECL_VINDEX (x))
4225         cp_error_at ("initializer specified for non-virtual method `%D'", x);
4226
4227       /* The name of the field is the original field name
4228          Save this in auxiliary field for later overloading.  */
4229       if (DECL_VINDEX (x))
4230         {
4231           TYPE_POLYMORPHIC_P (t) = 1;
4232           if (DECL_PURE_VIRTUAL_P (x))
4233             CLASSTYPE_PURE_VIRTUALS (t)
4234               = tree_cons (NULL_TREE, x, CLASSTYPE_PURE_VIRTUALS (t));
4235         }
4236
4237       if (DECL_ARRAY_DELETE_OPERATOR_P (x))
4238         {
4239           tree second_parm;
4240
4241           /* When dynamically allocating an array of this type, we
4242              need a "cookie" to record how many elements we allocated,
4243              even if the array elements have no non-trivial
4244              destructor, if the usual array deallocation function
4245              takes a second argument of type size_t.  The standard (in
4246              [class.free]) requires that the second argument be set
4247              correctly.  */
4248           second_parm = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (x)));
4249           /* Under the new ABI, we choose only those function that are
4250              explicitly declared as `operator delete[] (void *,
4251              size_t)'.  */
4252           if (!seen_one_arg_array_delete_p
4253               && second_parm
4254               && TREE_CHAIN (second_parm) == void_list_node
4255               && same_type_p (TREE_VALUE (second_parm), sizetype))
4256             TYPE_VEC_DELETE_TAKES_SIZE (t) = 1;
4257           /* If there's no second parameter, then this is the usual
4258              deallocation function.  */
4259           else if (second_parm == void_list_node)
4260             seen_one_arg_array_delete_p = 1;
4261         }
4262     }
4263 }
4264
4265 /* FN is a constructor or destructor.  Clone the declaration to create
4266    a specialized in-charge or not-in-charge version, as indicated by
4267    NAME.  */
4268
4269 static tree
4270 build_clone (fn, name)
4271      tree fn;
4272      tree name;
4273 {
4274   tree parms;
4275   tree clone;
4276
4277   /* Copy the function.  */
4278   clone = copy_decl (fn);
4279   /* Remember where this function came from.  */
4280   DECL_CLONED_FUNCTION (clone) = fn;
4281   DECL_ABSTRACT_ORIGIN (clone) = fn;
4282   /* Reset the function name.  */
4283   DECL_NAME (clone) = name;
4284   SET_DECL_ASSEMBLER_NAME (clone, NULL_TREE);
4285   /* There's no pending inline data for this function.  */
4286   DECL_PENDING_INLINE_INFO (clone) = NULL;
4287   DECL_PENDING_INLINE_P (clone) = 0;
4288   /* And it hasn't yet been deferred.  */
4289   DECL_DEFERRED_FN (clone) = 0;
4290
4291   /* The base-class destructor is not virtual.  */
4292   if (name == base_dtor_identifier)
4293     {
4294       DECL_VIRTUAL_P (clone) = 0;
4295       if (TREE_CODE (clone) != TEMPLATE_DECL)
4296         DECL_VINDEX (clone) = NULL_TREE;
4297     }
4298
4299   /* If there was an in-charge parameter, drop it from the function
4300      type.  */
4301   if (DECL_HAS_IN_CHARGE_PARM_P (clone))
4302     {
4303       tree basetype;
4304       tree parmtypes;
4305       tree exceptions;
4306
4307       exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (clone));
4308       basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (clone));
4309       parmtypes = TYPE_ARG_TYPES (TREE_TYPE (clone));
4310       /* Skip the `this' parameter.  */
4311       parmtypes = TREE_CHAIN (parmtypes);
4312       /* Skip the in-charge parameter.  */
4313       parmtypes = TREE_CHAIN (parmtypes);
4314       /* And the VTT parm, in a complete [cd]tor.  */
4315       if (DECL_HAS_VTT_PARM_P (fn)
4316           && ! DECL_NEEDS_VTT_PARM_P (clone))
4317         parmtypes = TREE_CHAIN (parmtypes);
4318        /* If this is subobject constructor or destructor, add the vtt
4319          parameter.  */
4320       TREE_TYPE (clone) 
4321         = build_cplus_method_type (basetype,
4322                                    TREE_TYPE (TREE_TYPE (clone)),
4323                                    parmtypes);
4324       if (exceptions)
4325         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone),
4326                                                      exceptions);
4327     }
4328
4329   /* Copy the function parameters.  But, DECL_ARGUMENTS on a TEMPLATE_DECL
4330      aren't function parameters; those are the template parameters.  */
4331   if (TREE_CODE (clone) != TEMPLATE_DECL)
4332     {
4333       DECL_ARGUMENTS (clone) = copy_list (DECL_ARGUMENTS (clone));
4334       /* Remove the in-charge parameter.  */
4335       if (DECL_HAS_IN_CHARGE_PARM_P (clone))
4336         {
4337           TREE_CHAIN (DECL_ARGUMENTS (clone))
4338             = TREE_CHAIN (TREE_CHAIN (DECL_ARGUMENTS (clone)));
4339           DECL_HAS_IN_CHARGE_PARM_P (clone) = 0;
4340         }
4341       /* And the VTT parm, in a complete [cd]tor.  */
4342       if (DECL_HAS_VTT_PARM_P (fn))
4343         {
4344           if (DECL_NEEDS_VTT_PARM_P (clone))
4345             DECL_HAS_VTT_PARM_P (clone) = 1;
4346           else
4347             {
4348               TREE_CHAIN (DECL_ARGUMENTS (clone))
4349                 = TREE_CHAIN (TREE_CHAIN (DECL_ARGUMENTS (clone)));
4350               DECL_HAS_VTT_PARM_P (clone) = 0;
4351             }
4352         }
4353
4354       for (parms = DECL_ARGUMENTS (clone); parms; parms = TREE_CHAIN (parms))
4355         {
4356           DECL_CONTEXT (parms) = clone;
4357           copy_lang_decl (parms);
4358         }
4359     }
4360
4361   /* Create the RTL for this function.  */
4362   SET_DECL_RTL (clone, NULL_RTX);
4363   rest_of_decl_compilation (clone, NULL, /*top_level=*/1, at_eof);
4364   
4365   /* Make it easy to find the CLONE given the FN.  */
4366   TREE_CHAIN (clone) = TREE_CHAIN (fn);
4367   TREE_CHAIN (fn) = clone;
4368
4369   /* If this is a template, handle the DECL_TEMPLATE_RESULT as well.  */
4370   if (TREE_CODE (clone) == TEMPLATE_DECL)
4371     {
4372       tree result;
4373
4374       DECL_TEMPLATE_RESULT (clone) 
4375         = build_clone (DECL_TEMPLATE_RESULT (clone), name);
4376       result = DECL_TEMPLATE_RESULT (clone);
4377       DECL_TEMPLATE_INFO (result) = copy_node (DECL_TEMPLATE_INFO (result));
4378       DECL_TI_TEMPLATE (result) = clone;
4379     }
4380   else if (DECL_DEFERRED_FN (fn))
4381     defer_fn (clone);
4382
4383   return clone;
4384 }
4385
4386 /* Produce declarations for all appropriate clones of FN.  If
4387    UPDATE_METHOD_VEC_P is non-zero, the clones are added to the
4388    CLASTYPE_METHOD_VEC as well.  */
4389
4390 void
4391 clone_function_decl (fn, update_method_vec_p)
4392      tree fn;
4393      int update_method_vec_p;
4394 {
4395   tree clone;
4396
4397   /* Avoid inappropriate cloning.  */
4398   if (TREE_CHAIN (fn)
4399       && DECL_CLONED_FUNCTION (TREE_CHAIN (fn)))
4400     return;
4401
4402   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
4403     {
4404       /* For each constructor, we need two variants: an in-charge version
4405          and a not-in-charge version.  */
4406       clone = build_clone (fn, complete_ctor_identifier);
4407       if (update_method_vec_p)
4408         add_method (DECL_CONTEXT (clone), clone, /*error_p=*/0);
4409       clone = build_clone (fn, base_ctor_identifier);
4410       if (update_method_vec_p)
4411         add_method (DECL_CONTEXT (clone), clone, /*error_p=*/0);
4412     }
4413   else
4414     {
4415       my_friendly_assert (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (fn), 20000411);
4416
4417       /* For each destructor, we need three variants: an in-charge
4418          version, a not-in-charge version, and an in-charge deleting
4419          version.  We clone the deleting version first because that
4420          means it will go second on the TYPE_METHODS list -- and that
4421          corresponds to the correct layout order in the virtual
4422          function table.  
4423
4424          For a non-virtual destructor, we do not build a deleting
4425          destructor.  */
4426       if (DECL_VIRTUAL_P (fn))
4427         {
4428           clone = build_clone (fn, deleting_dtor_identifier);
4429           if (update_method_vec_p)
4430             add_method (DECL_CONTEXT (clone), clone, /*error_p=*/0);
4431         }
4432       clone = build_clone (fn, complete_dtor_identifier);
4433       if (update_method_vec_p)
4434         add_method (DECL_CONTEXT (clone), clone, /*error_p=*/0);
4435       clone = build_clone (fn, base_dtor_identifier);
4436       if (update_method_vec_p)
4437         add_method (DECL_CONTEXT (clone), clone, /*error_p=*/0);
4438     }
4439
4440   /* Note that this is an abstract function that is never emitted.  */
4441   DECL_ABSTRACT (fn) = 1;
4442 }
4443
4444 /* DECL is an in charge constructor, which is being defined. This will
4445    have had an in class declaration, from whence clones were
4446    declared. An out-of-class definition can specify additional default
4447    arguments. As it is the clones that are involved in overload
4448    resolution, we must propagate the information from the DECL to its
4449    clones. */
4450
4451 void
4452 adjust_clone_args (decl)
4453      tree decl;
4454 {
4455   tree clone;
4456   
4457   for (clone = TREE_CHAIN (decl); clone && DECL_CLONED_FUNCTION (clone);
4458        clone = TREE_CHAIN (clone))
4459     {
4460       tree orig_clone_parms = TYPE_ARG_TYPES (TREE_TYPE (clone));
4461       tree orig_decl_parms = TYPE_ARG_TYPES (TREE_TYPE (decl));
4462       tree decl_parms, clone_parms;
4463
4464       clone_parms = orig_clone_parms;
4465       
4466       /* Skip the 'this' parameter. */
4467       orig_clone_parms = TREE_CHAIN (orig_clone_parms);
4468       orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4469
4470       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
4471         orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4472       if (DECL_HAS_VTT_PARM_P (decl))
4473         orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4474       
4475       clone_parms = orig_clone_parms;
4476       if (DECL_HAS_VTT_PARM_P (clone))
4477         clone_parms = TREE_CHAIN (clone_parms);
4478       
4479       for (decl_parms = orig_decl_parms; decl_parms;
4480            decl_parms = TREE_CHAIN (decl_parms),
4481              clone_parms = TREE_CHAIN (clone_parms))
4482         {
4483           my_friendly_assert (same_type_p (TREE_TYPE (decl_parms),
4484                                            TREE_TYPE (clone_parms)), 20010424);
4485           
4486           if (TREE_PURPOSE (decl_parms) && !TREE_PURPOSE (clone_parms))
4487             {
4488               /* A default parameter has been added. Adjust the
4489                  clone's parameters. */
4490               tree exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (clone));
4491               tree basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (clone));
4492               tree type;
4493
4494               clone_parms = orig_decl_parms;
4495
4496               if (DECL_HAS_VTT_PARM_P (clone))
4497                 {
4498                   clone_parms = tree_cons (TREE_PURPOSE (orig_clone_parms),
4499                                            TREE_VALUE (orig_clone_parms),
4500                                            clone_parms);
4501                   TREE_TYPE (clone_parms) = TREE_TYPE (orig_clone_parms);
4502                 }
4503               type = build_cplus_method_type (basetype,
4504                                               TREE_TYPE (TREE_TYPE (clone)),
4505                                               clone_parms);
4506               if (exceptions)
4507                 type = build_exception_variant (type, exceptions);
4508               TREE_TYPE (clone) = type;
4509               
4510               clone_parms = NULL_TREE;
4511               break;
4512             }
4513         }
4514       my_friendly_assert (!clone_parms, 20010424);
4515     }
4516 }
4517
4518 /* For each of the constructors and destructors in T, create an
4519    in-charge and not-in-charge variant.  */
4520
4521 static void
4522 clone_constructors_and_destructors (t)
4523      tree t;
4524 {
4525   tree fns;
4526
4527   /* If for some reason we don't have a CLASSTYPE_METHOD_VEC, we bail
4528      out now.  */
4529   if (!CLASSTYPE_METHOD_VEC (t))
4530     return;
4531
4532   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
4533     clone_function_decl (OVL_CURRENT (fns), /*update_method_vec_p=*/1);
4534   for (fns = CLASSTYPE_DESTRUCTORS (t); fns; fns = OVL_NEXT (fns))
4535     clone_function_decl (OVL_CURRENT (fns), /*update_method_vec_p=*/1);
4536 }
4537
4538 /* Remove all zero-width bit-fields from T.  */
4539
4540 static void
4541 remove_zero_width_bit_fields (t)
4542      tree t;
4543 {
4544   tree *fieldsp;
4545
4546   fieldsp = &TYPE_FIELDS (t); 
4547   while (*fieldsp)
4548     {
4549       if (TREE_CODE (*fieldsp) == FIELD_DECL
4550           && DECL_C_BIT_FIELD (*fieldsp) 
4551           && DECL_INITIAL (*fieldsp))
4552         *fieldsp = TREE_CHAIN (*fieldsp);
4553       else
4554         fieldsp = &TREE_CHAIN (*fieldsp);
4555     }
4556 }
4557
4558 /* Check the validity of the bases and members declared in T.  Add any
4559    implicitly-generated functions (like copy-constructors and
4560    assignment operators).  Compute various flag bits (like
4561    CLASSTYPE_NON_POD_T) for T.  This routine works purely at the C++
4562    level: i.e., independently of the ABI in use.  */
4563
4564 static void
4565 check_bases_and_members (t, empty_p)
4566      tree t;
4567      int *empty_p;
4568 {
4569   /* Nonzero if we are not allowed to generate a default constructor
4570      for this case.  */
4571   int cant_have_default_ctor;
4572   /* Nonzero if the implicitly generated copy constructor should take
4573      a non-const reference argument.  */
4574   int cant_have_const_ctor;
4575   /* Nonzero if the the implicitly generated assignment operator
4576      should take a non-const reference argument.  */
4577   int no_const_asn_ref;
4578   tree access_decls;
4579
4580   /* By default, we use const reference arguments and generate default
4581      constructors.  */
4582   cant_have_default_ctor = 0;
4583   cant_have_const_ctor = 0;
4584   no_const_asn_ref = 0;
4585
4586   /* Assume that the class is nearly empty; we'll clear this flag if
4587      it turns out not to be nearly empty.  */
4588   CLASSTYPE_NEARLY_EMPTY_P (t) = 1;
4589
4590   /* Check all the base-classes. */
4591   check_bases (t, &cant_have_default_ctor, &cant_have_const_ctor,
4592                &no_const_asn_ref);
4593
4594   /* Check all the data member declarations.  */
4595   check_field_decls (t, &access_decls, empty_p,
4596                      &cant_have_default_ctor,
4597                      &cant_have_const_ctor,
4598                      &no_const_asn_ref);
4599
4600   /* Check all the method declarations.  */
4601   check_methods (t);
4602
4603   /* A nearly-empty class has to be vptr-containing; a nearly empty
4604      class contains just a vptr.  */
4605   if (!TYPE_CONTAINS_VPTR_P (t))
4606     CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
4607
4608   /* Do some bookkeeping that will guide the generation of implicitly
4609      declared member functions.  */
4610   TYPE_HAS_COMPLEX_INIT_REF (t)
4611     |= (TYPE_HAS_INIT_REF (t) 
4612         || TYPE_USES_VIRTUAL_BASECLASSES (t)
4613         || TYPE_POLYMORPHIC_P (t));
4614   TYPE_NEEDS_CONSTRUCTING (t)
4615     |= (TYPE_HAS_CONSTRUCTOR (t) 
4616         || TYPE_USES_VIRTUAL_BASECLASSES (t)
4617         || TYPE_POLYMORPHIC_P (t));
4618   CLASSTYPE_NON_AGGREGATE (t) |= (TYPE_HAS_CONSTRUCTOR (t)
4619                                   || TYPE_POLYMORPHIC_P (t));
4620   CLASSTYPE_NON_POD_P (t)
4621     |= (CLASSTYPE_NON_AGGREGATE (t) || TYPE_HAS_DESTRUCTOR (t) 
4622         || TYPE_HAS_ASSIGN_REF (t));
4623   TYPE_HAS_REAL_ASSIGN_REF (t) |= TYPE_HAS_ASSIGN_REF (t);
4624   TYPE_HAS_COMPLEX_ASSIGN_REF (t)
4625     |= TYPE_HAS_ASSIGN_REF (t) || TYPE_USES_VIRTUAL_BASECLASSES (t);
4626
4627   /* Synthesize any needed methods.  Note that methods will be synthesized
4628      for anonymous unions; grok_x_components undoes that.  */
4629   add_implicitly_declared_members (t, cant_have_default_ctor,
4630                                    cant_have_const_ctor,
4631                                    no_const_asn_ref);
4632
4633   /* Create the in-charge and not-in-charge variants of constructors
4634      and destructors.  */
4635   clone_constructors_and_destructors (t);
4636
4637   /* Process the using-declarations.  */
4638   for (; access_decls; access_decls = TREE_CHAIN (access_decls))
4639     handle_using_decl (TREE_VALUE (access_decls), t);
4640
4641   /* Build and sort the CLASSTYPE_METHOD_VEC.  */
4642   finish_struct_methods (t);
4643 }
4644
4645 /* If T needs a pointer to its virtual function table, set TYPE_VFIELD
4646    accordingly.  If a new vfield was created (because T doesn't have a
4647    primary base class), then the newly created field is returned.  It
4648    is not added to the TYPE_FIELDS list; it is the caller's
4649    responsibility to do that.  */
4650
4651 static tree
4652 create_vtable_ptr (t, empty_p, vfuns_p,
4653                    new_virtuals_p, overridden_virtuals_p)
4654      tree t;
4655      int *empty_p;
4656      int *vfuns_p;
4657      tree *new_virtuals_p;
4658      tree *overridden_virtuals_p;
4659 {
4660   tree fn;
4661
4662   /* Loop over the virtual functions, adding them to our various
4663      vtables.  */
4664   for (fn = TYPE_METHODS (t); fn; fn = TREE_CHAIN (fn))
4665     if (DECL_VINDEX (fn) && !DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (fn))
4666       add_virtual_function (new_virtuals_p, overridden_virtuals_p,
4667                             vfuns_p, fn, t);
4668
4669   /* If we couldn't find an appropriate base class, create a new field
4670      here.  Even if there weren't any new virtual functions, we might need a
4671      new virtual function table if we're supposed to include vptrs in
4672      all classes that need them.  */
4673   if (!TYPE_VFIELD (t)
4674       && (*vfuns_p 
4675           || (TYPE_CONTAINS_VPTR_P (t) && vptrs_present_everywhere_p ())))
4676     {
4677       /* We build this decl with vtbl_ptr_type_node, which is a
4678          `vtable_entry_type*'.  It might seem more precise to use
4679          `vtable_entry_type (*)[N]' where N is the number of firtual
4680          functions.  However, that would require the vtable pointer in
4681          base classes to have a different type than the vtable pointer
4682          in derived classes.  We could make that happen, but that
4683          still wouldn't solve all the problems.  In particular, the
4684          type-based alias analysis code would decide that assignments
4685          to the base class vtable pointer can't alias assignments to
4686          the derived class vtable pointer, since they have different
4687          types.  Thus, in an derived class destructor, where the base
4688          class constructor was inlined, we could generate bad code for
4689          setting up the vtable pointer.  
4690
4691          Therefore, we use one type for all vtable pointers.  We still
4692          use a type-correct type; it's just doesn't indicate the array
4693          bounds.  That's better than using `void*' or some such; it's
4694          cleaner, and it let's the alias analysis code know that these
4695          stores cannot alias stores to void*!  */
4696       TYPE_VFIELD (t) 
4697         = build_vtbl_or_vbase_field (get_vfield_name (t),
4698                                      get_identifier (VFIELD_BASE),
4699                                      vtbl_ptr_type_node,
4700                                      t,
4701                                      t,
4702                                      empty_p);
4703
4704       if (CLASSTYPE_N_BASECLASSES (t))
4705         /* If there were any baseclasses, they can't possibly be at
4706            offset zero any more, because that's where the vtable
4707            pointer is.  So, converting to a base class is going to
4708            take work.  */
4709         TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (t) = 1;
4710
4711       return TYPE_VFIELD (t);
4712     }
4713
4714   return NULL_TREE;
4715 }
4716
4717 /* Fixup the inline function given by INFO now that the class is
4718    complete.  */
4719
4720 static void
4721 fixup_pending_inline (fn)
4722      tree fn;
4723 {
4724   if (DECL_PENDING_INLINE_INFO (fn))
4725     {
4726       tree args = DECL_ARGUMENTS (fn);
4727       while (args)
4728         {
4729           DECL_CONTEXT (args) = fn;
4730           args = TREE_CHAIN (args);
4731         }
4732     }
4733 }
4734
4735 /* Fixup the inline methods and friends in TYPE now that TYPE is
4736    complete.  */
4737
4738 static void
4739 fixup_inline_methods (type)
4740      tree type;
4741 {
4742   tree method = TYPE_METHODS (type);
4743
4744   if (method && TREE_CODE (method) == TREE_VEC)
4745     {
4746       if (TREE_VEC_ELT (method, 1))
4747         method = TREE_VEC_ELT (method, 1);
4748       else if (TREE_VEC_ELT (method, 0))
4749         method = TREE_VEC_ELT (method, 0);
4750       else
4751         method = TREE_VEC_ELT (method, 2);
4752     }
4753
4754   /* Do inline member functions.  */
4755   for (; method; method = TREE_CHAIN (method))
4756     fixup_pending_inline (method);
4757
4758   /* Do friends.  */
4759   for (method = CLASSTYPE_INLINE_FRIENDS (type); 
4760        method; 
4761        method = TREE_CHAIN (method))
4762     fixup_pending_inline (TREE_VALUE (method));
4763   CLASSTYPE_INLINE_FRIENDS (type) = NULL_TREE;
4764 }
4765
4766 /* Add OFFSET to all base types of BINFO which is a base in the
4767    hierarchy dominated by T.
4768
4769    OFFSET, which is a type offset, is number of bytes.  */
4770
4771 static void
4772 propagate_binfo_offsets (binfo, offset, t)
4773      tree binfo;
4774      tree offset;
4775      tree t;
4776 {
4777   int i;
4778   tree primary_binfo;
4779
4780   /* Update BINFO's offset.  */
4781   BINFO_OFFSET (binfo)
4782     = convert (sizetype, 
4783                size_binop (PLUS_EXPR,
4784                            convert (ssizetype, BINFO_OFFSET (binfo)),
4785                            offset));
4786
4787   /* Find the primary base class.  */
4788   primary_binfo = get_primary_binfo (binfo);
4789
4790   /* Scan all of the bases, pushing the BINFO_OFFSET adjust
4791      downwards.  */
4792   for (i = -1; i < BINFO_N_BASETYPES (binfo); ++i)
4793     {
4794       tree base_binfo;
4795
4796       /* On the first time through the loop, do the primary base.
4797          Because the primary base need not be an immediate base, we
4798          must handle the primary base specially.  */
4799       if (i == -1) 
4800         {
4801           if (!primary_binfo) 
4802             continue;
4803
4804           base_binfo = primary_binfo;
4805         }
4806       else
4807         {
4808           base_binfo = BINFO_BASETYPE (binfo, i);
4809           /* Don't do the primary base twice.  */
4810           if (base_binfo == primary_binfo)
4811             continue;
4812         }
4813
4814       /* Skip virtual bases that aren't our canonical primary base.  */
4815       if (TREE_VIA_VIRTUAL (base_binfo)
4816           && (BINFO_PRIMARY_BASE_OF (base_binfo) != binfo
4817               || base_binfo != binfo_for_vbase (BINFO_TYPE (base_binfo), t)))
4818         continue;
4819
4820       propagate_binfo_offsets (base_binfo, offset, t);
4821     }
4822 }
4823
4824 /* Called via dfs_walk from layout_virtual bases.  */
4825
4826 static tree
4827 dfs_set_offset_for_unshared_vbases (binfo, data)
4828      tree binfo;
4829      void *data;
4830 {
4831   /* If this is a virtual base, make sure it has the same offset as
4832      the shared copy.  If it's a primary base, then we know it's
4833      correct.  */
4834   if (TREE_VIA_VIRTUAL (binfo))
4835     {
4836       tree t = (tree) data;
4837       tree vbase;
4838       tree offset;
4839       
4840       vbase = binfo_for_vbase (BINFO_TYPE (binfo), t);
4841       if (vbase != binfo)
4842         {
4843           offset = size_diffop (BINFO_OFFSET (vbase), BINFO_OFFSET (binfo));
4844           propagate_binfo_offsets (binfo, offset, t);
4845         }
4846     }
4847
4848   return NULL_TREE;
4849 }
4850
4851 /* Set BINFO_OFFSET for all of the virtual bases for T.  Update
4852    TYPE_ALIGN and TYPE_SIZE for T.  OFFSETS gives the location of
4853    empty subobjects of T.  */
4854
4855 static void
4856 layout_virtual_bases (t, offsets)
4857      tree t;
4858      splay_tree offsets;
4859 {
4860   tree vbases;
4861   unsigned HOST_WIDE_INT dsize;
4862   unsigned HOST_WIDE_INT eoc;
4863
4864   if (CLASSTYPE_N_BASECLASSES (t) == 0)
4865     return;
4866
4867 #ifdef STRUCTURE_SIZE_BOUNDARY
4868   /* Packed structures don't need to have minimum size.  */
4869   if (! TYPE_PACKED (t))
4870     TYPE_ALIGN (t) = MAX (TYPE_ALIGN (t), STRUCTURE_SIZE_BOUNDARY);
4871 #endif
4872
4873   /* DSIZE is the size of the class without the virtual bases.  */
4874   dsize = tree_low_cst (TYPE_SIZE (t), 1);
4875
4876   /* Make every class have alignment of at least one.  */
4877   TYPE_ALIGN (t) = MAX (TYPE_ALIGN (t), BITS_PER_UNIT);
4878
4879   /* Go through the virtual bases, allocating space for each virtual
4880      base that is not already a primary base class.  Under the old
4881      ABI, these are allocated according to a depth-first left-to-right
4882      postorder traversal; in the new ABI, inheritance graph order is
4883      used instead.  */
4884   for (vbases = TYPE_BINFO (t);
4885        vbases; 
4886        vbases = TREE_CHAIN (vbases))
4887     {
4888       tree vbase;
4889
4890       if (!TREE_VIA_VIRTUAL (vbases))
4891         continue;
4892       vbase = binfo_for_vbase (BINFO_TYPE (vbases), t);
4893
4894       if (!BINFO_PRIMARY_P (vbase))
4895         {
4896           /* This virtual base is not a primary base of any class in the
4897              hierarchy, so we have to add space for it.  */
4898           tree basetype;
4899           unsigned int desired_align;
4900
4901           basetype = BINFO_TYPE (vbase);
4902
4903           desired_align = CLASSTYPE_ALIGN (basetype);
4904           TYPE_ALIGN (t) = MAX (TYPE_ALIGN (t), desired_align);
4905
4906           /* Add padding so that we can put the virtual base class at an
4907              appropriately aligned offset.  */
4908           dsize = CEIL (dsize, desired_align) * desired_align;
4909
4910           /* Under the new ABI, we try to squish empty virtual bases in
4911              just like ordinary empty bases.  */
4912           if (is_empty_class (basetype))
4913             layout_empty_base (vbase,
4914                                size_int (CEIL (dsize, BITS_PER_UNIT)),
4915                                offsets, t);
4916           else
4917             {
4918               tree offset;
4919
4920               offset = ssize_int (CEIL (dsize, BITS_PER_UNIT));
4921               offset = size_diffop (offset, 
4922                                     convert (ssizetype, 
4923                                              BINFO_OFFSET (vbase)));
4924
4925               /* And compute the offset of the virtual base.  */
4926               propagate_binfo_offsets (vbase, offset, t);
4927               /* Every virtual baseclass takes a least a UNIT, so that
4928                  we can take it's address and get something different
4929                  for each base.  */
4930               dsize += MAX (BITS_PER_UNIT,
4931                             tree_low_cst (CLASSTYPE_SIZE (basetype), 0));
4932             }
4933
4934           /* Keep track of the offsets assigned to this virtual base.  */
4935           record_subobject_offsets (BINFO_TYPE (vbase), 
4936                                     BINFO_OFFSET (vbase),
4937                                     offsets,
4938                                     /*vbases_p=*/0);
4939         }
4940     }
4941
4942   /* Now, go through the TYPE_BINFO hierarchy, setting the
4943      BINFO_OFFSETs correctly for all non-primary copies of the virtual
4944      bases and their direct and indirect bases.  The ambiguity checks
4945      in get_base_distance depend on the BINFO_OFFSETs being set
4946      correctly.  */
4947   dfs_walk (TYPE_BINFO (t), dfs_set_offset_for_unshared_vbases, NULL, t);
4948
4949   /* If we had empty base classes that protruded beyond the end of the
4950      class, we didn't update DSIZE above; we were hoping to overlay
4951      multiple such bases at the same location.  */
4952   eoc = end_of_class (t, /*include_virtuals_p=*/1);
4953   if (eoc * BITS_PER_UNIT > dsize)
4954     dsize = eoc * BITS_PER_UNIT;
4955
4956   /* Now, make sure that the total size of the type is a multiple of
4957      its alignment.  */
4958   dsize = CEIL (dsize, TYPE_ALIGN (t)) * TYPE_ALIGN (t);
4959   TYPE_SIZE (t) = bitsize_int (dsize);
4960   TYPE_SIZE_UNIT (t) = convert (sizetype,
4961                                 size_binop (CEIL_DIV_EXPR, TYPE_SIZE (t),
4962                                             bitsize_unit_node));
4963
4964   /* Check for ambiguous virtual bases.  */
4965   if (extra_warnings)
4966     for (vbases = CLASSTYPE_VBASECLASSES (t); 
4967          vbases; 
4968          vbases = TREE_CHAIN (vbases))
4969       {
4970         tree basetype = BINFO_TYPE (TREE_VALUE (vbases));
4971         if (get_base_distance (basetype, t, 0, (tree*)0) == -2)
4972           cp_warning ("virtual base `%T' inaccessible in `%T' due to ambiguity",
4973                       basetype, t);
4974       }
4975 }
4976
4977 /* Returns the offset of the byte just past the end of the base class
4978    with the highest offset in T.  If INCLUDE_VIRTUALS_P is zero, then
4979    only non-virtual bases are included.  */
4980
4981 static unsigned HOST_WIDE_INT
4982 end_of_class (t, include_virtuals_p)
4983      tree t;
4984      int include_virtuals_p;
4985 {
4986   unsigned HOST_WIDE_INT result = 0;
4987   int i;
4988
4989   for (i = 0; i < CLASSTYPE_N_BASECLASSES (t); ++i)
4990     {
4991       tree base_binfo;
4992       tree offset;
4993       tree size;
4994       unsigned HOST_WIDE_INT end_of_base;
4995
4996       base_binfo = BINFO_BASETYPE (TYPE_BINFO (t), i);
4997
4998       if (!include_virtuals_p
4999           && TREE_VIA_VIRTUAL (base_binfo) 
5000           && !BINFO_PRIMARY_P (base_binfo))
5001         continue;
5002
5003       if (is_empty_class (BINFO_TYPE (base_binfo)))
5004         /* An empty class has zero CLASSTYPE_SIZE_UNIT, but we need to
5005            allocate some space for it. It cannot have virtual bases,
5006            so TYPE_SIZE_UNIT is fine.  */
5007         size = TYPE_SIZE_UNIT (BINFO_TYPE (base_binfo));
5008       else
5009         size = CLASSTYPE_SIZE_UNIT (BINFO_TYPE (base_binfo));
5010       offset = size_binop (PLUS_EXPR, 
5011                            BINFO_OFFSET (base_binfo),
5012                            size);
5013       end_of_base = tree_low_cst (offset, /*pos=*/1);
5014       if (end_of_base > result)
5015         result = end_of_base;
5016     }
5017
5018   return result;
5019 }
5020
5021 /* Warn about direct bases of T that are inaccessible because they are
5022    ambiguous.  For example:
5023
5024      struct S {};
5025      struct T : public S {};
5026      struct U : public S, public T {};
5027
5028    Here, `(S*) new U' is not allowed because there are two `S'
5029    subobjects of U.  */
5030
5031 static void
5032 warn_about_ambiguous_direct_bases (t)
5033      tree t;
5034 {
5035   int i;
5036
5037   for (i = 0; i < CLASSTYPE_N_BASECLASSES (t); ++i)
5038     {
5039       tree basetype = TYPE_BINFO_BASETYPE (t, i);
5040
5041       if (get_base_distance (basetype, t, 0, NULL) == -2)
5042         cp_warning ("direct base `%T' inaccessible in `%T' due to ambiguity",
5043                     basetype, t);
5044     }
5045 }
5046
5047 /* Compare two INTEGER_CSTs K1 and K2.  */
5048
5049 static int
5050 splay_tree_compare_integer_csts (k1, k2)
5051      splay_tree_key k1;
5052      splay_tree_key k2;
5053 {
5054   return tree_int_cst_compare ((tree) k1, (tree) k2);
5055 }
5056
5057 /* Calculate the TYPE_SIZE, TYPE_ALIGN, etc for T.  Calculate
5058    BINFO_OFFSETs for all of the base-classes.  Position the vtable
5059    pointer.  */
5060
5061 static void
5062 layout_class_type (t, empty_p, vfuns_p, 
5063                    new_virtuals_p, overridden_virtuals_p)
5064      tree t;
5065      int *empty_p;
5066      int *vfuns_p;
5067      tree *new_virtuals_p;
5068      tree *overridden_virtuals_p;
5069 {
5070   tree non_static_data_members;
5071   tree field;
5072   tree vptr;
5073   record_layout_info rli;
5074   unsigned HOST_WIDE_INT eoc;
5075   /* Maps offsets (represented as INTEGER_CSTs) to a TREE_LIST of
5076      types that appear at that offset.  */
5077   splay_tree empty_base_offsets;
5078
5079   /* Keep track of the first non-static data member.  */
5080   non_static_data_members = TYPE_FIELDS (t);
5081
5082   /* Start laying out the record.  */
5083   rli = start_record_layout (t);
5084
5085   /* If possible, we reuse the virtual function table pointer from one
5086      of our base classes.  */
5087   determine_primary_base (t, vfuns_p);
5088
5089   /* Create a pointer to our virtual function table.  */
5090   vptr = create_vtable_ptr (t, empty_p, vfuns_p,
5091                             new_virtuals_p, overridden_virtuals_p);
5092
5093   /* Under the new ABI, the vptr is always the first thing in the
5094      class.  */
5095   if (vptr)
5096     {
5097       TYPE_FIELDS (t) = chainon (vptr, TYPE_FIELDS (t));
5098       place_field (rli, vptr);
5099     }
5100
5101   /* Build FIELD_DECLs for all of the non-virtual base-types.  */
5102   empty_base_offsets = splay_tree_new (splay_tree_compare_integer_csts, 
5103                                        NULL, NULL);
5104   if (build_base_fields (rli, empty_p, empty_base_offsets, t))
5105     CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
5106   
5107   /* Add pointers to all of our virtual base-classes.  */
5108   TYPE_FIELDS (t) = chainon (build_vbase_pointer_fields (rli, empty_p),
5109                              TYPE_FIELDS (t));
5110
5111   /* CLASSTYPE_INLINE_FRIENDS is really TYPE_NONCOPIED_PARTS.  Thus,
5112      we have to save this before we start modifying
5113      TYPE_NONCOPIED_PARTS.  */
5114   fixup_inline_methods (t);
5115
5116   /* Layout the non-static data members.  */
5117   for (field = non_static_data_members; field; field = TREE_CHAIN (field))
5118     {
5119       tree type;
5120       tree padding;
5121
5122       /* We still pass things that aren't non-static data members to
5123          the back-end, in case it wants to do something with them.  */
5124       if (TREE_CODE (field) != FIELD_DECL)
5125         {
5126           place_field (rli, field);
5127           continue;
5128         }
5129
5130       type = TREE_TYPE (field);
5131
5132       /* If this field is a bit-field whose width is greater than its
5133          type, then there are some special rules for allocating it
5134          under the new ABI.  Under the old ABI, there were no special
5135          rules, but the back-end can't handle bitfields longer than a
5136          `long long', so we use the same mechanism.  */
5137       if (DECL_C_BIT_FIELD (field)
5138           && INT_CST_LT (TYPE_SIZE (type), DECL_SIZE (field)))
5139         {
5140           integer_type_kind itk;
5141           tree integer_type;
5142
5143           /* We must allocate the bits as if suitably aligned for the
5144              longest integer type that fits in this many bits.  type
5145              of the field.  Then, we are supposed to use the left over
5146              bits as additional padding.  */
5147           for (itk = itk_char; itk != itk_none; ++itk)
5148             if (INT_CST_LT (DECL_SIZE (field), 
5149                             TYPE_SIZE (integer_types[itk])))
5150               break;
5151
5152           /* ITK now indicates a type that is too large for the
5153              field.  We have to back up by one to find the largest
5154              type that fits.  */
5155           integer_type = integer_types[itk - 1];
5156           padding = size_binop (MINUS_EXPR, DECL_SIZE (field), 
5157                                 TYPE_SIZE (integer_type));
5158           DECL_SIZE (field) = TYPE_SIZE (integer_type);
5159           DECL_ALIGN (field) = TYPE_ALIGN (integer_type);
5160           DECL_USER_ALIGN (field) = TYPE_USER_ALIGN (integer_type);
5161         }
5162       else
5163         padding = NULL_TREE;
5164
5165       layout_nonempty_base_or_field (rli, field, NULL_TREE,
5166                                      empty_base_offsets, t);
5167
5168       /* If we needed additional padding after this field, add it
5169          now.  */
5170       if (padding)
5171         {
5172           tree padding_field;
5173
5174           padding_field = build_decl (FIELD_DECL, 
5175                                       NULL_TREE,
5176                                       char_type_node); 
5177           DECL_BIT_FIELD (padding_field) = 1;
5178           DECL_SIZE (padding_field) = padding;
5179           DECL_ALIGN (padding_field) = 1;
5180           DECL_USER_ALIGN (padding_field) = 0;
5181           layout_nonempty_base_or_field (rli, padding_field,
5182                                          NULL_TREE, 
5183                                          empty_base_offsets, t);
5184         }
5185     }
5186
5187   /* It might be the case that we grew the class to allocate a
5188      zero-sized base class.  That won't be reflected in RLI, yet,
5189      because we are willing to overlay multiple bases at the same
5190      offset.  However, now we need to make sure that RLI is big enough
5191      to reflect the entire class.  */
5192   eoc = end_of_class (t, /*include_virtuals_p=*/0);
5193   if (TREE_CODE (rli_size_unit_so_far (rli)) == INTEGER_CST
5194       && compare_tree_int (rli_size_unit_so_far (rli), eoc) < 0)
5195     {
5196       rli->offset = size_binop (MAX_EXPR, rli->offset, size_int (eoc));
5197       rli->bitpos = bitsize_zero_node;
5198     }
5199
5200   /* We make all structures have at least one element, so that they
5201      have non-zero size.  In the new ABI, the class may be empty even
5202      if it has basetypes.  Therefore, we add the fake field after all
5203      the other fields; if there are already FIELD_DECLs on the list,
5204      their offsets will not be disturbed.  */
5205   if (!eoc && *empty_p)
5206     {
5207       tree padding;
5208
5209       padding = build_decl (FIELD_DECL, NULL_TREE, char_type_node);
5210       place_field (rli, padding);
5211       TYPE_NONCOPIED_PARTS (t) 
5212         = tree_cons (NULL_TREE, padding, TYPE_NONCOPIED_PARTS (t));
5213       TREE_STATIC (TYPE_NONCOPIED_PARTS (t)) = 1;
5214     }
5215
5216   /* Let the back-end lay out the type. Note that at this point we
5217      have only included non-virtual base-classes; we will lay out the
5218      virtual base classes later.  So, the TYPE_SIZE/TYPE_ALIGN after
5219      this call are not necessarily correct; they are just the size and
5220      alignment when no virtual base clases are used.  */
5221   finish_record_layout (rli);
5222
5223   /* Delete all zero-width bit-fields from the list of fields.  Now
5224      that the type is laid out they are no longer important.  */
5225   remove_zero_width_bit_fields (t);
5226
5227   /* Remember the size and alignment of the class before adding
5228      the virtual bases.  */
5229   if (*empty_p)
5230     {
5231       CLASSTYPE_SIZE (t) = bitsize_zero_node;
5232       CLASSTYPE_SIZE_UNIT (t) = size_zero_node;
5233     }
5234   else
5235     {
5236       CLASSTYPE_SIZE (t) = TYPE_BINFO_SIZE (t);
5237       CLASSTYPE_SIZE_UNIT (t) = TYPE_BINFO_SIZE_UNIT (t);
5238     }
5239
5240   CLASSTYPE_ALIGN (t) = TYPE_ALIGN (t);
5241   CLASSTYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (t);
5242
5243   /* Set the TYPE_DECL for this type to contain the right
5244      value for DECL_OFFSET, so that we can use it as part
5245      of a COMPONENT_REF for multiple inheritance.  */
5246   layout_decl (TYPE_MAIN_DECL (t), 0);
5247
5248   /* Now fix up any virtual base class types that we left lying
5249      around.  We must get these done before we try to lay out the
5250      virtual function table.  As a side-effect, this will remove the
5251      base subobject fields.  */
5252   layout_virtual_bases (t, empty_base_offsets);
5253
5254   /* Warn about direct bases that can't be talked about due to
5255      ambiguity.  */
5256   warn_about_ambiguous_direct_bases (t);
5257
5258   /* Clean up.  */
5259   splay_tree_delete (empty_base_offsets);
5260 }
5261
5262 /* Create a RECORD_TYPE or UNION_TYPE node for a C struct or union declaration
5263    (or C++ class declaration).
5264
5265    For C++, we must handle the building of derived classes.
5266    Also, C++ allows static class members.  The way that this is
5267    handled is to keep the field name where it is (as the DECL_NAME
5268    of the field), and place the overloaded decl in the bit position
5269    of the field.  layout_record and layout_union will know about this.
5270
5271    More C++ hair: inline functions have text in their
5272    DECL_PENDING_INLINE_INFO nodes which must somehow be parsed into
5273    meaningful tree structure.  After the struct has been laid out, set
5274    things up so that this can happen.
5275
5276    And still more: virtual functions.  In the case of single inheritance,
5277    when a new virtual function is seen which redefines a virtual function
5278    from the base class, the new virtual function is placed into
5279    the virtual function table at exactly the same address that
5280    it had in the base class.  When this is extended to multiple
5281    inheritance, the same thing happens, except that multiple virtual
5282    function tables must be maintained.  The first virtual function
5283    table is treated in exactly the same way as in the case of single
5284    inheritance.  Additional virtual function tables have different
5285    DELTAs, which tell how to adjust `this' to point to the right thing.
5286
5287    ATTRIBUTES is the set of decl attributes to be applied, if any.  */
5288
5289 void
5290 finish_struct_1 (t)
5291      tree t;
5292 {
5293   tree x;
5294   int vfuns;
5295   /* The NEW_VIRTUALS is a TREE_LIST.  The TREE_VALUE of each node is
5296      a FUNCTION_DECL.  Each of these functions is a virtual function
5297      declared in T that does not override any virtual function from a
5298      base class.  */
5299   tree new_virtuals = NULL_TREE;
5300   /* The OVERRIDDEN_VIRTUALS list is like the NEW_VIRTUALS list,
5301      except that each declaration here overrides the declaration from
5302      a base class.  */
5303   tree overridden_virtuals = NULL_TREE;
5304   int n_fields = 0;
5305   tree vfield;
5306   int empty = 1;
5307
5308   if (COMPLETE_TYPE_P (t))
5309     {
5310       if (IS_AGGR_TYPE (t))
5311         cp_error ("redefinition of `%#T'", t);
5312       else
5313         my_friendly_abort (172);
5314       popclass ();
5315       return;
5316     }
5317
5318   GNU_xref_decl (current_function_decl, t);
5319
5320   /* If this type was previously laid out as a forward reference,
5321      make sure we lay it out again.  */
5322   TYPE_SIZE (t) = NULL_TREE;
5323   CLASSTYPE_GOT_SEMICOLON (t) = 0;
5324   CLASSTYPE_PRIMARY_BINFO (t) = NULL_TREE;
5325   vfuns = 0;
5326   CLASSTYPE_RTTI (t) = NULL_TREE;
5327
5328   /* Do end-of-class semantic processing: checking the validity of the
5329      bases and members and add implicitly generated methods.  */
5330   check_bases_and_members (t, &empty);
5331
5332   /* Layout the class itself.  */
5333   layout_class_type (t, &empty, &vfuns,
5334                      &new_virtuals, &overridden_virtuals);
5335
5336   /* Make sure that we get our own copy of the vfield FIELD_DECL.  */
5337   vfield = TYPE_VFIELD (t);
5338   if (vfield != NULL_TREE
5339       && DECL_FIELD_CONTEXT (vfield) != t)
5340     {
5341       tree binfo = get_binfo (DECL_FIELD_CONTEXT (vfield), t, 0);
5342
5343       vfield = copy_decl (vfield);
5344
5345       DECL_FIELD_CONTEXT (vfield) = t;
5346       DECL_FIELD_OFFSET (vfield)
5347         = size_binop (PLUS_EXPR,
5348                       BINFO_OFFSET (binfo),
5349                       DECL_FIELD_OFFSET (vfield));
5350       TYPE_VFIELD (t) = vfield;
5351     }
5352
5353   overridden_virtuals 
5354     = modify_all_vtables (t, &vfuns, nreverse (overridden_virtuals));
5355
5356   /* If we created a new vtbl pointer for this class, add it to the
5357      list.  */
5358   if (TYPE_VFIELD (t) && !CLASSTYPE_HAS_PRIMARY_BASE_P (t))
5359     CLASSTYPE_VFIELDS (t) 
5360       = chainon (CLASSTYPE_VFIELDS (t), build_tree_list (NULL_TREE, t));
5361
5362   /* If necessary, create the primary vtable for this class.  */
5363   if (new_virtuals
5364       || overridden_virtuals
5365       || (TYPE_CONTAINS_VPTR_P (t) && vptrs_present_everywhere_p ()))
5366     {
5367       new_virtuals = nreverse (new_virtuals);
5368       /* We must enter these virtuals into the table.  */
5369       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
5370         build_primary_vtable (NULL_TREE, t);
5371       else if (! BINFO_NEW_VTABLE_MARKED (TYPE_BINFO (t), t))
5372         /* Here we know enough to change the type of our virtual
5373            function table, but we will wait until later this function.  */
5374         build_primary_vtable (CLASSTYPE_PRIMARY_BINFO (t), t);
5375
5376       /* If this type has basetypes with constructors, then those
5377          constructors might clobber the virtual function table.  But
5378          they don't if the derived class shares the exact vtable of the base
5379          class.  */
5380
5381       CLASSTYPE_NEEDS_VIRTUAL_REINIT (t) = 1;
5382     }
5383   /* If we didn't need a new vtable, see if we should copy one from
5384      the base.  */
5385   else if (CLASSTYPE_HAS_PRIMARY_BASE_P (t))
5386     {
5387       tree binfo = CLASSTYPE_PRIMARY_BINFO (t);
5388
5389       /* If this class uses a different vtable than its primary base
5390          then when we will need to initialize our vptr after the base
5391          class constructor runs.  */
5392       if (TYPE_BINFO_VTABLE (t) != BINFO_VTABLE (binfo))
5393         CLASSTYPE_NEEDS_VIRTUAL_REINIT (t) = 1;
5394     }
5395
5396   if (TYPE_CONTAINS_VPTR_P (t))
5397     {
5398       if (TYPE_BINFO_VTABLE (t))
5399         my_friendly_assert (DECL_VIRTUAL_P (TYPE_BINFO_VTABLE (t)),
5400                             20000116);
5401       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
5402         my_friendly_assert (TYPE_BINFO_VIRTUALS (t) == NULL_TREE,
5403                             20000116);
5404
5405       CLASSTYPE_VSIZE (t) = vfuns;
5406       /* Entries for virtual functions defined in the primary base are
5407          followed by entries for new functions unique to this class.  */
5408       TYPE_BINFO_VIRTUALS (t) 
5409         = chainon (TYPE_BINFO_VIRTUALS (t), new_virtuals);
5410       /* Finally, add entries for functions that override virtuals
5411          from non-primary bases.  */
5412       TYPE_BINFO_VIRTUALS (t) 
5413         = chainon (TYPE_BINFO_VIRTUALS (t), overridden_virtuals);
5414     }
5415
5416   finish_struct_bits (t);
5417
5418   /* Complete the rtl for any static member objects of the type we're
5419      working on.  */
5420   for (x = TYPE_FIELDS (t); x; x = TREE_CHAIN (x))
5421     if (TREE_CODE (x) == VAR_DECL && TREE_STATIC (x)
5422         && TREE_TYPE (x) == t)
5423       DECL_MODE (x) = TYPE_MODE (t);
5424
5425   /* Done with FIELDS...now decide whether to sort these for
5426      faster lookups later.
5427
5428      The C front-end only does this when n_fields > 15.  We use
5429      a smaller number because most searches fail (succeeding
5430      ultimately as the search bores through the inheritance
5431      hierarchy), and we want this failure to occur quickly.  */
5432
5433   n_fields = count_fields (TYPE_FIELDS (t));
5434   if (n_fields > 7)
5435     {
5436       tree field_vec = make_tree_vec (n_fields);
5437       add_fields_to_vec (TYPE_FIELDS (t), field_vec, 0);
5438       qsort (&TREE_VEC_ELT (field_vec, 0), n_fields, sizeof (tree),
5439              (int (*)(const void *, const void *))field_decl_cmp);
5440       if (! DECL_LANG_SPECIFIC (TYPE_MAIN_DECL (t)))
5441         retrofit_lang_decl (TYPE_MAIN_DECL (t));
5442       DECL_SORTED_FIELDS (TYPE_MAIN_DECL (t)) = field_vec;
5443     }
5444
5445   if (TYPE_HAS_CONSTRUCTOR (t))
5446     {
5447       tree vfields = CLASSTYPE_VFIELDS (t);
5448
5449       while (vfields)
5450         {
5451           /* Mark the fact that constructor for T
5452              could affect anybody inheriting from T
5453              who wants to initialize vtables for VFIELDS's type.  */
5454           if (VF_DERIVED_VALUE (vfields))
5455             TREE_ADDRESSABLE (vfields) = 1;
5456           vfields = TREE_CHAIN (vfields);
5457         }
5458     }
5459
5460   /* Make the rtl for any new vtables we have created, and unmark
5461      the base types we marked.  */
5462   finish_vtbls (t);
5463   
5464   /* Build the VTT for T.  */
5465   build_vtt (t);
5466
5467   if (TYPE_VFIELD (t))
5468     {
5469       /* In addition to this one, all the other vfields should be listed.  */
5470       /* Before that can be done, we have to have FIELD_DECLs for them, and
5471          a place to find them.  */
5472       TYPE_NONCOPIED_PARTS (t) 
5473         = tree_cons (default_conversion (TYPE_BINFO_VTABLE (t)),
5474                      TYPE_VFIELD (t), TYPE_NONCOPIED_PARTS (t));
5475
5476       if (warn_nonvdtor && TYPE_HAS_DESTRUCTOR (t)
5477           && DECL_VINDEX (TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (t), 1)) == NULL_TREE)
5478         cp_warning ("`%#T' has virtual functions but non-virtual destructor",
5479                     t);
5480     }
5481
5482   hack_incomplete_structures (t);
5483
5484   if (warn_overloaded_virtual)
5485     warn_hidden (t);
5486
5487   maybe_suppress_debug_info (t);
5488
5489   dump_class_hierarchy (t);
5490   
5491   /* Finish debugging output for this type.  */
5492   rest_of_type_compilation (t, ! LOCAL_CLASS_P (t));
5493 }
5494
5495 /* When T was built up, the member declarations were added in reverse
5496    order.  Rearrange them to declaration order.  */
5497
5498 void
5499 unreverse_member_declarations (t)
5500      tree t;
5501 {
5502   tree next;
5503   tree prev;
5504   tree x;
5505
5506   /* The TYPE_FIELDS, TYPE_METHODS, and CLASSTYPE_TAGS are all in
5507      reverse order.  Put them in declaration order now.  */
5508   TYPE_METHODS (t) = nreverse (TYPE_METHODS (t));
5509   CLASSTYPE_TAGS (t) = nreverse (CLASSTYPE_TAGS (t));
5510
5511   /* Actually, for the TYPE_FIELDS, only the non TYPE_DECLs are in
5512      reverse order, so we can't just use nreverse.  */
5513   prev = NULL_TREE;
5514   for (x = TYPE_FIELDS (t); 
5515        x && TREE_CODE (x) != TYPE_DECL; 
5516        x = next)
5517     {
5518       next = TREE_CHAIN (x);
5519       TREE_CHAIN (x) = prev;
5520       prev = x;
5521     }
5522   if (prev)
5523     {
5524       TREE_CHAIN (TYPE_FIELDS (t)) = x;
5525       if (prev)
5526         TYPE_FIELDS (t) = prev;
5527     }
5528 }
5529
5530 tree
5531 finish_struct (t, attributes)
5532      tree t, attributes;
5533 {
5534   const char *saved_filename = input_filename;
5535   int saved_lineno = lineno;
5536
5537   /* Now that we've got all the field declarations, reverse everything
5538      as necessary.  */
5539   unreverse_member_declarations (t);
5540
5541   cplus_decl_attributes (t, attributes, NULL_TREE);
5542
5543   /* Nadger the current location so that diagnostics point to the start of
5544      the struct, not the end.  */
5545   input_filename = DECL_SOURCE_FILE (TYPE_NAME (t));
5546   lineno = DECL_SOURCE_LINE (TYPE_NAME (t));
5547
5548   if (processing_template_decl)
5549     {
5550       finish_struct_methods (t);
5551       TYPE_SIZE (t) = bitsize_zero_node;
5552     }
5553   else
5554     finish_struct_1 (t);
5555
5556   input_filename = saved_filename;
5557   lineno = saved_lineno;
5558
5559   TYPE_BEING_DEFINED (t) = 0;
5560
5561   if (current_class_type)
5562     popclass ();
5563   else
5564     error ("trying to finish struct, but kicked out due to previous parse errors.");
5565
5566   if (processing_template_decl)
5567     {
5568       tree scope = current_scope ();
5569       if (scope && TREE_CODE (scope) == FUNCTION_DECL)
5570         add_stmt (build_min (TAG_DEFN, t));
5571     }
5572
5573   return t;
5574 }
5575 \f
5576 /* Return the dynamic type of INSTANCE, if known.
5577    Used to determine whether the virtual function table is needed
5578    or not.
5579
5580    *NONNULL is set iff INSTANCE can be known to be nonnull, regardless
5581    of our knowledge of its type.  *NONNULL should be initialized
5582    before this function is called.  */
5583
5584 static tree
5585 fixed_type_or_null (instance, nonnull, cdtorp)
5586      tree instance;
5587      int *nonnull;
5588      int *cdtorp;
5589 {
5590   switch (TREE_CODE (instance))
5591     {
5592     case INDIRECT_REF:
5593       /* Check that we are not going through a cast of some sort.  */
5594       if (TREE_TYPE (instance)
5595           == TREE_TYPE (TREE_TYPE (TREE_OPERAND (instance, 0))))
5596         instance = TREE_OPERAND (instance, 0);
5597       /* fall through...  */
5598     case CALL_EXPR:
5599       /* This is a call to a constructor, hence it's never zero.  */
5600       if (TREE_HAS_CONSTRUCTOR (instance))
5601         {
5602           if (nonnull)
5603             *nonnull = 1;
5604           return TREE_TYPE (instance);
5605         }
5606       return NULL_TREE;
5607
5608     case SAVE_EXPR:
5609       /* This is a call to a constructor, hence it's never zero.  */
5610       if (TREE_HAS_CONSTRUCTOR (instance))
5611         {
5612           if (nonnull)
5613             *nonnull = 1;
5614           return TREE_TYPE (instance);
5615         }
5616       return fixed_type_or_null (TREE_OPERAND (instance, 0), nonnull, cdtorp);
5617
5618     case RTL_EXPR:
5619       return NULL_TREE;
5620
5621     case PLUS_EXPR:
5622     case MINUS_EXPR:
5623       if (TREE_CODE (TREE_OPERAND (instance, 0)) == ADDR_EXPR)
5624         return fixed_type_or_null (TREE_OPERAND (instance, 0), nonnull, cdtorp);
5625       if (TREE_CODE (TREE_OPERAND (instance, 1)) == INTEGER_CST)
5626         /* Propagate nonnull.  */
5627         fixed_type_or_null (TREE_OPERAND (instance, 0), nonnull, cdtorp);
5628       return NULL_TREE;
5629
5630     case NOP_EXPR:
5631     case CONVERT_EXPR:
5632       return fixed_type_or_null (TREE_OPERAND (instance, 0), nonnull, cdtorp);
5633
5634     case ADDR_EXPR:
5635       if (nonnull)
5636         *nonnull = 1;
5637       return fixed_type_or_null (TREE_OPERAND (instance, 0), nonnull, cdtorp);
5638
5639     case COMPONENT_REF:
5640       return fixed_type_or_null (TREE_OPERAND (instance, 1), nonnull, cdtorp);
5641
5642     case VAR_DECL:
5643     case FIELD_DECL:
5644       if (TREE_CODE (TREE_TYPE (instance)) == ARRAY_TYPE
5645           && IS_AGGR_TYPE (TREE_TYPE (TREE_TYPE (instance))))
5646         {
5647           if (nonnull)
5648             *nonnull = 1;
5649           return TREE_TYPE (TREE_TYPE (instance));
5650         }
5651       /* fall through...  */
5652     case TARGET_EXPR:
5653     case PARM_DECL:
5654       if (IS_AGGR_TYPE (TREE_TYPE (instance)))
5655         {
5656           if (nonnull)
5657             *nonnull = 1;
5658           return TREE_TYPE (instance);
5659         }
5660       else if (instance == current_class_ptr)
5661         {
5662           if (nonnull)
5663             *nonnull = 1;
5664         
5665           /* if we're in a ctor or dtor, we know our type. */
5666           if (DECL_LANG_SPECIFIC (current_function_decl)
5667               && (DECL_CONSTRUCTOR_P (current_function_decl)
5668                   || DECL_DESTRUCTOR_P (current_function_decl)))
5669             {
5670               if (cdtorp)
5671                 *cdtorp = 1;
5672               return TREE_TYPE (TREE_TYPE (instance));
5673             }
5674         }
5675       else if (TREE_CODE (TREE_TYPE (instance)) == REFERENCE_TYPE)
5676         {
5677           /* Reference variables should be references to objects.  */
5678           if (nonnull)
5679             *nonnull = 1;
5680         }
5681       return NULL_TREE;
5682
5683     default:
5684       return NULL_TREE;
5685     }
5686 }
5687
5688 /* Return non-zero if the dynamic type of INSTANCE is known, and equivalent
5689    to the static type.  We also handle the case where INSTANCE is really
5690    a pointer. Return negative if this is a ctor/dtor. There the dynamic type
5691    is known, but this might not be the most derived base of the original object,
5692    and hence virtual bases may not be layed out according to this type.
5693
5694    Used to determine whether the virtual function table is needed
5695    or not.
5696
5697    *NONNULL is set iff INSTANCE can be known to be nonnull, regardless
5698    of our knowledge of its type.  *NONNULL should be initialized
5699    before this function is called.  */
5700
5701 int
5702 resolves_to_fixed_type_p (instance, nonnull)
5703      tree instance;
5704      int *nonnull;
5705 {
5706   tree t = TREE_TYPE (instance);
5707   int cdtorp = 0;
5708   
5709   tree fixed = fixed_type_or_null (instance, nonnull, &cdtorp);
5710   if (fixed == NULL_TREE)
5711     return 0;
5712   if (POINTER_TYPE_P (t))
5713     t = TREE_TYPE (t);
5714   if (!same_type_ignoring_top_level_qualifiers_p (t, fixed))
5715     return 0;
5716   return cdtorp ? -1 : 1;
5717 }
5718
5719 \f
5720 void
5721 init_class_processing ()
5722 {
5723   current_class_depth = 0;
5724   current_class_stack_size = 10;
5725   current_class_stack 
5726     = (class_stack_node_t) xmalloc (current_class_stack_size 
5727                                     * sizeof (struct class_stack_node));
5728   VARRAY_TREE_INIT (local_classes, 8, "local_classes");
5729   ggc_add_tree_varray_root (&local_classes, 1);
5730
5731   access_default_node = build_int_2 (0, 0);
5732   access_public_node = build_int_2 (ak_public, 0);
5733   access_protected_node = build_int_2 (ak_protected, 0);
5734   access_private_node = build_int_2 (ak_private, 0);
5735   access_default_virtual_node = build_int_2 (4, 0);
5736   access_public_virtual_node = build_int_2 (4 | ak_public, 0);
5737   access_protected_virtual_node = build_int_2 (4 | ak_protected, 0);
5738   access_private_virtual_node = build_int_2 (4 | ak_private, 0);
5739
5740   ridpointers[(int) RID_PUBLIC] = access_public_node;
5741   ridpointers[(int) RID_PRIVATE] = access_private_node;
5742   ridpointers[(int) RID_PROTECTED] = access_protected_node;
5743 }
5744
5745 /* Set current scope to NAME. CODE tells us if this is a
5746    STRUCT, UNION, or ENUM environment.
5747
5748    NAME may end up being NULL_TREE if this is an anonymous or
5749    late-bound struct (as in "struct { ... } foo;")  */
5750
5751 /* Set global variables CURRENT_CLASS_NAME and CURRENT_CLASS_TYPE to
5752    appropriate values, found by looking up the type definition of
5753    NAME (as a CODE).
5754
5755    If MODIFY is 1, we set IDENTIFIER_CLASS_VALUE's of names
5756    which can be seen locally to the class.  They are shadowed by
5757    any subsequent local declaration (including parameter names).
5758
5759    If MODIFY is 2, we set IDENTIFIER_CLASS_VALUE's of names
5760    which have static meaning (i.e., static members, static
5761    member functions, enum declarations, etc).
5762
5763    If MODIFY is 3, we set IDENTIFIER_CLASS_VALUE of names
5764    which can be seen locally to the class (as in 1), but
5765    know that we are doing this for declaration purposes
5766    (i.e. friend foo::bar (int)).
5767
5768    So that we may avoid calls to lookup_name, we cache the _TYPE
5769    nodes of local TYPE_DECLs in the TREE_TYPE field of the name.
5770
5771    For multiple inheritance, we perform a two-pass depth-first search
5772    of the type lattice.  The first pass performs a pre-order search,
5773    marking types after the type has had its fields installed in
5774    the appropriate IDENTIFIER_CLASS_VALUE slot.  The second pass merely
5775    unmarks the marked types.  If a field or member function name
5776    appears in an ambiguous way, the IDENTIFIER_CLASS_VALUE of
5777    that name becomes `error_mark_node'.  */
5778
5779 void
5780 pushclass (type, modify)
5781      tree type;
5782      int modify;
5783 {
5784   type = TYPE_MAIN_VARIANT (type);
5785
5786   /* Make sure there is enough room for the new entry on the stack.  */
5787   if (current_class_depth + 1 >= current_class_stack_size) 
5788     {
5789       current_class_stack_size *= 2;
5790       current_class_stack
5791         = (class_stack_node_t) xrealloc (current_class_stack,
5792                                          current_class_stack_size
5793                                          * sizeof (struct class_stack_node));
5794     }
5795
5796   /* Insert a new entry on the class stack.  */
5797   current_class_stack[current_class_depth].name = current_class_name;
5798   current_class_stack[current_class_depth].type = current_class_type;
5799   current_class_stack[current_class_depth].access = current_access_specifier;
5800   current_class_stack[current_class_depth].names_used = 0;
5801   current_class_depth++;
5802
5803   /* Now set up the new type.  */
5804   current_class_name = TYPE_NAME (type);
5805   if (TREE_CODE (current_class_name) == TYPE_DECL)
5806     current_class_name = DECL_NAME (current_class_name);
5807   current_class_type = type;
5808
5809   /* By default, things in classes are private, while things in
5810      structures or unions are public.  */
5811   current_access_specifier = (CLASSTYPE_DECLARED_CLASS (type) 
5812                               ? access_private_node 
5813                               : access_public_node);
5814
5815   if (previous_class_type != NULL_TREE
5816       && (type != previous_class_type 
5817           || !COMPLETE_TYPE_P (previous_class_type))
5818       && current_class_depth == 1)
5819     {
5820       /* Forcibly remove any old class remnants.  */
5821       invalidate_class_lookup_cache ();
5822     }
5823
5824   /* If we're about to enter a nested class, clear
5825      IDENTIFIER_CLASS_VALUE for the enclosing classes.  */
5826   if (modify && current_class_depth > 1)
5827     clear_identifier_class_values ();
5828
5829   pushlevel_class ();
5830
5831   if (modify)
5832     {
5833       if (type != previous_class_type || current_class_depth > 1)
5834         push_class_decls (type);
5835       else
5836         {
5837           tree item;
5838
5839           /* We are re-entering the same class we just left, so we
5840              don't have to search the whole inheritance matrix to find
5841              all the decls to bind again.  Instead, we install the
5842              cached class_shadowed list, and walk through it binding
5843              names and setting up IDENTIFIER_TYPE_VALUEs.  */
5844           set_class_shadows (previous_class_values);
5845           for (item = previous_class_values; item; item = TREE_CHAIN (item))
5846             {
5847               tree id = TREE_PURPOSE (item);
5848               tree decl = TREE_TYPE (item);
5849
5850               push_class_binding (id, decl);
5851               if (TREE_CODE (decl) == TYPE_DECL)
5852                 set_identifier_type_value (id, TREE_TYPE (decl));
5853             }
5854           unuse_fields (type);
5855         }
5856
5857       storetags (CLASSTYPE_TAGS (type));
5858     }
5859 }
5860
5861 /* When we exit a toplevel class scope, we save the
5862    IDENTIFIER_CLASS_VALUEs so that we can restore them quickly if we
5863    reenter the class.  Here, we've entered some other class, so we
5864    must invalidate our cache.  */
5865
5866 void
5867 invalidate_class_lookup_cache ()
5868 {
5869   tree t;
5870   
5871   /* The IDENTIFIER_CLASS_VALUEs are no longer valid.  */
5872   for (t = previous_class_values; t; t = TREE_CHAIN (t))
5873     IDENTIFIER_CLASS_VALUE (TREE_PURPOSE (t)) = NULL_TREE;
5874
5875   previous_class_values = NULL_TREE;
5876   previous_class_type = NULL_TREE;
5877 }
5878  
5879 /* Get out of the current class scope. If we were in a class scope
5880    previously, that is the one popped to.  */
5881
5882 void
5883 popclass ()
5884 {
5885   poplevel_class ();
5886   /* Since poplevel_class does the popping of class decls nowadays,
5887      this really only frees the obstack used for these decls.  */
5888   pop_class_decls ();
5889
5890   current_class_depth--;
5891   current_class_name = current_class_stack[current_class_depth].name;
5892   current_class_type = current_class_stack[current_class_depth].type;
5893   current_access_specifier = current_class_stack[current_class_depth].access;
5894   if (current_class_stack[current_class_depth].names_used)
5895     splay_tree_delete (current_class_stack[current_class_depth].names_used);
5896 }
5897
5898 /* Returns 1 if current_class_type is either T or a nested type of T.
5899    We start looking from 1 because entry 0 is from global scope, and has
5900    no type.  */
5901
5902 int
5903 currently_open_class (t)
5904      tree t;
5905 {
5906   int i;
5907   if (t == current_class_type)
5908     return 1;
5909   for (i = 1; i < current_class_depth; ++i)
5910     if (current_class_stack [i].type == t)
5911       return 1;
5912   return 0;
5913 }
5914
5915 /* If either current_class_type or one of its enclosing classes are derived
5916    from T, return the appropriate type.  Used to determine how we found
5917    something via unqualified lookup.  */
5918
5919 tree
5920 currently_open_derived_class (t)
5921      tree t;
5922 {
5923   int i;
5924
5925   if (DERIVED_FROM_P (t, current_class_type))
5926     return current_class_type;
5927
5928   for (i = current_class_depth - 1; i > 0; --i)
5929     if (DERIVED_FROM_P (t, current_class_stack[i].type))
5930       return current_class_stack[i].type;
5931
5932   return NULL_TREE;
5933 }
5934
5935 /* When entering a class scope, all enclosing class scopes' names with
5936    static meaning (static variables, static functions, types and enumerators)
5937    have to be visible.  This recursive function calls pushclass for all
5938    enclosing class contexts until global or a local scope is reached.
5939    TYPE is the enclosed class and MODIFY is equivalent with the pushclass
5940    formal of the same name.  */
5941
5942 void
5943 push_nested_class (type, modify)
5944      tree type;
5945      int modify;
5946 {
5947   tree context;
5948
5949   /* A namespace might be passed in error cases, like A::B:C.  */
5950   if (type == NULL_TREE 
5951       || type == error_mark_node 
5952       || TREE_CODE (type) == NAMESPACE_DECL
5953       || ! IS_AGGR_TYPE (type)
5954       || TREE_CODE (type) == TEMPLATE_TYPE_PARM
5955       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
5956     return;
5957   
5958   context = DECL_CONTEXT (TYPE_MAIN_DECL (type));
5959
5960   if (context && CLASS_TYPE_P (context))
5961     push_nested_class (context, 2);
5962   pushclass (type, modify);
5963 }
5964
5965 /* Undoes a push_nested_class call.  MODIFY is passed on to popclass.  */
5966
5967 void
5968 pop_nested_class ()
5969 {
5970   tree context = DECL_CONTEXT (TYPE_MAIN_DECL (current_class_type));
5971
5972   popclass ();
5973   if (context && CLASS_TYPE_P (context))
5974     pop_nested_class ();
5975 }
5976
5977 /* Returns the number of extern "LANG" blocks we are nested within.  */
5978
5979 int
5980 current_lang_depth ()
5981 {
5982   return VARRAY_ACTIVE_SIZE (current_lang_base);
5983 }
5984
5985 /* Set global variables CURRENT_LANG_NAME to appropriate value
5986    so that behavior of name-mangling machinery is correct.  */
5987
5988 void
5989 push_lang_context (name)
5990      tree name;
5991 {
5992   VARRAY_PUSH_TREE (current_lang_base, current_lang_name);
5993
5994   if (name == lang_name_cplusplus)
5995     {
5996       current_lang_name = name;
5997     }
5998   else if (name == lang_name_java)
5999     {
6000       current_lang_name = name;
6001       /* DECL_IGNORED_P is initially set for these types, to avoid clutter.
6002          (See record_builtin_java_type in decl.c.)  However, that causes
6003          incorrect debug entries if these types are actually used.
6004          So we re-enable debug output after extern "Java". */
6005       DECL_IGNORED_P (TYPE_NAME (java_byte_type_node)) = 0;
6006       DECL_IGNORED_P (TYPE_NAME (java_short_type_node)) = 0;
6007       DECL_IGNORED_P (TYPE_NAME (java_int_type_node)) = 0;
6008       DECL_IGNORED_P (TYPE_NAME (java_long_type_node)) = 0;
6009       DECL_IGNORED_P (TYPE_NAME (java_float_type_node)) = 0;
6010       DECL_IGNORED_P (TYPE_NAME (java_double_type_node)) = 0;
6011       DECL_IGNORED_P (TYPE_NAME (java_char_type_node)) = 0;
6012       DECL_IGNORED_P (TYPE_NAME (java_boolean_type_node)) = 0;
6013     }
6014   else if (name == lang_name_c)
6015     {
6016       current_lang_name = name;
6017     }
6018   else
6019     error ("language string `\"%s\"' not recognized", IDENTIFIER_POINTER (name));
6020 }
6021   
6022 /* Get out of the current language scope.  */
6023
6024 void
6025 pop_lang_context ()
6026 {
6027   current_lang_name = VARRAY_TOP_TREE (current_lang_base);
6028   VARRAY_POP (current_lang_base);
6029 }
6030 \f
6031 /* Type instantiation routines.  */
6032
6033 /* Given an OVERLOAD and a TARGET_TYPE, return the function that
6034    matches the TARGET_TYPE.  If there is no satisfactory match, return
6035    error_mark_node, and issue an error message if COMPLAIN is
6036    non-zero.  Permit pointers to member function if PTRMEM is non-zero.
6037    If TEMPLATE_ONLY, the name of the overloaded function
6038    was a template-id, and EXPLICIT_TARGS are the explicitly provided
6039    template arguments.  */
6040
6041 static tree
6042 resolve_address_of_overloaded_function (target_type, 
6043                                         overload,
6044                                         complain,
6045                                         ptrmem,
6046                                         template_only,
6047                                         explicit_targs)
6048      tree target_type;
6049      tree overload;
6050      int complain;
6051      int ptrmem;
6052      int template_only;
6053      tree explicit_targs;
6054 {
6055   /* Here's what the standard says:
6056      
6057        [over.over]
6058
6059        If the name is a function template, template argument deduction
6060        is done, and if the argument deduction succeeds, the deduced
6061        arguments are used to generate a single template function, which
6062        is added to the set of overloaded functions considered.
6063
6064        Non-member functions and static member functions match targets of
6065        type "pointer-to-function" or "reference-to-function."  Nonstatic
6066        member functions match targets of type "pointer-to-member
6067        function;" the function type of the pointer to member is used to
6068        select the member function from the set of overloaded member
6069        functions.  If a nonstatic member function is selected, the
6070        reference to the overloaded function name is required to have the
6071        form of a pointer to member as described in 5.3.1.
6072
6073        If more than one function is selected, any template functions in
6074        the set are eliminated if the set also contains a non-template
6075        function, and any given template function is eliminated if the
6076        set contains a second template function that is more specialized
6077        than the first according to the partial ordering rules 14.5.5.2.
6078        After such eliminations, if any, there shall remain exactly one
6079        selected function.  */
6080
6081   int is_ptrmem = 0;
6082   int is_reference = 0;
6083   /* We store the matches in a TREE_LIST rooted here.  The functions
6084      are the TREE_PURPOSE, not the TREE_VALUE, in this list, for easy
6085      interoperability with most_specialized_instantiation.  */
6086   tree matches = NULL_TREE;
6087   tree fn;
6088
6089   /* By the time we get here, we should be seeing only real
6090      pointer-to-member types, not the internal POINTER_TYPE to
6091      METHOD_TYPE representation.  */
6092   my_friendly_assert (!(TREE_CODE (target_type) == POINTER_TYPE
6093                         && (TREE_CODE (TREE_TYPE (target_type)) 
6094                             == METHOD_TYPE)), 0);
6095
6096   if (TREE_CODE (overload) == COMPONENT_REF)
6097     overload = TREE_OPERAND (overload, 1);
6098
6099   /* Check that the TARGET_TYPE is reasonable.  */
6100   if (TYPE_PTRFN_P (target_type))
6101     /* This is OK.  */;
6102   else if (TYPE_PTRMEMFUNC_P (target_type))
6103     /* This is OK, too.  */
6104     is_ptrmem = 1;
6105   else if (TREE_CODE (target_type) == FUNCTION_TYPE)
6106     {
6107       /* This is OK, too.  This comes from a conversion to reference
6108          type.  */
6109       target_type = build_reference_type (target_type);
6110       is_reference = 1;
6111     }
6112   else 
6113     {
6114       if (complain)
6115         cp_error ("\
6116 cannot resolve overloaded function `%D' based on conversion to type `%T'", 
6117                   DECL_NAME (OVL_FUNCTION (overload)), target_type);
6118       return error_mark_node;
6119     }
6120   
6121   /* If we can find a non-template function that matches, we can just
6122      use it.  There's no point in generating template instantiations
6123      if we're just going to throw them out anyhow.  But, of course, we
6124      can only do this when we don't *need* a template function.  */
6125   if (!template_only)
6126     {
6127       tree fns;
6128
6129       for (fns = overload; fns; fns = OVL_CHAIN (fns))
6130         {
6131           tree fn = OVL_FUNCTION (fns);
6132           tree fntype;
6133
6134           if (TREE_CODE (fn) == TEMPLATE_DECL)
6135             /* We're not looking for templates just yet.  */
6136             continue;
6137
6138           if ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
6139               != is_ptrmem)
6140             /* We're looking for a non-static member, and this isn't
6141                one, or vice versa.  */
6142             continue;
6143         
6144           /* See if there's a match.  */
6145           fntype = TREE_TYPE (fn);
6146           if (is_ptrmem)
6147             fntype = build_ptrmemfunc_type (build_pointer_type (fntype));
6148           else if (!is_reference)
6149             fntype = build_pointer_type (fntype);
6150
6151           if (can_convert_arg (target_type, fntype, fn))
6152             matches = tree_cons (fn, NULL_TREE, matches);
6153         }
6154     }
6155
6156   /* Now, if we've already got a match (or matches), there's no need
6157      to proceed to the template functions.  But, if we don't have a
6158      match we need to look at them, too.  */
6159   if (!matches) 
6160     {
6161       tree target_fn_type;
6162       tree target_arg_types;
6163       tree target_ret_type;
6164       tree fns;
6165
6166       if (is_ptrmem)
6167         target_fn_type
6168           = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (target_type));
6169       else
6170         target_fn_type = TREE_TYPE (target_type);
6171       target_arg_types = TYPE_ARG_TYPES (target_fn_type);
6172       target_ret_type = TREE_TYPE (target_fn_type);
6173
6174       /* Never do unification on the 'this' parameter.  */
6175       if (TREE_CODE (target_fn_type) == METHOD_TYPE)
6176         target_arg_types = TREE_CHAIN (target_arg_types);
6177           
6178       for (fns = overload; fns; fns = OVL_CHAIN (fns))
6179         {
6180           tree fn = OVL_FUNCTION (fns);
6181           tree instantiation;
6182           tree instantiation_type;
6183           tree targs;
6184
6185           if (TREE_CODE (fn) != TEMPLATE_DECL)
6186             /* We're only looking for templates.  */
6187             continue;
6188
6189           if ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
6190               != is_ptrmem)
6191             /* We're not looking for a non-static member, and this is
6192                one, or vice versa.  */
6193             continue;
6194
6195           /* Try to do argument deduction.  */
6196           targs = make_tree_vec (DECL_NTPARMS (fn));
6197           if (fn_type_unification (fn, explicit_targs, targs,
6198                                    target_arg_types, target_ret_type,
6199                                    DEDUCE_EXACT, -1) != 0)
6200             /* Argument deduction failed.  */
6201             continue;
6202
6203           /* Instantiate the template.  */
6204           instantiation = instantiate_template (fn, targs);
6205           if (instantiation == error_mark_node)
6206             /* Instantiation failed.  */
6207             continue;
6208
6209           /* See if there's a match.  */
6210           instantiation_type = TREE_TYPE (instantiation);
6211           if (is_ptrmem)
6212             instantiation_type = 
6213               build_ptrmemfunc_type (build_pointer_type (instantiation_type));
6214           else if (!is_reference)
6215             instantiation_type = build_pointer_type (instantiation_type);
6216           if (can_convert_arg (target_type, instantiation_type, instantiation))
6217             matches = tree_cons (instantiation, fn, matches);
6218         }
6219
6220       /* Now, remove all but the most specialized of the matches.  */
6221       if (matches)
6222         {
6223           tree match = most_specialized_instantiation (matches);
6224
6225           if (match != error_mark_node)
6226             matches = tree_cons (match, NULL_TREE, NULL_TREE);
6227         }
6228     }
6229
6230   /* Now we should have exactly one function in MATCHES.  */
6231   if (matches == NULL_TREE)
6232     {
6233       /* There were *no* matches.  */
6234       if (complain)
6235         {
6236           cp_error ("no matches converting function `%D' to type `%#T'", 
6237                     DECL_NAME (OVL_FUNCTION (overload)),
6238                     target_type);
6239
6240           /* print_candidates expects a chain with the functions in
6241              TREE_VALUE slots, so we cons one up here (we're losing anyway,
6242              so why be clever?).  */
6243           for (; overload; overload = OVL_NEXT (overload))
6244             matches = tree_cons (NULL_TREE, OVL_CURRENT (overload),
6245                                  matches);
6246           
6247           print_candidates (matches);
6248         }
6249       return error_mark_node;
6250     }
6251   else if (TREE_CHAIN (matches))
6252     {
6253       /* There were too many matches.  */
6254
6255       if (complain)
6256         {
6257           tree match;
6258
6259           cp_error ("converting overloaded function `%D' to type `%#T' is ambiguous", 
6260                     DECL_NAME (OVL_FUNCTION (overload)),
6261                     target_type);
6262
6263           /* Since print_candidates expects the functions in the
6264              TREE_VALUE slot, we flip them here.  */
6265           for (match = matches; match; match = TREE_CHAIN (match))
6266             TREE_VALUE (match) = TREE_PURPOSE (match);
6267
6268           print_candidates (matches);
6269         }
6270       
6271       return error_mark_node;
6272     }
6273
6274   /* Good, exactly one match.  Now, convert it to the correct type.  */
6275   fn = TREE_PURPOSE (matches);
6276
6277   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
6278       && !ptrmem && !flag_ms_extensions)
6279     {
6280       static int explained;
6281       
6282       if (!complain)
6283         return error_mark_node;
6284
6285       cp_pedwarn ("assuming pointer to member `%D'", fn);
6286       if (!explained)
6287         {
6288           cp_pedwarn ("(a pointer to member can only be formed with `&%E')", fn);
6289           explained = 1;
6290         }
6291     }
6292   mark_used (fn);
6293
6294   if (TYPE_PTRFN_P (target_type) || TYPE_PTRMEMFUNC_P (target_type))
6295     return build_unary_op (ADDR_EXPR, fn, 0);
6296   else
6297     {
6298       /* The target must be a REFERENCE_TYPE.  Above, build_unary_op
6299          will mark the function as addressed, but here we must do it
6300          explicitly.  */
6301       mark_addressable (fn);
6302
6303       return fn;
6304     }
6305 }
6306
6307 /* This function will instantiate the type of the expression given in
6308    RHS to match the type of LHSTYPE.  If errors exist, then return
6309    error_mark_node. FLAGS is a bit mask.  If ITF_COMPLAIN is set, then
6310    we complain on errors.  If we are not complaining, never modify rhs,
6311    as overload resolution wants to try many possible instantiations, in
6312    the hope that at least one will work.
6313    
6314    For non-recursive calls, LHSTYPE should be a function, pointer to
6315    function, or a pointer to member function.  */
6316
6317 tree
6318 instantiate_type (lhstype, rhs, flags)
6319      tree lhstype, rhs;
6320      enum instantiate_type_flags flags;
6321 {
6322   int complain = (flags & itf_complain);
6323   int strict = (flags & itf_no_attributes)
6324                ? COMPARE_NO_ATTRIBUTES : COMPARE_STRICT;
6325   int allow_ptrmem = flags & itf_ptrmem_ok;
6326   
6327   flags &= ~itf_ptrmem_ok;
6328   
6329   if (TREE_CODE (lhstype) == UNKNOWN_TYPE)
6330     {
6331       if (complain)
6332         error ("not enough type information");
6333       return error_mark_node;
6334     }
6335
6336   if (TREE_TYPE (rhs) != NULL_TREE && ! (type_unknown_p (rhs)))
6337     {
6338       if (comptypes (lhstype, TREE_TYPE (rhs), strict))
6339         return rhs;
6340       if (complain)
6341         cp_error ("argument of type `%T' does not match `%T'",
6342                   TREE_TYPE (rhs), lhstype);
6343       return error_mark_node;
6344     }
6345
6346   /* We don't overwrite rhs if it is an overloaded function.
6347      Copying it would destroy the tree link.  */
6348   if (TREE_CODE (rhs) != OVERLOAD)
6349     rhs = copy_node (rhs);
6350
6351   /* This should really only be used when attempting to distinguish
6352      what sort of a pointer to function we have.  For now, any
6353      arithmetic operation which is not supported on pointers
6354      is rejected as an error.  */
6355
6356   switch (TREE_CODE (rhs))
6357     {
6358     case TYPE_EXPR:
6359     case CONVERT_EXPR:
6360     case SAVE_EXPR:
6361     case CONSTRUCTOR:
6362     case BUFFER_REF:
6363       my_friendly_abort (177);
6364       return error_mark_node;
6365
6366     case INDIRECT_REF:
6367     case ARRAY_REF:
6368       {
6369         tree new_rhs;
6370
6371         new_rhs = instantiate_type (build_pointer_type (lhstype),
6372                                     TREE_OPERAND (rhs, 0), flags);
6373         if (new_rhs == error_mark_node)
6374           return error_mark_node;
6375
6376         TREE_TYPE (rhs) = lhstype;
6377         TREE_OPERAND (rhs, 0) = new_rhs;
6378         return rhs;
6379       }
6380
6381     case NOP_EXPR:
6382       rhs = copy_node (TREE_OPERAND (rhs, 0));
6383       TREE_TYPE (rhs) = unknown_type_node;
6384       return instantiate_type (lhstype, rhs, flags);
6385
6386     case COMPONENT_REF:
6387       return instantiate_type (lhstype, TREE_OPERAND (rhs, 1), flags);
6388
6389     case OFFSET_REF:
6390       rhs = TREE_OPERAND (rhs, 1);
6391       if (BASELINK_P (rhs))
6392         return instantiate_type (lhstype, TREE_VALUE (rhs),
6393                                  flags | allow_ptrmem);
6394
6395       /* This can happen if we are forming a pointer-to-member for a
6396          member template.  */
6397       my_friendly_assert (TREE_CODE (rhs) == TEMPLATE_ID_EXPR, 0);
6398
6399       /* Fall through.  */
6400
6401     case TEMPLATE_ID_EXPR:
6402       {
6403         tree fns = TREE_OPERAND (rhs, 0);
6404         tree args = TREE_OPERAND (rhs, 1);
6405
6406         return
6407           resolve_address_of_overloaded_function (lhstype,
6408                                                   fns,
6409                                                   complain,
6410                                                   allow_ptrmem,
6411                                                   /*template_only=*/1,
6412                                                   args);
6413       }
6414
6415     case OVERLOAD:
6416       return 
6417         resolve_address_of_overloaded_function (lhstype, 
6418                                                 rhs,
6419                                                 complain,
6420                                                 allow_ptrmem,
6421                                                 /*template_only=*/0,
6422                                                 /*explicit_targs=*/NULL_TREE);
6423
6424     case TREE_LIST:
6425       /* Now we should have a baselink. */
6426       my_friendly_assert (BASELINK_P (rhs), 990412);
6427
6428       return instantiate_type (lhstype, TREE_VALUE (rhs), flags);
6429
6430     case CALL_EXPR:
6431       /* This is too hard for now.  */
6432       my_friendly_abort (183);
6433       return error_mark_node;
6434
6435     case PLUS_EXPR:
6436     case MINUS_EXPR:
6437     case COMPOUND_EXPR:
6438       TREE_OPERAND (rhs, 0)
6439         = instantiate_type (lhstype, TREE_OPERAND (rhs, 0), flags);
6440       if (TREE_OPERAND (rhs, 0) == error_mark_node)
6441         return error_mark_node;
6442       TREE_OPERAND (rhs, 1)
6443         = instantiate_type (lhstype, TREE_OPERAND (rhs, 1), flags);
6444       if (TREE_OPERAND (rhs, 1) == error_mark_node)
6445         return error_mark_node;
6446
6447       TREE_TYPE (rhs) = lhstype;
6448       return rhs;
6449
6450     case MULT_EXPR:
6451     case TRUNC_DIV_EXPR:
6452     case FLOOR_DIV_EXPR:
6453     case CEIL_DIV_EXPR:
6454     case ROUND_DIV_EXPR:
6455     case RDIV_EXPR:
6456     case TRUNC_MOD_EXPR:
6457     case FLOOR_MOD_EXPR:
6458     case CEIL_MOD_EXPR:
6459     case ROUND_MOD_EXPR:
6460     case FIX_ROUND_EXPR:
6461     case FIX_FLOOR_EXPR:
6462     case FIX_CEIL_EXPR:
6463     case FIX_TRUNC_EXPR:
6464     case FLOAT_EXPR:
6465     case NEGATE_EXPR:
6466     case ABS_EXPR:
6467     case MAX_EXPR:
6468     case MIN_EXPR:
6469     case FFS_EXPR:
6470
6471     case BIT_AND_EXPR:
6472     case BIT_IOR_EXPR:
6473     case BIT_XOR_EXPR:
6474     case LSHIFT_EXPR:
6475     case RSHIFT_EXPR:
6476     case LROTATE_EXPR:
6477     case RROTATE_EXPR:
6478
6479     case PREINCREMENT_EXPR:
6480     case PREDECREMENT_EXPR:
6481     case POSTINCREMENT_EXPR:
6482     case POSTDECREMENT_EXPR:
6483       if (complain)
6484         error ("invalid operation on uninstantiated type");
6485       return error_mark_node;
6486
6487     case TRUTH_AND_EXPR:
6488     case TRUTH_OR_EXPR:
6489     case TRUTH_XOR_EXPR:
6490     case LT_EXPR:
6491     case LE_EXPR:
6492     case GT_EXPR:
6493     case GE_EXPR:
6494     case EQ_EXPR:
6495     case NE_EXPR:
6496     case TRUTH_ANDIF_EXPR:
6497     case TRUTH_ORIF_EXPR:
6498     case TRUTH_NOT_EXPR:
6499       if (complain)
6500         error ("not enough type information");
6501       return error_mark_node;
6502
6503     case COND_EXPR:
6504       if (type_unknown_p (TREE_OPERAND (rhs, 0)))
6505         {
6506           if (complain)
6507             error ("not enough type information");
6508           return error_mark_node;
6509         }
6510       TREE_OPERAND (rhs, 1)
6511         = instantiate_type (lhstype, TREE_OPERAND (rhs, 1), flags);
6512       if (TREE_OPERAND (rhs, 1) == error_mark_node)
6513         return error_mark_node;
6514       TREE_OPERAND (rhs, 2)
6515         = instantiate_type (lhstype, TREE_OPERAND (rhs, 2), flags);
6516       if (TREE_OPERAND (rhs, 2) == error_mark_node)
6517         return error_mark_node;
6518
6519       TREE_TYPE (rhs) = lhstype;
6520       return rhs;
6521
6522     case MODIFY_EXPR:
6523       TREE_OPERAND (rhs, 1)
6524         = instantiate_type (lhstype, TREE_OPERAND (rhs, 1), flags);
6525       if (TREE_OPERAND (rhs, 1) == error_mark_node)
6526         return error_mark_node;
6527
6528       TREE_TYPE (rhs) = lhstype;
6529       return rhs;
6530       
6531     case ADDR_EXPR:
6532     {
6533       if (PTRMEM_OK_P (rhs))
6534         flags |= itf_ptrmem_ok;
6535       
6536       return instantiate_type (lhstype, TREE_OPERAND (rhs, 0), flags);
6537     }
6538     case ENTRY_VALUE_EXPR:
6539       my_friendly_abort (184);
6540       return error_mark_node;
6541
6542     case ERROR_MARK:
6543       return error_mark_node;
6544
6545     default:
6546       my_friendly_abort (185);
6547       return error_mark_node;
6548     }
6549 }
6550 \f
6551 /* Return the name of the virtual function pointer field
6552    (as an IDENTIFIER_NODE) for the given TYPE.  Note that
6553    this may have to look back through base types to find the
6554    ultimate field name.  (For single inheritance, these could
6555    all be the same name.  Who knows for multiple inheritance).  */
6556
6557 static tree
6558 get_vfield_name (type)
6559      tree type;
6560 {
6561   tree binfo = TYPE_BINFO (type);
6562   char *buf;
6563
6564   while (BINFO_BASETYPES (binfo)
6565          && TYPE_CONTAINS_VPTR_P (BINFO_TYPE (BINFO_BASETYPE (binfo, 0)))
6566          && ! TREE_VIA_VIRTUAL (BINFO_BASETYPE (binfo, 0)))
6567     binfo = BINFO_BASETYPE (binfo, 0);
6568
6569   type = BINFO_TYPE (binfo);
6570   buf = (char *) alloca (sizeof (VFIELD_NAME_FORMAT)
6571                          + TYPE_NAME_LENGTH (type) + 2);
6572   sprintf (buf, VFIELD_NAME_FORMAT, TYPE_NAME_STRING (type));
6573   return get_identifier (buf);
6574 }
6575
6576 void
6577 print_class_statistics ()
6578 {
6579 #ifdef GATHER_STATISTICS
6580   fprintf (stderr, "convert_harshness = %d\n", n_convert_harshness);
6581   fprintf (stderr, "compute_conversion_costs = %d\n", n_compute_conversion_costs);
6582   fprintf (stderr, "build_method_call = %d (inner = %d)\n",
6583            n_build_method_call, n_inner_fields_searched);
6584   if (n_vtables)
6585     {
6586       fprintf (stderr, "vtables = %d; vtable searches = %d\n",
6587                n_vtables, n_vtable_searches);
6588       fprintf (stderr, "vtable entries = %d; vtable elems = %d\n",
6589                n_vtable_entries, n_vtable_elems);
6590     }
6591 #endif
6592 }
6593
6594 /* Build a dummy reference to ourselves so Derived::Base (and A::A) works,
6595    according to [class]:
6596                                           The class-name is also inserted
6597    into  the scope of the class itself.  For purposes of access checking,
6598    the inserted class name is treated as if it were a public member name.  */
6599
6600 void
6601 build_self_reference ()
6602 {
6603   tree name = constructor_name (current_class_type);
6604   tree value = build_lang_decl (TYPE_DECL, name, current_class_type);
6605   tree saved_cas;
6606
6607   DECL_NONLOCAL (value) = 1;
6608   DECL_CONTEXT (value) = current_class_type;
6609   DECL_ARTIFICIAL (value) = 1;
6610
6611   if (processing_template_decl)
6612     value = push_template_decl (value);
6613
6614   saved_cas = current_access_specifier;
6615   current_access_specifier = access_public_node;
6616   finish_member_declaration (value);
6617   current_access_specifier = saved_cas;
6618 }
6619
6620 /* Returns 1 if TYPE contains only padding bytes.  */
6621
6622 int
6623 is_empty_class (type)
6624      tree type;
6625 {
6626   if (type == error_mark_node)
6627     return 0;
6628
6629   if (! IS_AGGR_TYPE (type))
6630     return 0;
6631
6632   return integer_zerop (CLASSTYPE_SIZE (type));
6633 }
6634
6635 /* Find the enclosing class of the given NODE.  NODE can be a *_DECL or
6636    a *_TYPE node.  NODE can also be a local class.  */
6637
6638 tree
6639 get_enclosing_class (type)
6640      tree type;
6641 {
6642   tree node = type;
6643
6644   while (node && TREE_CODE (node) != NAMESPACE_DECL)
6645     {
6646       switch (TREE_CODE_CLASS (TREE_CODE (node)))
6647         {
6648         case 'd':
6649           node = DECL_CONTEXT (node);
6650           break;
6651
6652         case 't':
6653           if (node != type)
6654             return node;
6655           node = TYPE_CONTEXT (node);
6656           break;
6657
6658         default:
6659           my_friendly_abort (0);
6660         }
6661     }
6662   return NULL_TREE;
6663 }
6664
6665 /* Return 1 if TYPE or one of its enclosing classes is derived from BASE.  */
6666
6667 int
6668 is_base_of_enclosing_class (base, type)
6669      tree base, type;
6670 {
6671   while (type)
6672     {
6673       if (get_binfo (base, type, 0))
6674         return 1;
6675
6676       type = get_enclosing_class (type);
6677     }
6678   return 0;
6679 }
6680
6681 /* Note that NAME was looked up while the current class was being
6682    defined and that the result of that lookup was DECL.  */
6683
6684 void
6685 maybe_note_name_used_in_class (name, decl)
6686      tree name;
6687      tree decl;
6688 {
6689   splay_tree names_used;
6690
6691   /* If we're not defining a class, there's nothing to do.  */
6692   if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
6693     return;
6694   
6695   /* If there's already a binding for this NAME, then we don't have
6696      anything to worry about.  */
6697   if (IDENTIFIER_CLASS_VALUE (name))
6698     return;
6699
6700   if (!current_class_stack[current_class_depth - 1].names_used)
6701     current_class_stack[current_class_depth - 1].names_used
6702       = splay_tree_new (splay_tree_compare_pointers, 0, 0);
6703   names_used = current_class_stack[current_class_depth - 1].names_used;
6704
6705   splay_tree_insert (names_used,
6706                      (splay_tree_key) name, 
6707                      (splay_tree_value) decl);
6708 }
6709
6710 /* Note that NAME was declared (as DECL) in the current class.  Check
6711    to see that the declaration is legal.  */
6712
6713 void
6714 note_name_declared_in_class (name, decl)
6715      tree name;
6716      tree decl;
6717 {
6718   splay_tree names_used;
6719   splay_tree_node n;
6720
6721   /* Look to see if we ever used this name.  */
6722   names_used 
6723     = current_class_stack[current_class_depth - 1].names_used;
6724   if (!names_used)
6725     return;
6726
6727   n = splay_tree_lookup (names_used, (splay_tree_key) name);
6728   if (n)
6729     {
6730       /* [basic.scope.class]
6731          
6732          A name N used in a class S shall refer to the same declaration
6733          in its context and when re-evaluated in the completed scope of
6734          S.  */
6735       cp_error ("declaration of `%#D'", decl);
6736       cp_error_at ("changes meaning of `%D' from `%+#D'", 
6737                    DECL_NAME (OVL_CURRENT (decl)),
6738                    (tree) n->value);
6739     }
6740 }
6741
6742 /* Returns the VAR_DECL for the complete vtable associated with
6743    BINFO.  (Under the new ABI, secondary vtables are merged with
6744    primary vtables; this function will return the VAR_DECL for the
6745    primary vtable.)  */
6746
6747 tree
6748 get_vtbl_decl_for_binfo (binfo)
6749      tree binfo;
6750 {
6751   tree decl;
6752
6753   decl = BINFO_VTABLE (binfo);
6754   if (decl && TREE_CODE (decl) == PLUS_EXPR)
6755     {
6756       my_friendly_assert (TREE_CODE (TREE_OPERAND (decl, 0)) == ADDR_EXPR,
6757                           2000403);
6758       decl = TREE_OPERAND (TREE_OPERAND (decl, 0), 0);
6759     }
6760   if (decl)
6761     my_friendly_assert (TREE_CODE (decl) == VAR_DECL, 20000403);
6762   return decl;
6763 }
6764
6765 /* Called from get_primary_binfo via dfs_walk.  DATA is a TREE_LIST
6766    who's TREE_PURPOSE is the TYPE of the required primary base and
6767    who's TREE_VALUE is a list of candidate binfos that we fill in. */
6768
6769 static tree
6770 dfs_get_primary_binfo (binfo, data)
6771      tree binfo;
6772      void *data;
6773 {
6774   tree cons = (tree) data;
6775   tree primary_base = TREE_PURPOSE (cons);
6776
6777   if (TREE_VIA_VIRTUAL (binfo) 
6778       && same_type_p (BINFO_TYPE (binfo), primary_base))
6779     /* This is the right type of binfo, but it might be an unshared
6780        instance, and the shared instance is later in the dfs walk.  We
6781        must keep looking.  */
6782     TREE_VALUE (cons) = tree_cons (NULL, binfo, TREE_VALUE (cons));
6783   
6784   return NULL_TREE;
6785 }
6786
6787 /* Returns the unshared binfo for the primary base of BINFO.  Note
6788    that in a complex hierarchy the resulting BINFO may not actually
6789    *be* primary.  In particular if the resulting BINFO is a virtual
6790    base, and it occurs elsewhere in the hierarchy, then this
6791    occurrence may not actually be a primary base in the complete
6792    object.  Check BINFO_PRIMARY_P to be sure.  */
6793
6794 tree
6795 get_primary_binfo (binfo)
6796      tree binfo;
6797 {
6798   tree primary_base;
6799   tree result;
6800   tree virtuals;
6801   
6802   primary_base = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (binfo));
6803   if (!primary_base)
6804     return NULL_TREE;
6805
6806   /* A non-virtual primary base is always a direct base, and easy to
6807      find.  */
6808   if (!TREE_VIA_VIRTUAL (primary_base))
6809     {
6810       int i;
6811
6812       /* Scan the direct basetypes until we find a base with the same
6813          type as the primary base.  */
6814       for (i = 0; i < BINFO_N_BASETYPES (binfo); ++i)
6815         {
6816           tree base_binfo = BINFO_BASETYPE (binfo, i);
6817           
6818           if (same_type_p (BINFO_TYPE (base_binfo),
6819                            BINFO_TYPE (primary_base)))
6820             return base_binfo;
6821         }
6822
6823       /* We should always find the primary base.  */
6824       my_friendly_abort (20000729);
6825     }
6826
6827   /* For a primary virtual base, we have to scan the entire hierarchy
6828      rooted at BINFO; the virtual base could be an indirect virtual
6829      base.  There could be more than one instance of the primary base
6830      in the hierarchy, and if one is the canonical binfo we want that
6831      one.  If it exists, it should be the first one we find, but as a
6832      consistency check we find them all and make sure.  */
6833   virtuals = build_tree_list (BINFO_TYPE (primary_base), NULL_TREE);
6834   dfs_walk (binfo, dfs_get_primary_binfo, NULL, virtuals);
6835   virtuals = TREE_VALUE (virtuals);
6836   
6837   /* We must have found at least one instance.  */
6838   my_friendly_assert (virtuals, 20010612);
6839
6840   if (TREE_CHAIN (virtuals))
6841     {
6842       /* We found more than one instance of the base. We must make
6843          sure that, if one is the canonical one, it is the first one
6844          we found. As the chain is in reverse dfs order, that means
6845          the last on the list.  */
6846       tree complete_binfo;
6847       tree canonical;
6848       
6849       for (complete_binfo = binfo;
6850            BINFO_INHERITANCE_CHAIN (complete_binfo);
6851            complete_binfo = BINFO_INHERITANCE_CHAIN (complete_binfo))
6852         continue;
6853       canonical = binfo_for_vbase (BINFO_TYPE (primary_base),
6854                                    BINFO_TYPE (complete_binfo));
6855       
6856       for (; virtuals; virtuals = TREE_CHAIN (virtuals))
6857         {
6858           result = TREE_VALUE (virtuals);
6859
6860           if (canonical == result)
6861             {
6862               /* This is the unshared instance. Make sure it was the
6863                  first one found.  */
6864               my_friendly_assert (!TREE_CHAIN (virtuals), 20010612);
6865               break;
6866             }
6867         }
6868     }
6869   else
6870     result = TREE_VALUE (virtuals);
6871   return result;
6872 }
6873
6874 /* If INDENTED_P is zero, indent to INDENT. Return non-zero. */
6875
6876 static int
6877 maybe_indent_hierarchy (stream, indent, indented_p)
6878      FILE *stream;
6879      int indent;
6880      int indented_p;
6881 {
6882   if (!indented_p)
6883     fprintf (stream, "%*s", indent, "");
6884   return 1;
6885 }
6886
6887 /* Dump the offsets of all the bases rooted at BINFO (in the hierarchy
6888    dominated by T) to stderr.  INDENT should be zero when called from
6889    the top level; it is incremented recursively.  */
6890
6891 static void
6892 dump_class_hierarchy_r (stream, flags, t, binfo, indent)
6893      FILE *stream;
6894      int flags;
6895      tree t;
6896      tree binfo;
6897      int indent;
6898 {
6899   int i;
6900   int indented = 0;
6901   
6902   indented = maybe_indent_hierarchy (stream, indent, 0);
6903   fprintf (stream, "%s (0x%lx) ",
6904            type_as_string (binfo, TFF_PLAIN_IDENTIFIER),
6905            (unsigned long) binfo);
6906   fprintf (stream, HOST_WIDE_INT_PRINT_DEC,
6907            tree_low_cst (BINFO_OFFSET (binfo), 0));
6908   if (is_empty_class (BINFO_TYPE (binfo)))
6909     fprintf (stream, " empty");
6910   else if (CLASSTYPE_NEARLY_EMPTY_P (BINFO_TYPE (binfo)))
6911     fprintf (stream, " nearly-empty");
6912   if (TREE_VIA_VIRTUAL (binfo))
6913     {
6914       tree canonical = binfo_for_vbase (BINFO_TYPE (binfo), t);
6915
6916       fprintf (stream, " virtual");
6917       if (canonical == binfo)
6918         fprintf (stream, " canonical");
6919       else
6920         fprintf (stream, " non-canonical");
6921     }
6922   fprintf (stream, "\n");
6923
6924   indented = 0;
6925   if (BINFO_PRIMARY_BASE_OF (binfo))
6926     {
6927       indented = maybe_indent_hierarchy (stream, indent + 3, indented);
6928       fprintf (stream, " primary-for %s (0x%lx)",
6929                type_as_string (BINFO_PRIMARY_BASE_OF (binfo),
6930                                TFF_PLAIN_IDENTIFIER),
6931                (unsigned long)BINFO_PRIMARY_BASE_OF (binfo));
6932     }
6933   if (BINFO_LOST_PRIMARY_P (binfo))
6934     {
6935       indented = maybe_indent_hierarchy (stream, indent + 3, indented);
6936       fprintf (stream, " lost-primary");
6937     }
6938   if (indented)
6939     fprintf (stream, "\n");
6940
6941   if (!(flags & TDF_SLIM))
6942     {
6943       int indented = 0;
6944       
6945       if (BINFO_SUBVTT_INDEX (binfo))
6946         {
6947           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
6948           fprintf (stream, " subvttidx=%s",
6949                    expr_as_string (BINFO_SUBVTT_INDEX (binfo),
6950                                    TFF_PLAIN_IDENTIFIER));
6951         }
6952       if (BINFO_VPTR_INDEX (binfo))
6953         {
6954           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
6955           fprintf (stream, " vptridx=%s",
6956                    expr_as_string (BINFO_VPTR_INDEX (binfo),
6957                                    TFF_PLAIN_IDENTIFIER));
6958         }
6959       if (BINFO_VPTR_FIELD (binfo))
6960         {
6961           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
6962           fprintf (stream, " vbaseoffset=%s",
6963                    expr_as_string (BINFO_VPTR_FIELD (binfo),
6964                                    TFF_PLAIN_IDENTIFIER));
6965         }
6966       if (BINFO_VTABLE (binfo))
6967         {
6968           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
6969           fprintf (stream, " vptr=%s",
6970                    expr_as_string (BINFO_VTABLE (binfo),
6971                                    TFF_PLAIN_IDENTIFIER));
6972         }
6973       
6974       if (indented)
6975         fprintf (stream, "\n");
6976     }
6977   
6978
6979   for (i = 0; i < BINFO_N_BASETYPES (binfo); ++i)
6980     dump_class_hierarchy_r (stream, flags,
6981                             t, BINFO_BASETYPE (binfo, i),
6982                             indent + 2);
6983 }
6984
6985 /* Dump the BINFO hierarchy for T.  */
6986
6987 static void
6988 dump_class_hierarchy (t)
6989      tree t;
6990 {
6991   int flags;
6992   FILE *stream = dump_begin (TDI_class, &flags);
6993
6994   if (!stream)
6995     return;
6996   
6997   fprintf (stream, "Class %s\n", type_as_string (t, TFF_PLAIN_IDENTIFIER));
6998   fprintf (stream, "   size=%lu align=%lu\n",
6999            (unsigned long)(tree_low_cst (TYPE_SIZE (t), 0) / BITS_PER_UNIT),
7000            (unsigned long)(TYPE_ALIGN (t) / BITS_PER_UNIT));
7001   dump_class_hierarchy_r (stream, flags, t, TYPE_BINFO (t), 0);
7002   fprintf (stream, "\n");
7003   dump_end (TDI_class, stream);
7004 }
7005
7006 static void
7007 dump_array (stream, decl)
7008      FILE *stream;
7009      tree decl;
7010 {
7011   tree inits;
7012   int ix;
7013   HOST_WIDE_INT elt;
7014   tree size = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (decl)));
7015
7016   elt = (tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (decl))), 0)
7017          / BITS_PER_UNIT);
7018   fprintf (stream, "%s:", decl_as_string (decl, TFF_PLAIN_IDENTIFIER));
7019   fprintf (stream, " %s entries",
7020            expr_as_string (size_binop (PLUS_EXPR, size, size_one_node),
7021                            TFF_PLAIN_IDENTIFIER));
7022   fprintf (stream, "\n");
7023
7024   for (ix = 0, inits = TREE_OPERAND (DECL_INITIAL (decl), 1);
7025        inits; ix++, inits = TREE_CHAIN (inits))
7026     fprintf (stream, "%-4d  %s\n", ix * elt,
7027              expr_as_string (TREE_VALUE (inits), TFF_PLAIN_IDENTIFIER));
7028 }
7029
7030 static void
7031 dump_vtable (t, binfo, vtable)
7032      tree t;
7033      tree binfo;
7034      tree vtable;
7035 {
7036   int flags;
7037   FILE *stream = dump_begin (TDI_class, &flags);
7038
7039   if (!stream)
7040     return;
7041
7042   if (!(flags & TDF_SLIM))
7043     {
7044       int ctor_vtbl_p = TYPE_BINFO (t) != binfo;
7045       
7046       fprintf (stream, "%s for %s",
7047                ctor_vtbl_p ? "Construction vtable" : "Vtable",
7048                type_as_string (binfo, TFF_PLAIN_IDENTIFIER));
7049       if (ctor_vtbl_p)
7050         {
7051           if (!TREE_VIA_VIRTUAL (binfo))
7052             fprintf (stream, " (0x%lx instance)", (unsigned long)binfo);
7053           fprintf (stream, " in %s", type_as_string (t, TFF_PLAIN_IDENTIFIER));
7054         }
7055       fprintf (stream, "\n");
7056       dump_array (stream, vtable);
7057       fprintf (stream, "\n");
7058     }
7059   
7060   dump_end (TDI_class, stream);
7061 }
7062
7063 static void
7064 dump_vtt (t, vtt)
7065      tree t;
7066      tree vtt;
7067 {
7068   int flags;
7069   FILE *stream = dump_begin (TDI_class, &flags);
7070
7071   if (!stream)
7072     return;
7073
7074   if (!(flags & TDF_SLIM))
7075     {
7076       fprintf (stream, "VTT for %s\n",
7077                type_as_string (t, TFF_PLAIN_IDENTIFIER));
7078       dump_array (stream, vtt);
7079       fprintf (stream, "\n");
7080     }
7081   
7082   dump_end (TDI_class, stream);
7083 }
7084
7085 /* Virtual function table initialization.  */
7086
7087 /* Create all the necessary vtables for T and its base classes.  */
7088
7089 static void
7090 finish_vtbls (t)
7091      tree t;
7092 {
7093   if (merge_primary_and_secondary_vtables_p ())
7094     {
7095       tree list;
7096       tree vbase;
7097
7098       /* Under the new ABI, we lay out the primary and secondary
7099          vtables in one contiguous vtable.  The primary vtable is
7100          first, followed by the non-virtual secondary vtables in
7101          inheritance graph order.  */
7102       list = build_tree_list (TYPE_BINFO_VTABLE (t), NULL_TREE);
7103       accumulate_vtbl_inits (TYPE_BINFO (t), TYPE_BINFO (t),
7104                              TYPE_BINFO (t), t, list);
7105       /* Then come the virtual bases, also in inheritance graph
7106          order.  */
7107       for (vbase = TYPE_BINFO (t); vbase; vbase = TREE_CHAIN (vbase))
7108         {
7109           tree real_base;
7110           
7111           if (!TREE_VIA_VIRTUAL (vbase))
7112             continue;
7113           
7114           /* Although we walk in inheritance order, that might not get the
7115              canonical base.  */
7116           real_base = binfo_for_vbase (BINFO_TYPE (vbase), t);
7117           
7118           accumulate_vtbl_inits (real_base, real_base,
7119                                  TYPE_BINFO (t), t, list);
7120         }
7121
7122       if (TYPE_BINFO_VTABLE (t))
7123         initialize_vtable (TYPE_BINFO (t), TREE_VALUE (list));
7124     }
7125   else
7126     {
7127       dfs_walk (TYPE_BINFO (t), dfs_finish_vtbls, 
7128                 dfs_unmarked_real_bases_queue_p, t);
7129       dfs_walk (TYPE_BINFO (t), dfs_unmark, 
7130                 dfs_marked_real_bases_queue_p, t);
7131     }
7132 }
7133
7134 /* Called from finish_vtbls via dfs_walk.  */
7135
7136 static tree
7137 dfs_finish_vtbls (binfo, data)
7138      tree binfo;
7139      void *data;
7140 {
7141   tree t = (tree) data;
7142
7143   if (BINFO_NEW_VTABLE_MARKED (binfo, t))
7144     initialize_vtable (binfo, 
7145                        build_vtbl_initializer (binfo, binfo, t, 
7146                                                TYPE_BINFO (t), NULL));
7147
7148   SET_BINFO_MARKED (binfo);
7149
7150   return NULL_TREE;
7151 }
7152
7153 /* Initialize the vtable for BINFO with the INITS.  */
7154
7155 static void
7156 initialize_vtable (binfo, inits)
7157      tree binfo;
7158      tree inits;
7159 {
7160   tree decl;
7161
7162   layout_vtable_decl (binfo, list_length (inits));
7163   decl = get_vtbl_decl_for_binfo (binfo);
7164   initialize_array (decl, inits);
7165   dump_vtable (BINFO_TYPE (binfo), binfo, decl);
7166 }
7167
7168 /* Initialize DECL (a declaration for a namespace-scope array) with
7169    the INITS.  */
7170
7171 static void
7172 initialize_array (decl, inits)
7173   tree decl;
7174   tree inits;
7175 {
7176   tree context;
7177
7178   context = DECL_CONTEXT (decl);
7179   DECL_CONTEXT (decl) = NULL_TREE;
7180   DECL_INITIAL (decl) = build_nt (CONSTRUCTOR, NULL_TREE, inits);
7181   cp_finish_decl (decl, DECL_INITIAL (decl), NULL_TREE, 0);
7182   DECL_CONTEXT (decl) = context;
7183 }
7184
7185 /* Build the VTT (virtual table table) for T.
7186    A class requires a VTT if it has virtual bases.
7187    
7188    This holds
7189    1 - primary virtual pointer for complete object T
7190    2 - secondary VTTs for each direct non-virtual base of T which requires a
7191        VTT
7192    3 - secondary virtual pointers for each direct or indirect base of T which
7193        has virtual bases or is reachable via a virtual path from T.
7194    4 - secondary VTTs for each direct or indirect virtual base of T.
7195    
7196    Secondary VTTs look like complete object VTTs without part 4.  */
7197
7198 static void
7199 build_vtt (t)
7200      tree t;
7201 {
7202   tree inits;
7203   tree type;
7204   tree vtt;
7205   tree index;
7206
7207   /* Build up the initializers for the VTT.  */
7208   inits = NULL_TREE;
7209   index = size_zero_node;
7210   build_vtt_inits (TYPE_BINFO (t), t, &inits, &index);
7211
7212   /* If we didn't need a VTT, we're done.  */
7213   if (!inits)
7214     return;
7215
7216   /* Figure out the type of the VTT.  */
7217   type = build_index_type (size_int (list_length (inits) - 1));
7218   type = build_cplus_array_type (const_ptr_type_node, type);
7219                                  
7220   /* Now, build the VTT object itself.  */
7221   vtt = build_vtable (t, get_vtt_name (t), type);
7222   pushdecl_top_level (vtt);
7223   initialize_array (vtt, inits);
7224
7225   dump_vtt (t, vtt);
7226 }
7227
7228 /* The type corresponding to BASE_BINFO is a base of the type of BINFO, but
7229    from within some heirarchy which is inherited from the type of BINFO.
7230    Return BASE_BINFO's equivalent binfo from the hierarchy dominated by
7231    BINFO.  */
7232
7233 static tree
7234 get_original_base (base_binfo, binfo)
7235      tree base_binfo;
7236      tree binfo;
7237 {
7238   tree derived;
7239   int ix;
7240   
7241   if (same_type_p (BINFO_TYPE (base_binfo), BINFO_TYPE (binfo)))
7242     return binfo;
7243   if (TREE_VIA_VIRTUAL (base_binfo))
7244     return binfo_for_vbase (BINFO_TYPE (base_binfo), BINFO_TYPE (binfo));
7245   derived = get_original_base (BINFO_INHERITANCE_CHAIN (base_binfo), binfo);
7246   
7247   for (ix = 0; ix != BINFO_N_BASETYPES (derived); ix++)
7248     if (same_type_p (BINFO_TYPE (base_binfo),
7249                      BINFO_TYPE (BINFO_BASETYPE (derived, ix))))
7250       return BINFO_BASETYPE (derived, ix);
7251   my_friendly_abort (20010223);
7252   return NULL;
7253 }
7254
7255 /* When building a secondary VTT, BINFO_VTABLE is set to a TREE_LIST with
7256    PURPOSE the RTTI_BINFO, VALUE the real vtable pointer for this binfo,
7257    and CHAIN the vtable pointer for this binfo after construction is
7258    complete.  VALUE can also be another BINFO, in which case we recurse. */
7259
7260 static tree
7261 binfo_ctor_vtable (binfo)
7262      tree binfo;
7263 {
7264   tree vt;
7265
7266   while (1)
7267     {
7268       vt = BINFO_VTABLE (binfo);
7269       if (TREE_CODE (vt) == TREE_LIST)
7270         vt = TREE_VALUE (vt);
7271       if (TREE_CODE (vt) == TREE_VEC)
7272         binfo = vt;
7273       else
7274         break;
7275     }
7276
7277   return vt;
7278 }
7279
7280 /* Recursively build the VTT-initializer for BINFO (which is in the
7281    hierarchy dominated by T).  INITS points to the end of the initializer
7282    list to date.  INDEX is the VTT index where the next element will be
7283    replaced.  Iff BINFO is the binfo for T, this is the top level VTT (i.e.
7284    not a subvtt for some base of T).  When that is so, we emit the sub-VTTs
7285    for virtual bases of T. When it is not so, we build the constructor
7286    vtables for the BINFO-in-T variant.  */
7287
7288 static tree *
7289 build_vtt_inits (binfo, t, inits, index)
7290      tree binfo;
7291      tree t;
7292      tree *inits;
7293      tree *index;
7294 {
7295   int i;
7296   tree b;
7297   tree init;
7298   tree secondary_vptrs;
7299   int top_level_p = same_type_p (TREE_TYPE (binfo), t);
7300
7301   /* We only need VTTs for subobjects with virtual bases.  */
7302   if (!TYPE_USES_VIRTUAL_BASECLASSES (BINFO_TYPE (binfo)))
7303     return inits;
7304
7305   /* We need to use a construction vtable if this is not the primary
7306      VTT.  */
7307   if (!top_level_p)
7308     {
7309       build_ctor_vtbl_group (binfo, t);
7310
7311       /* Record the offset in the VTT where this sub-VTT can be found.  */
7312       BINFO_SUBVTT_INDEX (binfo) = *index;
7313     }
7314
7315   /* Add the address of the primary vtable for the complete object.  */
7316   init = binfo_ctor_vtable (binfo);
7317   *inits = build_tree_list (NULL_TREE, init);
7318   inits = &TREE_CHAIN (*inits);
7319   if (top_level_p)
7320     {
7321       my_friendly_assert (!BINFO_VPTR_INDEX (binfo), 20010129);
7322       BINFO_VPTR_INDEX (binfo) = *index;
7323     }
7324   *index = size_binop (PLUS_EXPR, *index, TYPE_SIZE_UNIT (ptr_type_node));
7325                        
7326   /* Recursively add the secondary VTTs for non-virtual bases.  */
7327   for (i = 0; i < BINFO_N_BASETYPES (binfo); ++i)
7328     {
7329       b = BINFO_BASETYPE (binfo, i);
7330       if (!TREE_VIA_VIRTUAL (b))
7331         inits = build_vtt_inits (BINFO_BASETYPE (binfo, i), t, 
7332                                  inits, index);
7333     }
7334       
7335   /* Add secondary virtual pointers for all subobjects of BINFO with
7336      either virtual bases or reachable along a virtual path, except
7337      subobjects that are non-virtual primary bases.  */
7338   secondary_vptrs = tree_cons (t, NULL_TREE, BINFO_TYPE (binfo));
7339   TREE_TYPE (secondary_vptrs) = *index;
7340   VTT_TOP_LEVEL_P (secondary_vptrs) = top_level_p;
7341   VTT_MARKED_BINFO_P (secondary_vptrs) = 0;
7342   
7343   dfs_walk_real (binfo,
7344                  dfs_build_secondary_vptr_vtt_inits,
7345                  NULL,
7346                  dfs_ctor_vtable_bases_queue_p,
7347                  secondary_vptrs);
7348   VTT_MARKED_BINFO_P (secondary_vptrs) = 1;
7349   dfs_walk (binfo, dfs_unmark, dfs_ctor_vtable_bases_queue_p,
7350             secondary_vptrs);
7351
7352   *index = TREE_TYPE (secondary_vptrs);
7353
7354   /* The secondary vptrs come back in reverse order.  After we reverse
7355      them, and add the INITS, the last init will be the first element
7356      of the chain.  */
7357   secondary_vptrs = TREE_VALUE (secondary_vptrs);
7358   if (secondary_vptrs)
7359     {
7360       *inits = nreverse (secondary_vptrs);
7361       inits = &TREE_CHAIN (secondary_vptrs);
7362       my_friendly_assert (*inits == NULL_TREE, 20000517);
7363     }
7364
7365   /* Add the secondary VTTs for virtual bases.  */
7366   if (top_level_p)
7367     for (b = TYPE_BINFO (BINFO_TYPE (binfo)); b; b = TREE_CHAIN (b))
7368       {
7369         tree vbase;
7370         
7371         if (!TREE_VIA_VIRTUAL (b))
7372           continue;
7373         
7374         vbase = binfo_for_vbase (BINFO_TYPE (b), t);
7375         inits = build_vtt_inits (vbase, t, inits, index);
7376       }
7377
7378   if (!top_level_p)
7379     {
7380       tree data = tree_cons (t, binfo, NULL_TREE);
7381       VTT_TOP_LEVEL_P (data) = 0;
7382       VTT_MARKED_BINFO_P (data) = 0;
7383       
7384       dfs_walk (binfo, dfs_fixup_binfo_vtbls,
7385                 dfs_ctor_vtable_bases_queue_p,
7386                 data);
7387     }
7388
7389   return inits;
7390 }
7391
7392 /* Called from build_vtt_inits via dfs_walk.  BINFO is the binfo
7393    for the base in most derived. DATA is a TREE_LIST who's
7394    TREE_CHAIN is the type of the base being
7395    constructed whilst this secondary vptr is live.  The TREE_UNSIGNED
7396    flag of DATA indicates that this is a constructor vtable.  The
7397    TREE_TOP_LEVEL flag indicates that this is the primary VTT.  */
7398
7399 static tree
7400 dfs_build_secondary_vptr_vtt_inits (binfo, data)
7401      tree binfo;
7402      void *data;
7403 {
7404   tree l; 
7405   tree t;
7406   tree init;
7407   tree index;
7408   int top_level_p;
7409
7410   l = (tree) data;
7411   t = TREE_CHAIN (l);
7412   top_level_p = VTT_TOP_LEVEL_P (l);
7413   
7414   SET_BINFO_MARKED (binfo);
7415
7416   /* We don't care about bases that don't have vtables.  */
7417   if (!TYPE_VFIELD (BINFO_TYPE (binfo)))
7418     return NULL_TREE;
7419
7420   /* We're only interested in proper subobjects of T.  */
7421   if (same_type_p (BINFO_TYPE (binfo), t))
7422     return NULL_TREE;
7423
7424   /* We're not interested in non-virtual primary bases.  */
7425   if (!TREE_VIA_VIRTUAL (binfo) && BINFO_PRIMARY_P (binfo))
7426     return NULL_TREE;
7427
7428   /* If BINFO has virtual bases or is reachable via a virtual path
7429      from T, it'll have a secondary vptr.  */
7430   if (!TYPE_USES_VIRTUAL_BASECLASSES (BINFO_TYPE (binfo))
7431       && !binfo_via_virtual (binfo, t))
7432     return NULL_TREE;
7433
7434   /* Record the index where this secondary vptr can be found.  */
7435   index = TREE_TYPE (l);
7436   if (top_level_p)
7437     {
7438       my_friendly_assert (!BINFO_VPTR_INDEX (binfo), 20010129);
7439       BINFO_VPTR_INDEX (binfo) = index;
7440     }
7441   TREE_TYPE (l) = size_binop (PLUS_EXPR, index, 
7442                               TYPE_SIZE_UNIT (ptr_type_node));
7443
7444   /* Add the initializer for the secondary vptr itself.  */
7445   if (top_level_p && TREE_VIA_VIRTUAL (binfo))
7446     {
7447       /* It's a primary virtual base, and this is not the construction
7448          vtable. Find the base this is primary of in the inheritance graph,
7449          and use that base's vtable now. */
7450       while (BINFO_PRIMARY_BASE_OF (binfo))
7451         binfo = BINFO_PRIMARY_BASE_OF (binfo);
7452     }
7453   init = binfo_ctor_vtable (binfo);
7454   TREE_VALUE (l) = tree_cons (NULL_TREE, init, TREE_VALUE (l));
7455
7456   return NULL_TREE;
7457 }
7458
7459 /* dfs_walk_real predicate for building vtables. DATA is a TREE_LIST,
7460    TREE_UNSIGNED indicates that a constructor vtable is being built.
7461    TREE_USED indicates whether marked or unmarked bases should be walked.
7462    TREE_PURPOSE is the TREE_TYPE that dominates the hierarchy.  */
7463
7464 static tree
7465 dfs_ctor_vtable_bases_queue_p (binfo, data)
7466      tree binfo;
7467      void *data;
7468 {
7469   if (TREE_VIA_VIRTUAL (binfo) && !BINFO_PRIMARY_P (binfo))
7470     {
7471       tree type = TREE_PURPOSE ((tree) data);
7472
7473       /* This is a non-primary virtual base, get the shared version.  */
7474       binfo = binfo_for_vbase (BINFO_TYPE (binfo), type);
7475       if (VTT_TOP_LEVEL_P ((tree) data) && BINFO_PRIMARY_P (binfo))
7476         return NULL_TREE;
7477     }
7478   if (!BINFO_MARKED (binfo) == VTT_MARKED_BINFO_P ((tree) data))
7479     return NULL_TREE;
7480   return binfo;
7481 }
7482
7483 /* Called from build_vtt_inits via dfs_walk. After building constructor
7484    vtables and generating the sub-vtt from them, we need to restore the
7485    BINFO_VTABLES that were scribbled on.  DATA is a TREE_LIST whose
7486    TREE_VALUE is the TREE_TYPE of the base whose sub vtt was generated.  */
7487
7488 static tree
7489 dfs_fixup_binfo_vtbls (binfo, data)
7490      tree binfo;
7491      void *data;
7492 {
7493   CLEAR_BINFO_MARKED (binfo);
7494
7495   /* We don't care about bases that don't have vtables.  */
7496   if (!TYPE_VFIELD (BINFO_TYPE (binfo)))
7497     return NULL_TREE;
7498
7499   /* If we scribbled the construction vtable vptr into BINFO, clear it
7500      out now.  */
7501   if (BINFO_VTABLE (binfo)
7502       && TREE_CODE (BINFO_VTABLE (binfo)) == TREE_LIST
7503       && (TREE_PURPOSE (BINFO_VTABLE (binfo)) 
7504           == TREE_VALUE ((tree) data)))
7505     BINFO_VTABLE (binfo) = TREE_CHAIN (BINFO_VTABLE (binfo));
7506
7507   return NULL_TREE;
7508 }
7509
7510 /* Build the construction vtable group for BINFO which is in the
7511    hierarchy dominated by T.  */
7512
7513 static void
7514 build_ctor_vtbl_group (binfo, t)
7515      tree binfo;
7516      tree t;
7517 {
7518   tree list;
7519   tree type;
7520   tree vtbl;
7521   tree inits;
7522   tree id;
7523   tree vbase;
7524
7525   /* See if we've already created this construction vtable group.  */
7526   id = mangle_ctor_vtbl_for_type (t, binfo);
7527   if (IDENTIFIER_GLOBAL_VALUE (id))
7528     return;
7529
7530   my_friendly_assert (!same_type_p (BINFO_TYPE (binfo), t), 20010124);
7531   /* Build a version of VTBL (with the wrong type) for use in
7532      constructing the addresses of secondary vtables in the
7533      construction vtable group.  */
7534   vtbl = build_vtable (t, id, ptr_type_node);
7535   list = build_tree_list (vtbl, NULL_TREE);
7536   accumulate_vtbl_inits (binfo, TYPE_BINFO (TREE_TYPE (binfo)),
7537                          binfo, t, list);
7538
7539   /* Add the vtables for each of our virtual bases using the vbase in T
7540      binfo.  */
7541   for (vbase = TYPE_BINFO (BINFO_TYPE (binfo)); 
7542        vbase; 
7543        vbase = TREE_CHAIN (vbase))
7544     {
7545       tree b;
7546       tree orig_base;
7547
7548       if (!TREE_VIA_VIRTUAL (vbase))
7549         continue;
7550       b = binfo_for_vbase (BINFO_TYPE (vbase), t);
7551       orig_base = binfo_for_vbase (BINFO_TYPE (vbase), BINFO_TYPE (binfo));
7552       
7553       accumulate_vtbl_inits (b, orig_base, binfo, t, list);
7554     }
7555   inits = TREE_VALUE (list);
7556
7557   /* Figure out the type of the construction vtable.  */
7558   type = build_index_type (size_int (list_length (inits) - 1));
7559   type = build_cplus_array_type (vtable_entry_type, type);
7560   TREE_TYPE (vtbl) = type;
7561
7562   /* Initialize the construction vtable.  */
7563   pushdecl_top_level (vtbl);
7564   initialize_array (vtbl, inits);
7565   dump_vtable (t, binfo, vtbl);
7566 }
7567
7568 /* Add the vtbl initializers for BINFO (and its bases other than
7569    non-virtual primaries) to the list of INITS.  BINFO is in the
7570    hierarchy dominated by T.  RTTI_BINFO is the binfo within T of
7571    the constructor the vtbl inits should be accumulated for. (If this
7572    is the complete object vtbl then RTTI_BINFO will be TYPE_BINFO (T).)
7573    ORIG_BINFO is the binfo for this object within BINFO_TYPE (RTTI_BINFO).
7574    BINFO is the active base equivalent of ORIG_BINFO in the inheritance
7575    graph of T. Both BINFO and ORIG_BINFO will have the same BINFO_TYPE,
7576    but are not necessarily the same in terms of layout.  */
7577
7578 static void
7579 accumulate_vtbl_inits (binfo, orig_binfo, rtti_binfo, t, inits)
7580      tree binfo;
7581      tree orig_binfo;
7582      tree rtti_binfo;
7583      tree t;
7584      tree inits;
7585 {
7586   int i;
7587   int ctor_vtbl_p = !same_type_p (BINFO_TYPE (rtti_binfo), t);
7588
7589   my_friendly_assert (same_type_p (BINFO_TYPE (binfo),
7590                                    BINFO_TYPE (orig_binfo)),
7591                       20000517);
7592
7593   /* If it doesn't have a vptr, we don't do anything. */
7594   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
7595     return;
7596   
7597   /* If we're building a construction vtable, we're not interested in
7598      subobjects that don't require construction vtables.  */
7599   if (ctor_vtbl_p 
7600       && !TYPE_USES_VIRTUAL_BASECLASSES (BINFO_TYPE (binfo))
7601       && !binfo_via_virtual (orig_binfo, BINFO_TYPE (rtti_binfo)))
7602     return;
7603
7604   /* Build the initializers for the BINFO-in-T vtable.  */
7605   TREE_VALUE (inits) 
7606     = chainon (TREE_VALUE (inits),
7607                dfs_accumulate_vtbl_inits (binfo, orig_binfo,
7608                                           rtti_binfo, t, inits));
7609                       
7610   /* Walk the BINFO and its bases.  We walk in preorder so that as we
7611      initialize each vtable we can figure out at what offset the
7612      secondary vtable lies from the primary vtable.  We can't use
7613      dfs_walk here because we need to iterate through bases of BINFO
7614      and RTTI_BINFO simultaneously.  */
7615   for (i = 0; i < BINFO_N_BASETYPES (binfo); ++i)
7616     {
7617       tree base_binfo = BINFO_BASETYPE (binfo, i);
7618       
7619       /* Skip virtual bases.  */
7620       if (TREE_VIA_VIRTUAL (base_binfo))
7621         continue;
7622       accumulate_vtbl_inits (base_binfo,
7623                              BINFO_BASETYPE (orig_binfo, i),
7624                              rtti_binfo, t,
7625                              inits);
7626     }
7627 }
7628
7629 /* Called from accumulate_vtbl_inits when using the new ABI.
7630    Accumulates the vtable initializers for all of the vtables into
7631    TREE_VALUE (DATA).  Returns the initializers for the BINFO vtable.  */
7632
7633 static tree
7634 dfs_accumulate_vtbl_inits (binfo, orig_binfo, rtti_binfo, t, l)
7635      tree binfo;
7636      tree orig_binfo;
7637      tree rtti_binfo;
7638      tree t;
7639      tree l;
7640 {
7641   tree inits = NULL_TREE;
7642   tree vtbl = NULL_TREE;
7643   int ctor_vtbl_p = !same_type_p (BINFO_TYPE (rtti_binfo), t);
7644
7645   if (ctor_vtbl_p
7646       && TREE_VIA_VIRTUAL (orig_binfo) && BINFO_PRIMARY_P (orig_binfo))
7647     {
7648       /* In the hierarchy of BINFO_TYPE (RTTI_BINFO), this is a
7649          primary virtual base.  If it is not the same primary in
7650          the hierarchy of T, we'll need to generate a ctor vtable
7651          for it, to place at its location in T.  If it is the same
7652          primary, we still need a VTT entry for the vtable, but it
7653          should point to the ctor vtable for the base it is a
7654          primary for within the sub-hierarchy of RTTI_BINFO.
7655               
7656          There are three possible cases:
7657               
7658          1) We are in the same place.
7659          2) We are a primary base within a lost primary virtual base of
7660          RTTI_BINFO.
7661          3) We are primary to something not a base of RTTI_BINFO.  */
7662           
7663       tree b = BINFO_PRIMARY_BASE_OF (binfo);
7664       tree last = NULL_TREE;
7665
7666       /* First, look through the bases we are primary to for RTTI_BINFO
7667          or a virtual base.  */
7668       for (; b; b = BINFO_PRIMARY_BASE_OF (b))
7669         {
7670           last = b;
7671           if (TREE_VIA_VIRTUAL (b) || b == rtti_binfo)
7672             break;
7673         }
7674       /* If we run out of primary links, keep looking down our
7675          inheritance chain; we might be an indirect primary.  */
7676       if (b == NULL_TREE)
7677         for (b = last; b; b = BINFO_INHERITANCE_CHAIN (b))
7678           if (TREE_VIA_VIRTUAL (b) || b == rtti_binfo)
7679             break;
7680
7681       /* If we found RTTI_BINFO, this is case 1.  If we found a virtual
7682          base B and it is a base of RTTI_BINFO, this is case 2.  In
7683          either case, we share our vtable with LAST, i.e. the
7684          derived-most base within B of which we are a primary.  */
7685       if (b == rtti_binfo
7686           || (b && binfo_for_vbase (BINFO_TYPE (b),
7687                                     BINFO_TYPE (rtti_binfo))))
7688         /* Just set our BINFO_VTABLE to point to LAST, as we may not have
7689            set LAST's BINFO_VTABLE yet.  We'll extract the actual vptr in
7690            binfo_ctor_vtable after everything's been set up.  */
7691         vtbl = last;
7692
7693       /* Otherwise, this is case 3 and we get our own.  */
7694     }
7695   else if (!BINFO_NEW_VTABLE_MARKED (orig_binfo, BINFO_TYPE (rtti_binfo)))
7696     return inits;
7697
7698   if (!vtbl)
7699     {
7700       tree index;
7701       int non_fn_entries;
7702
7703       /* Compute the initializer for this vtable.  */
7704       inits = build_vtbl_initializer (binfo, orig_binfo, t, rtti_binfo,
7705                                       &non_fn_entries);
7706
7707       /* Figure out the position to which the VPTR should point.  */
7708       vtbl = TREE_PURPOSE (l);
7709       vtbl = build1 (ADDR_EXPR, 
7710                      vtbl_ptr_type_node,
7711                      vtbl);
7712       TREE_CONSTANT (vtbl) = 1;
7713       index = size_binop (PLUS_EXPR,
7714                           size_int (non_fn_entries),
7715                           size_int (list_length (TREE_VALUE (l))));
7716       index = size_binop (MULT_EXPR,
7717                           TYPE_SIZE_UNIT (vtable_entry_type),
7718                           index);
7719       vtbl = build (PLUS_EXPR, TREE_TYPE (vtbl), vtbl, index);
7720       TREE_CONSTANT (vtbl) = 1;
7721     }
7722
7723   if (ctor_vtbl_p)
7724     /* For a construction vtable, we can't overwrite BINFO_VTABLE.
7725        So, we make a TREE_LIST.  Later, dfs_fixup_binfo_vtbls will
7726        straighten this out.  */
7727     BINFO_VTABLE (binfo) = tree_cons (rtti_binfo, vtbl, BINFO_VTABLE (binfo));
7728   else if (BINFO_PRIMARY_P (binfo) && TREE_VIA_VIRTUAL (binfo))
7729     inits = NULL_TREE;
7730   else
7731      /* For an ordinary vtable, set BINFO_VTABLE.  */
7732     BINFO_VTABLE (binfo) = vtbl;
7733
7734   return inits;
7735 }
7736
7737 /* Construct the initializer for BINFO's virtual function table.  BINFO
7738    is part of the hierarchy dominated by T.  If we're building a
7739    construction vtable, the ORIG_BINFO is the binfo we should use to
7740    find the actual function pointers to put in the vtable - but they
7741    can be overridden on the path to most-derived in the graph that
7742    ORIG_BINFO belongs.  Otherwise,
7743    ORIG_BINFO should be the same as BINFO.  The RTTI_BINFO is the
7744    BINFO that should be indicated by the RTTI information in the
7745    vtable; it will be a base class of T, rather than T itself, if we
7746    are building a construction vtable.
7747
7748    The value returned is a TREE_LIST suitable for wrapping in a
7749    CONSTRUCTOR to use as the DECL_INITIAL for a vtable.  If
7750    NON_FN_ENTRIES_P is not NULL, *NON_FN_ENTRIES_P is set to the
7751    number of non-function entries in the vtable.  
7752
7753    It might seem that this function should never be called with a
7754    BINFO for which BINFO_PRIMARY_P holds, the vtable for such a
7755    base is always subsumed by a derived class vtable.  However, when
7756    we are building construction vtables, we do build vtables for
7757    primary bases; we need these while the primary base is being
7758    constructed.  */
7759
7760 static tree
7761 build_vtbl_initializer (binfo, orig_binfo, t, rtti_binfo, non_fn_entries_p)
7762      tree binfo;
7763      tree orig_binfo;
7764      tree t;
7765      tree rtti_binfo;
7766      int *non_fn_entries_p;
7767 {
7768   tree v, b;
7769   tree vfun_inits;
7770   tree vbase;
7771   vtbl_init_data vid;
7772
7773   /* Initialize VID.  */
7774   memset (&vid, 0, sizeof (vid));
7775   vid.binfo = binfo;
7776   vid.derived = t;
7777   vid.rtti_binfo = rtti_binfo;
7778   vid.last_init = &vid.inits;
7779   vid.primary_vtbl_p = (binfo == TYPE_BINFO (t));
7780   vid.ctor_vtbl_p = !same_type_p (BINFO_TYPE (rtti_binfo), t);
7781   /* The first vbase or vcall offset is at index -3 in the vtable.  */
7782   vid.index = ssize_int (-3);
7783
7784   /* Add entries to the vtable for RTTI.  */
7785   build_rtti_vtbl_entries (binfo, &vid);
7786
7787   /* Create an array for keeping track of the functions we've
7788      processed.  When we see multiple functions with the same
7789      signature, we share the vcall offsets.  */
7790   VARRAY_TREE_INIT (vid.fns, 32, "fns");
7791   /* Add the vcall and vbase offset entries.  */
7792   build_vcall_and_vbase_vtbl_entries (binfo, &vid);
7793   /* Clean up.  */
7794   VARRAY_FREE (vid.fns);
7795   /* Clear BINFO_VTABLE_PATH_MARKED; it's set by
7796      build_vbase_offset_vtbl_entries.  */
7797   for (vbase = CLASSTYPE_VBASECLASSES (t); 
7798        vbase; 
7799        vbase = TREE_CHAIN (vbase))
7800     CLEAR_BINFO_VTABLE_PATH_MARKED (TREE_VALUE (vbase));
7801
7802   if (non_fn_entries_p)
7803     *non_fn_entries_p = list_length (vid.inits);
7804
7805   /* Go through all the ordinary virtual functions, building up
7806      initializers.  */
7807   vfun_inits = NULL_TREE;
7808   for (v = BINFO_VIRTUALS (orig_binfo); v; v = TREE_CHAIN (v))
7809     {
7810       tree delta;
7811       tree vcall_index;
7812       tree fn;
7813       tree pfn;
7814       tree init;
7815       
7816       /* Pull the offset for `this', and the function to call, out of
7817          the list.  */
7818       delta = BV_DELTA (v);
7819
7820       if (BV_USE_VCALL_INDEX_P (v))
7821         {
7822           vcall_index = BV_VCALL_INDEX (v);
7823           my_friendly_assert (vcall_index != NULL_TREE, 20000621);
7824         }
7825       else
7826         vcall_index = NULL_TREE;
7827
7828       fn = BV_FN (v);
7829       my_friendly_assert (TREE_CODE (delta) == INTEGER_CST, 19990727);
7830       my_friendly_assert (TREE_CODE (fn) == FUNCTION_DECL, 19990727);
7831
7832       /* You can't call an abstract virtual function; it's abstract.
7833          So, we replace these functions with __pure_virtual.  */
7834       if (DECL_PURE_VIRTUAL_P (fn))
7835         fn = abort_fndecl;
7836
7837       /* Take the address of the function, considering it to be of an
7838          appropriate generic type.  */
7839       pfn = build1 (ADDR_EXPR, vfunc_ptr_type_node, fn);
7840       /* The address of a function can't change.  */
7841       TREE_CONSTANT (pfn) = 1;
7842
7843       /* Enter it in the vtable.  */
7844       init = build_vtable_entry (delta, vcall_index, pfn);
7845
7846       /* If the only definition of this function signature along our
7847          primary base chain is from a lost primary, this vtable slot will
7848          never be used, so just zero it out.  This is important to avoid
7849          requiring extra thunks which cannot be generated with the function.
7850
7851          We could also handle this in update_vtable_entry_for_fn; doing it
7852          here means we zero out unused slots in ctor vtables as well,
7853          rather than filling them with erroneous values (though harmless,
7854          apart from relocation costs).  */
7855       if (fn != abort_fndecl)
7856         for (b = binfo; ; b = get_primary_binfo (b))
7857           {
7858             /* We found a defn before a lost primary; go ahead as normal.  */
7859             if (look_for_overrides_here (BINFO_TYPE (b), fn))
7860               break;
7861
7862             /* The nearest definition is from a lost primary; clear the
7863                slot.  */
7864             if (BINFO_LOST_PRIMARY_P (b))
7865               {
7866                 init = size_zero_node;
7867                 break;
7868               }
7869           }
7870
7871       /* And add it to the chain of initializers.  */
7872       vfun_inits = tree_cons (NULL_TREE, init, vfun_inits);
7873     }
7874
7875   /* The initializers for virtual functions were built up in reverse
7876      order; straighten them out now.  */
7877   vfun_inits = nreverse (vfun_inits);
7878   
7879   /* The negative offset initializers are also in reverse order.  */
7880   vid.inits = nreverse (vid.inits);
7881
7882   /* Chain the two together.  */
7883   return chainon (vid.inits, vfun_inits);
7884 }
7885
7886 /* Adds to vid->inits the initializers for the vbase and vcall
7887    offsets in BINFO, which is in the hierarchy dominated by T.  */
7888
7889 static void
7890 build_vcall_and_vbase_vtbl_entries (binfo, vid)
7891      tree binfo;
7892      vtbl_init_data *vid;
7893 {
7894   tree b;
7895
7896   /* If this is a derived class, we must first create entries
7897      corresponding to the primary base class.  */
7898   b = get_primary_binfo (binfo);
7899   if (b)
7900     build_vcall_and_vbase_vtbl_entries (b, vid);
7901
7902   /* Add the vbase entries for this base.  */
7903   build_vbase_offset_vtbl_entries (binfo, vid);
7904   /* Add the vcall entries for this base.  */
7905   build_vcall_offset_vtbl_entries (binfo, vid);
7906 }
7907
7908 /* Returns the initializers for the vbase offset entries in the vtable
7909    for BINFO (which is part of the class hierarchy dominated by T), in
7910    reverse order.  VBASE_OFFSET_INDEX gives the vtable index
7911    where the next vbase offset will go.  */
7912
7913 static void
7914 build_vbase_offset_vtbl_entries (binfo, vid)
7915      tree binfo;
7916      vtbl_init_data *vid;
7917 {
7918   tree vbase;
7919   tree t;
7920
7921   /* Under the old ABI, pointers to virtual bases are stored in each
7922      object.  */
7923   if (!vbase_offsets_in_vtable_p ())
7924     return;
7925
7926   /* If there are no virtual baseclasses, then there is nothing to
7927      do.  */
7928   if (!TYPE_USES_VIRTUAL_BASECLASSES (BINFO_TYPE (binfo)))
7929     return;
7930
7931   t = vid->derived;
7932
7933   /* Go through the virtual bases, adding the offsets.  */
7934   for (vbase = TYPE_BINFO (BINFO_TYPE (binfo));
7935        vbase;
7936        vbase = TREE_CHAIN (vbase))
7937     {
7938       tree b;
7939       tree delta;
7940       
7941       if (!TREE_VIA_VIRTUAL (vbase))
7942         continue;
7943
7944       /* Find the instance of this virtual base in the complete
7945          object.  */
7946       b = binfo_for_vbase (BINFO_TYPE (vbase), t);
7947
7948       /* If we've already got an offset for this virtual base, we
7949          don't need another one.  */
7950       if (BINFO_VTABLE_PATH_MARKED (b))
7951         continue;
7952       SET_BINFO_VTABLE_PATH_MARKED (b);
7953
7954       /* Figure out where we can find this vbase offset.  */
7955       delta = size_binop (MULT_EXPR, 
7956                           vid->index,
7957                           convert (ssizetype,
7958                                    TYPE_SIZE_UNIT (vtable_entry_type)));
7959       if (vid->primary_vtbl_p)
7960         BINFO_VPTR_FIELD (b) = delta;
7961
7962       if (binfo != TYPE_BINFO (t))
7963         {
7964           tree orig_vbase;
7965
7966           /* Find the instance of this virtual base in the type of BINFO.  */
7967           orig_vbase = binfo_for_vbase (BINFO_TYPE (vbase),
7968                                         BINFO_TYPE (binfo));
7969
7970           /* The vbase offset had better be the same.  */
7971           if (!tree_int_cst_equal (delta,
7972                                    BINFO_VPTR_FIELD (orig_vbase)))
7973             my_friendly_abort (20000403);
7974         }
7975
7976       /* The next vbase will come at a more negative offset.  */
7977       vid->index = size_binop (MINUS_EXPR, vid->index, ssize_int (1));
7978
7979       /* The initializer is the delta from BINFO to this virtual base.
7980          The vbase offsets go in reverse inheritance-graph order, and
7981          we are walking in inheritance graph order so these end up in
7982          the right order.  */
7983       delta = size_diffop (BINFO_OFFSET (b), BINFO_OFFSET (binfo));
7984       *vid->last_init 
7985         = build_tree_list (NULL_TREE,
7986                            fold (build1 (NOP_EXPR, 
7987                                          vtable_entry_type,
7988                                          delta)));
7989       vid->last_init = &TREE_CHAIN (*vid->last_init);
7990     }
7991 }
7992
7993 /* Adds the initializers for the vcall offset entries in the vtable
7994    for BINFO (which is part of the class hierarchy dominated by VID->DERIVED)
7995    to VID->INITS.  */
7996
7997 static void
7998 build_vcall_offset_vtbl_entries (binfo, vid)
7999      tree binfo;
8000      vtbl_init_data *vid;
8001 {
8002   /* Under the old ABI, the adjustments to the `this' pointer were made
8003      elsewhere.  */
8004   if (!vcall_offsets_in_vtable_p ())
8005     return;
8006
8007   /* We only need these entries if this base is a virtual base.  */
8008   if (!TREE_VIA_VIRTUAL (binfo))
8009     return;
8010
8011   /* We need a vcall offset for each of the virtual functions in this
8012      vtable.  For example:
8013
8014        class A { virtual void f (); };
8015        class B1 : virtual public A { virtual void f (); };
8016        class B2 : virtual public A { virtual void f (); };
8017        class C: public B1, public B2 { virtual void f (); };
8018
8019      A C object has a primary base of B1, which has a primary base of A.  A
8020      C also has a secondary base of B2, which no longer has a primary base
8021      of A.  So the B2-in-C construction vtable needs a secondary vtable for
8022      A, which will adjust the A* to a B2* to call f.  We have no way of
8023      knowing what (or even whether) this offset will be when we define B2,
8024      so we store this "vcall offset" in the A sub-vtable and look it up in
8025      a "virtual thunk" for B2::f.
8026
8027      We need entries for all the functions in our primary vtable and
8028      in our non-virtual bases' secondary vtables.  */
8029   vid->vbase = binfo;
8030   /* Now, walk through the non-virtual bases, adding vcall offsets.  */
8031   add_vcall_offset_vtbl_entries_r (binfo, vid);
8032 }
8033
8034 /* Build vcall offsets, starting with those for BINFO.  */
8035
8036 static void
8037 add_vcall_offset_vtbl_entries_r (binfo, vid)
8038      tree binfo;
8039      vtbl_init_data *vid;
8040 {
8041   int i;
8042   tree primary_binfo;
8043
8044   /* Don't walk into virtual bases -- except, of course, for the
8045      virtual base for which we are building vcall offsets.  Any
8046      primary virtual base will have already had its offsets generated
8047      through the recursion in build_vcall_and_vbase_vtbl_entries.  */
8048   if (TREE_VIA_VIRTUAL (binfo) && vid->vbase != binfo)
8049     return;
8050   
8051   /* If BINFO has a primary base, process it first.  */
8052   primary_binfo = get_primary_binfo (binfo);
8053   if (primary_binfo)
8054     add_vcall_offset_vtbl_entries_r (primary_binfo, vid);
8055
8056   /* Add BINFO itself to the list.  */
8057   add_vcall_offset_vtbl_entries_1 (binfo, vid);
8058
8059   /* Scan the non-primary bases of BINFO.  */
8060   for (i = 0; i < BINFO_N_BASETYPES (binfo); ++i) 
8061     {
8062       tree base_binfo;
8063       
8064       base_binfo = BINFO_BASETYPE (binfo, i);
8065       if (base_binfo != primary_binfo)
8066         add_vcall_offset_vtbl_entries_r (base_binfo, vid);
8067     }
8068 }
8069
8070 /* Called from build_vcall_offset_vtbl_entries_r.  */
8071
8072 static void
8073 add_vcall_offset_vtbl_entries_1 (binfo, vid)
8074      tree binfo;
8075      vtbl_init_data* vid;
8076 {
8077   tree derived_virtuals;
8078   tree base_virtuals;
8079   tree orig_virtuals;
8080   tree binfo_inits;
8081   /* If BINFO is a primary base, the most derived class which has BINFO as
8082      a primary base; otherwise, just BINFO.  */
8083   tree non_primary_binfo;
8084
8085   binfo_inits = NULL_TREE;
8086
8087   /* We might be a primary base class.  Go up the inheritance hierarchy
8088      until we find the most derived class of which we are a primary base:
8089      it is the BINFO_VIRTUALS there that we need to consider.  */
8090   non_primary_binfo = binfo;
8091   while (BINFO_INHERITANCE_CHAIN (non_primary_binfo))
8092     {
8093       tree b;
8094
8095       /* If we have reached a virtual base, then it must be vid->vbase,
8096          because we ignore other virtual bases in
8097          add_vcall_offset_vtbl_entries_r.  In turn, it must be a primary
8098          base (possibly multi-level) of vid->binfo, or we wouldn't
8099          have called build_vcall_and_vbase_vtbl_entries for it.  But it
8100          might be a lost primary, so just skip down to vid->binfo.  */
8101       if (TREE_VIA_VIRTUAL (non_primary_binfo))
8102         {
8103           if (non_primary_binfo != vid->vbase)
8104             abort ();
8105           non_primary_binfo = vid->binfo;
8106           break;
8107         }
8108
8109       b = BINFO_INHERITANCE_CHAIN (non_primary_binfo);
8110       if (get_primary_binfo (b) != non_primary_binfo)
8111         break;
8112       non_primary_binfo = b;
8113     }
8114
8115   if (vid->ctor_vtbl_p)
8116     /* For a ctor vtable we need the equivalent binfo within the hierarchy
8117        where rtti_binfo is the most derived type.  */
8118     non_primary_binfo = get_original_base
8119           (non_primary_binfo, TYPE_BINFO (BINFO_TYPE (vid->rtti_binfo)));
8120
8121   /* Make entries for the rest of the virtuals.  */
8122   for (base_virtuals = BINFO_VIRTUALS (binfo),
8123          derived_virtuals = BINFO_VIRTUALS (non_primary_binfo),
8124          orig_virtuals = BINFO_VIRTUALS (TYPE_BINFO (BINFO_TYPE (binfo)));
8125        base_virtuals;
8126        base_virtuals = TREE_CHAIN (base_virtuals),
8127          derived_virtuals = TREE_CHAIN (derived_virtuals),
8128          orig_virtuals = TREE_CHAIN (orig_virtuals))
8129     {
8130       tree orig_fn;
8131       tree fn;
8132       tree base;
8133       tree base_binfo;
8134       size_t i;
8135       tree vcall_offset;
8136
8137       /* Find the declaration that originally caused this function to
8138          be present in BINFO_TYPE (binfo).  */
8139       orig_fn = BV_FN (orig_virtuals);
8140
8141       /* When processing BINFO, we only want to generate vcall slots for
8142          function slots introduced in BINFO.  So don't try to generate
8143          one if the function isn't even defined in BINFO.  */
8144       if (!same_type_p (DECL_CONTEXT (orig_fn), BINFO_TYPE (binfo)))
8145         continue;
8146
8147       /* Find the overriding function.  */
8148       fn = BV_FN (derived_virtuals);
8149
8150       /* If there is already an entry for a function with the same
8151          signature as FN, then we do not need a second vcall offset.
8152          Check the list of functions already present in the derived
8153          class vtable.  */
8154       for (i = 0; i < VARRAY_ACTIVE_SIZE (vid->fns); ++i) 
8155         {
8156           tree derived_entry;
8157
8158           derived_entry = VARRAY_TREE (vid->fns, i);
8159           if (same_signature_p (BV_FN (derived_entry), fn)
8160               /* We only use one vcall offset for virtual destructors,
8161                  even though there are two virtual table entries.  */
8162               || (DECL_DESTRUCTOR_P (BV_FN (derived_entry))
8163                   && DECL_DESTRUCTOR_P (fn)))
8164             {
8165               if (!vid->ctor_vtbl_p)
8166                 BV_VCALL_INDEX (derived_virtuals) 
8167                   = BV_VCALL_INDEX (derived_entry);
8168               break;
8169             }
8170         }
8171       if (i != VARRAY_ACTIVE_SIZE (vid->fns))
8172         continue;
8173
8174       /* The FN comes from BASE.  So, we must calculate the adjustment from
8175          vid->vbase to BASE.  We can just look for BASE in the complete
8176          object because we are converting from a virtual base, so if there
8177          were multiple copies, there would not be a unique final overrider
8178          and vid->derived would be ill-formed.  */
8179       base = DECL_CONTEXT (fn);
8180       base_binfo = get_binfo (base, vid->derived, /*protect=*/0);
8181
8182       /* Compute the vcall offset.  */
8183       /* As mentioned above, the vbase we're working on is a primary base of
8184          vid->binfo.  But it might be a lost primary, so its BINFO_OFFSET
8185          might be wrong, so we just use the BINFO_OFFSET from vid->binfo.  */
8186       vcall_offset = BINFO_OFFSET (vid->binfo);
8187       vcall_offset = size_diffop (BINFO_OFFSET (base_binfo),
8188                                   vcall_offset);
8189       vcall_offset = fold (build1 (NOP_EXPR, vtable_entry_type,
8190                                    vcall_offset));
8191       
8192       *vid->last_init = build_tree_list (NULL_TREE, vcall_offset);
8193       vid->last_init = &TREE_CHAIN (*vid->last_init);
8194
8195       /* Keep track of the vtable index where this vcall offset can be
8196          found.  For a construction vtable, we already made this
8197          annotation when we built the original vtable.  */
8198       if (!vid->ctor_vtbl_p)
8199         BV_VCALL_INDEX (derived_virtuals) = vid->index;
8200
8201       /* The next vcall offset will be found at a more negative
8202          offset.  */
8203       vid->index = size_binop (MINUS_EXPR, vid->index, ssize_int (1));
8204
8205       /* Keep track of this function.  */
8206       VARRAY_PUSH_TREE (vid->fns, derived_virtuals);
8207     }
8208 }
8209
8210 /* Return vtbl initializers for the RTTI entries coresponding to the
8211    BINFO's vtable.  The RTTI entries should indicate the object given
8212    by VID->rtti_binfo.  */
8213
8214 static void
8215 build_rtti_vtbl_entries (binfo, vid)
8216      tree binfo;
8217      vtbl_init_data *vid;
8218 {
8219   tree b;
8220   tree t;
8221   tree basetype;
8222   tree offset;
8223   tree decl;
8224   tree init;
8225
8226   basetype = BINFO_TYPE (binfo);
8227   t = BINFO_TYPE (vid->rtti_binfo);
8228
8229   /* To find the complete object, we will first convert to our most
8230      primary base, and then add the offset in the vtbl to that value.  */
8231   b = binfo;
8232   while (CLASSTYPE_HAS_PRIMARY_BASE_P (BINFO_TYPE (b))
8233          && !BINFO_LOST_PRIMARY_P (b))
8234     {
8235       tree primary_base;
8236
8237       primary_base = get_primary_binfo (b);
8238       my_friendly_assert (BINFO_PRIMARY_BASE_OF (primary_base) == b, 20010127);
8239       b = primary_base;
8240     }
8241   offset = size_diffop (BINFO_OFFSET (vid->rtti_binfo), BINFO_OFFSET (b));
8242
8243   /* The second entry is the address of the typeinfo object.  */
8244   if (flag_rtti)
8245     decl = build_unary_op (ADDR_EXPR, get_tinfo_decl (t), 0);
8246   else
8247     decl = integer_zero_node;
8248   
8249   /* Convert the declaration to a type that can be stored in the
8250      vtable.  */
8251   init = build1 (NOP_EXPR, vfunc_ptr_type_node, decl);
8252   TREE_CONSTANT (init) = 1;
8253   *vid->last_init = build_tree_list (NULL_TREE, init);
8254   vid->last_init = &TREE_CHAIN (*vid->last_init);
8255
8256   /* Add the offset-to-top entry.  It comes earlier in the vtable that
8257      the the typeinfo entry.  */
8258   if (flag_vtable_thunks)
8259     {
8260       /* Convert the offset to look like a function pointer, so that
8261          we can put it in the vtable.  */
8262       init = build1 (NOP_EXPR, vfunc_ptr_type_node, offset);
8263       TREE_CONSTANT (init) = 1;
8264       *vid->last_init = build_tree_list (NULL_TREE, init);
8265       vid->last_init = &TREE_CHAIN (*vid->last_init);
8266     }
8267 }
8268
8269 /* Build an entry in the virtual function table.  DELTA is the offset
8270    for the `this' pointer.  VCALL_INDEX is the vtable index containing
8271    the vcall offset; NULL_TREE if none.  ENTRY is the virtual function
8272    table entry itself.  It's TREE_TYPE must be VFUNC_PTR_TYPE_NODE,
8273    but it may not actually be a virtual function table pointer.  (For
8274    example, it might be the address of the RTTI object, under the new
8275    ABI.)  */
8276
8277 static tree
8278 build_vtable_entry (delta, vcall_index, entry)
8279      tree delta;
8280      tree vcall_index;
8281      tree entry;
8282 {
8283   if (flag_vtable_thunks)
8284     {
8285       tree fn;
8286
8287       fn = TREE_OPERAND (entry, 0);
8288       if ((!integer_zerop (delta) || vcall_index != NULL_TREE)
8289           && fn != abort_fndecl)
8290         {
8291           entry = make_thunk (entry, delta, vcall_index);
8292           entry = build1 (ADDR_EXPR, vtable_entry_type, entry);
8293           TREE_READONLY (entry) = 1;
8294           TREE_CONSTANT (entry) = 1;
8295         }
8296 #ifdef GATHER_STATISTICS
8297       n_vtable_entries += 1;
8298 #endif
8299       return entry;
8300     }
8301   else
8302     {
8303       tree elems = tree_cons (NULL_TREE, delta,
8304                               tree_cons (NULL_TREE, integer_zero_node,
8305                                          build_tree_list (NULL_TREE, entry)));
8306       tree entry = build (CONSTRUCTOR, vtable_entry_type, NULL_TREE, elems);
8307
8308       /* We don't use vcall offsets when not using vtable thunks.  */
8309       my_friendly_assert (vcall_index == NULL_TREE, 20000125);
8310
8311       /* DELTA used to be constructed by `size_int' and/or size_binop,
8312          which caused overflow problems when it was negative.  That should
8313          be fixed now.  */
8314
8315       if (! int_fits_type_p (delta, delta_type_node))
8316         {
8317           if (flag_huge_objects)
8318             sorry ("object size exceeds built-in limit for virtual function table implementation");
8319           else
8320             sorry ("object size exceeds normal limit for virtual function table implementation, recompile all source and use -fhuge-objects");
8321         }
8322       
8323       TREE_CONSTANT (entry) = 1;
8324       TREE_STATIC (entry) = 1;
8325       TREE_READONLY (entry) = 1;
8326
8327 #ifdef GATHER_STATISTICS
8328       n_vtable_entries += 1;
8329 #endif
8330
8331       return entry;
8332     }
8333 }