OSDN Git Service

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