OSDN Git Service

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