OSDN Git Service

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