OSDN Git Service

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