d59d351537dc67c2ba20794f06e2cb6a4855333a
[dragonfly.git] / contrib / gcc-5.0 / gcc / cp / class.c
1 /* Functions related to building classes and their related objects.
2    Copyright (C) 1987-2015 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com)
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21
22 /* High-level class interface.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "hash-set.h"
28 #include "machmode.h"
29 #include "vec.h"
30 #include "double-int.h"
31 #include "input.h"
32 #include "alias.h"
33 #include "symtab.h"
34 #include "options.h"
35 #include "wide-int.h"
36 #include "inchash.h"
37 #include "tm.h"
38 #include "tree.h"
39 #include "stringpool.h"
40 #include "stor-layout.h"
41 #include "attribs.h"
42 #include "hash-table.h"
43 #include "cp-tree.h"
44 #include "flags.h"
45 #include "toplev.h"
46 #include "target.h"
47 #include "convert.h"
48 #include "hash-map.h"
49 #include "is-a.h"
50 #include "plugin-api.h"
51 #include "hard-reg-set.h"
52 #include "input.h"
53 #include "function.h"
54 #include "ipa-ref.h"
55 #include "cgraph.h"
56 #include "dumpfile.h"
57 #include "splay-tree.h"
58 #include "gimplify.h"
59 #include "wide-int.h"
60
61 /* The number of nested classes being processed.  If we are not in the
62    scope of any class, this is zero.  */
63
64 int current_class_depth;
65
66 /* In order to deal with nested classes, we keep a stack of classes.
67    The topmost entry is the innermost class, and is the entry at index
68    CURRENT_CLASS_DEPTH  */
69
70 typedef struct class_stack_node {
71   /* The name of the class.  */
72   tree name;
73
74   /* The _TYPE node for the class.  */
75   tree type;
76
77   /* The access specifier pending for new declarations in the scope of
78      this class.  */
79   tree access;
80
81   /* If were defining TYPE, the names used in this class.  */
82   splay_tree names_used;
83
84   /* Nonzero if this class is no longer open, because of a call to
85      push_to_top_level.  */
86   size_t hidden;
87 }* class_stack_node_t;
88
89 typedef struct vtbl_init_data_s
90 {
91   /* The base for which we're building initializers.  */
92   tree binfo;
93   /* The type of the most-derived type.  */
94   tree derived;
95   /* The binfo for the dynamic type. This will be TYPE_BINFO (derived),
96      unless ctor_vtbl_p is true.  */
97   tree rtti_binfo;
98   /* The negative-index vtable initializers built up so far.  These
99      are in order from least negative index to most negative index.  */
100   vec<constructor_elt, va_gc> *inits;
101   /* The binfo for the virtual base for which we're building
102      vcall offset initializers.  */
103   tree vbase;
104   /* The functions in vbase for which we have already provided vcall
105      offsets.  */
106   vec<tree, va_gc> *fns;
107   /* The vtable index of the next vcall or vbase offset.  */
108   tree index;
109   /* Nonzero if we are building the initializer for the primary
110      vtable.  */
111   int primary_vtbl_p;
112   /* Nonzero if we are building the initializer for a construction
113      vtable.  */
114   int ctor_vtbl_p;
115   /* True when adding vcall offset entries to the vtable.  False when
116      merely computing the indices.  */
117   bool generate_vcall_entries;
118 } vtbl_init_data;
119
120 /* The type of a function passed to walk_subobject_offsets.  */
121 typedef int (*subobject_offset_fn) (tree, tree, splay_tree);
122
123 /* The stack itself.  This is a dynamically resized array.  The
124    number of elements allocated is CURRENT_CLASS_STACK_SIZE.  */
125 static int current_class_stack_size;
126 static class_stack_node_t current_class_stack;
127
128 /* The size of the largest empty class seen in this translation unit.  */
129 static GTY (()) tree sizeof_biggest_empty_class;
130
131 /* An array of all local classes present in this translation unit, in
132    declaration order.  */
133 vec<tree, va_gc> *local_classes;
134
135 static tree get_vfield_name (tree);
136 static void finish_struct_anon (tree);
137 static tree get_vtable_name (tree);
138 static void get_basefndecls (tree, tree, vec<tree> *);
139 static int build_primary_vtable (tree, tree);
140 static int build_secondary_vtable (tree);
141 static void finish_vtbls (tree);
142 static void modify_vtable_entry (tree, tree, tree, tree, tree *);
143 static void finish_struct_bits (tree);
144 static int alter_access (tree, tree, tree);
145 static void handle_using_decl (tree, tree);
146 static tree dfs_modify_vtables (tree, void *);
147 static tree modify_all_vtables (tree, tree);
148 static void determine_primary_bases (tree);
149 static void finish_struct_methods (tree);
150 static void maybe_warn_about_overly_private_class (tree);
151 static int method_name_cmp (const void *, const void *);
152 static int resort_method_name_cmp (const void *, const void *);
153 static void add_implicitly_declared_members (tree, tree*, int, int);
154 static tree fixed_type_or_null (tree, int *, int *);
155 static tree build_simple_base_path (tree expr, tree binfo);
156 static tree build_vtbl_ref_1 (tree, tree);
157 static void build_vtbl_initializer (tree, tree, tree, tree, int *,
158                                     vec<constructor_elt, va_gc> **);
159 static int count_fields (tree);
160 static int add_fields_to_record_type (tree, struct sorted_fields_type*, int);
161 static void insert_into_classtype_sorted_fields (tree, tree, int);
162 static bool check_bitfield_decl (tree);
163 static void check_field_decl (tree, tree, int *, int *, int *);
164 static void check_field_decls (tree, tree *, int *, int *);
165 static tree *build_base_field (record_layout_info, tree, splay_tree, tree *);
166 static void build_base_fields (record_layout_info, splay_tree, tree *);
167 static void check_methods (tree);
168 static void remove_zero_width_bit_fields (tree);
169 static bool accessible_nvdtor_p (tree);
170 static void check_bases (tree, int *, int *);
171 static void check_bases_and_members (tree);
172 static tree create_vtable_ptr (tree, tree *);
173 static void include_empty_classes (record_layout_info);
174 static void layout_class_type (tree, tree *);
175 static void propagate_binfo_offsets (tree, tree);
176 static void layout_virtual_bases (record_layout_info, splay_tree);
177 static void build_vbase_offset_vtbl_entries (tree, vtbl_init_data *);
178 static void add_vcall_offset_vtbl_entries_r (tree, vtbl_init_data *);
179 static void add_vcall_offset_vtbl_entries_1 (tree, vtbl_init_data *);
180 static void build_vcall_offset_vtbl_entries (tree, vtbl_init_data *);
181 static void add_vcall_offset (tree, tree, vtbl_init_data *);
182 static void layout_vtable_decl (tree, int);
183 static tree dfs_find_final_overrider_pre (tree, void *);
184 static tree dfs_find_final_overrider_post (tree, void *);
185 static tree find_final_overrider (tree, tree, tree);
186 static int make_new_vtable (tree, tree);
187 static tree get_primary_binfo (tree);
188 static int maybe_indent_hierarchy (FILE *, int, int);
189 static tree dump_class_hierarchy_r (FILE *, int, tree, tree, int);
190 static void dump_class_hierarchy (tree);
191 static void dump_class_hierarchy_1 (FILE *, int, tree);
192 static void dump_array (FILE *, tree);
193 static void dump_vtable (tree, tree, tree);
194 static void dump_vtt (tree, tree);
195 static void dump_thunk (FILE *, int, tree);
196 static tree build_vtable (tree, tree, tree);
197 static void initialize_vtable (tree, vec<constructor_elt, va_gc> *);
198 static void layout_nonempty_base_or_field (record_layout_info,
199                                            tree, tree, splay_tree);
200 static tree end_of_class (tree, int);
201 static bool layout_empty_base (record_layout_info, tree, tree, splay_tree);
202 static void accumulate_vtbl_inits (tree, tree, tree, tree, tree,
203                                    vec<constructor_elt, va_gc> **);
204 static void dfs_accumulate_vtbl_inits (tree, tree, tree, tree, tree,
205                                        vec<constructor_elt, va_gc> **);
206 static void build_rtti_vtbl_entries (tree, vtbl_init_data *);
207 static void build_vcall_and_vbase_vtbl_entries (tree, vtbl_init_data *);
208 static void clone_constructors_and_destructors (tree);
209 static tree build_clone (tree, tree);
210 static void update_vtable_entry_for_fn (tree, tree, tree, tree *, unsigned);
211 static void build_ctor_vtbl_group (tree, tree);
212 static void build_vtt (tree);
213 static tree binfo_ctor_vtable (tree);
214 static void build_vtt_inits (tree, tree, vec<constructor_elt, va_gc> **,
215                              tree *);
216 static tree dfs_build_secondary_vptr_vtt_inits (tree, void *);
217 static tree dfs_fixup_binfo_vtbls (tree, void *);
218 static int record_subobject_offset (tree, tree, splay_tree);
219 static int check_subobject_offset (tree, tree, splay_tree);
220 static int walk_subobject_offsets (tree, subobject_offset_fn,
221                                    tree, splay_tree, tree, int);
222 static void record_subobject_offsets (tree, tree, splay_tree, bool);
223 static int layout_conflict_p (tree, tree, splay_tree, int);
224 static int splay_tree_compare_integer_csts (splay_tree_key k1,
225                                             splay_tree_key k2);
226 static void warn_about_ambiguous_bases (tree);
227 static bool type_requires_array_cookie (tree);
228 static bool base_derived_from (tree, tree);
229 static int empty_base_at_nonzero_offset_p (tree, tree, splay_tree);
230 static tree end_of_base (tree);
231 static tree get_vcall_index (tree, tree);
232
233 /* Variables shared between class.c and call.c.  */
234
235 int n_vtables = 0;
236 int n_vtable_entries = 0;
237 int n_vtable_searches = 0;
238 int n_vtable_elems = 0;
239 int n_convert_harshness = 0;
240 int n_compute_conversion_costs = 0;
241 int n_inner_fields_searched = 0;
242
243 /* Convert to or from a base subobject.  EXPR is an expression of type
244    `A' or `A*', an expression of type `B' or `B*' is returned.  To
245    convert A to a base B, CODE is PLUS_EXPR and BINFO is the binfo for
246    the B base instance within A.  To convert base A to derived B, CODE
247    is MINUS_EXPR and BINFO is the binfo for the A instance within B.
248    In this latter case, A must not be a morally virtual base of B.
249    NONNULL is true if EXPR is known to be non-NULL (this is only
250    needed when EXPR is of pointer type).  CV qualifiers are preserved
251    from EXPR.  */
252
253 tree
254 build_base_path (enum tree_code code,
255                  tree expr,
256                  tree binfo,
257                  int nonnull,
258                  tsubst_flags_t complain)
259 {
260   tree v_binfo = NULL_TREE;
261   tree d_binfo = NULL_TREE;
262   tree probe;
263   tree offset;
264   tree target_type;
265   tree null_test = NULL;
266   tree ptr_target_type;
267   int fixed_type_p;
268   int want_pointer = TYPE_PTR_P (TREE_TYPE (expr));
269   bool has_empty = false;
270   bool virtual_access;
271   bool rvalue = false;
272
273   if (expr == error_mark_node || binfo == error_mark_node || !binfo)
274     return error_mark_node;
275
276   for (probe = binfo; probe; probe = BINFO_INHERITANCE_CHAIN (probe))
277     {
278       d_binfo = probe;
279       if (is_empty_class (BINFO_TYPE (probe)))
280         has_empty = true;
281       if (!v_binfo && BINFO_VIRTUAL_P (probe))
282         v_binfo = probe;
283     }
284
285   probe = TYPE_MAIN_VARIANT (TREE_TYPE (expr));
286   if (want_pointer)
287     probe = TYPE_MAIN_VARIANT (TREE_TYPE (probe));
288
289   if (code == PLUS_EXPR
290       && !SAME_BINFO_TYPE_P (BINFO_TYPE (d_binfo), probe))
291     {
292       /* This can happen when adjust_result_of_qualified_name_lookup can't
293          find a unique base binfo in a call to a member function.  We
294          couldn't give the diagnostic then since we might have been calling
295          a static member function, so we do it now.  */
296       if (complain & tf_error)
297         {
298           tree base = lookup_base (probe, BINFO_TYPE (d_binfo),
299                                    ba_unique, NULL, complain);
300           gcc_assert (base == error_mark_node);
301         }
302       return error_mark_node;
303     }
304
305   gcc_assert ((code == MINUS_EXPR
306                && SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), probe))
307               || code == PLUS_EXPR);
308
309   if (binfo == d_binfo)
310     /* Nothing to do.  */
311     return expr;
312
313   if (code == MINUS_EXPR && v_binfo)
314     {
315       if (complain & tf_error)
316         {
317           if (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), BINFO_TYPE (v_binfo)))
318             {
319               if (want_pointer)
320                 error ("cannot convert from pointer to base class %qT to "
321                        "pointer to derived class %qT because the base is "
322                        "virtual", BINFO_TYPE (binfo), BINFO_TYPE (d_binfo));
323               else
324                 error ("cannot convert from base class %qT to derived "
325                        "class %qT because the base is virtual",
326                        BINFO_TYPE (binfo), BINFO_TYPE (d_binfo));
327             }         
328           else
329             {
330               if (want_pointer)
331                 error ("cannot convert from pointer to base class %qT to "
332                        "pointer to derived class %qT via virtual base %qT",
333                        BINFO_TYPE (binfo), BINFO_TYPE (d_binfo),
334                        BINFO_TYPE (v_binfo));
335               else
336                 error ("cannot convert from base class %qT to derived "
337                        "class %qT via virtual base %qT", BINFO_TYPE (binfo),
338                        BINFO_TYPE (d_binfo), BINFO_TYPE (v_binfo));
339             }
340         }
341       return error_mark_node;
342     }
343
344   if (!want_pointer)
345     {
346       rvalue = !real_lvalue_p (expr);
347       /* This must happen before the call to save_expr.  */
348       expr = cp_build_addr_expr (expr, complain);
349     }
350   else
351     expr = mark_rvalue_use (expr);
352
353   offset = BINFO_OFFSET (binfo);
354   fixed_type_p = resolves_to_fixed_type_p (expr, &nonnull);
355   target_type = code == PLUS_EXPR ? BINFO_TYPE (binfo) : BINFO_TYPE (d_binfo);
356   /* TARGET_TYPE has been extracted from BINFO, and, is therefore always
357      cv-unqualified.  Extract the cv-qualifiers from EXPR so that the
358      expression returned matches the input.  */
359   target_type = cp_build_qualified_type
360     (target_type, cp_type_quals (TREE_TYPE (TREE_TYPE (expr))));
361   ptr_target_type = build_pointer_type (target_type);
362
363   /* Do we need to look in the vtable for the real offset?  */
364   virtual_access = (v_binfo && fixed_type_p <= 0);
365
366   /* Don't bother with the calculations inside sizeof; they'll ICE if the
367      source type is incomplete and the pointer value doesn't matter.  In a
368      template (even in instantiate_non_dependent_expr), we don't have vtables
369      set up properly yet, and the value doesn't matter there either; we're
370      just interested in the result of overload resolution.  */
371   if (cp_unevaluated_operand != 0
372       || in_template_function ())
373     {
374       expr = build_nop (ptr_target_type, expr);
375       goto indout;
376     }
377
378   /* If we're in an NSDMI, we don't have the full constructor context yet
379      that we need for converting to a virtual base, so just build a stub
380      CONVERT_EXPR and expand it later in bot_replace.  */
381   if (virtual_access && fixed_type_p < 0
382       && current_scope () != current_function_decl)
383     {
384       expr = build1 (CONVERT_EXPR, ptr_target_type, expr);
385       CONVERT_EXPR_VBASE_PATH (expr) = true;
386       goto indout;
387     }
388
389   /* Do we need to check for a null pointer?  */
390   if (want_pointer && !nonnull)
391     {
392       /* If we know the conversion will not actually change the value
393          of EXPR, then we can avoid testing the expression for NULL.
394          We have to avoid generating a COMPONENT_REF for a base class
395          field, because other parts of the compiler know that such
396          expressions are always non-NULL.  */
397       if (!virtual_access && integer_zerop (offset))
398         return build_nop (ptr_target_type, expr);
399       null_test = error_mark_node;
400     }
401
402   /* Protect against multiple evaluation if necessary.  */
403   if (TREE_SIDE_EFFECTS (expr) && (null_test || virtual_access))
404     expr = save_expr (expr);
405
406   /* Now that we've saved expr, build the real null test.  */
407   if (null_test)
408     {
409       tree zero = cp_convert (TREE_TYPE (expr), nullptr_node, complain);
410       null_test = fold_build2_loc (input_location, NE_EXPR, boolean_type_node,
411                                expr, zero);
412     }
413
414   /* If this is a simple base reference, express it as a COMPONENT_REF.  */
415   if (code == PLUS_EXPR && !virtual_access
416       /* We don't build base fields for empty bases, and they aren't very
417          interesting to the optimizers anyway.  */
418       && !has_empty)
419     {
420       expr = cp_build_indirect_ref (expr, RO_NULL, complain);
421       expr = build_simple_base_path (expr, binfo);
422       if (rvalue)
423         expr = move (expr);
424       if (want_pointer)
425         expr = build_address (expr);
426       target_type = TREE_TYPE (expr);
427       goto out;
428     }
429
430   if (virtual_access)
431     {
432       /* Going via virtual base V_BINFO.  We need the static offset
433          from V_BINFO to BINFO, and the dynamic offset from D_BINFO to
434          V_BINFO.  That offset is an entry in D_BINFO's vtable.  */
435       tree v_offset;
436
437       if (fixed_type_p < 0 && in_base_initializer)
438         {
439           /* In a base member initializer, we cannot rely on the
440              vtable being set up.  We have to indirect via the
441              vtt_parm.  */
442           tree t;
443
444           t = TREE_TYPE (TYPE_VFIELD (current_class_type));
445           t = build_pointer_type (t);
446           v_offset = convert (t, current_vtt_parm);
447           v_offset = cp_build_indirect_ref (v_offset, RO_NULL, complain);
448         }
449       else
450         {
451           tree t = expr;
452           if ((flag_sanitize & SANITIZE_VPTR) && fixed_type_p == 0)
453             {
454               t = cp_ubsan_maybe_instrument_cast_to_vbase (input_location,
455                                                            probe, expr);
456               if (t == NULL_TREE)
457                 t = expr;
458             }
459           v_offset = build_vfield_ref (cp_build_indirect_ref (t, RO_NULL,
460                                                               complain),
461           TREE_TYPE (TREE_TYPE (expr)));
462         }
463
464       if (v_offset == error_mark_node)
465         return error_mark_node;
466
467       v_offset = fold_build_pointer_plus (v_offset, BINFO_VPTR_FIELD (v_binfo));
468       v_offset = build1 (NOP_EXPR,
469                          build_pointer_type (ptrdiff_type_node),
470                          v_offset);
471       v_offset = cp_build_indirect_ref (v_offset, RO_NULL, complain);
472       TREE_CONSTANT (v_offset) = 1;
473
474       offset = convert_to_integer (ptrdiff_type_node,
475                                    size_diffop_loc (input_location, offset,
476                                                 BINFO_OFFSET (v_binfo)));
477
478       if (!integer_zerop (offset))
479         v_offset = build2 (code, ptrdiff_type_node, v_offset, offset);
480
481       if (fixed_type_p < 0)
482         /* Negative fixed_type_p means this is a constructor or destructor;
483            virtual base layout is fixed in in-charge [cd]tors, but not in
484            base [cd]tors.  */
485         offset = build3 (COND_EXPR, ptrdiff_type_node,
486                          build2 (EQ_EXPR, boolean_type_node,
487                                  current_in_charge_parm, integer_zero_node),
488                          v_offset,
489                          convert_to_integer (ptrdiff_type_node,
490                                              BINFO_OFFSET (binfo)));
491       else
492         offset = v_offset;
493     }
494
495   if (want_pointer)
496     target_type = ptr_target_type;
497
498   expr = build1 (NOP_EXPR, ptr_target_type, expr);
499
500   if (!integer_zerop (offset))
501     {
502       offset = fold_convert (sizetype, offset);
503       if (code == MINUS_EXPR)
504         offset = fold_build1_loc (input_location, NEGATE_EXPR, sizetype, offset);
505       expr = fold_build_pointer_plus (expr, offset);
506     }
507   else
508     null_test = NULL;
509
510  indout:
511   if (!want_pointer)
512     {
513       expr = cp_build_indirect_ref (expr, RO_NULL, complain);
514       if (rvalue)
515         expr = move (expr);
516     }
517
518  out:
519   if (null_test)
520     expr = fold_build3_loc (input_location, COND_EXPR, target_type, null_test, expr,
521                             build_zero_cst (target_type));
522
523   return expr;
524 }
525
526 /* Subroutine of build_base_path; EXPR and BINFO are as in that function.
527    Perform a derived-to-base conversion by recursively building up a
528    sequence of COMPONENT_REFs to the appropriate base fields.  */
529
530 static tree
531 build_simple_base_path (tree expr, tree binfo)
532 {
533   tree type = BINFO_TYPE (binfo);
534   tree d_binfo = BINFO_INHERITANCE_CHAIN (binfo);
535   tree field;
536
537   if (d_binfo == NULL_TREE)
538     {
539       tree temp;
540
541       gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (expr)) == type);
542
543       /* Transform `(a, b).x' into `(*(a, &b)).x', `(a ? b : c).x'
544          into `(*(a ?  &b : &c)).x', and so on.  A COND_EXPR is only
545          an lvalue in the front end; only _DECLs and _REFs are lvalues
546          in the back end.  */
547       temp = unary_complex_lvalue (ADDR_EXPR, expr);
548       if (temp)
549         expr = cp_build_indirect_ref (temp, RO_NULL, tf_warning_or_error);
550
551       return expr;
552     }
553
554   /* Recurse.  */
555   expr = build_simple_base_path (expr, d_binfo);
556
557   for (field = TYPE_FIELDS (BINFO_TYPE (d_binfo));
558        field; field = DECL_CHAIN (field))
559     /* Is this the base field created by build_base_field?  */
560     if (TREE_CODE (field) == FIELD_DECL
561         && DECL_FIELD_IS_BASE (field)
562         && TREE_TYPE (field) == type
563         /* If we're looking for a field in the most-derived class,
564            also check the field offset; we can have two base fields
565            of the same type if one is an indirect virtual base and one
566            is a direct non-virtual base.  */
567         && (BINFO_INHERITANCE_CHAIN (d_binfo)
568             || tree_int_cst_equal (byte_position (field),
569                                    BINFO_OFFSET (binfo))))
570       {
571         /* We don't use build_class_member_access_expr here, as that
572            has unnecessary checks, and more importantly results in
573            recursive calls to dfs_walk_once.  */
574         int type_quals = cp_type_quals (TREE_TYPE (expr));
575
576         expr = build3 (COMPONENT_REF,
577                        cp_build_qualified_type (type, type_quals),
578                        expr, field, NULL_TREE);
579         expr = fold_if_not_in_template (expr);
580
581         /* Mark the expression const or volatile, as appropriate.
582            Even though we've dealt with the type above, we still have
583            to mark the expression itself.  */
584         if (type_quals & TYPE_QUAL_CONST)
585           TREE_READONLY (expr) = 1;
586         if (type_quals & TYPE_QUAL_VOLATILE)
587           TREE_THIS_VOLATILE (expr) = 1;
588
589         return expr;
590       }
591
592   /* Didn't find the base field?!?  */
593   gcc_unreachable ();
594 }
595
596 /* Convert OBJECT to the base TYPE.  OBJECT is an expression whose
597    type is a class type or a pointer to a class type.  In the former
598    case, TYPE is also a class type; in the latter it is another
599    pointer type.  If CHECK_ACCESS is true, an error message is emitted
600    if TYPE is inaccessible.  If OBJECT has pointer type, the value is
601    assumed to be non-NULL.  */
602
603 tree
604 convert_to_base (tree object, tree type, bool check_access, bool nonnull,
605                  tsubst_flags_t complain)
606 {
607   tree binfo;
608   tree object_type;
609
610   if (TYPE_PTR_P (TREE_TYPE (object)))
611     {
612       object_type = TREE_TYPE (TREE_TYPE (object));
613       type = TREE_TYPE (type);
614     }
615   else
616     object_type = TREE_TYPE (object);
617
618   binfo = lookup_base (object_type, type, check_access ? ba_check : ba_unique,
619                        NULL, complain);
620   if (!binfo || binfo == error_mark_node)
621     return error_mark_node;
622
623   return build_base_path (PLUS_EXPR, object, binfo, nonnull, complain);
624 }
625
626 /* EXPR is an expression with unqualified class type.  BASE is a base
627    binfo of that class type.  Returns EXPR, converted to the BASE
628    type.  This function assumes that EXPR is the most derived class;
629    therefore virtual bases can be found at their static offsets.  */
630
631 tree
632 convert_to_base_statically (tree expr, tree base)
633 {
634   tree expr_type;
635
636   expr_type = TREE_TYPE (expr);
637   if (!SAME_BINFO_TYPE_P (BINFO_TYPE (base), expr_type))
638     {
639       /* If this is a non-empty base, use a COMPONENT_REF.  */
640       if (!is_empty_class (BINFO_TYPE (base)))
641         return build_simple_base_path (expr, base);
642
643       /* We use fold_build2 and fold_convert below to simplify the trees
644          provided to the optimizers.  It is not safe to call these functions
645          when processing a template because they do not handle C++-specific
646          trees.  */
647       gcc_assert (!processing_template_decl);
648       expr = cp_build_addr_expr (expr, tf_warning_or_error);
649       if (!integer_zerop (BINFO_OFFSET (base)))
650         expr = fold_build_pointer_plus_loc (input_location,
651                                             expr, BINFO_OFFSET (base));
652       expr = fold_convert (build_pointer_type (BINFO_TYPE (base)), expr);
653       expr = build_fold_indirect_ref_loc (input_location, expr);
654     }
655
656   return expr;
657 }
658
659 \f
660 tree
661 build_vfield_ref (tree datum, tree type)
662 {
663   tree vfield, vcontext;
664
665   if (datum == error_mark_node
666       /* Can happen in case of duplicate base types (c++/59082).  */
667       || !TYPE_VFIELD (type))
668     return error_mark_node;
669
670   /* First, convert to the requested type.  */
671   if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (datum), type))
672     datum = convert_to_base (datum, type, /*check_access=*/false,
673                              /*nonnull=*/true, tf_warning_or_error);
674
675   /* Second, the requested type may not be the owner of its own vptr.
676      If not, convert to the base class that owns it.  We cannot use
677      convert_to_base here, because VCONTEXT may appear more than once
678      in the inheritance hierarchy of TYPE, and thus direct conversion
679      between the types may be ambiguous.  Following the path back up
680      one step at a time via primary bases avoids the problem.  */
681   vfield = TYPE_VFIELD (type);
682   vcontext = DECL_CONTEXT (vfield);
683   while (!same_type_ignoring_top_level_qualifiers_p (vcontext, type))
684     {
685       datum = build_simple_base_path (datum, CLASSTYPE_PRIMARY_BINFO (type));
686       type = TREE_TYPE (datum);
687     }
688
689   return build3 (COMPONENT_REF, TREE_TYPE (vfield), datum, vfield, NULL_TREE);
690 }
691
692 /* Given an object INSTANCE, return an expression which yields the
693    vtable element corresponding to INDEX.  There are many special
694    cases for INSTANCE which we take care of here, mainly to avoid
695    creating extra tree nodes when we don't have to.  */
696
697 static tree
698 build_vtbl_ref_1 (tree instance, tree idx)
699 {
700   tree aref;
701   tree vtbl = NULL_TREE;
702
703   /* Try to figure out what a reference refers to, and
704      access its virtual function table directly.  */
705
706   int cdtorp = 0;
707   tree fixed_type = fixed_type_or_null (instance, NULL, &cdtorp);
708
709   tree basetype = non_reference (TREE_TYPE (instance));
710
711   if (fixed_type && !cdtorp)
712     {
713       tree binfo = lookup_base (fixed_type, basetype,
714                                 ba_unique, NULL, tf_none);
715       if (binfo && binfo != error_mark_node)
716         vtbl = unshare_expr (BINFO_VTABLE (binfo));
717     }
718
719   if (!vtbl)
720     vtbl = build_vfield_ref (instance, basetype);
721
722   aref = build_array_ref (input_location, vtbl, idx);
723   TREE_CONSTANT (aref) |= TREE_CONSTANT (vtbl) && TREE_CONSTANT (idx);
724
725   return aref;
726 }
727
728 tree
729 build_vtbl_ref (tree instance, tree idx)
730 {
731   tree aref = build_vtbl_ref_1 (instance, idx);
732
733   return aref;
734 }
735
736 /* Given a stable object pointer INSTANCE_PTR, return an expression which
737    yields a function pointer corresponding to vtable element INDEX.  */
738
739 tree
740 build_vfn_ref (tree instance_ptr, tree idx)
741 {
742   tree aref;
743
744   aref = build_vtbl_ref_1 (cp_build_indirect_ref (instance_ptr, RO_NULL,
745                                                   tf_warning_or_error), 
746                            idx);
747
748   /* When using function descriptors, the address of the
749      vtable entry is treated as a function pointer.  */
750   if (TARGET_VTABLE_USES_DESCRIPTORS)
751     aref = build1 (NOP_EXPR, TREE_TYPE (aref),
752                    cp_build_addr_expr (aref, tf_warning_or_error));
753
754   /* Remember this as a method reference, for later devirtualization.  */
755   aref = build3 (OBJ_TYPE_REF, TREE_TYPE (aref), aref, instance_ptr, idx);
756
757   return aref;
758 }
759
760 /* Return the name of the virtual function table (as an IDENTIFIER_NODE)
761    for the given TYPE.  */
762
763 static tree
764 get_vtable_name (tree type)
765 {
766   return mangle_vtbl_for_type (type);
767 }
768
769 /* DECL is an entity associated with TYPE, like a virtual table or an
770    implicitly generated constructor.  Determine whether or not DECL
771    should have external or internal linkage at the object file
772    level.  This routine does not deal with COMDAT linkage and other
773    similar complexities; it simply sets TREE_PUBLIC if it possible for
774    entities in other translation units to contain copies of DECL, in
775    the abstract.  */
776
777 void
778 set_linkage_according_to_type (tree /*type*/, tree decl)
779 {
780   TREE_PUBLIC (decl) = 1;
781   determine_visibility (decl);
782 }
783
784 /* Create a VAR_DECL for a primary or secondary vtable for CLASS_TYPE.
785    (For a secondary vtable for B-in-D, CLASS_TYPE should be D, not B.)
786    Use NAME for the name of the vtable, and VTABLE_TYPE for its type.  */
787
788 static tree
789 build_vtable (tree class_type, tree name, tree vtable_type)
790 {
791   tree decl;
792
793   decl = build_lang_decl (VAR_DECL, name, vtable_type);
794   /* vtable names are already mangled; give them their DECL_ASSEMBLER_NAME
795      now to avoid confusion in mangle_decl.  */
796   SET_DECL_ASSEMBLER_NAME (decl, name);
797   DECL_CONTEXT (decl) = class_type;
798   DECL_ARTIFICIAL (decl) = 1;
799   TREE_STATIC (decl) = 1;
800   TREE_READONLY (decl) = 1;
801   DECL_VIRTUAL_P (decl) = 1;
802   DECL_ALIGN (decl) = TARGET_VTABLE_ENTRY_ALIGN;
803   DECL_USER_ALIGN (decl) = true;
804   DECL_VTABLE_OR_VTT_P (decl) = 1;
805   set_linkage_according_to_type (class_type, decl);
806   /* The vtable has not been defined -- yet.  */
807   DECL_EXTERNAL (decl) = 1;
808   DECL_NOT_REALLY_EXTERN (decl) = 1;
809
810   /* Mark the VAR_DECL node representing the vtable itself as a
811      "gratuitous" one, thereby forcing dwarfout.c to ignore it.  It
812      is rather important that such things be ignored because any
813      effort to actually generate DWARF for them will run into
814      trouble when/if we encounter code like:
815
816      #pragma interface
817      struct S { virtual void member (); };
818
819      because the artificial declaration of the vtable itself (as
820      manufactured by the g++ front end) will say that the vtable is
821      a static member of `S' but only *after* the debug output for
822      the definition of `S' has already been output.  This causes
823      grief because the DWARF entry for the definition of the vtable
824      will try to refer back to an earlier *declaration* of the
825      vtable as a static member of `S' and there won't be one.  We
826      might be able to arrange to have the "vtable static member"
827      attached to the member list for `S' before the debug info for
828      `S' get written (which would solve the problem) but that would
829      require more intrusive changes to the g++ front end.  */
830   DECL_IGNORED_P (decl) = 1;
831
832   return decl;
833 }
834
835 /* Get the VAR_DECL of the vtable for TYPE. TYPE need not be polymorphic,
836    or even complete.  If this does not exist, create it.  If COMPLETE is
837    nonzero, then complete the definition of it -- that will render it
838    impossible to actually build the vtable, but is useful to get at those
839    which are known to exist in the runtime.  */
840
841 tree
842 get_vtable_decl (tree type, int complete)
843 {
844   tree decl;
845
846   if (CLASSTYPE_VTABLES (type))
847     return CLASSTYPE_VTABLES (type);
848
849   decl = build_vtable (type, get_vtable_name (type), vtbl_type_node);
850   CLASSTYPE_VTABLES (type) = decl;
851
852   if (complete)
853     {
854       DECL_EXTERNAL (decl) = 1;
855       cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
856     }
857
858   return decl;
859 }
860
861 /* Build the primary virtual function table for TYPE.  If BINFO is
862    non-NULL, build the vtable starting with the initial approximation
863    that it is the same as the one which is the head of the association
864    list.  Returns a nonzero value if a new vtable is actually
865    created.  */
866
867 static int
868 build_primary_vtable (tree binfo, tree type)
869 {
870   tree decl;
871   tree virtuals;
872
873   decl = get_vtable_decl (type, /*complete=*/0);
874
875   if (binfo)
876     {
877       if (BINFO_NEW_VTABLE_MARKED (binfo))
878         /* We have already created a vtable for this base, so there's
879            no need to do it again.  */
880         return 0;
881
882       virtuals = copy_list (BINFO_VIRTUALS (binfo));
883       TREE_TYPE (decl) = TREE_TYPE (get_vtbl_decl_for_binfo (binfo));
884       DECL_SIZE (decl) = TYPE_SIZE (TREE_TYPE (decl));
885       DECL_SIZE_UNIT (decl) = TYPE_SIZE_UNIT (TREE_TYPE (decl));
886     }
887   else
888     {
889       gcc_assert (TREE_TYPE (decl) == vtbl_type_node);
890       virtuals = NULL_TREE;
891     }
892
893   if (GATHER_STATISTICS)
894     {
895       n_vtables += 1;
896       n_vtable_elems += list_length (virtuals);
897     }
898
899   /* Initialize the association list for this type, based
900      on our first approximation.  */
901   BINFO_VTABLE (TYPE_BINFO (type)) = decl;
902   BINFO_VIRTUALS (TYPE_BINFO (type)) = virtuals;
903   SET_BINFO_NEW_VTABLE_MARKED (TYPE_BINFO (type));
904   return 1;
905 }
906
907 /* Give BINFO a new virtual function table which is initialized
908    with a skeleton-copy of its original initialization.  The only
909    entry that changes is the `delta' entry, so we can really
910    share a lot of structure.
911
912    FOR_TYPE is the most derived type which caused this table to
913    be needed.
914
915    Returns nonzero if we haven't met BINFO before.
916
917    The order in which vtables are built (by calling this function) for
918    an object must remain the same, otherwise a binary incompatibility
919    can result.  */
920
921 static int
922 build_secondary_vtable (tree binfo)
923 {
924   if (BINFO_NEW_VTABLE_MARKED (binfo))
925     /* We already created a vtable for this base.  There's no need to
926        do it again.  */
927     return 0;
928
929   /* Remember that we've created a vtable for this BINFO, so that we
930      don't try to do so again.  */
931   SET_BINFO_NEW_VTABLE_MARKED (binfo);
932
933   /* Make fresh virtual list, so we can smash it later.  */
934   BINFO_VIRTUALS (binfo) = copy_list (BINFO_VIRTUALS (binfo));
935
936   /* Secondary vtables are laid out as part of the same structure as
937      the primary vtable.  */
938   BINFO_VTABLE (binfo) = NULL_TREE;
939   return 1;
940 }
941
942 /* Create a new vtable for BINFO which is the hierarchy dominated by
943    T. Return nonzero if we actually created a new vtable.  */
944
945 static int
946 make_new_vtable (tree t, tree binfo)
947 {
948   if (binfo == TYPE_BINFO (t))
949     /* In this case, it is *type*'s vtable we are modifying.  We start
950        with the approximation that its vtable is that of the
951        immediate base class.  */
952     return build_primary_vtable (binfo, t);
953   else
954     /* This is our very own copy of `basetype' to play with.  Later,
955        we will fill in all the virtual functions that override the
956        virtual functions in these base classes which are not defined
957        by the current type.  */
958     return build_secondary_vtable (binfo);
959 }
960
961 /* Make *VIRTUALS, an entry on the BINFO_VIRTUALS list for BINFO
962    (which is in the hierarchy dominated by T) list FNDECL as its
963    BV_FN.  DELTA is the required constant adjustment from the `this'
964    pointer where the vtable entry appears to the `this' required when
965    the function is actually called.  */
966
967 static void
968 modify_vtable_entry (tree t,
969                      tree binfo,
970                      tree fndecl,
971                      tree delta,
972                      tree *virtuals)
973 {
974   tree v;
975
976   v = *virtuals;
977
978   if (fndecl != BV_FN (v)
979       || !tree_int_cst_equal (delta, BV_DELTA (v)))
980     {
981       /* We need a new vtable for BINFO.  */
982       if (make_new_vtable (t, binfo))
983         {
984           /* If we really did make a new vtable, we also made a copy
985              of the BINFO_VIRTUALS list.  Now, we have to find the
986              corresponding entry in that list.  */
987           *virtuals = BINFO_VIRTUALS (binfo);
988           while (BV_FN (*virtuals) != BV_FN (v))
989             *virtuals = TREE_CHAIN (*virtuals);
990           v = *virtuals;
991         }
992
993       BV_DELTA (v) = delta;
994       BV_VCALL_INDEX (v) = NULL_TREE;
995       BV_FN (v) = fndecl;
996     }
997 }
998
999 \f
1000 /* Add method METHOD to class TYPE.  If USING_DECL is non-null, it is
1001    the USING_DECL naming METHOD.  Returns true if the method could be
1002    added to the method vec.  */
1003
1004 bool
1005 add_method (tree type, tree method, tree using_decl)
1006 {
1007   unsigned slot;
1008   tree overload;
1009   bool template_conv_p = false;
1010   bool conv_p;
1011   vec<tree, va_gc> *method_vec;
1012   bool complete_p;
1013   bool insert_p = false;
1014   tree current_fns;
1015   tree fns;
1016
1017   if (method == error_mark_node)
1018     return false;
1019
1020   complete_p = COMPLETE_TYPE_P (type);
1021   conv_p = DECL_CONV_FN_P (method);
1022   if (conv_p)
1023     template_conv_p = (TREE_CODE (method) == TEMPLATE_DECL
1024                        && DECL_TEMPLATE_CONV_FN_P (method));
1025
1026   method_vec = CLASSTYPE_METHOD_VEC (type);
1027   if (!method_vec)
1028     {
1029       /* Make a new method vector.  We start with 8 entries.  We must
1030          allocate at least two (for constructors and destructors), and
1031          we're going to end up with an assignment operator at some
1032          point as well.  */
1033       vec_alloc (method_vec, 8);
1034       /* Create slots for constructors and destructors.  */
1035       method_vec->quick_push (NULL_TREE);
1036       method_vec->quick_push (NULL_TREE);
1037       CLASSTYPE_METHOD_VEC (type) = method_vec;
1038     }
1039
1040   /* Maintain TYPE_HAS_USER_CONSTRUCTOR, etc.  */
1041   grok_special_member_properties (method);
1042
1043   /* Constructors and destructors go in special slots.  */
1044   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (method))
1045     slot = CLASSTYPE_CONSTRUCTOR_SLOT;
1046   else if (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (method))
1047     {
1048       slot = CLASSTYPE_DESTRUCTOR_SLOT;
1049
1050       if (TYPE_FOR_JAVA (type))
1051         {
1052           if (!DECL_ARTIFICIAL (method))
1053             error ("Java class %qT cannot have a destructor", type);
1054           else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1055             error ("Java class %qT cannot have an implicit non-trivial "
1056                    "destructor",
1057                    type);
1058         }
1059     }
1060   else
1061     {
1062       tree m;
1063
1064       insert_p = true;
1065       /* See if we already have an entry with this name.  */
1066       for (slot = CLASSTYPE_FIRST_CONVERSION_SLOT;
1067            vec_safe_iterate (method_vec, slot, &m);
1068            ++slot)
1069         {
1070           m = OVL_CURRENT (m);
1071           if (template_conv_p)
1072             {
1073               if (TREE_CODE (m) == TEMPLATE_DECL
1074                   && DECL_TEMPLATE_CONV_FN_P (m))
1075                 insert_p = false;
1076               break;
1077             }
1078           if (conv_p && !DECL_CONV_FN_P (m))
1079             break;
1080           if (DECL_NAME (m) == DECL_NAME (method))
1081             {
1082               insert_p = false;
1083               break;
1084             }
1085           if (complete_p
1086               && !DECL_CONV_FN_P (m)
1087               && DECL_NAME (m) > DECL_NAME (method))
1088             break;
1089         }
1090     }
1091   current_fns = insert_p ? NULL_TREE : (*method_vec)[slot];
1092
1093   /* Check to see if we've already got this method.  */
1094   for (fns = current_fns; fns; fns = OVL_NEXT (fns))
1095     {
1096       tree fn = OVL_CURRENT (fns);
1097       tree fn_type;
1098       tree method_type;
1099       tree parms1;
1100       tree parms2;
1101
1102       if (TREE_CODE (fn) != TREE_CODE (method))
1103         continue;
1104
1105       /* [over.load] Member function declarations with the
1106          same name and the same parameter types cannot be
1107          overloaded if any of them is a static member
1108          function declaration.
1109
1110          [over.load] Member function declarations with the same name and
1111          the same parameter-type-list as well as member function template
1112          declarations with the same name, the same parameter-type-list, and
1113          the same template parameter lists cannot be overloaded if any of
1114          them, but not all, have a ref-qualifier.
1115
1116          [namespace.udecl] When a using-declaration brings names
1117          from a base class into a derived class scope, member
1118          functions in the derived class override and/or hide member
1119          functions with the same name and parameter types in a base
1120          class (rather than conflicting).  */
1121       fn_type = TREE_TYPE (fn);
1122       method_type = TREE_TYPE (method);
1123       parms1 = TYPE_ARG_TYPES (fn_type);
1124       parms2 = TYPE_ARG_TYPES (method_type);
1125
1126       /* Compare the quals on the 'this' parm.  Don't compare
1127          the whole types, as used functions are treated as
1128          coming from the using class in overload resolution.  */
1129       if (! DECL_STATIC_FUNCTION_P (fn)
1130           && ! DECL_STATIC_FUNCTION_P (method)
1131           /* Either both or neither need to be ref-qualified for
1132              differing quals to allow overloading.  */
1133           && (FUNCTION_REF_QUALIFIED (fn_type)
1134               == FUNCTION_REF_QUALIFIED (method_type))
1135           && (type_memfn_quals (fn_type) != type_memfn_quals (method_type)
1136               || type_memfn_rqual (fn_type) != type_memfn_rqual (method_type)))
1137           continue;
1138
1139       /* For templates, the return type and template parameters
1140          must be identical.  */
1141       if (TREE_CODE (fn) == TEMPLATE_DECL
1142           && (!same_type_p (TREE_TYPE (fn_type),
1143                             TREE_TYPE (method_type))
1144               || !comp_template_parms (DECL_TEMPLATE_PARMS (fn),
1145                                        DECL_TEMPLATE_PARMS (method))))
1146         continue;
1147
1148       if (! DECL_STATIC_FUNCTION_P (fn))
1149         parms1 = TREE_CHAIN (parms1);
1150       if (! DECL_STATIC_FUNCTION_P (method))
1151         parms2 = TREE_CHAIN (parms2);
1152
1153       if (compparms (parms1, parms2)
1154           && (!DECL_CONV_FN_P (fn)
1155               || same_type_p (TREE_TYPE (fn_type),
1156                               TREE_TYPE (method_type))))
1157         {
1158           /* For function versions, their parms and types match
1159              but they are not duplicates.  Record function versions
1160              as and when they are found.  extern "C" functions are
1161              not treated as versions.  */
1162           if (TREE_CODE (fn) == FUNCTION_DECL
1163               && TREE_CODE (method) == FUNCTION_DECL
1164               && !DECL_EXTERN_C_P (fn)
1165               && !DECL_EXTERN_C_P (method)
1166               && targetm.target_option.function_versions (fn, method))
1167             {
1168               /* Mark functions as versions if necessary.  Modify the mangled
1169                  decl name if necessary.  */
1170               if (!DECL_FUNCTION_VERSIONED (fn))
1171                 {
1172                   DECL_FUNCTION_VERSIONED (fn) = 1;
1173                   if (DECL_ASSEMBLER_NAME_SET_P (fn))
1174                     mangle_decl (fn);
1175                 }
1176               if (!DECL_FUNCTION_VERSIONED (method))
1177                 {
1178                   DECL_FUNCTION_VERSIONED (method) = 1;
1179                   if (DECL_ASSEMBLER_NAME_SET_P (method))
1180                     mangle_decl (method);
1181                 }
1182               cgraph_node::record_function_versions (fn, method);
1183               continue;
1184             }
1185           if (DECL_INHERITED_CTOR_BASE (method))
1186             {
1187               if (DECL_INHERITED_CTOR_BASE (fn))
1188                 {
1189                   error_at (DECL_SOURCE_LOCATION (method),
1190                             "%q#D inherited from %qT", method,
1191                             DECL_INHERITED_CTOR_BASE (method));
1192                   error_at (DECL_SOURCE_LOCATION (fn),
1193                             "conflicts with version inherited from %qT",
1194                             DECL_INHERITED_CTOR_BASE (fn));
1195                 }
1196               /* Otherwise defer to the other function.  */
1197               return false;
1198             }
1199           if (using_decl)
1200             {
1201               if (DECL_CONTEXT (fn) == type)
1202                 /* Defer to the local function.  */
1203                 return false;
1204             }
1205           else
1206             {
1207               error ("%q+#D cannot be overloaded", method);
1208               error ("with %q+#D", fn);
1209             }
1210
1211           /* We don't call duplicate_decls here to merge the
1212              declarations because that will confuse things if the
1213              methods have inline definitions.  In particular, we
1214              will crash while processing the definitions.  */
1215           return false;
1216         }
1217     }
1218
1219   /* A class should never have more than one destructor.  */
1220   if (current_fns && DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (method))
1221     return false;
1222
1223   /* Add the new binding.  */
1224   if (using_decl)
1225     {
1226       overload = ovl_cons (method, current_fns);
1227       OVL_USED (overload) = true;
1228     }
1229   else
1230     overload = build_overload (method, current_fns);
1231
1232   if (conv_p)
1233     TYPE_HAS_CONVERSION (type) = 1;
1234   else if (slot >= CLASSTYPE_FIRST_CONVERSION_SLOT && !complete_p)
1235     push_class_level_binding (DECL_NAME (method), overload);
1236
1237   if (insert_p)
1238     {
1239       bool reallocated;
1240
1241       /* We only expect to add few methods in the COMPLETE_P case, so
1242          just make room for one more method in that case.  */
1243       if (complete_p)
1244         reallocated = vec_safe_reserve_exact (method_vec, 1);
1245       else
1246         reallocated = vec_safe_reserve (method_vec, 1);
1247       if (reallocated)
1248         CLASSTYPE_METHOD_VEC (type) = method_vec;
1249       if (slot == method_vec->length ())
1250         method_vec->quick_push (overload);
1251       else
1252         method_vec->quick_insert (slot, overload);
1253     }
1254   else
1255     /* Replace the current slot.  */
1256     (*method_vec)[slot] = overload;
1257   return true;
1258 }
1259
1260 /* Subroutines of finish_struct.  */
1261
1262 /* Change the access of FDECL to ACCESS in T.  Return 1 if change was
1263    legit, otherwise return 0.  */
1264
1265 static int
1266 alter_access (tree t, tree fdecl, tree access)
1267 {
1268   tree elem;
1269
1270   if (!DECL_LANG_SPECIFIC (fdecl))
1271     retrofit_lang_decl (fdecl);
1272
1273   gcc_assert (!DECL_DISCRIMINATOR_P (fdecl));
1274
1275   elem = purpose_member (t, DECL_ACCESS (fdecl));
1276   if (elem)
1277     {
1278       if (TREE_VALUE (elem) != access)
1279         {
1280           if (TREE_CODE (TREE_TYPE (fdecl)) == FUNCTION_DECL)
1281             error ("conflicting access specifications for method"
1282                    " %q+D, ignored", TREE_TYPE (fdecl));
1283           else
1284             error ("conflicting access specifications for field %qE, ignored",
1285                    DECL_NAME (fdecl));
1286         }
1287       else
1288         {
1289           /* They're changing the access to the same thing they changed
1290              it to before.  That's OK.  */
1291           ;
1292         }
1293     }
1294   else
1295     {
1296       perform_or_defer_access_check (TYPE_BINFO (t), fdecl, fdecl,
1297                                      tf_warning_or_error);
1298       DECL_ACCESS (fdecl) = tree_cons (t, access, DECL_ACCESS (fdecl));
1299       return 1;
1300     }
1301   return 0;
1302 }
1303
1304 /* Process the USING_DECL, which is a member of T.  */
1305
1306 static void
1307 handle_using_decl (tree using_decl, tree t)
1308 {
1309   tree decl = USING_DECL_DECLS (using_decl);
1310   tree name = DECL_NAME (using_decl);
1311   tree access
1312     = TREE_PRIVATE (using_decl) ? access_private_node
1313     : TREE_PROTECTED (using_decl) ? access_protected_node
1314     : access_public_node;
1315   tree flist = NULL_TREE;
1316   tree old_value;
1317
1318   gcc_assert (!processing_template_decl && decl);
1319
1320   old_value = lookup_member (t, name, /*protect=*/0, /*want_type=*/false,
1321                              tf_warning_or_error);
1322   if (old_value)
1323     {
1324       if (is_overloaded_fn (old_value))
1325         old_value = OVL_CURRENT (old_value);
1326
1327       if (DECL_P (old_value) && DECL_CONTEXT (old_value) == t)
1328         /* OK */;
1329       else
1330         old_value = NULL_TREE;
1331     }
1332
1333   cp_emit_debug_info_for_using (decl, t);
1334
1335   if (is_overloaded_fn (decl))
1336     flist = decl;
1337
1338   if (! old_value)
1339     ;
1340   else if (is_overloaded_fn (old_value))
1341     {
1342       if (flist)
1343         /* It's OK to use functions from a base when there are functions with
1344            the same name already present in the current class.  */;
1345       else
1346         {
1347           error ("%q+D invalid in %q#T", using_decl, t);
1348           error ("  because of local method %q+#D with same name",
1349                  OVL_CURRENT (old_value));
1350           return;
1351         }
1352     }
1353   else if (!DECL_ARTIFICIAL (old_value))
1354     {
1355       error ("%q+D invalid in %q#T", using_decl, t);
1356       error ("  because of local member %q+#D with same name", old_value);
1357       return;
1358     }
1359
1360   /* Make type T see field decl FDECL with access ACCESS.  */
1361   if (flist)
1362     for (; flist; flist = OVL_NEXT (flist))
1363       {
1364         add_method (t, OVL_CURRENT (flist), using_decl);
1365         alter_access (t, OVL_CURRENT (flist), access);
1366       }
1367   else
1368     alter_access (t, decl, access);
1369 }
1370 \f
1371 /* Data structure for find_abi_tags_r, below.  */
1372
1373 struct abi_tag_data
1374 {
1375   tree t;               // The type that we're checking for missing tags.
1376   tree subob;           // The subobject of T that we're getting tags from.
1377   tree tags; // error_mark_node for diagnostics, or a list of missing tags.
1378 };
1379
1380 /* Subroutine of find_abi_tags_r. Handle a single TAG found on the class TP
1381    in the context of P.  TAG can be either an identifier (the DECL_NAME of
1382    a tag NAMESPACE_DECL) or a STRING_CST (a tag attribute).  */
1383
1384 static void
1385 check_tag (tree tag, tree id, tree *tp, abi_tag_data *p)
1386 {
1387   if (!IDENTIFIER_MARKED (id))
1388     {
1389       if (p->tags != error_mark_node)
1390         {
1391           /* We're collecting tags from template arguments or from
1392              the type of a variable or function return type.  */
1393           p->tags = tree_cons (NULL_TREE, tag, p->tags);
1394
1395           /* Don't inherit this tag multiple times.  */
1396           IDENTIFIER_MARKED (id) = true;
1397
1398           if (TYPE_P (p->t))
1399             {
1400               /* Tags inherited from type template arguments are only used
1401                  to avoid warnings.  */
1402               ABI_TAG_IMPLICIT (p->tags) = true;
1403               return;
1404             }
1405           /* For functions and variables we want to warn, too.  */
1406         }
1407
1408       /* Otherwise we're diagnosing missing tags.  */
1409       if (TREE_CODE (p->t) == FUNCTION_DECL)
1410         {
1411           if (warning (OPT_Wabi_tag, "%qD inherits the %E ABI tag "
1412                        "that %qT (used in its return type) has",
1413                        p->t, tag, *tp))
1414             inform (location_of (*tp), "%qT declared here", *tp);
1415         }
1416       else if (TREE_CODE (p->t) == VAR_DECL)
1417         {
1418           if (warning (OPT_Wabi_tag, "%qD inherits the %E ABI tag "
1419                        "that %qT (used in its type) has", p->t, tag, *tp))
1420             inform (location_of (*tp), "%qT declared here", *tp);
1421         }
1422       else if (TYPE_P (p->subob))
1423         {
1424           if (warning (OPT_Wabi_tag, "%qT does not have the %E ABI tag "
1425                        "that base %qT has", p->t, tag, p->subob))
1426             inform (location_of (p->subob), "%qT declared here",
1427                     p->subob);
1428         }
1429       else
1430         {
1431           if (warning (OPT_Wabi_tag, "%qT does not have the %E ABI tag "
1432                        "that %qT (used in the type of %qD) has",
1433                        p->t, tag, *tp, p->subob))
1434             {
1435               inform (location_of (p->subob), "%qD declared here",
1436                       p->subob);
1437               inform (location_of (*tp), "%qT declared here", *tp);
1438             }
1439         }
1440     }
1441 }
1442
1443 /* Find all the ABI tags in the attribute list ATTR and either call
1444    check_tag (if TP is non-null) or set IDENTIFIER_MARKED to val.  */
1445
1446 static void
1447 mark_or_check_attr_tags (tree attr, tree *tp, abi_tag_data *p, bool val)
1448 {
1449   if (!attr)
1450     return;
1451   for (; (attr = lookup_attribute ("abi_tag", attr));
1452        attr = TREE_CHAIN (attr))
1453     for (tree list = TREE_VALUE (attr); list;
1454          list = TREE_CHAIN (list))
1455       {
1456         tree tag = TREE_VALUE (list);
1457         tree id = get_identifier (TREE_STRING_POINTER (tag));
1458         if (tp)
1459           check_tag (tag, id, tp, p);
1460         else
1461           IDENTIFIER_MARKED (id) = val;
1462       }
1463 }
1464
1465 /* Find all the ABI tags on T and its enclosing scopes and either call
1466    check_tag (if TP is non-null) or set IDENTIFIER_MARKED to val.  */
1467
1468 static void
1469 mark_or_check_tags (tree t, tree *tp, abi_tag_data *p, bool val)
1470 {
1471   while (t != global_namespace)
1472     {
1473       tree attr;
1474       if (TYPE_P (t))
1475         {
1476           attr = TYPE_ATTRIBUTES (t);
1477           t = CP_TYPE_CONTEXT (t);
1478         }
1479       else
1480         {
1481           attr = DECL_ATTRIBUTES (t);
1482           t = CP_DECL_CONTEXT (t);
1483         }
1484       mark_or_check_attr_tags (attr, tp, p, val);
1485     }
1486 }
1487
1488 /* walk_tree callback for check_abi_tags: if the type at *TP involves any
1489    types with ABI tags, add the corresponding identifiers to the VEC in
1490    *DATA and set IDENTIFIER_MARKED.  */
1491
1492 static tree
1493 find_abi_tags_r (tree *tp, int *walk_subtrees, void *data)
1494 {
1495   if (!OVERLOAD_TYPE_P (*tp))
1496     return NULL_TREE;
1497
1498   /* walk_tree shouldn't be walking into any subtrees of a RECORD_TYPE
1499      anyway, but let's make sure of it.  */
1500   *walk_subtrees = false;
1501
1502   abi_tag_data *p = static_cast<struct abi_tag_data*>(data);
1503
1504   mark_or_check_tags (*tp, tp, p, false);
1505
1506   return NULL_TREE;
1507 }
1508
1509 /* walk_tree callback for mark_abi_tags: if *TP is a class, set
1510    IDENTIFIER_MARKED on its ABI tags.  */
1511
1512 static tree
1513 mark_abi_tags_r (tree *tp, int *walk_subtrees, void *data)
1514 {
1515   if (!OVERLOAD_TYPE_P (*tp))
1516     return NULL_TREE;
1517
1518   /* walk_tree shouldn't be walking into any subtrees of a RECORD_TYPE
1519      anyway, but let's make sure of it.  */
1520   *walk_subtrees = false;
1521
1522   bool *valp = static_cast<bool*>(data);
1523
1524   mark_or_check_tags (*tp, NULL, NULL, *valp);
1525
1526   return NULL_TREE;
1527 }
1528
1529 /* Set IDENTIFIER_MARKED on all the ABI tags on T and its enclosing
1530    scopes.  */
1531
1532 static void
1533 mark_abi_tags (tree t, bool val)
1534 {
1535   mark_or_check_tags (t, NULL, NULL, val);
1536   if (DECL_P (t))
1537     {
1538       if (DECL_LANG_SPECIFIC (t) && DECL_USE_TEMPLATE (t)
1539           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)))
1540         {
1541           /* Template arguments are part of the signature.  */
1542           tree level = INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (t));
1543           for (int j = 0; j < TREE_VEC_LENGTH (level); ++j)
1544             {
1545               tree arg = TREE_VEC_ELT (level, j);
1546               cp_walk_tree_without_duplicates (&arg, mark_abi_tags_r, &val);
1547             }
1548         }
1549       if (TREE_CODE (t) == FUNCTION_DECL)
1550         /* A function's parameter types are part of the signature, so
1551            we don't need to inherit any tags that are also in them.  */
1552         for (tree arg = FUNCTION_FIRST_USER_PARMTYPE (t); arg;
1553              arg = TREE_CHAIN (arg))
1554           cp_walk_tree_without_duplicates (&TREE_VALUE (arg),
1555                                            mark_abi_tags_r, &val);
1556     }
1557 }
1558
1559 /* Check that T has all the ABI tags that subobject SUBOB has, or
1560    warn if not.  If T is a (variable or function) declaration, also
1561    add any missing tags.  */
1562
1563 static void
1564 check_abi_tags (tree t, tree subob)
1565 {
1566   bool inherit = DECL_P (t);
1567
1568   if (!inherit && !warn_abi_tag)
1569     return;
1570
1571   tree decl = TYPE_P (t) ? TYPE_NAME (t) : t;
1572   if (!TREE_PUBLIC (decl))
1573     /* No need to worry about things local to this TU.  */
1574     return;
1575
1576   mark_abi_tags (t, true);
1577
1578   tree subtype = TYPE_P (subob) ? subob : TREE_TYPE (subob);
1579   struct abi_tag_data data = { t, subob, error_mark_node };
1580   if (inherit)
1581     data.tags = NULL_TREE;
1582
1583   cp_walk_tree_without_duplicates (&subtype, find_abi_tags_r, &data);
1584
1585   if (inherit && data.tags)
1586     {
1587       tree attr = lookup_attribute ("abi_tag", DECL_ATTRIBUTES (t));
1588       if (attr)
1589         TREE_VALUE (attr) = chainon (data.tags, TREE_VALUE (attr));
1590       else
1591         DECL_ATTRIBUTES (t)
1592           = tree_cons (get_identifier ("abi_tag"), data.tags,
1593                        DECL_ATTRIBUTES (t));
1594     }
1595
1596   mark_abi_tags (t, false);
1597 }
1598
1599 /* Check that DECL has all the ABI tags that are used in parts of its type
1600    that are not reflected in its mangled name.  */
1601
1602 void
1603 check_abi_tags (tree decl)
1604 {
1605   if (TREE_CODE (decl) == VAR_DECL)
1606     check_abi_tags (decl, TREE_TYPE (decl));
1607   else if (TREE_CODE (decl) == FUNCTION_DECL
1608            && !mangle_return_type_p (decl))
1609     check_abi_tags (decl, TREE_TYPE (TREE_TYPE (decl)));
1610 }
1611
1612 void
1613 inherit_targ_abi_tags (tree t)
1614 {
1615   if (!CLASS_TYPE_P (t)
1616       || CLASSTYPE_TEMPLATE_INFO (t) == NULL_TREE)
1617     return;
1618
1619   mark_abi_tags (t, true);
1620
1621   tree args = CLASSTYPE_TI_ARGS (t);
1622   struct abi_tag_data data = { t, NULL_TREE, NULL_TREE };
1623   for (int i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
1624     {
1625       tree level = TMPL_ARGS_LEVEL (args, i+1);
1626       for (int j = 0; j < TREE_VEC_LENGTH (level); ++j)
1627         {
1628           tree arg = TREE_VEC_ELT (level, j);
1629           data.subob = arg;
1630           cp_walk_tree_without_duplicates (&arg, find_abi_tags_r, &data);
1631         }
1632     }
1633
1634   // If we found some tags on our template arguments, add them to our
1635   // abi_tag attribute.
1636   if (data.tags)
1637     {
1638       tree attr = lookup_attribute ("abi_tag", TYPE_ATTRIBUTES (t));
1639       if (attr)
1640         TREE_VALUE (attr) = chainon (data.tags, TREE_VALUE (attr));
1641       else
1642         TYPE_ATTRIBUTES (t)
1643           = tree_cons (get_identifier ("abi_tag"), data.tags,
1644                        TYPE_ATTRIBUTES (t));
1645     }
1646
1647   mark_abi_tags (t, false);
1648 }
1649
1650 /* Return true, iff class T has a non-virtual destructor that is
1651    accessible from outside the class heirarchy (i.e. is public, or
1652    there's a suitable friend.  */
1653
1654 static bool
1655 accessible_nvdtor_p (tree t)
1656 {
1657   tree dtor = CLASSTYPE_DESTRUCTORS (t);
1658
1659   /* An implicitly declared destructor is always public.  And,
1660      if it were virtual, we would have created it by now.  */
1661   if (!dtor)
1662     return true;
1663
1664   if (DECL_VINDEX (dtor))
1665     return false; /* Virtual */
1666   
1667   if (!TREE_PRIVATE (dtor) && !TREE_PROTECTED (dtor))
1668     return true;  /* Public */
1669
1670   if (CLASSTYPE_FRIEND_CLASSES (t)
1671       || DECL_FRIENDLIST (TYPE_MAIN_DECL (t)))
1672     return true;   /* Has friends */
1673
1674   return false;
1675 }
1676
1677 /* Run through the base classes of T, updating CANT_HAVE_CONST_CTOR_P,
1678    and NO_CONST_ASN_REF_P.  Also set flag bits in T based on
1679    properties of the bases.  */
1680
1681 static void
1682 check_bases (tree t,
1683              int* cant_have_const_ctor_p,
1684              int* no_const_asn_ref_p)
1685 {
1686   int i;
1687   bool seen_non_virtual_nearly_empty_base_p = 0;
1688   int seen_tm_mask = 0;
1689   tree base_binfo;
1690   tree binfo;
1691   tree field = NULL_TREE;
1692
1693   if (!CLASSTYPE_NON_STD_LAYOUT (t))
1694     for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
1695       if (TREE_CODE (field) == FIELD_DECL)
1696         break;
1697
1698   for (binfo = TYPE_BINFO (t), i = 0;
1699        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
1700     {
1701       tree basetype = TREE_TYPE (base_binfo);
1702
1703       gcc_assert (COMPLETE_TYPE_P (basetype));
1704
1705       if (CLASSTYPE_FINAL (basetype))
1706         error ("cannot derive from %<final%> base %qT in derived type %qT",
1707                basetype, t);
1708
1709       /* If any base class is non-literal, so is the derived class.  */
1710       if (!CLASSTYPE_LITERAL_P (basetype))
1711         CLASSTYPE_LITERAL_P (t) = false;
1712
1713       /* If the base class doesn't have copy constructors or
1714          assignment operators that take const references, then the
1715          derived class cannot have such a member automatically
1716          generated.  */
1717       if (TYPE_HAS_COPY_CTOR (basetype)
1718           && ! TYPE_HAS_CONST_COPY_CTOR (basetype))
1719         *cant_have_const_ctor_p = 1;
1720       if (TYPE_HAS_COPY_ASSIGN (basetype)
1721           && !TYPE_HAS_CONST_COPY_ASSIGN (basetype))
1722         *no_const_asn_ref_p = 1;
1723
1724       if (BINFO_VIRTUAL_P (base_binfo))
1725         /* A virtual base does not effect nearly emptiness.  */
1726         ;
1727       else if (CLASSTYPE_NEARLY_EMPTY_P (basetype))
1728         {
1729           if (seen_non_virtual_nearly_empty_base_p)
1730             /* And if there is more than one nearly empty base, then the
1731                derived class is not nearly empty either.  */
1732             CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
1733           else
1734             /* Remember we've seen one.  */
1735             seen_non_virtual_nearly_empty_base_p = 1;
1736         }
1737       else if (!is_empty_class (basetype))
1738         /* If the base class is not empty or nearly empty, then this
1739            class cannot be nearly empty.  */
1740         CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
1741
1742       /* A lot of properties from the bases also apply to the derived
1743          class.  */
1744       TYPE_NEEDS_CONSTRUCTING (t) |= TYPE_NEEDS_CONSTRUCTING (basetype);
1745       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
1746         |= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (basetype);
1747       TYPE_HAS_COMPLEX_COPY_ASSIGN (t)
1748         |= (TYPE_HAS_COMPLEX_COPY_ASSIGN (basetype)
1749             || !TYPE_HAS_COPY_ASSIGN (basetype));
1750       TYPE_HAS_COMPLEX_COPY_CTOR (t) |= (TYPE_HAS_COMPLEX_COPY_CTOR (basetype)
1751                                          || !TYPE_HAS_COPY_CTOR (basetype));
1752       TYPE_HAS_COMPLEX_MOVE_ASSIGN (t)
1753         |= TYPE_HAS_COMPLEX_MOVE_ASSIGN (basetype);
1754       TYPE_HAS_COMPLEX_MOVE_CTOR (t) |= TYPE_HAS_COMPLEX_MOVE_CTOR (basetype);
1755       TYPE_POLYMORPHIC_P (t) |= TYPE_POLYMORPHIC_P (basetype);
1756       CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t)
1757         |= CLASSTYPE_CONTAINS_EMPTY_CLASS_P (basetype);
1758       TYPE_HAS_COMPLEX_DFLT (t) |= (!TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
1759                                     || TYPE_HAS_COMPLEX_DFLT (basetype));
1760       SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT
1761         (t, CLASSTYPE_READONLY_FIELDS_NEED_INIT (t)
1762          | CLASSTYPE_READONLY_FIELDS_NEED_INIT (basetype));
1763       SET_CLASSTYPE_REF_FIELDS_NEED_INIT
1764         (t, CLASSTYPE_REF_FIELDS_NEED_INIT (t)
1765          | CLASSTYPE_REF_FIELDS_NEED_INIT (basetype));
1766
1767       /*  A standard-layout class is a class that:
1768           ...
1769           * has no non-standard-layout base classes,  */
1770       CLASSTYPE_NON_STD_LAYOUT (t) |= CLASSTYPE_NON_STD_LAYOUT (basetype);
1771       if (!CLASSTYPE_NON_STD_LAYOUT (t))
1772         {
1773           tree basefield;
1774           /* ...has no base classes of the same type as the first non-static
1775              data member...  */
1776           if (field && DECL_CONTEXT (field) == t
1777               && (same_type_ignoring_top_level_qualifiers_p
1778                   (TREE_TYPE (field), basetype)))
1779             CLASSTYPE_NON_STD_LAYOUT (t) = 1;
1780           else
1781             /* ...either has no non-static data members in the most-derived
1782                class and at most one base class with non-static data
1783                members, or has no base classes with non-static data
1784                members */
1785             for (basefield = TYPE_FIELDS (basetype); basefield;
1786                  basefield = DECL_CHAIN (basefield))
1787               if (TREE_CODE (basefield) == FIELD_DECL)
1788                 {
1789                   if (field)
1790                     CLASSTYPE_NON_STD_LAYOUT (t) = 1;
1791                   else
1792                     field = basefield;
1793                   break;
1794                 }
1795         }
1796
1797       /* Don't bother collecting tm attributes if transactional memory
1798          support is not enabled.  */
1799       if (flag_tm)
1800         {
1801           tree tm_attr = find_tm_attribute (TYPE_ATTRIBUTES (basetype));
1802           if (tm_attr)
1803             seen_tm_mask |= tm_attr_to_mask (tm_attr);
1804         }
1805
1806       check_abi_tags (t, basetype);
1807     }
1808
1809   /* If one of the base classes had TM attributes, and the current class
1810      doesn't define its own, then the current class inherits one.  */
1811   if (seen_tm_mask && !find_tm_attribute (TYPE_ATTRIBUTES (t)))
1812     {
1813       tree tm_attr = tm_mask_to_attr (seen_tm_mask & -seen_tm_mask);
1814       TYPE_ATTRIBUTES (t) = tree_cons (tm_attr, NULL, TYPE_ATTRIBUTES (t));
1815     }
1816 }
1817
1818 /* Determine all the primary bases within T.  Sets BINFO_PRIMARY_BASE_P for
1819    those that are primaries.  Sets BINFO_LOST_PRIMARY_P for those
1820    that have had a nearly-empty virtual primary base stolen by some
1821    other base in the hierarchy.  Determines CLASSTYPE_PRIMARY_BASE for
1822    T.  */
1823
1824 static void
1825 determine_primary_bases (tree t)
1826 {
1827   unsigned i;
1828   tree primary = NULL_TREE;
1829   tree type_binfo = TYPE_BINFO (t);
1830   tree base_binfo;
1831
1832   /* Determine the primary bases of our bases.  */
1833   for (base_binfo = TREE_CHAIN (type_binfo); base_binfo;
1834        base_binfo = TREE_CHAIN (base_binfo))
1835     {
1836       tree primary = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (base_binfo));
1837
1838       /* See if we're the non-virtual primary of our inheritance
1839          chain.  */
1840       if (!BINFO_VIRTUAL_P (base_binfo))
1841         {
1842           tree parent = BINFO_INHERITANCE_CHAIN (base_binfo);
1843           tree parent_primary = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (parent));
1844
1845           if (parent_primary
1846               && SAME_BINFO_TYPE_P (BINFO_TYPE (base_binfo),
1847                                     BINFO_TYPE (parent_primary)))
1848             /* We are the primary binfo.  */
1849             BINFO_PRIMARY_P (base_binfo) = 1;
1850         }
1851       /* Determine if we have a virtual primary base, and mark it so.
1852        */
1853       if (primary && BINFO_VIRTUAL_P (primary))
1854         {
1855           tree this_primary = copied_binfo (primary, base_binfo);
1856
1857           if (BINFO_PRIMARY_P (this_primary))
1858             /* Someone already claimed this base.  */
1859             BINFO_LOST_PRIMARY_P (base_binfo) = 1;
1860           else
1861             {
1862               tree delta;
1863
1864               BINFO_PRIMARY_P (this_primary) = 1;
1865               BINFO_INHERITANCE_CHAIN (this_primary) = base_binfo;
1866
1867               /* A virtual binfo might have been copied from within
1868                  another hierarchy. As we're about to use it as a
1869                  primary base, make sure the offsets match.  */
1870               delta = size_diffop_loc (input_location,
1871                                    convert (ssizetype,
1872                                             BINFO_OFFSET (base_binfo)),
1873                                    convert (ssizetype,
1874                                             BINFO_OFFSET (this_primary)));
1875
1876               propagate_binfo_offsets (this_primary, delta);
1877             }
1878         }
1879     }
1880
1881   /* First look for a dynamic direct non-virtual base.  */
1882   for (i = 0; BINFO_BASE_ITERATE (type_binfo, i, base_binfo); i++)
1883     {
1884       tree basetype = BINFO_TYPE (base_binfo);
1885
1886       if (TYPE_CONTAINS_VPTR_P (basetype) && !BINFO_VIRTUAL_P (base_binfo))
1887         {
1888           primary = base_binfo;
1889           goto found;
1890         }
1891     }
1892
1893   /* A "nearly-empty" virtual base class can be the primary base
1894      class, if no non-virtual polymorphic base can be found.  Look for
1895      a nearly-empty virtual dynamic base that is not already a primary
1896      base of something in the hierarchy.  If there is no such base,
1897      just pick the first nearly-empty virtual base.  */
1898
1899   for (base_binfo = TREE_CHAIN (type_binfo); base_binfo;
1900        base_binfo = TREE_CHAIN (base_binfo))
1901     if (BINFO_VIRTUAL_P (base_binfo)
1902         && CLASSTYPE_NEARLY_EMPTY_P (BINFO_TYPE (base_binfo)))
1903       {
1904         if (!BINFO_PRIMARY_P (base_binfo))
1905           {
1906             /* Found one that is not primary.  */
1907             primary = base_binfo;
1908             goto found;
1909           }
1910         else if (!primary)
1911           /* Remember the first candidate.  */
1912           primary = base_binfo;
1913       }
1914
1915  found:
1916   /* If we've got a primary base, use it.  */
1917   if (primary)
1918     {
1919       tree basetype = BINFO_TYPE (primary);
1920
1921       CLASSTYPE_PRIMARY_BINFO (t) = primary;
1922       if (BINFO_PRIMARY_P (primary))
1923         /* We are stealing a primary base.  */
1924         BINFO_LOST_PRIMARY_P (BINFO_INHERITANCE_CHAIN (primary)) = 1;
1925       BINFO_PRIMARY_P (primary) = 1;
1926       if (BINFO_VIRTUAL_P (primary))
1927         {
1928           tree delta;
1929
1930           BINFO_INHERITANCE_CHAIN (primary) = type_binfo;
1931           /* A virtual binfo might have been copied from within
1932              another hierarchy. As we're about to use it as a primary
1933              base, make sure the offsets match.  */
1934           delta = size_diffop_loc (input_location, ssize_int (0),
1935                                convert (ssizetype, BINFO_OFFSET (primary)));
1936
1937           propagate_binfo_offsets (primary, delta);
1938         }
1939
1940       primary = TYPE_BINFO (basetype);
1941
1942       TYPE_VFIELD (t) = TYPE_VFIELD (basetype);
1943       BINFO_VTABLE (type_binfo) = BINFO_VTABLE (primary);
1944       BINFO_VIRTUALS (type_binfo) = BINFO_VIRTUALS (primary);
1945     }
1946 }
1947
1948 /* Update the variant types of T.  */
1949
1950 void
1951 fixup_type_variants (tree t)
1952 {
1953   tree variants;
1954
1955   if (!t)
1956     return;
1957
1958   for (variants = TYPE_NEXT_VARIANT (t);
1959        variants;
1960        variants = TYPE_NEXT_VARIANT (variants))
1961     {
1962       /* These fields are in the _TYPE part of the node, not in
1963          the TYPE_LANG_SPECIFIC component, so they are not shared.  */
1964       TYPE_HAS_USER_CONSTRUCTOR (variants) = TYPE_HAS_USER_CONSTRUCTOR (t);
1965       TYPE_NEEDS_CONSTRUCTING (variants) = TYPE_NEEDS_CONSTRUCTING (t);
1966       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (variants)
1967         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t);
1968
1969       TYPE_POLYMORPHIC_P (variants) = TYPE_POLYMORPHIC_P (t);
1970
1971       TYPE_BINFO (variants) = TYPE_BINFO (t);
1972
1973       /* Copy whatever these are holding today.  */
1974       TYPE_VFIELD (variants) = TYPE_VFIELD (t);
1975       TYPE_METHODS (variants) = TYPE_METHODS (t);
1976       TYPE_FIELDS (variants) = TYPE_FIELDS (t);
1977     }
1978 }
1979
1980 /* Early variant fixups: we apply attributes at the beginning of the class
1981    definition, and we need to fix up any variants that have already been
1982    made via elaborated-type-specifier so that check_qualified_type works.  */
1983
1984 void
1985 fixup_attribute_variants (tree t)
1986 {
1987   tree variants;
1988
1989   if (!t)
1990     return;
1991
1992   for (variants = TYPE_NEXT_VARIANT (t);
1993        variants;
1994        variants = TYPE_NEXT_VARIANT (variants))
1995     {
1996       /* These are the two fields that check_qualified_type looks at and
1997          are affected by attributes.  */
1998       TYPE_ATTRIBUTES (variants) = TYPE_ATTRIBUTES (t);
1999       TYPE_ALIGN (variants) = TYPE_ALIGN (t);
2000     }
2001 }
2002 \f
2003 /* Set memoizing fields and bits of T (and its variants) for later
2004    use.  */
2005
2006 static void
2007 finish_struct_bits (tree t)
2008 {
2009   /* Fix up variants (if any).  */
2010   fixup_type_variants (t);
2011
2012   if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)) && TYPE_POLYMORPHIC_P (t))
2013     /* For a class w/o baseclasses, 'finish_struct' has set
2014        CLASSTYPE_PURE_VIRTUALS correctly (by definition).
2015        Similarly for a class whose base classes do not have vtables.
2016        When neither of these is true, we might have removed abstract
2017        virtuals (by providing a definition), added some (by declaring
2018        new ones), or redeclared ones from a base class.  We need to
2019        recalculate what's really an abstract virtual at this point (by
2020        looking in the vtables).  */
2021     get_pure_virtuals (t);
2022
2023   /* If this type has a copy constructor or a destructor, force its
2024      mode to be BLKmode, and force its TREE_ADDRESSABLE bit to be
2025      nonzero.  This will cause it to be passed by invisible reference
2026      and prevent it from being returned in a register.  */
2027   if (type_has_nontrivial_copy_init (t)
2028       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
2029     {
2030       tree variants;
2031       DECL_MODE (TYPE_MAIN_DECL (t)) = BLKmode;
2032       for (variants = t; variants; variants = TYPE_NEXT_VARIANT (variants))
2033         {
2034           SET_TYPE_MODE (variants, BLKmode);
2035           TREE_ADDRESSABLE (variants) = 1;
2036         }
2037     }
2038 }
2039
2040 /* Issue warnings about T having private constructors, but no friends,
2041    and so forth.
2042
2043    HAS_NONPRIVATE_METHOD is nonzero if T has any non-private methods or
2044    static members.  HAS_NONPRIVATE_STATIC_FN is nonzero if T has any
2045    non-private static member functions.  */
2046
2047 static void
2048 maybe_warn_about_overly_private_class (tree t)
2049 {
2050   int has_member_fn = 0;
2051   int has_nonprivate_method = 0;
2052   tree fn;
2053
2054   if (!warn_ctor_dtor_privacy
2055       /* If the class has friends, those entities might create and
2056          access instances, so we should not warn.  */
2057       || (CLASSTYPE_FRIEND_CLASSES (t)
2058           || DECL_FRIENDLIST (TYPE_MAIN_DECL (t)))
2059       /* We will have warned when the template was declared; there's
2060          no need to warn on every instantiation.  */
2061       || CLASSTYPE_TEMPLATE_INSTANTIATION (t))
2062     /* There's no reason to even consider warning about this
2063        class.  */
2064     return;
2065
2066   /* We only issue one warning, if more than one applies, because
2067      otherwise, on code like:
2068
2069      class A {
2070        // Oops - forgot `public:'
2071        A();
2072        A(const A&);
2073        ~A();
2074      };
2075
2076      we warn several times about essentially the same problem.  */
2077
2078   /* Check to see if all (non-constructor, non-destructor) member
2079      functions are private.  (Since there are no friends or
2080      non-private statics, we can't ever call any of the private member
2081      functions.)  */
2082   for (fn = TYPE_METHODS (t); fn; fn = DECL_CHAIN (fn))
2083     /* We're not interested in compiler-generated methods; they don't
2084        provide any way to call private members.  */
2085     if (!DECL_ARTIFICIAL (fn))
2086       {
2087         if (!TREE_PRIVATE (fn))
2088           {
2089             if (DECL_STATIC_FUNCTION_P (fn))
2090               /* A non-private static member function is just like a
2091                  friend; it can create and invoke private member
2092                  functions, and be accessed without a class
2093                  instance.  */
2094               return;
2095
2096             has_nonprivate_method = 1;
2097             /* Keep searching for a static member function.  */
2098           }
2099         else if (!DECL_CONSTRUCTOR_P (fn) && !DECL_DESTRUCTOR_P (fn))
2100           has_member_fn = 1;
2101       }
2102
2103   if (!has_nonprivate_method && has_member_fn)
2104     {
2105       /* There are no non-private methods, and there's at least one
2106          private member function that isn't a constructor or
2107          destructor.  (If all the private members are
2108          constructors/destructors we want to use the code below that
2109          issues error messages specifically referring to
2110          constructors/destructors.)  */
2111       unsigned i;
2112       tree binfo = TYPE_BINFO (t);
2113
2114       for (i = 0; i != BINFO_N_BASE_BINFOS (binfo); i++)
2115         if (BINFO_BASE_ACCESS (binfo, i) != access_private_node)
2116           {
2117             has_nonprivate_method = 1;
2118             break;
2119           }
2120       if (!has_nonprivate_method)
2121         {
2122           warning (OPT_Wctor_dtor_privacy,
2123                    "all member functions in class %qT are private", t);
2124           return;
2125         }
2126     }
2127
2128   /* Even if some of the member functions are non-private, the class
2129      won't be useful for much if all the constructors or destructors
2130      are private: such an object can never be created or destroyed.  */
2131   fn = CLASSTYPE_DESTRUCTORS (t);
2132   if (fn && TREE_PRIVATE (fn))
2133     {
2134       warning (OPT_Wctor_dtor_privacy,
2135                "%q#T only defines a private destructor and has no friends",
2136                t);
2137       return;
2138     }
2139
2140   /* Warn about classes that have private constructors and no friends.  */
2141   if (TYPE_HAS_USER_CONSTRUCTOR (t)
2142       /* Implicitly generated constructors are always public.  */
2143       && (!CLASSTYPE_LAZY_DEFAULT_CTOR (t)
2144           || !CLASSTYPE_LAZY_COPY_CTOR (t)))
2145     {
2146       int nonprivate_ctor = 0;
2147
2148       /* If a non-template class does not define a copy
2149          constructor, one is defined for it, enabling it to avoid
2150          this warning.  For a template class, this does not
2151          happen, and so we would normally get a warning on:
2152
2153            template <class T> class C { private: C(); };
2154
2155          To avoid this asymmetry, we check TYPE_HAS_COPY_CTOR.  All
2156          complete non-template or fully instantiated classes have this
2157          flag set.  */
2158       if (!TYPE_HAS_COPY_CTOR (t))
2159         nonprivate_ctor = 1;
2160       else
2161         for (fn = CLASSTYPE_CONSTRUCTORS (t); fn; fn = OVL_NEXT (fn))
2162           {
2163             tree ctor = OVL_CURRENT (fn);
2164             /* Ideally, we wouldn't count copy constructors (or, in
2165                fact, any constructor that takes an argument of the
2166                class type as a parameter) because such things cannot
2167                be used to construct an instance of the class unless
2168                you already have one.  But, for now at least, we're
2169                more generous.  */
2170             if (! TREE_PRIVATE (ctor))
2171               {
2172                 nonprivate_ctor = 1;
2173                 break;
2174               }
2175           }
2176
2177       if (nonprivate_ctor == 0)
2178         {
2179           warning (OPT_Wctor_dtor_privacy,
2180                    "%q#T only defines private constructors and has no friends",
2181                    t);
2182           return;
2183         }
2184     }
2185 }
2186
2187 static struct {
2188   gt_pointer_operator new_value;
2189   void *cookie;
2190 } resort_data;
2191
2192 /* Comparison function to compare two TYPE_METHOD_VEC entries by name.  */
2193
2194 static int
2195 method_name_cmp (const void* m1_p, const void* m2_p)
2196 {
2197   const tree *const m1 = (const tree *) m1_p;
2198   const tree *const m2 = (const tree *) m2_p;
2199
2200   if (*m1 == NULL_TREE && *m2 == NULL_TREE)
2201     return 0;
2202   if (*m1 == NULL_TREE)
2203     return -1;
2204   if (*m2 == NULL_TREE)
2205     return 1;
2206   if (DECL_NAME (OVL_CURRENT (*m1)) < DECL_NAME (OVL_CURRENT (*m2)))
2207     return -1;
2208   return 1;
2209 }
2210
2211 /* This routine compares two fields like method_name_cmp but using the
2212    pointer operator in resort_field_decl_data.  */
2213
2214 static int
2215 resort_method_name_cmp (const void* m1_p, const void* m2_p)
2216 {
2217   const tree *const m1 = (const tree *) m1_p;
2218   const tree *const m2 = (const tree *) m2_p;
2219   if (*m1 == NULL_TREE && *m2 == NULL_TREE)
2220     return 0;
2221   if (*m1 == NULL_TREE)
2222     return -1;
2223   if (*m2 == NULL_TREE)
2224     return 1;
2225   {
2226     tree d1 = DECL_NAME (OVL_CURRENT (*m1));
2227     tree d2 = DECL_NAME (OVL_CURRENT (*m2));
2228     resort_data.new_value (&d1, resort_data.cookie);
2229     resort_data.new_value (&d2, resort_data.cookie);
2230     if (d1 < d2)
2231       return -1;
2232   }
2233   return 1;
2234 }
2235
2236 /* Resort TYPE_METHOD_VEC because pointers have been reordered.  */
2237
2238 void
2239 resort_type_method_vec (void* obj,
2240                         void* /*orig_obj*/,
2241                         gt_pointer_operator new_value,
2242                         void* cookie)
2243 {
2244   vec<tree, va_gc> *method_vec = (vec<tree, va_gc> *) obj;
2245   int len = vec_safe_length (method_vec);
2246   size_t slot;
2247   tree fn;
2248
2249   /* The type conversion ops have to live at the front of the vec, so we
2250      can't sort them.  */
2251   for (slot = CLASSTYPE_FIRST_CONVERSION_SLOT;
2252        vec_safe_iterate (method_vec, slot, &fn);
2253        ++slot)
2254     if (!DECL_CONV_FN_P (OVL_CURRENT (fn)))
2255       break;
2256
2257   if (len - slot > 1)
2258     {
2259       resort_data.new_value = new_value;
2260       resort_data.cookie = cookie;
2261       qsort (method_vec->address () + slot, len - slot, sizeof (tree),
2262              resort_method_name_cmp);
2263     }
2264 }
2265
2266 /* Warn about duplicate methods in fn_fields.
2267
2268    Sort methods that are not special (i.e., constructors, destructors,
2269    and type conversion operators) so that we can find them faster in
2270    search.  */
2271
2272 static void
2273 finish_struct_methods (tree t)
2274 {
2275   tree fn_fields;
2276   vec<tree, va_gc> *method_vec;
2277   int slot, len;
2278
2279   method_vec = CLASSTYPE_METHOD_VEC (t);
2280   if (!method_vec)
2281     return;
2282
2283   len = method_vec->length ();
2284
2285   /* Clear DECL_IN_AGGR_P for all functions.  */
2286   for (fn_fields = TYPE_METHODS (t); fn_fields;
2287        fn_fields = DECL_CHAIN (fn_fields))
2288     DECL_IN_AGGR_P (fn_fields) = 0;
2289
2290   /* Issue warnings about private constructors and such.  If there are
2291      no methods, then some public defaults are generated.  */
2292   maybe_warn_about_overly_private_class (t);
2293
2294   /* The type conversion ops have to live at the front of the vec, so we
2295      can't sort them.  */
2296   for (slot = CLASSTYPE_FIRST_CONVERSION_SLOT;
2297        method_vec->iterate (slot, &fn_fields);
2298        ++slot)
2299     if (!DECL_CONV_FN_P (OVL_CURRENT (fn_fields)))
2300       break;
2301   if (len - slot > 1)
2302     qsort (method_vec->address () + slot,
2303            len-slot, sizeof (tree), method_name_cmp);
2304 }
2305
2306 /* Make BINFO's vtable have N entries, including RTTI entries,
2307    vbase and vcall offsets, etc.  Set its type and call the back end
2308    to lay it out.  */
2309
2310 static void
2311 layout_vtable_decl (tree binfo, int n)
2312 {
2313   tree atype;
2314   tree vtable;
2315
2316   atype = build_array_of_n_type (vtable_entry_type, n);
2317   layout_type (atype);
2318
2319   /* We may have to grow the vtable.  */
2320   vtable = get_vtbl_decl_for_binfo (binfo);
2321   if (!same_type_p (TREE_TYPE (vtable), atype))
2322     {
2323       TREE_TYPE (vtable) = atype;
2324       DECL_SIZE (vtable) = DECL_SIZE_UNIT (vtable) = NULL_TREE;
2325       layout_decl (vtable, 0);
2326     }
2327 }
2328
2329 /* True iff FNDECL and BASE_FNDECL (both non-static member functions)
2330    have the same signature.  */
2331
2332 int
2333 same_signature_p (const_tree fndecl, const_tree base_fndecl)
2334 {
2335   /* One destructor overrides another if they are the same kind of
2336      destructor.  */
2337   if (DECL_DESTRUCTOR_P (base_fndecl) && DECL_DESTRUCTOR_P (fndecl)
2338       && special_function_p (base_fndecl) == special_function_p (fndecl))
2339     return 1;
2340   /* But a non-destructor never overrides a destructor, nor vice
2341      versa, nor do different kinds of destructors override
2342      one-another.  For example, a complete object destructor does not
2343      override a deleting destructor.  */
2344   if (DECL_DESTRUCTOR_P (base_fndecl) || DECL_DESTRUCTOR_P (fndecl))
2345     return 0;
2346
2347   if (DECL_NAME (fndecl) == DECL_NAME (base_fndecl)
2348       || (DECL_CONV_FN_P (fndecl)
2349           && DECL_CONV_FN_P (base_fndecl)
2350           && same_type_p (DECL_CONV_FN_TYPE (fndecl),
2351                           DECL_CONV_FN_TYPE (base_fndecl))))
2352     {
2353       tree fntype = TREE_TYPE (fndecl);
2354       tree base_fntype = TREE_TYPE (base_fndecl);
2355       if (type_memfn_quals (fntype) == type_memfn_quals (base_fntype)
2356           && type_memfn_rqual (fntype) == type_memfn_rqual (base_fntype)
2357           && compparms (FUNCTION_FIRST_USER_PARMTYPE (fndecl),
2358                         FUNCTION_FIRST_USER_PARMTYPE (base_fndecl)))
2359         return 1;
2360     }
2361   return 0;
2362 }
2363
2364 /* Returns TRUE if DERIVED is a binfo containing the binfo BASE as a
2365    subobject.  */
2366
2367 static bool
2368 base_derived_from (tree derived, tree base)
2369 {
2370   tree probe;
2371
2372   for (probe = base; probe; probe = BINFO_INHERITANCE_CHAIN (probe))
2373     {
2374       if (probe == derived)
2375         return true;
2376       else if (BINFO_VIRTUAL_P (probe))
2377         /* If we meet a virtual base, we can't follow the inheritance
2378            any more.  See if the complete type of DERIVED contains
2379            such a virtual base.  */
2380         return (binfo_for_vbase (BINFO_TYPE (probe), BINFO_TYPE (derived))
2381                 != NULL_TREE);
2382     }
2383   return false;
2384 }
2385
2386 typedef struct find_final_overrider_data_s {
2387   /* The function for which we are trying to find a final overrider.  */
2388   tree fn;
2389   /* The base class in which the function was declared.  */
2390   tree declaring_base;
2391   /* The candidate overriders.  */
2392   tree candidates;
2393   /* Path to most derived.  */
2394   vec<tree> path;
2395 } find_final_overrider_data;
2396
2397 /* Add the overrider along the current path to FFOD->CANDIDATES.
2398    Returns true if an overrider was found; false otherwise.  */
2399
2400 static bool
2401 dfs_find_final_overrider_1 (tree binfo,
2402                             find_final_overrider_data *ffod,
2403                             unsigned depth)
2404 {
2405   tree method;
2406
2407   /* If BINFO is not the most derived type, try a more derived class.
2408      A definition there will overrider a definition here.  */
2409   if (depth)
2410     {
2411       depth--;
2412       if (dfs_find_final_overrider_1
2413           (ffod->path[depth], ffod, depth))
2414         return true;
2415     }
2416
2417   method = look_for_overrides_here (BINFO_TYPE (binfo), ffod->fn);
2418   if (method)
2419     {
2420       tree *candidate = &ffod->candidates;
2421
2422       /* Remove any candidates overridden by this new function.  */
2423       while (*candidate)
2424         {
2425           /* If *CANDIDATE overrides METHOD, then METHOD
2426              cannot override anything else on the list.  */
2427           if (base_derived_from (TREE_VALUE (*candidate), binfo))
2428             return true;
2429           /* If METHOD overrides *CANDIDATE, remove *CANDIDATE.  */
2430           if (base_derived_from (binfo, TREE_VALUE (*candidate)))
2431             *candidate = TREE_CHAIN (*candidate);
2432           else
2433             candidate = &TREE_CHAIN (*candidate);
2434         }
2435
2436       /* Add the new function.  */
2437       ffod->candidates = tree_cons (method, binfo, ffod->candidates);
2438       return true;
2439     }
2440
2441   return false;
2442 }
2443
2444 /* Called from find_final_overrider via dfs_walk.  */
2445
2446 static tree
2447 dfs_find_final_overrider_pre (tree binfo, void *data)
2448 {
2449   find_final_overrider_data *ffod = (find_final_overrider_data *) data;
2450
2451   if (binfo == ffod->declaring_base)
2452     dfs_find_final_overrider_1 (binfo, ffod, ffod->path.length ());
2453   ffod->path.safe_push (binfo);
2454
2455   return NULL_TREE;
2456 }
2457
2458 static tree
2459 dfs_find_final_overrider_post (tree /*binfo*/, void *data)
2460 {
2461   find_final_overrider_data *ffod = (find_final_overrider_data *) data;
2462   ffod->path.pop ();
2463
2464   return NULL_TREE;
2465 }
2466
2467 /* Returns a TREE_LIST whose TREE_PURPOSE is the final overrider for
2468    FN and whose TREE_VALUE is the binfo for the base where the
2469    overriding occurs.  BINFO (in the hierarchy dominated by the binfo
2470    DERIVED) is the base object in which FN is declared.  */
2471
2472 static tree
2473 find_final_overrider (tree derived, tree binfo, tree fn)
2474 {
2475   find_final_overrider_data ffod;
2476
2477   /* Getting this right is a little tricky.  This is valid:
2478
2479        struct S { virtual void f (); };
2480        struct T { virtual void f (); };
2481        struct U : public S, public T { };
2482
2483      even though calling `f' in `U' is ambiguous.  But,
2484
2485        struct R { virtual void f(); };
2486        struct S : virtual public R { virtual void f (); };
2487        struct T : virtual public R { virtual void f (); };
2488        struct U : public S, public T { };
2489
2490      is not -- there's no way to decide whether to put `S::f' or
2491      `T::f' in the vtable for `R'.
2492
2493      The solution is to look at all paths to BINFO.  If we find
2494      different overriders along any two, then there is a problem.  */
2495   if (DECL_THUNK_P (fn))
2496     fn = THUNK_TARGET (fn);
2497
2498   /* Determine the depth of the hierarchy.  */
2499   ffod.fn = fn;
2500   ffod.declaring_base = binfo;
2501   ffod.candidates = NULL_TREE;
2502   ffod.path.create (30);
2503
2504   dfs_walk_all (derived, dfs_find_final_overrider_pre,
2505                 dfs_find_final_overrider_post, &ffod);
2506
2507   ffod.path.release ();
2508
2509   /* If there was no winner, issue an error message.  */
2510   if (!ffod.candidates || TREE_CHAIN (ffod.candidates))
2511     return error_mark_node;
2512
2513   return ffod.candidates;
2514 }
2515
2516 /* Return the index of the vcall offset for FN when TYPE is used as a
2517    virtual base.  */
2518
2519 static tree
2520 get_vcall_index (tree fn, tree type)
2521 {
2522   vec<tree_pair_s, va_gc> *indices = CLASSTYPE_VCALL_INDICES (type);
2523   tree_pair_p p;
2524   unsigned ix;
2525
2526   FOR_EACH_VEC_SAFE_ELT (indices, ix, p)
2527     if ((DECL_DESTRUCTOR_P (fn) && DECL_DESTRUCTOR_P (p->purpose))
2528         || same_signature_p (fn, p->purpose))
2529       return p->value;
2530
2531   /* There should always be an appropriate index.  */
2532   gcc_unreachable ();
2533 }
2534
2535 /* Update an entry in the vtable for BINFO, which is in the hierarchy
2536    dominated by T.  FN is the old function; VIRTUALS points to the
2537    corresponding position in the new BINFO_VIRTUALS list.  IX is the index
2538    of that entry in the list.  */
2539
2540 static void
2541 update_vtable_entry_for_fn (tree t, tree binfo, tree fn, tree* virtuals,
2542                             unsigned ix)
2543 {
2544   tree b;
2545   tree overrider;
2546   tree delta;
2547   tree virtual_base;
2548   tree first_defn;
2549   tree overrider_fn, overrider_target;
2550   tree target_fn = DECL_THUNK_P (fn) ? THUNK_TARGET (fn) : fn;
2551   tree over_return, base_return;
2552   bool lost = false;
2553
2554   /* Find the nearest primary base (possibly binfo itself) which defines
2555      this function; this is the class the caller will convert to when
2556      calling FN through BINFO.  */
2557   for (b = binfo; ; b = get_primary_binfo (b))
2558     {
2559       gcc_assert (b);
2560       if (look_for_overrides_here (BINFO_TYPE (b), target_fn))
2561         break;
2562
2563       /* The nearest definition is from a lost primary.  */
2564       if (BINFO_LOST_PRIMARY_P (b))
2565         lost = true;
2566     }
2567   first_defn = b;
2568
2569   /* Find the final overrider.  */
2570   overrider = find_final_overrider (TYPE_BINFO (t), b, target_fn);
2571   if (overrider == error_mark_node)
2572     {
2573       error ("no unique final overrider for %qD in %qT", target_fn, t);
2574       return;
2575     }
2576   overrider_target = overrider_fn = TREE_PURPOSE (overrider);
2577
2578   /* Check for adjusting covariant return types.  */
2579   over_return = TREE_TYPE (TREE_TYPE (overrider_target));
2580   base_return = TREE_TYPE (TREE_TYPE (target_fn));
2581
2582   if (POINTER_TYPE_P (over_return)
2583       && TREE_CODE (over_return) == TREE_CODE (base_return)
2584       && CLASS_TYPE_P (TREE_TYPE (over_return))
2585       && CLASS_TYPE_P (TREE_TYPE (base_return))
2586       /* If the overrider is invalid, don't even try.  */
2587       && !DECL_INVALID_OVERRIDER_P (overrider_target))
2588     {
2589       /* If FN is a covariant thunk, we must figure out the adjustment
2590          to the final base FN was converting to. As OVERRIDER_TARGET might
2591          also be converting to the return type of FN, we have to
2592          combine the two conversions here.  */
2593       tree fixed_offset, virtual_offset;
2594
2595       over_return = TREE_TYPE (over_return);
2596       base_return = TREE_TYPE (base_return);
2597
2598       if (DECL_THUNK_P (fn))
2599         {
2600           gcc_assert (DECL_RESULT_THUNK_P (fn));
2601           fixed_offset = ssize_int (THUNK_FIXED_OFFSET (fn));
2602           virtual_offset = THUNK_VIRTUAL_OFFSET (fn);
2603         }
2604       else
2605         fixed_offset = virtual_offset = NULL_TREE;
2606
2607       if (virtual_offset)
2608         /* Find the equivalent binfo within the return type of the
2609            overriding function. We will want the vbase offset from
2610            there.  */
2611         virtual_offset = binfo_for_vbase (BINFO_TYPE (virtual_offset),
2612                                           over_return);
2613       else if (!same_type_ignoring_top_level_qualifiers_p
2614                (over_return, base_return))
2615         {
2616           /* There was no existing virtual thunk (which takes
2617              precedence).  So find the binfo of the base function's
2618              return type within the overriding function's return type.
2619              We cannot call lookup base here, because we're inside a
2620              dfs_walk, and will therefore clobber the BINFO_MARKED
2621              flags.  Fortunately we know the covariancy is valid (it
2622              has already been checked), so we can just iterate along
2623              the binfos, which have been chained in inheritance graph
2624              order.  Of course it is lame that we have to repeat the
2625              search here anyway -- we should really be caching pieces
2626              of the vtable and avoiding this repeated work.  */
2627           tree thunk_binfo, base_binfo;
2628
2629           /* Find the base binfo within the overriding function's
2630              return type.  We will always find a thunk_binfo, except
2631              when the covariancy is invalid (which we will have
2632              already diagnosed).  */
2633           for (base_binfo = TYPE_BINFO (base_return),
2634                thunk_binfo = TYPE_BINFO (over_return);
2635                thunk_binfo;
2636                thunk_binfo = TREE_CHAIN (thunk_binfo))
2637             if (SAME_BINFO_TYPE_P (BINFO_TYPE (thunk_binfo),
2638                                    BINFO_TYPE (base_binfo)))
2639               break;
2640
2641           /* See if virtual inheritance is involved.  */
2642           for (virtual_offset = thunk_binfo;
2643                virtual_offset;
2644                virtual_offset = BINFO_INHERITANCE_CHAIN (virtual_offset))
2645             if (BINFO_VIRTUAL_P (virtual_offset))
2646               break;
2647
2648           if (virtual_offset
2649               || (thunk_binfo && !BINFO_OFFSET_ZEROP (thunk_binfo)))
2650             {
2651               tree offset = convert (ssizetype, BINFO_OFFSET (thunk_binfo));
2652
2653               if (virtual_offset)
2654                 {
2655                   /* We convert via virtual base.  Adjust the fixed
2656                      offset to be from there.  */
2657                   offset = 
2658                     size_diffop (offset,
2659                                  convert (ssizetype,
2660                                           BINFO_OFFSET (virtual_offset)));
2661                 }
2662               if (fixed_offset)
2663                 /* There was an existing fixed offset, this must be
2664                    from the base just converted to, and the base the
2665                    FN was thunking to.  */
2666                 fixed_offset = size_binop (PLUS_EXPR, fixed_offset, offset);
2667               else
2668                 fixed_offset = offset;
2669             }
2670         }
2671
2672       if (fixed_offset || virtual_offset)
2673         /* Replace the overriding function with a covariant thunk.  We
2674            will emit the overriding function in its own slot as
2675            well.  */
2676         overrider_fn = make_thunk (overrider_target, /*this_adjusting=*/0,
2677                                    fixed_offset, virtual_offset);
2678     }
2679   else
2680     gcc_assert (DECL_INVALID_OVERRIDER_P (overrider_target) ||
2681                 !DECL_THUNK_P (fn));
2682
2683   /* If we need a covariant thunk, then we may need to adjust first_defn.
2684      The ABI specifies that the thunks emitted with a function are
2685      determined by which bases the function overrides, so we need to be
2686      sure that we're using a thunk for some overridden base; even if we
2687      know that the necessary this adjustment is zero, there may not be an
2688      appropriate zero-this-adjusment thunk for us to use since thunks for
2689      overriding virtual bases always use the vcall offset.
2690
2691      Furthermore, just choosing any base that overrides this function isn't
2692      quite right, as this slot won't be used for calls through a type that
2693      puts a covariant thunk here.  Calling the function through such a type
2694      will use a different slot, and that slot is the one that determines
2695      the thunk emitted for that base.
2696
2697      So, keep looking until we find the base that we're really overriding
2698      in this slot: the nearest primary base that doesn't use a covariant
2699      thunk in this slot.  */
2700   if (overrider_target != overrider_fn)
2701     {
2702       if (BINFO_TYPE (b) == DECL_CONTEXT (overrider_target))
2703         /* We already know that the overrider needs a covariant thunk.  */
2704         b = get_primary_binfo (b);
2705       for (; ; b = get_primary_binfo (b))
2706         {
2707           tree main_binfo = TYPE_BINFO (BINFO_TYPE (b));
2708           tree bv = chain_index (ix, BINFO_VIRTUALS (main_binfo));
2709           if (!DECL_THUNK_P (TREE_VALUE (bv)))
2710             break;
2711           if (BINFO_LOST_PRIMARY_P (b))
2712             lost = true;
2713         }
2714       first_defn = b;
2715     }
2716
2717   /* Assume that we will produce a thunk that convert all the way to
2718      the final overrider, and not to an intermediate virtual base.  */
2719   virtual_base = NULL_TREE;
2720
2721   /* See if we can convert to an intermediate virtual base first, and then
2722      use the vcall offset located there to finish the conversion.  */
2723   for (; b; b = BINFO_INHERITANCE_CHAIN (b))
2724     {
2725       /* If we find the final overrider, then we can stop
2726          walking.  */
2727       if (SAME_BINFO_TYPE_P (BINFO_TYPE (b),
2728                              BINFO_TYPE (TREE_VALUE (overrider))))
2729         break;
2730
2731       /* If we find a virtual base, and we haven't yet found the
2732          overrider, then there is a virtual base between the
2733          declaring base (first_defn) and the final overrider.  */
2734       if (BINFO_VIRTUAL_P (b))
2735         {
2736           virtual_base = b;
2737           break;
2738         }
2739     }
2740
2741   /* Compute the constant adjustment to the `this' pointer.  The
2742      `this' pointer, when this function is called, will point at BINFO
2743      (or one of its primary bases, which are at the same offset).  */
2744   if (virtual_base)
2745     /* The `this' pointer needs to be adjusted from the declaration to
2746        the nearest virtual base.  */
2747     delta = size_diffop_loc (input_location,
2748                          convert (ssizetype, BINFO_OFFSET (virtual_base)),
2749                          convert (ssizetype, BINFO_OFFSET (first_defn)));
2750   else if (lost)
2751     /* If the nearest definition is in a lost primary, we don't need an
2752        entry in our vtable.  Except possibly in a constructor vtable,
2753        if we happen to get our primary back.  In that case, the offset
2754        will be zero, as it will be a primary base.  */
2755     delta = size_zero_node;
2756   else
2757     /* The `this' pointer needs to be adjusted from pointing to
2758        BINFO to pointing at the base where the final overrider
2759        appears.  */
2760     delta = size_diffop_loc (input_location,
2761                          convert (ssizetype,
2762                                   BINFO_OFFSET (TREE_VALUE (overrider))),
2763                          convert (ssizetype, BINFO_OFFSET (binfo)));
2764
2765   modify_vtable_entry (t, binfo, overrider_fn, delta, virtuals);
2766
2767   if (virtual_base)
2768     BV_VCALL_INDEX (*virtuals)
2769       = get_vcall_index (overrider_target, BINFO_TYPE (virtual_base));
2770   else
2771     BV_VCALL_INDEX (*virtuals) = NULL_TREE;
2772
2773   BV_LOST_PRIMARY (*virtuals) = lost;
2774 }
2775
2776 /* Called from modify_all_vtables via dfs_walk.  */
2777
2778 static tree
2779 dfs_modify_vtables (tree binfo, void* data)
2780 {
2781   tree t = (tree) data;
2782   tree virtuals;
2783   tree old_virtuals;
2784   unsigned ix;
2785
2786   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
2787     /* A base without a vtable needs no modification, and its bases
2788        are uninteresting.  */
2789     return dfs_skip_bases;
2790
2791   if (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t)
2792       && !CLASSTYPE_HAS_PRIMARY_BASE_P (t))
2793     /* Don't do the primary vtable, if it's new.  */
2794     return NULL_TREE;
2795
2796   if (BINFO_PRIMARY_P (binfo) && !BINFO_VIRTUAL_P (binfo))
2797     /* There's no need to modify the vtable for a non-virtual primary
2798        base; we're not going to use that vtable anyhow.  We do still
2799        need to do this for virtual primary bases, as they could become
2800        non-primary in a construction vtable.  */
2801     return NULL_TREE;
2802
2803   make_new_vtable (t, binfo);
2804
2805   /* Now, go through each of the virtual functions in the virtual
2806      function table for BINFO.  Find the final overrider, and update
2807      the BINFO_VIRTUALS list appropriately.  */
2808   for (ix = 0, virtuals = BINFO_VIRTUALS (binfo),
2809          old_virtuals = BINFO_VIRTUALS (TYPE_BINFO (BINFO_TYPE (binfo)));
2810        virtuals;
2811        ix++, virtuals = TREE_CHAIN (virtuals),
2812          old_virtuals = TREE_CHAIN (old_virtuals))
2813     update_vtable_entry_for_fn (t,
2814                                 binfo,
2815                                 BV_FN (old_virtuals),
2816                                 &virtuals, ix);
2817
2818   return NULL_TREE;
2819 }
2820
2821 /* Update all of the primary and secondary vtables for T.  Create new
2822    vtables as required, and initialize their RTTI information.  Each
2823    of the functions in VIRTUALS is declared in T and may override a
2824    virtual function from a base class; find and modify the appropriate
2825    entries to point to the overriding functions.  Returns a list, in
2826    declaration order, of the virtual functions that are declared in T,
2827    but do not appear in the primary base class vtable, and which
2828    should therefore be appended to the end of the vtable for T.  */
2829
2830 static tree
2831 modify_all_vtables (tree t, tree virtuals)
2832 {
2833   tree binfo = TYPE_BINFO (t);
2834   tree *fnsp;
2835
2836   /* Mangle the vtable name before entering dfs_walk (c++/51884).  */
2837   if (TYPE_CONTAINS_VPTR_P (t))
2838     get_vtable_decl (t, false);
2839
2840   /* Update all of the vtables.  */
2841   dfs_walk_once (binfo, dfs_modify_vtables, NULL, t);
2842
2843   /* Add virtual functions not already in our primary vtable. These
2844      will be both those introduced by this class, and those overridden
2845      from secondary bases.  It does not include virtuals merely
2846      inherited from secondary bases.  */
2847   for (fnsp = &virtuals; *fnsp; )
2848     {
2849       tree fn = TREE_VALUE (*fnsp);
2850
2851       if (!value_member (fn, BINFO_VIRTUALS (binfo))
2852           || DECL_VINDEX (fn) == error_mark_node)
2853         {
2854           /* We don't need to adjust the `this' pointer when
2855              calling this function.  */
2856           BV_DELTA (*fnsp) = integer_zero_node;
2857           BV_VCALL_INDEX (*fnsp) = NULL_TREE;
2858
2859           /* This is a function not already in our vtable.  Keep it.  */
2860           fnsp = &TREE_CHAIN (*fnsp);
2861         }
2862       else
2863         /* We've already got an entry for this function.  Skip it.  */
2864         *fnsp = TREE_CHAIN (*fnsp);
2865     }
2866
2867   return virtuals;
2868 }
2869
2870 /* Get the base virtual function declarations in T that have the
2871    indicated NAME.  */
2872
2873 static void
2874 get_basefndecls (tree name, tree t, vec<tree> *base_fndecls)
2875 {
2876   tree methods;
2877   int n_baseclasses = BINFO_N_BASE_BINFOS (TYPE_BINFO (t));
2878   int i;
2879
2880   /* Find virtual functions in T with the indicated NAME.  */
2881   i = lookup_fnfields_1 (t, name);
2882   bool found_decls = false;
2883   if (i != -1)
2884     for (methods = (*CLASSTYPE_METHOD_VEC (t))[i];
2885          methods;
2886          methods = OVL_NEXT (methods))
2887       {
2888         tree method = OVL_CURRENT (methods);
2889
2890         if (TREE_CODE (method) == FUNCTION_DECL
2891             && DECL_VINDEX (method))
2892           {
2893             base_fndecls->safe_push (method);
2894             found_decls = true;
2895           }
2896       }
2897
2898   if (found_decls)
2899     return;
2900
2901   for (i = 0; i < n_baseclasses; i++)
2902     {
2903       tree basetype = BINFO_TYPE (BINFO_BASE_BINFO (TYPE_BINFO (t), i));
2904       get_basefndecls (name, basetype, base_fndecls);
2905     }
2906 }
2907
2908 /* If this declaration supersedes the declaration of
2909    a method declared virtual in the base class, then
2910    mark this field as being virtual as well.  */
2911
2912 void
2913 check_for_override (tree decl, tree ctype)
2914 {
2915   bool overrides_found = false;
2916   if (TREE_CODE (decl) == TEMPLATE_DECL)
2917     /* In [temp.mem] we have:
2918
2919          A specialization of a member function template does not
2920          override a virtual function from a base class.  */
2921     return;
2922   if ((DECL_DESTRUCTOR_P (decl)
2923        || IDENTIFIER_VIRTUAL_P (DECL_NAME (decl))
2924        || DECL_CONV_FN_P (decl))
2925       && look_for_overrides (ctype, decl)
2926       && !DECL_STATIC_FUNCTION_P (decl))
2927     /* Set DECL_VINDEX to a value that is neither an INTEGER_CST nor
2928        the error_mark_node so that we know it is an overriding
2929        function.  */
2930     {
2931       DECL_VINDEX (decl) = decl;
2932       overrides_found = true;
2933       if (warn_override && !DECL_OVERRIDE_P (decl)
2934           && !DECL_DESTRUCTOR_P (decl))
2935         warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wsuggest_override,
2936                     "%q+D can be marked override", decl);
2937     }
2938
2939   if (DECL_VIRTUAL_P (decl))
2940     {
2941       if (!DECL_VINDEX (decl))
2942         DECL_VINDEX (decl) = error_mark_node;
2943       IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = 1;
2944       if (DECL_DESTRUCTOR_P (decl))
2945         TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype) = true;
2946     }
2947   else if (DECL_FINAL_P (decl))
2948     error ("%q+#D marked %<final%>, but is not virtual", decl);
2949   if (DECL_OVERRIDE_P (decl) && !overrides_found)
2950     error ("%q+#D marked %<override%>, but does not override", decl);
2951 }
2952
2953 /* Warn about hidden virtual functions that are not overridden in t.
2954    We know that constructors and destructors don't apply.  */
2955
2956 static void
2957 warn_hidden (tree t)
2958 {
2959   vec<tree, va_gc> *method_vec = CLASSTYPE_METHOD_VEC (t);
2960   tree fns;
2961   size_t i;
2962
2963   /* We go through each separately named virtual function.  */
2964   for (i = CLASSTYPE_FIRST_CONVERSION_SLOT;
2965        vec_safe_iterate (method_vec, i, &fns);
2966        ++i)
2967     {
2968       tree fn;
2969       tree name;
2970       tree fndecl;
2971       tree base_binfo;
2972       tree binfo;
2973       int j;
2974
2975       /* All functions in this slot in the CLASSTYPE_METHOD_VEC will
2976          have the same name.  Figure out what name that is.  */
2977       name = DECL_NAME (OVL_CURRENT (fns));
2978       /* There are no possibly hidden functions yet.  */
2979       auto_vec<tree, 20> base_fndecls;
2980       /* Iterate through all of the base classes looking for possibly
2981          hidden functions.  */
2982       for (binfo = TYPE_BINFO (t), j = 0;
2983            BINFO_BASE_ITERATE (binfo, j, base_binfo); j++)
2984         {
2985           tree basetype = BINFO_TYPE (base_binfo);
2986           get_basefndecls (name, basetype, &base_fndecls);
2987         }
2988
2989       /* If there are no functions to hide, continue.  */
2990       if (base_fndecls.is_empty ())
2991         continue;
2992
2993       /* Remove any overridden functions.  */
2994       for (fn = fns; fn; fn = OVL_NEXT (fn))
2995         {
2996           fndecl = OVL_CURRENT (fn);
2997           if (TREE_CODE (fndecl) == FUNCTION_DECL
2998               && DECL_VINDEX (fndecl))
2999             {
3000                 /* If the method from the base class has the same
3001                    signature as the method from the derived class, it
3002                    has been overridden.  */
3003                 for (size_t k = 0; k < base_fndecls.length (); k++)
3004                 if (base_fndecls[k]
3005                     && same_signature_p (fndecl, base_fndecls[k]))
3006                   base_fndecls[k] = NULL_TREE;
3007             }
3008         }
3009
3010       /* Now give a warning for all base functions without overriders,
3011          as they are hidden.  */
3012       size_t k;
3013       tree base_fndecl;
3014       FOR_EACH_VEC_ELT (base_fndecls, k, base_fndecl)
3015         if (base_fndecl)
3016           {
3017               /* Here we know it is a hider, and no overrider exists.  */
3018               warning (OPT_Woverloaded_virtual, "%q+D was hidden", base_fndecl);
3019               warning (OPT_Woverloaded_virtual, "  by %q+D", fns);
3020           }
3021     }
3022 }
3023
3024 /* Recursive helper for finish_struct_anon.  */
3025
3026 static void
3027 finish_struct_anon_r (tree field, bool complain)
3028 {
3029   bool is_union = TREE_CODE (TREE_TYPE (field)) == UNION_TYPE;
3030   tree elt = TYPE_FIELDS (TREE_TYPE (field));
3031   for (; elt; elt = DECL_CHAIN (elt))
3032     {
3033       /* We're generally only interested in entities the user
3034          declared, but we also find nested classes by noticing
3035          the TYPE_DECL that we create implicitly.  You're
3036          allowed to put one anonymous union inside another,
3037          though, so we explicitly tolerate that.  We use
3038          TYPE_ANONYMOUS_P rather than ANON_AGGR_TYPE_P so that
3039          we also allow unnamed types used for defining fields.  */
3040       if (DECL_ARTIFICIAL (elt)
3041           && (!DECL_IMPLICIT_TYPEDEF_P (elt)
3042               || TYPE_ANONYMOUS_P (TREE_TYPE (elt))))
3043         continue;
3044
3045       if (TREE_CODE (elt) != FIELD_DECL)
3046         {
3047           /* We already complained about static data members in
3048              finish_static_data_member_decl.  */
3049           if (complain && TREE_CODE (elt) != VAR_DECL)
3050             {
3051               if (is_union)
3052                 permerror (input_location,
3053                            "%q+#D invalid; an anonymous union can "
3054                            "only have non-static data members", elt);
3055               else
3056                 permerror (input_location,
3057                            "%q+#D invalid; an anonymous struct can "
3058                            "only have non-static data members", elt);
3059             }
3060           continue;
3061         }
3062
3063       if (complain)
3064         {
3065           if (TREE_PRIVATE (elt))
3066             {
3067               if (is_union)
3068                 permerror (input_location,
3069                            "private member %q+#D in anonymous union", elt);
3070               else
3071                 permerror (input_location,
3072                            "private member %q+#D in anonymous struct", elt);
3073             }
3074           else if (TREE_PROTECTED (elt))
3075             {
3076               if (is_union)
3077                 permerror (input_location,
3078                            "protected member %q+#D in anonymous union", elt);
3079               else
3080                 permerror (input_location,
3081                            "protected member %q+#D in anonymous struct", elt);
3082             }
3083         }
3084
3085       TREE_PRIVATE (elt) = TREE_PRIVATE (field);
3086       TREE_PROTECTED (elt) = TREE_PROTECTED (field);
3087
3088       /* Recurse into the anonymous aggregates to handle correctly
3089          access control (c++/24926):
3090
3091          class A {
3092            union {
3093              union {
3094                int i;
3095              };
3096            };
3097          };
3098
3099          int j=A().i;  */
3100       if (DECL_NAME (elt) == NULL_TREE
3101           && ANON_AGGR_TYPE_P (TREE_TYPE (elt)))
3102         finish_struct_anon_r (elt, /*complain=*/false);
3103     }
3104 }
3105
3106 /* Check for things that are invalid.  There are probably plenty of other
3107    things we should check for also.  */
3108
3109 static void
3110 finish_struct_anon (tree t)
3111 {
3112   for (tree field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
3113     {
3114       if (TREE_STATIC (field))
3115         continue;
3116       if (TREE_CODE (field) != FIELD_DECL)
3117         continue;
3118
3119       if (DECL_NAME (field) == NULL_TREE
3120           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
3121         finish_struct_anon_r (field, /*complain=*/true);
3122     }
3123 }
3124
3125 /* Add T to CLASSTYPE_DECL_LIST of current_class_type which
3126    will be used later during class template instantiation.
3127    When FRIEND_P is zero, T can be a static member data (VAR_DECL),
3128    a non-static member data (FIELD_DECL), a member function
3129    (FUNCTION_DECL), a nested type (RECORD_TYPE, ENUM_TYPE),
3130    a typedef (TYPE_DECL) or a member class template (TEMPLATE_DECL)
3131    When FRIEND_P is nonzero, T is either a friend class
3132    (RECORD_TYPE, TEMPLATE_DECL) or a friend function
3133    (FUNCTION_DECL, TEMPLATE_DECL).  */
3134
3135 void
3136 maybe_add_class_template_decl_list (tree type, tree t, int friend_p)
3137 {
3138   /* Save some memory by not creating TREE_LIST if TYPE is not template.  */
3139   if (CLASSTYPE_TEMPLATE_INFO (type))
3140     CLASSTYPE_DECL_LIST (type)
3141       = tree_cons (friend_p ? NULL_TREE : type,
3142                    t, CLASSTYPE_DECL_LIST (type));
3143 }
3144
3145 /* This function is called from declare_virt_assop_and_dtor via
3146    dfs_walk_all.
3147
3148    DATA is a type that direcly or indirectly inherits the base
3149    represented by BINFO.  If BINFO contains a virtual assignment [copy
3150    assignment or move assigment] operator or a virtual constructor,
3151    declare that function in DATA if it hasn't been already declared.  */
3152
3153 static tree
3154 dfs_declare_virt_assop_and_dtor (tree binfo, void *data)
3155 {
3156   tree bv, fn, t = (tree)data;
3157   tree opname = ansi_assopname (NOP_EXPR);
3158
3159   gcc_assert (t && CLASS_TYPE_P (t));
3160   gcc_assert (binfo && TREE_CODE (binfo) == TREE_BINFO);
3161
3162   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
3163     /* A base without a vtable needs no modification, and its bases
3164        are uninteresting.  */
3165     return dfs_skip_bases;
3166
3167   if (BINFO_PRIMARY_P (binfo))
3168     /* If this is a primary base, then we have already looked at the
3169        virtual functions of its vtable.  */
3170     return NULL_TREE;
3171
3172   for (bv = BINFO_VIRTUALS (binfo); bv; bv = TREE_CHAIN (bv))
3173     {
3174       fn = BV_FN (bv);
3175
3176       if (DECL_NAME (fn) == opname)
3177         {
3178           if (CLASSTYPE_LAZY_COPY_ASSIGN (t))
3179             lazily_declare_fn (sfk_copy_assignment, t);
3180           if (CLASSTYPE_LAZY_MOVE_ASSIGN (t))
3181             lazily_declare_fn (sfk_move_assignment, t);
3182         }
3183       else if (DECL_DESTRUCTOR_P (fn)
3184                && CLASSTYPE_LAZY_DESTRUCTOR (t))
3185         lazily_declare_fn (sfk_destructor, t);
3186     }
3187
3188   return NULL_TREE;
3189 }
3190
3191 /* If the class type T has a direct or indirect base that contains a
3192    virtual assignment operator or a virtual destructor, declare that
3193    function in T if it hasn't been already declared.  */
3194
3195 static void
3196 declare_virt_assop_and_dtor (tree t)
3197 {
3198   if (!(TYPE_POLYMORPHIC_P (t)
3199         && (CLASSTYPE_LAZY_COPY_ASSIGN (t)
3200             || CLASSTYPE_LAZY_MOVE_ASSIGN (t)
3201             || CLASSTYPE_LAZY_DESTRUCTOR (t))))
3202     return;
3203
3204   dfs_walk_all (TYPE_BINFO (t),
3205                 dfs_declare_virt_assop_and_dtor,
3206                 NULL, t);
3207 }
3208
3209 /* Declare the inheriting constructor for class T inherited from base
3210    constructor CTOR with the parameter array PARMS of size NPARMS.  */
3211
3212 static void
3213 one_inheriting_sig (tree t, tree ctor, tree *parms, int nparms)
3214 {
3215   /* We don't declare an inheriting ctor that would be a default,
3216      copy or move ctor for derived or base.  */
3217   if (nparms == 0)
3218     return;
3219   if (nparms == 1
3220       && TREE_CODE (parms[0]) == REFERENCE_TYPE)
3221     {
3222       tree parm = TYPE_MAIN_VARIANT (TREE_TYPE (parms[0]));
3223       if (parm == t || parm == DECL_CONTEXT (ctor))
3224         return;
3225     }
3226
3227   tree parmlist = void_list_node;
3228   for (int i = nparms - 1; i >= 0; i--)
3229     parmlist = tree_cons (NULL_TREE, parms[i], parmlist);
3230   tree fn = implicitly_declare_fn (sfk_inheriting_constructor,
3231                                    t, false, ctor, parmlist);
3232   if (add_method (t, fn, NULL_TREE))
3233     {
3234       DECL_CHAIN (fn) = TYPE_METHODS (t);
3235       TYPE_METHODS (t) = fn;
3236     }
3237 }
3238
3239 /* Declare all the inheriting constructors for class T inherited from base
3240    constructor CTOR.  */
3241
3242 static void
3243 one_inherited_ctor (tree ctor, tree t)
3244 {
3245   tree parms = FUNCTION_FIRST_USER_PARMTYPE (ctor);
3246
3247   tree *new_parms = XALLOCAVEC (tree, list_length (parms));
3248   int i = 0;
3249   for (; parms && parms != void_list_node; parms = TREE_CHAIN (parms))
3250     {
3251       if (TREE_PURPOSE (parms))
3252         one_inheriting_sig (t, ctor, new_parms, i);
3253       new_parms[i++] = TREE_VALUE (parms);
3254     }
3255   one_inheriting_sig (t, ctor, new_parms, i);
3256   if (parms == NULL_TREE)
3257     {
3258       if (warning (OPT_Winherited_variadic_ctor,
3259                    "the ellipsis in %qD is not inherited", ctor))
3260         inform (DECL_SOURCE_LOCATION (ctor), "%qD declared here", ctor);
3261     }
3262 }
3263
3264 /* Create default constructors, assignment operators, and so forth for
3265    the type indicated by T, if they are needed.  CANT_HAVE_CONST_CTOR,
3266    and CANT_HAVE_CONST_ASSIGNMENT are nonzero if, for whatever reason,
3267    the class cannot have a default constructor, copy constructor
3268    taking a const reference argument, or an assignment operator taking
3269    a const reference, respectively.  */
3270
3271 static void
3272 add_implicitly_declared_members (tree t, tree* access_decls,
3273                                  int cant_have_const_cctor,
3274                                  int cant_have_const_assignment)
3275 {
3276   bool move_ok = false;
3277
3278   if (cxx_dialect >= cxx11 && !CLASSTYPE_DESTRUCTORS (t)
3279       && !TYPE_HAS_COPY_CTOR (t) && !TYPE_HAS_COPY_ASSIGN (t)
3280       && !type_has_move_constructor (t) && !type_has_move_assign (t))
3281     move_ok = true;
3282
3283   /* Destructor.  */
3284   if (!CLASSTYPE_DESTRUCTORS (t))
3285     {
3286       /* In general, we create destructors lazily.  */
3287       CLASSTYPE_LAZY_DESTRUCTOR (t) = 1;
3288
3289       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
3290           && TYPE_FOR_JAVA (t))
3291         /* But if this is a Java class, any non-trivial destructor is
3292            invalid, even if compiler-generated.  Therefore, if the
3293            destructor is non-trivial we create it now.  */
3294         lazily_declare_fn (sfk_destructor, t);
3295     }
3296
3297   /* [class.ctor]
3298
3299      If there is no user-declared constructor for a class, a default
3300      constructor is implicitly declared.  */
3301   if (! TYPE_HAS_USER_CONSTRUCTOR (t))
3302     {
3303       TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 1;
3304       CLASSTYPE_LAZY_DEFAULT_CTOR (t) = 1;
3305       if (cxx_dialect >= cxx11)
3306         TYPE_HAS_CONSTEXPR_CTOR (t)
3307           /* This might force the declaration.  */
3308           = type_has_constexpr_default_constructor (t);
3309     }
3310
3311   /* [class.ctor]
3312
3313      If a class definition does not explicitly declare a copy
3314      constructor, one is declared implicitly.  */
3315   if (! TYPE_HAS_COPY_CTOR (t) && ! TYPE_FOR_JAVA (t))
3316     {
3317       TYPE_HAS_COPY_CTOR (t) = 1;
3318       TYPE_HAS_CONST_COPY_CTOR (t) = !cant_have_const_cctor;
3319       CLASSTYPE_LAZY_COPY_CTOR (t) = 1;
3320       if (move_ok)
3321         CLASSTYPE_LAZY_MOVE_CTOR (t) = 1;
3322     }
3323
3324   /* If there is no assignment operator, one will be created if and
3325      when it is needed.  For now, just record whether or not the type
3326      of the parameter to the assignment operator will be a const or
3327      non-const reference.  */
3328   if (!TYPE_HAS_COPY_ASSIGN (t) && !TYPE_FOR_JAVA (t))
3329     {
3330       TYPE_HAS_COPY_ASSIGN (t) = 1;
3331       TYPE_HAS_CONST_COPY_ASSIGN (t) = !cant_have_const_assignment;
3332       CLASSTYPE_LAZY_COPY_ASSIGN (t) = 1;
3333       if (move_ok && !LAMBDA_TYPE_P (t))
3334         CLASSTYPE_LAZY_MOVE_ASSIGN (t) = 1;
3335     }
3336
3337   /* We can't be lazy about declaring functions that might override
3338      a virtual function from a base class.  */
3339   declare_virt_assop_and_dtor (t);
3340
3341   while (*access_decls)
3342     {
3343       tree using_decl = TREE_VALUE (*access_decls);
3344       tree decl = USING_DECL_DECLS (using_decl);
3345       if (DECL_NAME (using_decl) == ctor_identifier)
3346         {
3347           /* declare, then remove the decl */
3348           tree ctor_list = decl;
3349           location_t loc = input_location;
3350           input_location = DECL_SOURCE_LOCATION (using_decl);
3351           if (ctor_list)
3352             for (; ctor_list; ctor_list = OVL_NEXT (ctor_list))
3353               one_inherited_ctor (OVL_CURRENT (ctor_list), t);
3354           *access_decls = TREE_CHAIN (*access_decls);
3355           input_location = loc;
3356         }
3357       else
3358         access_decls = &TREE_CHAIN (*access_decls);
3359     }
3360 }
3361
3362 /* Subroutine of insert_into_classtype_sorted_fields.  Recursively
3363    count the number of fields in TYPE, including anonymous union
3364    members.  */
3365
3366 static int
3367 count_fields (tree fields)
3368 {
3369   tree x;
3370   int n_fields = 0;
3371   for (x = fields; x; x = DECL_CHAIN (x))
3372     {
3373       if (TREE_CODE (x) == FIELD_DECL && ANON_AGGR_TYPE_P (TREE_TYPE (x)))
3374         n_fields += count_fields (TYPE_FIELDS (TREE_TYPE (x)));
3375       else
3376         n_fields += 1;
3377     }
3378   return n_fields;
3379 }
3380
3381 /* Subroutine of insert_into_classtype_sorted_fields.  Recursively add
3382    all the fields in the TREE_LIST FIELDS to the SORTED_FIELDS_TYPE
3383    elts, starting at offset IDX.  */
3384
3385 static int
3386 add_fields_to_record_type (tree fields, struct sorted_fields_type *field_vec, int idx)
3387 {
3388   tree x;
3389   for (x = fields; x; x = DECL_CHAIN (x))
3390     {
3391       if (TREE_CODE (x) == FIELD_DECL && ANON_AGGR_TYPE_P (TREE_TYPE (x)))
3392         idx = add_fields_to_record_type (TYPE_FIELDS (TREE_TYPE (x)), field_vec, idx);
3393       else
3394         field_vec->elts[idx++] = x;
3395     }
3396   return idx;
3397 }
3398
3399 /* Add all of the enum values of ENUMTYPE, to the FIELD_VEC elts,
3400    starting at offset IDX.  */
3401
3402 static int
3403 add_enum_fields_to_record_type (tree enumtype,
3404                                 struct sorted_fields_type *field_vec,
3405                                 int idx)
3406 {
3407   tree values;
3408   for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
3409       field_vec->elts[idx++] = TREE_VALUE (values);
3410   return idx;
3411 }
3412
3413 /* FIELD is a bit-field.  We are finishing the processing for its
3414    enclosing type.  Issue any appropriate messages and set appropriate
3415    flags.  Returns false if an error has been diagnosed.  */
3416
3417 static bool
3418 check_bitfield_decl (tree field)
3419 {
3420   tree type = TREE_TYPE (field);
3421   tree w;
3422
3423   /* Extract the declared width of the bitfield, which has been
3424      temporarily stashed in DECL_INITIAL.  */
3425   w = DECL_INITIAL (field);
3426   gcc_assert (w != NULL_TREE);
3427   /* Remove the bit-field width indicator so that the rest of the
3428      compiler does not treat that value as an initializer.  */
3429   DECL_INITIAL (field) = NULL_TREE;
3430
3431   /* Detect invalid bit-field type.  */
3432   if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
3433     {
3434       error ("bit-field %q+#D with non-integral type", field);
3435       w = error_mark_node;
3436     }
3437   else
3438     {
3439       location_t loc = input_location;
3440       /* Avoid the non_lvalue wrapper added by fold for PLUS_EXPRs.  */
3441       STRIP_NOPS (w);
3442
3443       /* detect invalid field size.  */
3444       input_location = DECL_SOURCE_LOCATION (field);
3445       w = cxx_constant_value (w);
3446       input_location = loc;
3447
3448       if (TREE_CODE (w) != INTEGER_CST)
3449         {
3450           error ("bit-field %q+D width not an integer constant", field);
3451           w = error_mark_node;
3452         }
3453       else if (tree_int_cst_sgn (w) < 0)
3454         {
3455           error ("negative width in bit-field %q+D", field);
3456           w = error_mark_node;
3457         }
3458       else if (integer_zerop (w) && DECL_NAME (field) != 0)
3459         {
3460           error ("zero width for bit-field %q+D", field);
3461           w = error_mark_node;
3462         }
3463       else if ((TREE_CODE (type) != ENUMERAL_TYPE
3464                 && TREE_CODE (type) != BOOLEAN_TYPE
3465                 && compare_tree_int (w, TYPE_PRECISION (type)) > 0)
3466                || ((TREE_CODE (type) == ENUMERAL_TYPE
3467                     || TREE_CODE (type) == BOOLEAN_TYPE)
3468                    && tree_int_cst_lt (TYPE_SIZE (type), w)))
3469         warning (0, "width of %q+D exceeds its type", field);
3470       else if (TREE_CODE (type) == ENUMERAL_TYPE
3471                && (0 > (compare_tree_int
3472                         (w, TYPE_PRECISION (ENUM_UNDERLYING_TYPE (type))))))
3473         warning (0, "%q+D is too small to hold all values of %q#T", field, type);
3474     }
3475
3476   if (w != error_mark_node)
3477     {
3478       DECL_SIZE (field) = convert (bitsizetype, w);
3479       DECL_BIT_FIELD (field) = 1;
3480       return true;
3481     }
3482   else
3483     {
3484       /* Non-bit-fields are aligned for their type.  */
3485       DECL_BIT_FIELD (field) = 0;
3486       CLEAR_DECL_C_BIT_FIELD (field);
3487       return false;
3488     }
3489 }
3490
3491 /* FIELD is a non bit-field.  We are finishing the processing for its
3492    enclosing type T.  Issue any appropriate messages and set appropriate
3493    flags.  */
3494
3495 static void
3496 check_field_decl (tree field,
3497                   tree t,
3498                   int* cant_have_const_ctor,
3499                   int* no_const_asn_ref,
3500                   int* any_default_members)
3501 {
3502   tree type = strip_array_types (TREE_TYPE (field));
3503
3504   /* In C++98 an anonymous union cannot contain any fields which would change
3505      the settings of CANT_HAVE_CONST_CTOR and friends.  */
3506   if (ANON_UNION_TYPE_P (type) && cxx_dialect < cxx11)
3507     ;
3508   /* And, we don't set TYPE_HAS_CONST_COPY_CTOR, etc., for anonymous
3509      structs.  So, we recurse through their fields here.  */
3510   else if (ANON_AGGR_TYPE_P (type))
3511     {
3512       tree fields;
3513
3514       for (fields = TYPE_FIELDS (type); fields; fields = DECL_CHAIN (fields))
3515         if (TREE_CODE (fields) == FIELD_DECL && !DECL_C_BIT_FIELD (field))
3516           check_field_decl (fields, t, cant_have_const_ctor,
3517                             no_const_asn_ref, any_default_members);
3518     }
3519   /* Check members with class type for constructors, destructors,
3520      etc.  */
3521   else if (CLASS_TYPE_P (type))
3522     {
3523       /* Never let anything with uninheritable virtuals
3524          make it through without complaint.  */
3525       abstract_virtuals_error (field, type);
3526
3527       if (TREE_CODE (t) == UNION_TYPE && cxx_dialect < cxx11)
3528         {
3529           static bool warned;
3530           int oldcount = errorcount;
3531           if (TYPE_NEEDS_CONSTRUCTING (type))
3532             error ("member %q+#D with constructor not allowed in union",
3533                    field);
3534           if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3535             error ("member %q+#D with destructor not allowed in union", field);
3536           if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
3537             error ("member %q+#D with copy assignment operator not allowed in union",
3538                    field);
3539           if (!warned && errorcount > oldcount)
3540             {
3541               inform (DECL_SOURCE_LOCATION (field), "unrestricted unions "
3542                       "only available with -std=c++11 or -std=gnu++11");
3543               warned = true;
3544             }
3545         }
3546       else
3547         {
3548           TYPE_NEEDS_CONSTRUCTING (t) |= TYPE_NEEDS_CONSTRUCTING (type);
3549           TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
3550             |= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type);
3551           TYPE_HAS_COMPLEX_COPY_ASSIGN (t)
3552             |= (TYPE_HAS_COMPLEX_COPY_ASSIGN (type)
3553                 || !TYPE_HAS_COPY_ASSIGN (type));
3554           TYPE_HAS_COMPLEX_COPY_CTOR (t) |= (TYPE_HAS_COMPLEX_COPY_CTOR (type)
3555                                              || !TYPE_HAS_COPY_CTOR (type));
3556           TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) |= TYPE_HAS_COMPLEX_MOVE_ASSIGN (type);
3557           TYPE_HAS_COMPLEX_MOVE_CTOR (t) |= TYPE_HAS_COMPLEX_MOVE_CTOR (type);
3558           TYPE_HAS_COMPLEX_DFLT (t) |= (!TYPE_HAS_DEFAULT_CONSTRUCTOR (type)
3559                                         || TYPE_HAS_COMPLEX_DFLT (type));
3560         }
3561
3562       if (TYPE_HAS_COPY_CTOR (type)
3563           && !TYPE_HAS_CONST_COPY_CTOR (type))
3564         *cant_have_const_ctor = 1;
3565
3566       if (TYPE_HAS_COPY_ASSIGN (type)
3567           && !TYPE_HAS_CONST_COPY_ASSIGN (type))
3568         *no_const_asn_ref = 1;
3569     }
3570
3571   check_abi_tags (t, field);
3572
3573   if (DECL_INITIAL (field) != NULL_TREE)
3574     {
3575       /* `build_class_init_list' does not recognize
3576          non-FIELD_DECLs.  */
3577       if (TREE_CODE (t) == UNION_TYPE && *any_default_members != 0)
3578         error ("multiple fields in union %qT initialized", t);
3579       *any_default_members = 1;
3580     }
3581 }
3582
3583 /* Check the data members (both static and non-static), class-scoped
3584    typedefs, etc., appearing in the declaration of T.  Issue
3585    appropriate diagnostics.  Sets ACCESS_DECLS to a list (in
3586    declaration order) of access declarations; each TREE_VALUE in this
3587    list is a USING_DECL.
3588
3589    In addition, set the following flags:
3590
3591      EMPTY_P
3592        The class is empty, i.e., contains no non-static data members.
3593
3594      CANT_HAVE_CONST_CTOR_P
3595        This class cannot have an implicitly generated copy constructor
3596        taking a const reference.
3597
3598      CANT_HAVE_CONST_ASN_REF
3599        This class cannot have an implicitly generated assignment
3600        operator taking a const reference.
3601
3602    All of these flags should be initialized before calling this
3603    function.
3604
3605    Returns a pointer to the end of the TYPE_FIELDs chain; additional
3606    fields can be added by adding to this chain.  */
3607
3608 static void
3609 check_field_decls (tree t, tree *access_decls,
3610                    int *cant_have_const_ctor_p,
3611                    int *no_const_asn_ref_p)
3612 {
3613   tree *field;
3614   tree *next;
3615   bool has_pointers;
3616   int any_default_members;
3617   int cant_pack = 0;
3618   int field_access = -1;
3619
3620   /* Assume there are no access declarations.  */
3621   *access_decls = NULL_TREE;
3622   /* Assume this class has no pointer members.  */
3623   has_pointers = false;
3624   /* Assume none of the members of this class have default
3625      initializations.  */
3626   any_default_members = 0;
3627
3628   for (field = &TYPE_FIELDS (t); *field; field = next)
3629     {
3630       tree x = *field;
3631       tree type = TREE_TYPE (x);
3632       int this_field_access;
3633
3634       next = &DECL_CHAIN (x);
3635
3636       if (TREE_CODE (x) == USING_DECL)
3637         {
3638           /* Save the access declarations for our caller.  */
3639           *access_decls = tree_cons (NULL_TREE, x, *access_decls);
3640           continue;
3641         }
3642
3643       if (TREE_CODE (x) == TYPE_DECL
3644           || TREE_CODE (x) == TEMPLATE_DECL)
3645         continue;
3646
3647       /* If we've gotten this far, it's a data member, possibly static,
3648          or an enumerator.  */
3649       if (TREE_CODE (x) != CONST_DECL)
3650         DECL_CONTEXT (x) = t;
3651
3652       /* When this goes into scope, it will be a non-local reference.  */
3653       DECL_NONLOCAL (x) = 1;
3654
3655       if (TREE_CODE (t) == UNION_TYPE
3656           && cxx_dialect < cxx11)
3657         {
3658           /* [class.union] (C++98)
3659
3660              If a union contains a static data member, or a member of
3661              reference type, the program is ill-formed.
3662
3663              In C++11 this limitation doesn't exist anymore.  */
3664           if (VAR_P (x))
3665             {
3666               error ("in C++98 %q+D may not be static because it is "
3667                      "a member of a union", x);
3668               continue;
3669             }
3670           if (TREE_CODE (type) == REFERENCE_TYPE)
3671             {
3672               error ("in C++98 %q+D may not have reference type %qT "
3673                      "because it is a member of a union", x, type);
3674               continue;
3675             }
3676         }
3677
3678       /* Perform error checking that did not get done in
3679          grokdeclarator.  */
3680       if (TREE_CODE (type) == FUNCTION_TYPE)
3681         {
3682           error ("field %q+D invalidly declared function type", x);
3683           type = build_pointer_type (type);
3684           TREE_TYPE (x) = type;
3685         }
3686       else if (TREE_CODE (type) == METHOD_TYPE)
3687         {
3688           error ("field %q+D invalidly declared method type", x);
3689           type = build_pointer_type (type);
3690           TREE_TYPE (x) = type;
3691         }
3692
3693       if (type == error_mark_node)
3694         continue;
3695
3696       if (TREE_CODE (x) == CONST_DECL || VAR_P (x))
3697         continue;
3698
3699       /* Now it can only be a FIELD_DECL.  */
3700
3701       if (TREE_PRIVATE (x) || TREE_PROTECTED (x))
3702         CLASSTYPE_NON_AGGREGATE (t) = 1;
3703
3704       /* If at least one non-static data member is non-literal, the whole
3705          class becomes non-literal.  Per Core/1453, volatile non-static
3706          data members and base classes are also not allowed.
3707          Note: if the type is incomplete we will complain later on.  */
3708       if (COMPLETE_TYPE_P (type)
3709           && (!literal_type_p (type) || CP_TYPE_VOLATILE_P (type))) 
3710         CLASSTYPE_LITERAL_P (t) = false;
3711
3712       /* A standard-layout class is a class that:
3713          ...
3714          has the same access control (Clause 11) for all non-static data members,
3715          ...  */
3716       this_field_access = TREE_PROTECTED (x) ? 1 : TREE_PRIVATE (x) ? 2 : 0;
3717       if (field_access == -1)
3718         field_access = this_field_access;
3719       else if (this_field_access != field_access)
3720         CLASSTYPE_NON_STD_LAYOUT (t) = 1;
3721
3722       /* If this is of reference type, check if it needs an init.  */
3723       if (TREE_CODE (type) == REFERENCE_TYPE)
3724         {
3725           CLASSTYPE_NON_LAYOUT_POD_P (t) = 1;
3726           CLASSTYPE_NON_STD_LAYOUT (t) = 1;
3727           if (DECL_INITIAL (x) == NULL_TREE)
3728             SET_CLASSTYPE_REF_FIELDS_NEED_INIT (t, 1);
3729           if (cxx_dialect < cxx11)
3730             {
3731               /* ARM $12.6.2: [A member initializer list] (or, for an
3732                  aggregate, initialization by a brace-enclosed list) is the
3733                  only way to initialize nonstatic const and reference
3734                  members.  */
3735               TYPE_HAS_COMPLEX_COPY_ASSIGN (t) = 1;
3736               TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) = 1;
3737             }
3738         }
3739
3740       type = strip_array_types (type);
3741
3742       if (TYPE_PACKED (t))
3743         {
3744           if (!layout_pod_type_p (type) && !TYPE_PACKED (type))
3745             {
3746               warning
3747                 (0,
3748                  "ignoring packed attribute because of unpacked non-POD field %q+#D",
3749                  x);
3750               cant_pack = 1;
3751             }
3752           else if (DECL_C_BIT_FIELD (x)
3753                    || TYPE_ALIGN (TREE_TYPE (x)) > BITS_PER_UNIT)
3754             DECL_PACKED (x) = 1;
3755         }
3756
3757       if (DECL_C_BIT_FIELD (x) && integer_zerop (DECL_INITIAL (x)))
3758         /* We don't treat zero-width bitfields as making a class
3759            non-empty.  */
3760         ;
3761       else
3762         {
3763           /* The class is non-empty.  */
3764           CLASSTYPE_EMPTY_P (t) = 0;
3765           /* The class is not even nearly empty.  */
3766           CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
3767           /* If one of the data members contains an empty class,
3768              so does T.  */
3769           if (CLASS_TYPE_P (type)
3770               && CLASSTYPE_CONTAINS_EMPTY_CLASS_P (type))
3771             CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t) = 1;
3772         }
3773
3774       /* This is used by -Weffc++ (see below). Warn only for pointers
3775          to members which might hold dynamic memory. So do not warn
3776          for pointers to functions or pointers to members.  */
3777       if (TYPE_PTR_P (type)
3778           && !TYPE_PTRFN_P (type))
3779         has_pointers = true;
3780
3781       if (CLASS_TYPE_P (type))
3782         {
3783           if (CLASSTYPE_REF_FIELDS_NEED_INIT (type))
3784             SET_CLASSTYPE_REF_FIELDS_NEED_INIT (t, 1);
3785           if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (type))
3786             SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT (t, 1);
3787         }
3788
3789       if (DECL_MUTABLE_P (x) || TYPE_HAS_MUTABLE_P (type))
3790         CLASSTYPE_HAS_MUTABLE (t) = 1;
3791
3792       if (DECL_MUTABLE_P (x))
3793         {
3794           if (CP_TYPE_CONST_P (type))
3795             {
3796               error ("member %q+D cannot be declared both %<const%> "
3797                      "and %<mutable%>", x);
3798               continue;
3799             }
3800           if (TREE_CODE (type) == REFERENCE_TYPE)
3801             {
3802               error ("member %q+D cannot be declared as a %<mutable%> "
3803                      "reference", x);
3804               continue;
3805             }
3806         }
3807
3808       if (! layout_pod_type_p (type))
3809         /* DR 148 now allows pointers to members (which are POD themselves),
3810            to be allowed in POD structs.  */
3811         CLASSTYPE_NON_LAYOUT_POD_P (t) = 1;
3812
3813       if (!std_layout_type_p (type))
3814         CLASSTYPE_NON_STD_LAYOUT (t) = 1;
3815
3816       if (! zero_init_p (type))
3817         CLASSTYPE_NON_ZERO_INIT_P (t) = 1;
3818
3819       /* We set DECL_C_BIT_FIELD in grokbitfield.
3820          If the type and width are valid, we'll also set DECL_BIT_FIELD.  */
3821       if (! DECL_C_BIT_FIELD (x) || ! check_bitfield_decl (x))
3822         check_field_decl (x, t,
3823                           cant_have_const_ctor_p,
3824                           no_const_asn_ref_p,
3825                           &any_default_members);
3826
3827       /* Now that we've removed bit-field widths from DECL_INITIAL,
3828          anything left in DECL_INITIAL is an NSDMI that makes the class
3829          non-aggregate in C++11.  */
3830       if (DECL_INITIAL (x) && cxx_dialect < cxx14)
3831         CLASSTYPE_NON_AGGREGATE (t) = true;
3832
3833       /* If any field is const, the structure type is pseudo-const.  */
3834       if (CP_TYPE_CONST_P (type))
3835         {
3836           C_TYPE_FIELDS_READONLY (t) = 1;
3837           if (DECL_INITIAL (x) == NULL_TREE)
3838             SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT (t, 1);
3839           if (cxx_dialect < cxx11)
3840             {
3841               /* ARM $12.6.2: [A member initializer list] (or, for an
3842                  aggregate, initialization by a brace-enclosed list) is the
3843                  only way to initialize nonstatic const and reference
3844                  members.  */
3845               TYPE_HAS_COMPLEX_COPY_ASSIGN (t) = 1;
3846               TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) = 1;
3847             }
3848         }
3849       /* A field that is pseudo-const makes the structure likewise.  */
3850       else if (CLASS_TYPE_P (type))
3851         {
3852           C_TYPE_FIELDS_READONLY (t) |= C_TYPE_FIELDS_READONLY (type);
3853           SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT (t,
3854             CLASSTYPE_READONLY_FIELDS_NEED_INIT (t)
3855             | CLASSTYPE_READONLY_FIELDS_NEED_INIT (type));
3856         }
3857
3858       /* Core issue 80: A nonstatic data member is required to have a
3859          different name from the class iff the class has a
3860          user-declared constructor.  */
3861       if (constructor_name_p (DECL_NAME (x), t)
3862           && TYPE_HAS_USER_CONSTRUCTOR (t))
3863         permerror (input_location, "field %q+#D with same name as class", x);
3864     }
3865
3866   /* Effective C++ rule 11: if a class has dynamic memory held by pointers,
3867      it should also define a copy constructor and an assignment operator to
3868      implement the correct copy semantic (deep vs shallow, etc.). As it is
3869      not feasible to check whether the constructors do allocate dynamic memory
3870      and store it within members, we approximate the warning like this:
3871
3872      -- Warn only if there are members which are pointers
3873      -- Warn only if there is a non-trivial constructor (otherwise,
3874         there cannot be memory allocated).
3875      -- Warn only if there is a non-trivial destructor. We assume that the
3876         user at least implemented the cleanup correctly, and a destructor
3877         is needed to free dynamic memory.
3878
3879      This seems enough for practical purposes.  */
3880   if (warn_ecpp
3881       && has_pointers
3882       && TYPE_HAS_USER_CONSTRUCTOR (t)
3883       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
3884       && !(TYPE_HAS_COPY_CTOR (t) && TYPE_HAS_COPY_ASSIGN (t)))
3885     {
3886       warning (OPT_Weffc__, "%q#T has pointer data members", t);
3887
3888       if (! TYPE_HAS_COPY_CTOR (t))
3889         {
3890           warning (OPT_Weffc__,
3891                    "  but does not override %<%T(const %T&)%>", t, t);
3892           if (!TYPE_HAS_COPY_ASSIGN (t))
3893             warning (OPT_Weffc__, "  or %<operator=(const %T&)%>", t);
3894         }
3895       else if (! TYPE_HAS_COPY_ASSIGN (t))
3896         warning (OPT_Weffc__,
3897                  "  but does not override %<operator=(const %T&)%>", t);
3898     }
3899
3900   /* Non-static data member initializers make the default constructor
3901      non-trivial.  */
3902   if (any_default_members)
3903     {
3904       TYPE_NEEDS_CONSTRUCTING (t) = true;
3905       TYPE_HAS_COMPLEX_DFLT (t) = true;
3906     }
3907
3908   /* If any of the fields couldn't be packed, unset TYPE_PACKED.  */
3909   if (cant_pack)
3910     TYPE_PACKED (t) = 0;
3911
3912   /* Check anonymous struct/anonymous union fields.  */
3913   finish_struct_anon (t);
3914
3915   /* We've built up the list of access declarations in reverse order.
3916      Fix that now.  */
3917   *access_decls = nreverse (*access_decls);
3918 }
3919
3920 /* If TYPE is an empty class type, records its OFFSET in the table of
3921    OFFSETS.  */
3922
3923 static int
3924 record_subobject_offset (tree type, tree offset, splay_tree offsets)
3925 {
3926   splay_tree_node n;
3927
3928   if (!is_empty_class (type))
3929     return 0;
3930
3931   /* Record the location of this empty object in OFFSETS.  */
3932   n = splay_tree_lookup (offsets, (splay_tree_key) offset);
3933   if (!n)
3934     n = splay_tree_insert (offsets,
3935                            (splay_tree_key) offset,
3936                            (splay_tree_value) NULL_TREE);
3937   n->value = ((splay_tree_value)
3938               tree_cons (NULL_TREE,
3939                          type,
3940                          (tree) n->value));
3941
3942   return 0;
3943 }
3944
3945 /* Returns nonzero if TYPE is an empty class type and there is
3946    already an entry in OFFSETS for the same TYPE as the same OFFSET.  */
3947
3948 static int
3949 check_subobject_offset (tree type, tree offset, splay_tree offsets)
3950 {
3951   splay_tree_node n;
3952   tree t;
3953
3954   if (!is_empty_class (type))
3955     return 0;
3956
3957   /* Record the location of this empty object in OFFSETS.  */
3958   n = splay_tree_lookup (offsets, (splay_tree_key) offset);
3959   if (!n)
3960     return 0;
3961
3962   for (t = (tree) n->value; t; t = TREE_CHAIN (t))
3963     if (same_type_p (TREE_VALUE (t), type))
3964       return 1;
3965
3966   return 0;
3967 }
3968
3969 /* Walk through all the subobjects of TYPE (located at OFFSET).  Call
3970    F for every subobject, passing it the type, offset, and table of
3971    OFFSETS.  If VBASES_P is one, then virtual non-primary bases should
3972    be traversed.
3973
3974    If MAX_OFFSET is non-NULL, then subobjects with an offset greater
3975    than MAX_OFFSET will not be walked.
3976
3977    If F returns a nonzero value, the traversal ceases, and that value
3978    is returned.  Otherwise, returns zero.  */
3979
3980 static int
3981 walk_subobject_offsets (tree type,
3982                         subobject_offset_fn f,
3983                         tree offset,
3984                         splay_tree offsets,
3985                         tree max_offset,
3986                         int vbases_p)
3987 {
3988   int r = 0;
3989   tree type_binfo = NULL_TREE;
3990
3991   /* If this OFFSET is bigger than the MAX_OFFSET, then we should
3992      stop.  */
3993   if (max_offset && tree_int_cst_lt (max_offset, offset))
3994     return 0;
3995
3996   if (type == error_mark_node)
3997     return 0;
3998
3999   if (!TYPE_P (type))
4000     {
4001       type_binfo = type;
4002       type = BINFO_TYPE (type);
4003     }
4004
4005   if (CLASS_TYPE_P (type))
4006     {
4007       tree field;
4008       tree binfo;
4009       int i;
4010
4011       /* Avoid recursing into objects that are not interesting.  */
4012       if (!CLASSTYPE_CONTAINS_EMPTY_CLASS_P (type))
4013         return 0;
4014
4015       /* Record the location of TYPE.  */
4016       r = (*f) (type, offset, offsets);
4017       if (r)
4018         return r;
4019
4020       /* Iterate through the direct base classes of TYPE.  */
4021       if (!type_binfo)
4022         type_binfo = TYPE_BINFO (type);
4023       for (i = 0; BINFO_BASE_ITERATE (type_binfo, i, binfo); i++)
4024         {
4025           tree binfo_offset;
4026
4027           if (BINFO_VIRTUAL_P (binfo))
4028             continue;
4029
4030           tree orig_binfo;
4031           /* We cannot rely on BINFO_OFFSET being set for the base
4032              class yet, but the offsets for direct non-virtual
4033              bases can be calculated by going back to the TYPE.  */
4034           orig_binfo = BINFO_BASE_BINFO (TYPE_BINFO (type), i);
4035           binfo_offset = size_binop (PLUS_EXPR,
4036                                      offset,
4037                                      BINFO_OFFSET (orig_binfo));
4038
4039           r = walk_subobject_offsets (binfo,
4040                                       f,
4041                                       binfo_offset,
4042                                       offsets,
4043                                       max_offset,
4044                                       /*vbases_p=*/0);
4045           if (r)
4046             return r;
4047         }
4048
4049       if (CLASSTYPE_VBASECLASSES (type))
4050         {
4051           unsigned ix;
4052           vec<tree, va_gc> *vbases;
4053
4054           /* Iterate through the virtual base classes of TYPE.  In G++
4055              3.2, we included virtual bases in the direct base class
4056              loop above, which results in incorrect results; the
4057              correct offsets for virtual bases are only known when
4058              working with the most derived type.  */
4059           if (vbases_p)
4060             for (vbases = CLASSTYPE_VBASECLASSES (type), ix = 0;
4061                  vec_safe_iterate (vbases, ix, &binfo); ix++)
4062               {
4063                 r = walk_subobject_offsets (binfo,
4064                                             f,
4065                                             size_binop (PLUS_EXPR,
4066                                                         offset,
4067                                                         BINFO_OFFSET (binfo)),
4068                                             offsets,
4069                                             max_offset,
4070                                             /*vbases_p=*/0);
4071                 if (r)
4072                   return r;
4073               }
4074           else
4075             {
4076               /* We still have to walk the primary base, if it is
4077                  virtual.  (If it is non-virtual, then it was walked
4078                  above.)  */
4079               tree vbase = get_primary_binfo (type_binfo);
4080
4081               if (vbase && BINFO_VIRTUAL_P (vbase)
4082                   && BINFO_PRIMARY_P (vbase)
4083                   && BINFO_INHERITANCE_CHAIN (vbase) == type_binfo)
4084                 {
4085                   r = (walk_subobject_offsets
4086                        (vbase, f, offset,
4087                         offsets, max_offset, /*vbases_p=*/0));
4088                   if (r)
4089                     return r;
4090                 }
4091             }
4092         }
4093
4094       /* Iterate through the fields of TYPE.  */
4095       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4096         if (TREE_CODE (field) == FIELD_DECL
4097             && TREE_TYPE (field) != error_mark_node
4098             && !DECL_ARTIFICIAL (field))
4099           {
4100             tree field_offset;
4101
4102             field_offset = byte_position (field);
4103
4104             r = walk_subobject_offsets (TREE_TYPE (field),
4105                                         f,
4106                                         size_binop (PLUS_EXPR,
4107                                                     offset,
4108                                                     field_offset),
4109                                         offsets,
4110                                         max_offset,
4111                                         /*vbases_p=*/1);
4112             if (r)
4113               return r;
4114           }
4115     }
4116   else if (TREE_CODE (type) == ARRAY_TYPE)
4117     {
4118       tree element_type = strip_array_types (type);
4119       tree domain = TYPE_DOMAIN (type);
4120       tree index;
4121
4122       /* Avoid recursing into objects that are not interesting.  */
4123       if (!CLASS_TYPE_P (element_type)
4124           || !CLASSTYPE_CONTAINS_EMPTY_CLASS_P (element_type))
4125         return 0;
4126
4127       /* Step through each of the elements in the array.  */
4128       for (index = size_zero_node;
4129            !tree_int_cst_lt (TYPE_MAX_VALUE (domain), index);
4130            index = size_binop (PLUS_EXPR, index, size_one_node))
4131         {
4132           r = walk_subobject_offsets (TREE_TYPE (type),
4133                                       f,
4134                                       offset,
4135                                       offsets,
4136                                       max_offset,
4137                                       /*vbases_p=*/1);
4138           if (r)
4139             return r;
4140           offset = size_binop (PLUS_EXPR, offset,
4141                                TYPE_SIZE_UNIT (TREE_TYPE (type)));
4142           /* If this new OFFSET is bigger than the MAX_OFFSET, then
4143              there's no point in iterating through the remaining
4144              elements of the array.  */
4145           if (max_offset && tree_int_cst_lt (max_offset, offset))
4146             break;
4147         }
4148     }
4149
4150   return 0;
4151 }
4152
4153 /* Record all of the empty subobjects of TYPE (either a type or a
4154    binfo).  If IS_DATA_MEMBER is true, then a non-static data member
4155    is being placed at OFFSET; otherwise, it is a base class that is
4156    being placed at OFFSET.  */
4157
4158 static void
4159 record_subobject_offsets (tree type,
4160                           tree offset,
4161                           splay_tree offsets,
4162                           bool is_data_member)
4163 {
4164   tree max_offset;
4165   /* If recording subobjects for a non-static data member or a
4166      non-empty base class , we do not need to record offsets beyond
4167      the size of the biggest empty class.  Additional data members
4168      will go at the end of the class.  Additional base classes will go
4169      either at offset zero (if empty, in which case they cannot
4170      overlap with offsets past the size of the biggest empty class) or
4171      at the end of the class.
4172
4173      However, if we are placing an empty base class, then we must record
4174      all offsets, as either the empty class is at offset zero (where
4175      other empty classes might later be placed) or at the end of the
4176      class (where other objects might then be placed, so other empty
4177      subobjects might later overlap).  */
4178   if (is_data_member
4179       || !is_empty_class (BINFO_TYPE (type)))
4180     max_offset = sizeof_biggest_empty_class;
4181   else
4182     max_offset = NULL_TREE;
4183   walk_subobject_offsets (type, record_subobject_offset, offset,
4184                           offsets, max_offset, is_data_member);
4185 }
4186
4187 /* Returns nonzero if any of the empty subobjects of TYPE (located at
4188    OFFSET) conflict with entries in OFFSETS.  If VBASES_P is nonzero,
4189    virtual bases of TYPE are examined.  */
4190
4191 static int
4192 layout_conflict_p (tree type,
4193                    tree offset,
4194                    splay_tree offsets,
4195                    int vbases_p)
4196 {
4197   splay_tree_node max_node;
4198
4199   /* Get the node in OFFSETS that indicates the maximum offset where
4200      an empty subobject is located.  */
4201   max_node = splay_tree_max (offsets);
4202   /* If there aren't any empty subobjects, then there's no point in
4203      performing this check.  */
4204   if (!max_node)
4205     return 0;
4206
4207   return walk_subobject_offsets (type, check_subobject_offset, offset,
4208                                  offsets, (tree) (max_node->key),
4209                                  vbases_p);
4210 }
4211
4212 /* DECL is a FIELD_DECL corresponding either to a base subobject of a
4213    non-static data member of the type indicated by RLI.  BINFO is the
4214    binfo corresponding to the base subobject, OFFSETS maps offsets to
4215    types already located at those offsets.  This function determines
4216    the position of the DECL.  */
4217
4218 static void
4219 layout_nonempty_base_or_field (record_layout_info rli,
4220                                tree decl,
4221                                tree binfo,
4222                                splay_tree offsets)
4223 {
4224   tree offset = NULL_TREE;
4225   bool field_p;
4226   tree type;
4227
4228   if (binfo)
4229     {
4230       /* For the purposes of determining layout conflicts, we want to
4231          use the class type of BINFO; TREE_TYPE (DECL) will be the
4232          CLASSTYPE_AS_BASE version, which does not contain entries for
4233          zero-sized bases.  */
4234       type = TREE_TYPE (binfo);
4235       field_p = false;
4236     }
4237   else
4238     {
4239       type = TREE_TYPE (decl);
4240       field_p = true;
4241     }
4242
4243   /* Try to place the field.  It may take more than one try if we have
4244      a hard time placing the field without putting two objects of the
4245      same type at the same address.  */
4246   while (1)
4247     {
4248       struct record_layout_info_s old_rli = *rli;
4249
4250       /* Place this field.  */
4251       place_field (rli, decl);
4252       offset = byte_position (decl);
4253
4254       /* We have to check to see whether or not there is already
4255          something of the same type at the offset we're about to use.
4256          For example, consider:
4257
4258            struct S {};
4259            struct T : public S { int i; };
4260            struct U : public S, public T {};
4261
4262          Here, we put S at offset zero in U.  Then, we can't put T at
4263          offset zero -- its S component would be at the same address
4264          as the S we already allocated.  So, we have to skip ahead.
4265          Since all data members, including those whose type is an
4266          empty class, have nonzero size, any overlap can happen only
4267          with a direct or indirect base-class -- it can't happen with
4268          a data member.  */
4269       /* In a union, overlap is permitted; all members are placed at
4270          offset zero.  */
4271       if (TREE_CODE (rli->t) == UNION_TYPE)
4272         break;
4273       if (layout_conflict_p (field_p ? type : binfo, offset,
4274                              offsets, field_p))
4275         {
4276           /* Strip off the size allocated to this field.  That puts us
4277              at the first place we could have put the field with
4278              proper alignment.  */
4279           *rli = old_rli;
4280
4281           /* Bump up by the alignment required for the type.  */
4282           rli->bitpos
4283             = size_binop (PLUS_EXPR, rli->bitpos,
4284                           bitsize_int (binfo
4285                                        ? CLASSTYPE_ALIGN (type)
4286                                        : TYPE_ALIGN (type)));
4287           normalize_rli (rli);
4288         }
4289       else if (TREE_CODE (type) == NULLPTR_TYPE
4290                && warn_abi && abi_version_crosses (9))
4291         {
4292           /* Before ABI v9, we were giving nullptr_t alignment of 1; if
4293              the offset wasn't aligned like a pointer when we started to
4294              layout this field, that affects its position.  */
4295           tree pos = rli_size_unit_so_far (&old_rli);
4296           if (int_cst_value (pos) % TYPE_ALIGN_UNIT (ptr_type_node) != 0)
4297             {
4298               if (abi_version_at_least (9))
4299                 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wabi,
4300                             "alignment of %qD increased in -fabi-version=9 "
4301                             "(GCC 5.2)", decl);
4302               else
4303                 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wabi, "alignment "
4304                             "of %qD will increase in -fabi-version=9", decl);
4305             }
4306           break;
4307         }
4308       else
4309         /* There was no conflict.  We're done laying out this field.  */
4310         break;
4311     }
4312
4313   /* Now that we know where it will be placed, update its
4314      BINFO_OFFSET.  */
4315   if (binfo && CLASS_TYPE_P (BINFO_TYPE (binfo)))
4316     /* Indirect virtual bases may have a nonzero BINFO_OFFSET at
4317        this point because their BINFO_OFFSET is copied from another
4318        hierarchy.  Therefore, we may not need to add the entire
4319        OFFSET.  */
4320     propagate_binfo_offsets (binfo,
4321                              size_diffop_loc (input_location,
4322                                           convert (ssizetype, offset),
4323                                           convert (ssizetype,
4324                                                    BINFO_OFFSET (binfo))));
4325 }
4326
4327 /* Returns true if TYPE is empty and OFFSET is nonzero.  */
4328
4329 static int
4330 empty_base_at_nonzero_offset_p (tree type,
4331                                 tree offset,
4332                                 splay_tree /*offsets*/)
4333 {
4334   return is_empty_class (type) && !integer_zerop (offset);
4335 }
4336
4337 /* Layout the empty base BINFO.  EOC indicates the byte currently just
4338    past the end of the class, and should be correctly aligned for a
4339    class of the type indicated by BINFO; OFFSETS gives the offsets of
4340    the empty bases allocated so far. T is the most derived
4341    type.  Return nonzero iff we added it at the end.  */
4342
4343 static bool
4344 layout_empty_base (record_layout_info rli, tree binfo,
4345                    tree eoc, splay_tree offsets)
4346 {
4347   tree alignment;
4348   tree basetype = BINFO_TYPE (binfo);
4349   bool atend = false;
4350
4351   /* This routine should only be used for empty classes.  */
4352   gcc_assert (is_empty_class (basetype));
4353   alignment = ssize_int (CLASSTYPE_ALIGN_UNIT (basetype));
4354
4355   if (!integer_zerop (BINFO_OFFSET (binfo)))
4356     propagate_binfo_offsets
4357       (binfo, size_diffop_loc (input_location,
4358                                size_zero_node, BINFO_OFFSET (binfo)));
4359
4360   /* This is an empty base class.  We first try to put it at offset
4361      zero.  */
4362   if (layout_conflict_p (binfo,
4363                          BINFO_OFFSET (binfo),
4364                          offsets,
4365                          /*vbases_p=*/0))
4366     {
4367       /* That didn't work.  Now, we move forward from the next
4368          available spot in the class.  */
4369       atend = true;
4370       propagate_binfo_offsets (binfo, convert (ssizetype, eoc));
4371       while (1)
4372         {
4373           if (!layout_conflict_p (binfo,
4374                                   BINFO_OFFSET (binfo),
4375                                   offsets,
4376                                   /*vbases_p=*/0))
4377             /* We finally found a spot where there's no overlap.  */
4378             break;
4379
4380           /* There's overlap here, too.  Bump along to the next spot.  */
4381           propagate_binfo_offsets (binfo, alignment);
4382         }
4383     }
4384
4385   if (CLASSTYPE_USER_ALIGN (basetype))
4386     {
4387       rli->record_align = MAX (rli->record_align, CLASSTYPE_ALIGN (basetype));
4388       if (warn_packed)
4389         rli->unpacked_align = MAX (rli->unpacked_align, CLASSTYPE_ALIGN (basetype));
4390       TYPE_USER_ALIGN (rli->t) = 1;
4391     }
4392
4393   return atend;
4394 }
4395
4396 /* Layout the base given by BINFO in the class indicated by RLI.
4397    *BASE_ALIGN is a running maximum of the alignments of
4398    any base class.  OFFSETS gives the location of empty base
4399    subobjects.  T is the most derived type.  Return nonzero if the new
4400    object cannot be nearly-empty.  A new FIELD_DECL is inserted at
4401    *NEXT_FIELD, unless BINFO is for an empty base class.
4402
4403    Returns the location at which the next field should be inserted.  */
4404
4405 static tree *
4406 build_base_field (record_layout_info rli, tree binfo,
4407                   splay_tree offsets, tree *next_field)
4408 {
4409   tree t = rli->t;
4410   tree basetype = BINFO_TYPE (binfo);
4411
4412   if (!COMPLETE_TYPE_P (basetype))
4413     /* This error is now reported in xref_tag, thus giving better
4414        location information.  */
4415     return next_field;
4416
4417   /* Place the base class.  */
4418   if (!is_empty_class (basetype))
4419     {
4420       tree decl;
4421
4422       /* The containing class is non-empty because it has a non-empty
4423          base class.  */
4424       CLASSTYPE_EMPTY_P (t) = 0;
4425
4426       /* Create the FIELD_DECL.  */
4427       decl = build_decl (input_location,
4428                          FIELD_DECL, NULL_TREE, CLASSTYPE_AS_BASE (basetype));
4429       DECL_ARTIFICIAL (decl) = 1;
4430       DECL_IGNORED_P (decl) = 1;
4431       DECL_FIELD_CONTEXT (decl) = t;
4432       if (CLASSTYPE_AS_BASE (basetype))
4433         {
4434           DECL_SIZE (decl) = CLASSTYPE_SIZE (basetype);
4435           DECL_SIZE_UNIT (decl) = CLASSTYPE_SIZE_UNIT (basetype);
4436           DECL_ALIGN (decl) = CLASSTYPE_ALIGN (basetype);
4437           DECL_USER_ALIGN (decl) = CLASSTYPE_USER_ALIGN (basetype);
4438           DECL_MODE (decl) = TYPE_MODE (basetype);
4439           DECL_FIELD_IS_BASE (decl) = 1;
4440
4441           /* Try to place the field.  It may take more than one try if we
4442              have a hard time placing the field without putting two
4443              objects of the same type at the same address.  */
4444           layout_nonempty_base_or_field (rli, decl, binfo, offsets);
4445           /* Add the new FIELD_DECL to the list of fields for T.  */
4446           DECL_CHAIN (decl) = *next_field;
4447           *next_field = decl;
4448           next_field = &DECL_CHAIN (decl);
4449         }
4450     }
4451   else
4452     {
4453       tree eoc;
4454       bool atend;
4455
4456       /* On some platforms (ARM), even empty classes will not be
4457          byte-aligned.  */
4458       eoc = round_up_loc (input_location,
4459                       rli_size_unit_so_far (rli),
4460                       CLASSTYPE_ALIGN_UNIT (basetype));
4461       atend = layout_empty_base (rli, binfo, eoc, offsets);
4462       /* A nearly-empty class "has no proper base class that is empty,
4463          not morally virtual, and at an offset other than zero."  */
4464       if (!BINFO_VIRTUAL_P (binfo) && CLASSTYPE_NEARLY_EMPTY_P (t))
4465         {
4466           if (atend)
4467             CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
4468           /* The check above (used in G++ 3.2) is insufficient because
4469              an empty class placed at offset zero might itself have an
4470              empty base at a nonzero offset.  */
4471           else if (walk_subobject_offsets (basetype,
4472                                            empty_base_at_nonzero_offset_p,
4473                                            size_zero_node,
4474                                            /*offsets=*/NULL,
4475                                            /*max_offset=*/NULL_TREE,
4476                                            /*vbases_p=*/true))
4477             CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
4478         }
4479
4480       /* We do not create a FIELD_DECL for empty base classes because
4481          it might overlap some other field.  We want to be able to
4482          create CONSTRUCTORs for the class by iterating over the
4483          FIELD_DECLs, and the back end does not handle overlapping
4484          FIELD_DECLs.  */
4485
4486       /* An empty virtual base causes a class to be non-empty
4487          -- but in that case we do not need to clear CLASSTYPE_EMPTY_P
4488          here because that was already done when the virtual table
4489          pointer was created.  */
4490     }
4491
4492   /* Record the offsets of BINFO and its base subobjects.  */
4493   record_subobject_offsets (binfo,
4494                             BINFO_OFFSET (binfo),
4495                             offsets,
4496                             /*is_data_member=*/false);
4497
4498   return next_field;
4499 }
4500
4501 /* Layout all of the non-virtual base classes.  Record empty
4502    subobjects in OFFSETS.  T is the most derived type.  Return nonzero
4503    if the type cannot be nearly empty.  The fields created
4504    corresponding to the base classes will be inserted at
4505    *NEXT_FIELD.  */
4506
4507 static void
4508 build_base_fields (record_layout_info rli,
4509                    splay_tree offsets, tree *next_field)
4510 {
4511   /* Chain to hold all the new FIELD_DECLs which stand in for base class
4512      subobjects.  */
4513   tree t = rli->t;
4514   int n_baseclasses = BINFO_N_BASE_BINFOS (TYPE_BINFO (t));
4515   int i;
4516
4517   /* The primary base class is always allocated first.  */
4518   if (CLASSTYPE_HAS_PRIMARY_BASE_P (t))
4519     next_field = build_base_field (rli, CLASSTYPE_PRIMARY_BINFO (t),
4520                                    offsets, next_field);
4521
4522   /* Now allocate the rest of the bases.  */
4523   for (i = 0; i < n_baseclasses; ++i)
4524     {
4525       tree base_binfo;
4526
4527       base_binfo = BINFO_BASE_BINFO (TYPE_BINFO (t), i);
4528
4529       /* The primary base was already allocated above, so we don't
4530          need to allocate it again here.  */
4531       if (base_binfo == CLASSTYPE_PRIMARY_BINFO (t))
4532         continue;
4533
4534       /* Virtual bases are added at the end (a primary virtual base
4535          will have already been added).  */
4536       if (BINFO_VIRTUAL_P (base_binfo))
4537         continue;
4538
4539       next_field = build_base_field (rli, base_binfo,
4540                                      offsets, next_field);
4541     }
4542 }
4543
4544 /* Go through the TYPE_METHODS of T issuing any appropriate
4545    diagnostics, figuring out which methods override which other
4546    methods, and so forth.  */
4547
4548 static void
4549 check_methods (tree t)
4550 {
4551   tree x;
4552
4553   for (x = TYPE_METHODS (t); x; x = DECL_CHAIN (x))
4554     {
4555       check_for_override (x, t);
4556       if (DECL_PURE_VIRTUAL_P (x) && (TREE_CODE (x) != FUNCTION_DECL || ! DECL_VINDEX (x)))
4557         error ("initializer specified for non-virtual method %q+D", x);
4558       /* The name of the field is the original field name
4559          Save this in auxiliary field for later overloading.  */
4560       if (TREE_CODE (x) == FUNCTION_DECL && DECL_VINDEX (x))
4561         {
4562           TYPE_POLYMORPHIC_P (t) = 1;
4563           if (DECL_PURE_VIRTUAL_P (x))
4564             vec_safe_push (CLASSTYPE_PURE_VIRTUALS (t), x);
4565         }
4566       /* All user-provided destructors are non-trivial.
4567          Constructors and assignment ops are handled in
4568          grok_special_member_properties.  */
4569       if (DECL_DESTRUCTOR_P (x) && user_provided_p (x))
4570         TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) = 1;
4571     }
4572 }
4573
4574 /* FN is a constructor or destructor.  Clone the declaration to create
4575    a specialized in-charge or not-in-charge version, as indicated by
4576    NAME.  */
4577
4578 static tree
4579 build_clone (tree fn, tree name)
4580 {
4581   tree parms;
4582   tree clone;
4583
4584   /* Copy the function.  */
4585   clone = copy_decl (fn);
4586   /* Reset the function name.  */
4587   DECL_NAME (clone) = name;
4588   /* Remember where this function came from.  */
4589   DECL_ABSTRACT_ORIGIN (clone) = fn;
4590   /* Make it easy to find the CLONE given the FN.  */
4591   DECL_CHAIN (clone) = DECL_CHAIN (fn);
4592   DECL_CHAIN (fn) = clone;
4593
4594   /* If this is a template, do the rest on the DECL_TEMPLATE_RESULT.  */
4595   if (TREE_CODE (clone) == TEMPLATE_DECL)
4596     {
4597       tree result = build_clone (DECL_TEMPLATE_RESULT (clone), name);
4598       DECL_TEMPLATE_RESULT (clone) = result;
4599       DECL_TEMPLATE_INFO (result) = copy_node (DECL_TEMPLATE_INFO (result));
4600       DECL_TI_TEMPLATE (result) = clone;
4601       TREE_TYPE (clone) = TREE_TYPE (result);
4602       return clone;
4603     }
4604
4605   SET_DECL_ASSEMBLER_NAME (clone, NULL_TREE);
4606   DECL_CLONED_FUNCTION (clone) = fn;
4607   /* There's no pending inline data for this function.  */
4608   DECL_PENDING_INLINE_INFO (clone) = NULL;
4609   DECL_PENDING_INLINE_P (clone) = 0;
4610
4611   /* The base-class destructor is not virtual.  */
4612   if (name == base_dtor_identifier)
4613     {
4614       DECL_VIRTUAL_P (clone) = 0;
4615       if (TREE_CODE (clone) != TEMPLATE_DECL)
4616         DECL_VINDEX (clone) = NULL_TREE;
4617     }
4618
4619   /* If there was an in-charge parameter, drop it from the function
4620      type.  */
4621   if (DECL_HAS_IN_CHARGE_PARM_P (clone))
4622     {
4623       tree basetype;
4624       tree parmtypes;
4625       tree exceptions;
4626
4627       exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (clone));
4628       basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (clone));
4629       parmtypes = TYPE_ARG_TYPES (TREE_TYPE (clone));
4630       /* Skip the `this' parameter.  */
4631       parmtypes = TREE_CHAIN (parmtypes);
4632       /* Skip the in-charge parameter.  */
4633       parmtypes = TREE_CHAIN (parmtypes);
4634       /* And the VTT parm, in a complete [cd]tor.  */
4635       if (DECL_HAS_VTT_PARM_P (fn)
4636           && ! DECL_NEEDS_VTT_PARM_P (clone))
4637         parmtypes = TREE_CHAIN (parmtypes);
4638        /* If this is subobject constructor or destructor, add the vtt
4639          parameter.  */
4640       TREE_TYPE (clone)
4641         = build_method_type_directly (basetype,
4642                                       TREE_TYPE (TREE_TYPE (clone)),
4643                                       parmtypes);
4644       if (exceptions)
4645         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone),
4646                                                      exceptions);
4647       TREE_TYPE (clone)
4648         = cp_build_type_attribute_variant (TREE_TYPE (clone),
4649                                            TYPE_ATTRIBUTES (TREE_TYPE (fn)));
4650     }
4651
4652   /* Copy the function parameters.  */
4653   DECL_ARGUMENTS (clone) = copy_list (DECL_ARGUMENTS (clone));
4654   /* Remove the in-charge parameter.  */
4655   if (DECL_HAS_IN_CHARGE_PARM_P (clone))
4656     {
4657       DECL_CHAIN (DECL_ARGUMENTS (clone))
4658         = DECL_CHAIN (DECL_CHAIN (DECL_ARGUMENTS (clone)));
4659       DECL_HAS_IN_CHARGE_PARM_P (clone) = 0;
4660     }
4661   /* And the VTT parm, in a complete [cd]tor.  */
4662   if (DECL_HAS_VTT_PARM_P (fn))
4663     {
4664       if (DECL_NEEDS_VTT_PARM_P (clone))
4665         DECL_HAS_VTT_PARM_P (clone) = 1;
4666       else
4667         {
4668           DECL_CHAIN (DECL_ARGUMENTS (clone))
4669             = DECL_CHAIN (DECL_CHAIN (DECL_ARGUMENTS (clone)));
4670           DECL_HAS_VTT_PARM_P (clone) = 0;
4671         }
4672     }
4673
4674   for (parms = DECL_ARGUMENTS (clone); parms; parms = DECL_CHAIN (parms))
4675     {
4676       DECL_CONTEXT (parms) = clone;
4677       cxx_dup_lang_specific_decl (parms);
4678     }
4679
4680   /* Create the RTL for this function.  */
4681   SET_DECL_RTL (clone, NULL);
4682   rest_of_decl_compilation (clone, /*top_level=*/1, at_eof);
4683
4684   if (pch_file)
4685     note_decl_for_pch (clone);
4686
4687   return clone;
4688 }
4689
4690 /* Implementation of DECL_CLONED_FUNCTION and DECL_CLONED_FUNCTION_P, do
4691    not invoke this function directly.
4692
4693    For a non-thunk function, returns the address of the slot for storing
4694    the function it is a clone of.  Otherwise returns NULL_TREE.
4695
4696    If JUST_TESTING, looks through TEMPLATE_DECL and returns NULL if
4697    cloned_function is unset.  This is to support the separate
4698    DECL_CLONED_FUNCTION and DECL_CLONED_FUNCTION_P modes; using the latter
4699    on a template makes sense, but not the former.  */
4700
4701 tree *
4702 decl_cloned_function_p (const_tree decl, bool just_testing)
4703 {
4704   tree *ptr;
4705   if (just_testing)
4706     decl = STRIP_TEMPLATE (decl);
4707
4708   if (TREE_CODE (decl) != FUNCTION_DECL
4709       || !DECL_LANG_SPECIFIC (decl)
4710       || DECL_LANG_SPECIFIC (decl)->u.fn.thunk_p)
4711     {
4712 #if defined ENABLE_TREE_CHECKING && (GCC_VERSION >= 2007)
4713       if (!just_testing)
4714         lang_check_failed (__FILE__, __LINE__, __FUNCTION__);
4715       else
4716 #endif
4717         return NULL;
4718     }
4719
4720   ptr = &DECL_LANG_SPECIFIC (decl)->u.fn.u5.cloned_function;
4721   if (just_testing && *ptr == NULL_TREE)
4722     return NULL;
4723   else
4724     return ptr;
4725 }
4726
4727 /* Produce declarations for all appropriate clones of FN.  If
4728    UPDATE_METHOD_VEC_P is nonzero, the clones are added to the
4729    CLASTYPE_METHOD_VEC as well.  */
4730
4731 void
4732 clone_function_decl (tree fn, int update_method_vec_p)
4733 {
4734   tree clone;
4735
4736   /* Avoid inappropriate cloning.  */
4737   if (DECL_CHAIN (fn)
4738       && DECL_CLONED_FUNCTION_P (DECL_CHAIN (fn)))
4739     return;
4740
4741   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
4742     {
4743       /* For each constructor, we need two variants: an in-charge version
4744          and a not-in-charge version.  */
4745       clone = build_clone (fn, complete_ctor_identifier);
4746       if (update_method_vec_p)
4747         add_method (DECL_CONTEXT (clone), clone, NULL_TREE);
4748       clone = build_clone (fn, base_ctor_identifier);
4749       if (update_method_vec_p)
4750         add_method (DECL_CONTEXT (clone), clone, NULL_TREE);
4751     }
4752   else
4753     {
4754       gcc_assert (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (fn));
4755
4756       /* For each destructor, we need three variants: an in-charge
4757          version, a not-in-charge version, and an in-charge deleting
4758          version.  We clone the deleting version first because that
4759          means it will go second on the TYPE_METHODS list -- and that
4760          corresponds to the correct layout order in the virtual
4761          function table.
4762
4763          For a non-virtual destructor, we do not build a deleting
4764          destructor.  */
4765       if (DECL_VIRTUAL_P (fn))
4766         {
4767           clone = build_clone (fn, deleting_dtor_identifier);
4768           if (update_method_vec_p)
4769             add_method (DECL_CONTEXT (clone), clone, NULL_TREE);
4770         }
4771       clone = build_clone (fn, complete_dtor_identifier);
4772       if (update_method_vec_p)
4773         add_method (DECL_CONTEXT (clone), clone, NULL_TREE);
4774       clone = build_clone (fn, base_dtor_identifier);
4775       if (update_method_vec_p)
4776         add_method (DECL_CONTEXT (clone), clone, NULL_TREE);
4777     }
4778
4779   /* Note that this is an abstract function that is never emitted.  */
4780   DECL_ABSTRACT_P (fn) = true;
4781 }
4782
4783 /* DECL is an in charge constructor, which is being defined. This will
4784    have had an in class declaration, from whence clones were
4785    declared. An out-of-class definition can specify additional default
4786    arguments. As it is the clones that are involved in overload
4787    resolution, we must propagate the information from the DECL to its
4788    clones.  */
4789
4790 void
4791 adjust_clone_args (tree decl)
4792 {
4793   tree clone;
4794
4795   for (clone = DECL_CHAIN (decl); clone && DECL_CLONED_FUNCTION_P (clone);
4796        clone = DECL_CHAIN (clone))
4797     {
4798       tree orig_clone_parms = TYPE_ARG_TYPES (TREE_TYPE (clone));
4799       tree orig_decl_parms = TYPE_ARG_TYPES (TREE_TYPE (decl));
4800       tree decl_parms, clone_parms;
4801
4802       clone_parms = orig_clone_parms;
4803
4804       /* Skip the 'this' parameter.  */
4805       orig_clone_parms = TREE_CHAIN (orig_clone_parms);
4806       orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4807
4808       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
4809         orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4810       if (DECL_HAS_VTT_PARM_P (decl))
4811         orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4812
4813       clone_parms = orig_clone_parms;
4814       if (DECL_HAS_VTT_PARM_P (clone))
4815         clone_parms = TREE_CHAIN (clone_parms);
4816
4817       for (decl_parms = orig_decl_parms; decl_parms;
4818            decl_parms = TREE_CHAIN (decl_parms),
4819              clone_parms = TREE_CHAIN (clone_parms))
4820         {
4821           gcc_assert (same_type_p (TREE_TYPE (decl_parms),
4822                                    TREE_TYPE (clone_parms)));
4823
4824           if (TREE_PURPOSE (decl_parms) && !TREE_PURPOSE (clone_parms))
4825             {
4826               /* A default parameter has been added. Adjust the
4827                  clone's parameters.  */
4828               tree exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (clone));
4829               tree attrs = TYPE_ATTRIBUTES (TREE_TYPE (clone));
4830               tree basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (clone));
4831               tree type;
4832
4833               clone_parms = orig_decl_parms;
4834
4835               if (DECL_HAS_VTT_PARM_P (clone))
4836                 {
4837                   clone_parms = tree_cons (TREE_PURPOSE (orig_clone_parms),
4838                                            TREE_VALUE (orig_clone_parms),
4839                                            clone_parms);
4840                   TREE_TYPE (clone_parms) = TREE_TYPE (orig_clone_parms);
4841                 }
4842               type = build_method_type_directly (basetype,
4843                                                  TREE_TYPE (TREE_TYPE (clone)),
4844                                                  clone_parms);
4845               if (exceptions)
4846                 type = build_exception_variant (type, exceptions);
4847               if (attrs)
4848                 type = cp_build_type_attribute_variant (type, attrs);
4849               TREE_TYPE (clone) = type;
4850
4851               clone_parms = NULL_TREE;
4852               break;
4853             }
4854         }
4855       gcc_assert (!clone_parms);
4856     }
4857 }
4858
4859 /* For each of the constructors and destructors in T, create an
4860    in-charge and not-in-charge variant.  */
4861
4862 static void
4863 clone_constructors_and_destructors (tree t)
4864 {
4865   tree fns;
4866
4867   /* If for some reason we don't have a CLASSTYPE_METHOD_VEC, we bail
4868      out now.  */
4869   if (!CLASSTYPE_METHOD_VEC (t))
4870     return;
4871
4872   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
4873     clone_function_decl (OVL_CURRENT (fns), /*update_method_vec_p=*/1);
4874   for (fns = CLASSTYPE_DESTRUCTORS (t); fns; fns = OVL_NEXT (fns))
4875     clone_function_decl (OVL_CURRENT (fns), /*update_method_vec_p=*/1);
4876 }
4877
4878 /* Deduce noexcept for a destructor DTOR.  */
4879
4880 void
4881 deduce_noexcept_on_destructor (tree dtor)
4882 {
4883   if (!TYPE_RAISES_EXCEPTIONS (TREE_TYPE (dtor)))
4884     {
4885       tree eh_spec = unevaluated_noexcept_spec ();
4886       TREE_TYPE (dtor) = build_exception_variant (TREE_TYPE (dtor), eh_spec);
4887     }
4888 }
4889
4890 /* For each destructor in T, deduce noexcept:
4891
4892    12.4/3: A declaration of a destructor that does not have an
4893    exception-specification is implicitly considered to have the
4894    same exception-specification as an implicit declaration (15.4).  */
4895
4896 static void
4897 deduce_noexcept_on_destructors (tree t)
4898 {
4899   /* If for some reason we don't have a CLASSTYPE_METHOD_VEC, we bail
4900      out now.  */
4901   if (!CLASSTYPE_METHOD_VEC (t))
4902     return;
4903
4904   for (tree fns = CLASSTYPE_DESTRUCTORS (t); fns; fns = OVL_NEXT (fns))
4905     deduce_noexcept_on_destructor (OVL_CURRENT (fns));
4906 }
4907
4908 /* Subroutine of set_one_vmethod_tm_attributes.  Search base classes
4909    of TYPE for virtual functions which FNDECL overrides.  Return a
4910    mask of the tm attributes found therein.  */
4911
4912 static int
4913 look_for_tm_attr_overrides (tree type, tree fndecl)
4914 {
4915   tree binfo = TYPE_BINFO (type);
4916   tree base_binfo;
4917   int ix, found = 0;
4918
4919   for (ix = 0; BINFO_BASE_ITERATE (binfo, ix, base_binfo); ++ix)
4920     {
4921       tree o, basetype = BINFO_TYPE (base_binfo);
4922
4923       if (!TYPE_POLYMORPHIC_P (basetype))
4924         continue;
4925
4926       o = look_for_overrides_here (basetype, fndecl);
4927       if (o)
4928         found |= tm_attr_to_mask (find_tm_attribute
4929                                   (TYPE_ATTRIBUTES (TREE_TYPE (o))));
4930       else
4931         found |= look_for_tm_attr_overrides (basetype, fndecl);
4932     }
4933
4934   return found;
4935 }
4936
4937 /* Subroutine of set_method_tm_attributes.  Handle the checks and
4938    inheritance for one virtual method FNDECL.  */
4939
4940 static void
4941 set_one_vmethod_tm_attributes (tree type, tree fndecl)
4942 {
4943   tree tm_attr;
4944   int found, have;
4945
4946   found = look_for_tm_attr_overrides (type, fndecl);
4947
4948   /* If FNDECL doesn't actually override anything (i.e. T is the
4949      class that first declares FNDECL virtual), then we're done.  */
4950   if (found == 0)
4951     return;
4952
4953   tm_attr = find_tm_attribute (TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
4954   have = tm_attr_to_mask (tm_attr);
4955
4956   /* Intel STM Language Extension 3.0, Section 4.2 table 4:
4957      tm_pure must match exactly, otherwise no weakening of
4958      tm_safe > tm_callable > nothing.  */
4959   /* ??? The tm_pure attribute didn't make the transition to the
4960      multivendor language spec.  */
4961   if (have == TM_ATTR_PURE)
4962     {
4963       if (found != TM_ATTR_PURE)
4964         {
4965           found &= -found;
4966           goto err_override;
4967         }
4968     }
4969   /* If the overridden function is tm_pure, then FNDECL must be.  */
4970   else if (found == TM_ATTR_PURE && tm_attr)
4971     goto err_override;
4972   /* Look for base class combinations that cannot be satisfied.  */
4973   else if (found != TM_ATTR_PURE && (found & TM_ATTR_PURE))
4974     {
4975       found &= ~TM_ATTR_PURE;
4976       found &= -found;
4977       error_at (DECL_SOURCE_LOCATION (fndecl),
4978                 "method overrides both %<transaction_pure%> and %qE methods",
4979                 tm_mask_to_attr (found));
4980     }
4981   /* If FNDECL did not declare an attribute, then inherit the most
4982      restrictive one.  */
4983   else if (tm_attr == NULL)
4984     {
4985       apply_tm_attr (fndecl, tm_mask_to_attr (found & -found));
4986     }
4987   /* Otherwise validate that we're not weaker than a function
4988      that is being overridden.  */
4989   else
4990     {
4991       found &= -found;
4992       if (found <= TM_ATTR_CALLABLE && have > found)
4993         goto err_override;
4994     }
4995   return;
4996
4997  err_override:
4998   error_at (DECL_SOURCE_LOCATION (fndecl),
4999             "method declared %qE overriding %qE method",
5000             tm_attr, tm_mask_to_attr (found));
5001 }
5002
5003 /* For each of the methods in T, propagate a class-level tm attribute.  */
5004
5005 static void
5006 set_method_tm_attributes (tree t)
5007 {
5008   tree class_tm_attr, fndecl;
5009
5010   /* Don't bother collecting tm attributes if transactional memory
5011      support is not enabled.  */
5012   if (!flag_tm)
5013     return;
5014
5015   /* Process virtual methods first, as they inherit directly from the
5016      base virtual function and also require validation of new attributes.  */
5017   if (TYPE_CONTAINS_VPTR_P (t))
5018     {
5019       tree vchain;
5020       for (vchain = BINFO_VIRTUALS (TYPE_BINFO (t)); vchain;
5021            vchain = TREE_CHAIN (vchain))
5022         {
5023           fndecl = BV_FN (vchain);
5024           if (DECL_THUNK_P (fndecl))
5025             fndecl = THUNK_TARGET (fndecl);
5026           set_one_vmethod_tm_attributes (t, fndecl);
5027         }
5028     }
5029
5030   /* If the class doesn't have an attribute, nothing more to do.  */
5031   class_tm_attr = find_tm_attribute (TYPE_ATTRIBUTES (t));
5032   if (class_tm_attr == NULL)
5033     return;
5034
5035   /* Any method that does not yet have a tm attribute inherits
5036      the one from the class.  */
5037   for (fndecl = TYPE_METHODS (t); fndecl; fndecl = TREE_CHAIN (fndecl))
5038     {
5039       if (!find_tm_attribute (TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
5040         apply_tm_attr (fndecl, class_tm_attr);
5041     }
5042 }
5043
5044 /* Returns true iff class T has a user-defined constructor other than
5045    the default constructor.  */
5046
5047 bool
5048 type_has_user_nondefault_constructor (tree t)
5049 {
5050   tree fns;
5051
5052   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
5053     return false;
5054
5055   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5056     {
5057       tree fn = OVL_CURRENT (fns);
5058       if (!DECL_ARTIFICIAL (fn)
5059           && (TREE_CODE (fn) == TEMPLATE_DECL
5060               || (skip_artificial_parms_for (fn, DECL_ARGUMENTS (fn))
5061                   != NULL_TREE)))
5062         return true;
5063     }
5064
5065   return false;
5066 }
5067
5068 /* Returns the defaulted constructor if T has one. Otherwise, returns
5069    NULL_TREE.  */
5070
5071 tree
5072 in_class_defaulted_default_constructor (tree t)
5073 {
5074   tree fns, args;
5075
5076   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
5077     return NULL_TREE;
5078
5079   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5080     {
5081       tree fn = OVL_CURRENT (fns);
5082
5083       if (DECL_DEFAULTED_IN_CLASS_P (fn))
5084         {
5085           args = FUNCTION_FIRST_USER_PARMTYPE (fn);
5086           while (args && TREE_PURPOSE (args))
5087             args = TREE_CHAIN (args);
5088           if (!args || args == void_list_node)
5089             return fn;
5090         }
5091     }
5092
5093   return NULL_TREE;
5094 }
5095
5096 /* Returns true iff FN is a user-provided function, i.e. user-declared
5097    and not defaulted at its first declaration; or explicit, private,
5098    protected, or non-const.  */
5099
5100 bool
5101 user_provided_p (tree fn)
5102 {
5103   if (TREE_CODE (fn) == TEMPLATE_DECL)
5104     return true;
5105   else
5106     return (!DECL_ARTIFICIAL (fn)
5107             && !(DECL_INITIALIZED_IN_CLASS_P (fn)
5108                  && (DECL_DEFAULTED_FN (fn) || DECL_DELETED_FN (fn))));
5109 }
5110
5111 /* Returns true iff class T has a user-provided constructor.  */
5112
5113 bool
5114 type_has_user_provided_constructor (tree t)
5115 {
5116   tree fns;
5117
5118   if (!CLASS_TYPE_P (t))
5119     return false;
5120
5121   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
5122     return false;
5123
5124   /* This can happen in error cases; avoid crashing.  */
5125   if (!CLASSTYPE_METHOD_VEC (t))
5126     return false;
5127
5128   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5129     if (user_provided_p (OVL_CURRENT (fns)))
5130       return true;
5131
5132   return false;
5133 }
5134
5135 /* Returns true iff class T has a non-user-provided (i.e. implicitly
5136    declared or explicitly defaulted in the class body) default
5137    constructor.  */
5138
5139 bool
5140 type_has_non_user_provided_default_constructor (tree t)
5141 {
5142   tree fns;
5143
5144   if (!TYPE_HAS_DEFAULT_CONSTRUCTOR (t))
5145     return false;
5146   if (CLASSTYPE_LAZY_DEFAULT_CTOR (t))
5147     return true;
5148
5149   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5150     {
5151       tree fn = OVL_CURRENT (fns);
5152       if (TREE_CODE (fn) == FUNCTION_DECL
5153           && !user_provided_p (fn)
5154           && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)))
5155         return true;
5156     }
5157
5158   return false;
5159 }
5160
5161 /* TYPE is being used as a virtual base, and has a non-trivial move
5162    assignment.  Return true if this is due to there being a user-provided
5163    move assignment in TYPE or one of its subobjects; if there isn't, then
5164    multiple move assignment can't cause any harm.  */
5165
5166 bool
5167 vbase_has_user_provided_move_assign (tree type)
5168 {
5169   /* Does the type itself have a user-provided move assignment operator?  */
5170   for (tree fns
5171          = lookup_fnfields_slot_nolazy (type, ansi_assopname (NOP_EXPR));
5172        fns; fns = OVL_NEXT (fns))
5173     {
5174       tree fn = OVL_CURRENT (fns);
5175       if (move_fn_p (fn) && user_provided_p (fn))
5176         return true;
5177     }
5178
5179   /* Do any of its bases?  */
5180   tree binfo = TYPE_BINFO (type);
5181   tree base_binfo;
5182   for (int i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
5183     if (vbase_has_user_provided_move_assign (BINFO_TYPE (base_binfo)))
5184       return true;
5185
5186   /* Or non-static data members?  */
5187   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5188     {
5189       if (TREE_CODE (field) == FIELD_DECL
5190           && CLASS_TYPE_P (TREE_TYPE (field))
5191           && vbase_has_user_provided_move_assign (TREE_TYPE (field)))
5192         return true;
5193     }
5194
5195   /* Seems not.  */
5196   return false;
5197 }
5198
5199 /* If default-initialization leaves part of TYPE uninitialized, returns
5200    a DECL for the field or TYPE itself (DR 253).  */
5201
5202 tree
5203 default_init_uninitialized_part (tree type)
5204 {
5205   tree t, r, binfo;
5206   int i;
5207
5208   type = strip_array_types (type);
5209   if (!CLASS_TYPE_P (type))
5210     return type;
5211   if (!type_has_non_user_provided_default_constructor (type))
5212     return NULL_TREE;
5213   for (binfo = TYPE_BINFO (type), i = 0;
5214        BINFO_BASE_ITERATE (binfo, i, t); ++i)
5215     {
5216       r = default_init_uninitialized_part (BINFO_TYPE (t));
5217       if (r)
5218         return r;
5219     }
5220   for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
5221     if (TREE_CODE (t) == FIELD_DECL
5222         && !DECL_ARTIFICIAL (t)
5223         && !DECL_INITIAL (t))
5224       {
5225         r = default_init_uninitialized_part (TREE_TYPE (t));
5226         if (r)
5227           return DECL_P (r) ? r : t;
5228       }
5229
5230   return NULL_TREE;
5231 }
5232
5233 /* Returns true iff for class T, a trivial synthesized default constructor
5234    would be constexpr.  */
5235
5236 bool
5237 trivial_default_constructor_is_constexpr (tree t)
5238 {
5239   /* A defaulted trivial default constructor is constexpr
5240      if there is nothing to initialize.  */
5241   gcc_assert (!TYPE_HAS_COMPLEX_DFLT (t));
5242   return is_really_empty_class (t);
5243 }
5244
5245 /* Returns true iff class T has a constexpr default constructor.  */
5246
5247 bool
5248 type_has_constexpr_default_constructor (tree t)
5249 {
5250   tree fns;
5251
5252   if (!CLASS_TYPE_P (t))
5253     {
5254       /* The caller should have stripped an enclosing array.  */
5255       gcc_assert (TREE_CODE (t) != ARRAY_TYPE);
5256       return false;
5257     }
5258   if (CLASSTYPE_LAZY_DEFAULT_CTOR (t))
5259     {
5260       if (!TYPE_HAS_COMPLEX_DFLT (t))
5261         return trivial_default_constructor_is_constexpr (t);
5262       /* Non-trivial, we need to check subobject constructors.  */
5263       lazily_declare_fn (sfk_constructor, t);
5264     }
5265   fns = locate_ctor (t);
5266   return (fns && DECL_DECLARED_CONSTEXPR_P (fns));
5267 }
5268
5269 /* Returns true iff class TYPE has a virtual destructor.  */
5270
5271 bool
5272 type_has_virtual_destructor (tree type)
5273 {
5274   tree dtor;
5275
5276   if (!CLASS_TYPE_P (type))
5277     return false;
5278
5279   gcc_assert (COMPLETE_TYPE_P (type));
5280   dtor = CLASSTYPE_DESTRUCTORS (type);
5281   return (dtor && DECL_VIRTUAL_P (dtor));
5282 }
5283
5284 /* Returns true iff class T has a move constructor.  */
5285
5286 bool
5287 type_has_move_constructor (tree t)
5288 {
5289   tree fns;
5290
5291   if (CLASSTYPE_LAZY_MOVE_CTOR (t))
5292     {
5293       gcc_assert (COMPLETE_TYPE_P (t));
5294       lazily_declare_fn (sfk_move_constructor, t);
5295     }
5296
5297   if (!CLASSTYPE_METHOD_VEC (t))
5298     return false;
5299
5300   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5301     if (move_fn_p (OVL_CURRENT (fns)))
5302       return true;
5303
5304   return false;
5305 }
5306
5307 /* Returns true iff class T has a move assignment operator.  */
5308
5309 bool
5310 type_has_move_assign (tree t)
5311 {
5312   tree fns;
5313
5314   if (CLASSTYPE_LAZY_MOVE_ASSIGN (t))
5315     {
5316       gcc_assert (COMPLETE_TYPE_P (t));
5317       lazily_declare_fn (sfk_move_assignment, t);
5318     }
5319
5320   for (fns = lookup_fnfields_slot_nolazy (t, ansi_assopname (NOP_EXPR));
5321        fns; fns = OVL_NEXT (fns))
5322     if (move_fn_p (OVL_CURRENT (fns)))
5323       return true;
5324
5325   return false;
5326 }
5327
5328 /* Returns true iff class T has a move constructor that was explicitly
5329    declared in the class body.  Note that this is different from
5330    "user-provided", which doesn't include functions that are defaulted in
5331    the class.  */
5332
5333 bool
5334 type_has_user_declared_move_constructor (tree t)
5335 {
5336   tree fns;
5337
5338   if (CLASSTYPE_LAZY_MOVE_CTOR (t))
5339     return false;
5340
5341   if (!CLASSTYPE_METHOD_VEC (t))
5342     return false;
5343
5344   for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5345     {
5346       tree fn = OVL_CURRENT (fns);
5347       if (move_fn_p (fn) && !DECL_ARTIFICIAL (fn))
5348         return true;
5349     }
5350
5351   return false;
5352 }
5353
5354 /* Returns true iff class T has a move assignment operator that was
5355    explicitly declared in the class body.  */
5356
5357 bool
5358 type_has_user_declared_move_assign (tree t)
5359 {
5360   tree fns;
5361
5362   if (CLASSTYPE_LAZY_MOVE_ASSIGN (t))
5363     return false;
5364
5365   for (fns = lookup_fnfields_slot_nolazy (t, ansi_assopname (NOP_EXPR));
5366        fns; fns = OVL_NEXT (fns))
5367     {
5368       tree fn = OVL_CURRENT (fns);
5369       if (move_fn_p (fn) && !DECL_ARTIFICIAL (fn))
5370         return true;
5371     }
5372
5373   return false;
5374 }
5375
5376 /* Nonzero if we need to build up a constructor call when initializing an
5377    object of this class, either because it has a user-declared constructor
5378    or because it doesn't have a default constructor (so we need to give an
5379    error if no initializer is provided).  Use TYPE_NEEDS_CONSTRUCTING when
5380    what you care about is whether or not an object can be produced by a
5381    constructor (e.g. so we don't set TREE_READONLY on const variables of
5382    such type); use this function when what you care about is whether or not
5383    to try to call a constructor to create an object.  The latter case is
5384    the former plus some cases of constructors that cannot be called.  */
5385
5386 bool
5387 type_build_ctor_call (tree t)
5388 {
5389   tree inner;
5390   if (TYPE_NEEDS_CONSTRUCTING (t))
5391     return true;
5392   inner = strip_array_types (t);
5393   if (!CLASS_TYPE_P (inner) || ANON_AGGR_TYPE_P (inner))
5394     return false;
5395   if (!TYPE_HAS_DEFAULT_CONSTRUCTOR (inner))
5396     return true;
5397   if (cxx_dialect < cxx11)
5398     return false;
5399   /* A user-declared constructor might be private, and a constructor might
5400      be trivial but deleted.  */
5401   for (tree fns = lookup_fnfields_slot (inner, complete_ctor_identifier);
5402        fns; fns = OVL_NEXT (fns))
5403     {
5404       tree fn = OVL_CURRENT (fns);
5405       if (!DECL_ARTIFICIAL (fn)
5406           || DECL_DELETED_FN (fn))
5407         return true;
5408     }
5409   return false;
5410 }
5411
5412 /* Like type_build_ctor_call, but for destructors.  */
5413
5414 bool
5415 type_build_dtor_call (tree t)
5416 {
5417   tree inner;
5418   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
5419     return true;
5420   inner = strip_array_types (t);
5421   if (!CLASS_TYPE_P (inner) || ANON_AGGR_TYPE_P (inner)
5422       || !COMPLETE_TYPE_P (inner))
5423     return false;
5424   if (cxx_dialect < cxx11)
5425     return false;
5426   /* A user-declared destructor might be private, and a destructor might
5427      be trivial but deleted.  */
5428   for (tree fns = lookup_fnfields_slot (inner, complete_dtor_identifier);
5429        fns; fns = OVL_NEXT (fns))
5430     {
5431       tree fn = OVL_CURRENT (fns);
5432       if (!DECL_ARTIFICIAL (fn)
5433           || DECL_DELETED_FN (fn))
5434         return true;
5435     }
5436   return false;
5437 }
5438
5439 /* Remove all zero-width bit-fields from T.  */
5440
5441 static void
5442 remove_zero_width_bit_fields (tree t)
5443 {
5444   tree *fieldsp;
5445
5446   fieldsp = &TYPE_FIELDS (t);
5447   while (*fieldsp)
5448     {
5449       if (TREE_CODE (*fieldsp) == FIELD_DECL
5450           && DECL_C_BIT_FIELD (*fieldsp)
5451           /* We should not be confused by the fact that grokbitfield
5452              temporarily sets the width of the bit field into
5453              DECL_INITIAL (*fieldsp).
5454              check_bitfield_decl eventually sets DECL_SIZE (*fieldsp)
5455              to that width.  */
5456           && (DECL_SIZE (*fieldsp) == NULL_TREE
5457               || integer_zerop (DECL_SIZE (*fieldsp))))
5458         *fieldsp = DECL_CHAIN (*fieldsp);
5459       else
5460         fieldsp = &DECL_CHAIN (*fieldsp);
5461     }
5462 }
5463
5464 /* Returns TRUE iff we need a cookie when dynamically allocating an
5465    array whose elements have the indicated class TYPE.  */
5466
5467 static bool
5468 type_requires_array_cookie (tree type)
5469 {
5470   tree fns;
5471   bool has_two_argument_delete_p = false;
5472
5473   gcc_assert (CLASS_TYPE_P (type));
5474
5475   /* If there's a non-trivial destructor, we need a cookie.  In order
5476      to iterate through the array calling the destructor for each
5477      element, we'll have to know how many elements there are.  */
5478   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5479     return true;
5480
5481   /* If the usual deallocation function is a two-argument whose second
5482      argument is of type `size_t', then we have to pass the size of
5483      the array to the deallocation function, so we will need to store
5484      a cookie.  */
5485   fns = lookup_fnfields (TYPE_BINFO (type),
5486                          ansi_opname (VEC_DELETE_EXPR),
5487                          /*protect=*/0);
5488   /* If there are no `operator []' members, or the lookup is
5489      ambiguous, then we don't need a cookie.  */
5490   if (!fns || fns == error_mark_node)
5491     return false;
5492   /* Loop through all of the functions.  */
5493   for (fns = BASELINK_FUNCTIONS (fns); fns; fns = OVL_NEXT (fns))
5494     {
5495       tree fn;
5496       tree second_parm;
5497
5498       /* Select the current function.  */
5499       fn = OVL_CURRENT (fns);
5500       /* See if this function is a one-argument delete function.  If
5501          it is, then it will be the usual deallocation function.  */
5502       second_parm = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn)));
5503       if (second_parm == void_list_node)
5504         return false;
5505       /* Do not consider this function if its second argument is an
5506          ellipsis.  */
5507       if (!second_parm)
5508         continue;
5509       /* Otherwise, if we have a two-argument function and the second
5510          argument is `size_t', it will be the usual deallocation
5511          function -- unless there is one-argument function, too.  */
5512       if (TREE_CHAIN (second_parm) == void_list_node
5513           && same_type_p (TREE_VALUE (second_parm), size_type_node))
5514         has_two_argument_delete_p = true;
5515     }
5516
5517   return has_two_argument_delete_p;
5518 }
5519
5520 /* Finish computing the `literal type' property of class type T.
5521
5522    At this point, we have already processed base classes and
5523    non-static data members.  We need to check whether the copy
5524    constructor is trivial, the destructor is trivial, and there
5525    is a trivial default constructor or at least one constexpr
5526    constructor other than the copy constructor.  */
5527
5528 static void
5529 finalize_literal_type_property (tree t)
5530 {
5531   tree fn;
5532
5533   if (cxx_dialect < cxx11
5534       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
5535     CLASSTYPE_LITERAL_P (t) = false;
5536   else if (CLASSTYPE_LITERAL_P (t) && !TYPE_HAS_TRIVIAL_DFLT (t)
5537            && CLASSTYPE_NON_AGGREGATE (t)
5538            && !TYPE_HAS_CONSTEXPR_CTOR (t))
5539     CLASSTYPE_LITERAL_P (t) = false;
5540
5541   if (!CLASSTYPE_LITERAL_P (t))
5542     for (fn = TYPE_METHODS (t); fn; fn = DECL_CHAIN (fn))
5543       if (DECL_DECLARED_CONSTEXPR_P (fn)
5544           && TREE_CODE (fn) != TEMPLATE_DECL
5545           && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
5546           && !DECL_CONSTRUCTOR_P (fn))
5547         {
5548           DECL_DECLARED_CONSTEXPR_P (fn) = false;
5549           if (!DECL_GENERATED_P (fn))
5550             {
5551               error ("enclosing class of constexpr non-static member "
5552                      "function %q+#D is not a literal type", fn);
5553               explain_non_literal_class (t);
5554             }
5555         }
5556 }
5557
5558 /* T is a non-literal type used in a context which requires a constant
5559    expression.  Explain why it isn't literal.  */
5560
5561 void
5562 explain_non_literal_class (tree t)
5563 {
5564   static hash_set<tree> *diagnosed;
5565
5566   if (!CLASS_TYPE_P (t))
5567     return;
5568   t = TYPE_MAIN_VARIANT (t);
5569
5570   if (diagnosed == NULL)
5571     diagnosed = new hash_set<tree>;
5572   if (diagnosed->add (t))
5573     /* Already explained.  */
5574     return;
5575
5576   inform (0, "%q+T is not literal because:", t);
5577   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
5578     inform (0, "  %q+T has a non-trivial destructor", t);
5579   else if (CLASSTYPE_NON_AGGREGATE (t)
5580            && !TYPE_HAS_TRIVIAL_DFLT (t)
5581            && !TYPE_HAS_CONSTEXPR_CTOR (t))
5582     {
5583       inform (0, "  %q+T is not an aggregate, does not have a trivial "
5584               "default constructor, and has no constexpr constructor that "
5585               "is not a copy or move constructor", t);
5586       if (type_has_non_user_provided_default_constructor (t))
5587         {
5588           /* Note that we can't simply call locate_ctor because when the
5589              constructor is deleted it just returns NULL_TREE.  */
5590           tree fns;
5591           for (fns = CLASSTYPE_CONSTRUCTORS (t); fns; fns = OVL_NEXT (fns))
5592             {
5593               tree fn = OVL_CURRENT (fns);
5594               tree parms = TYPE_ARG_TYPES (TREE_TYPE (fn));
5595
5596               parms = skip_artificial_parms_for (fn, parms);
5597
5598               if (sufficient_parms_p (parms))
5599                 {
5600                   if (DECL_DELETED_FN (fn))
5601                     maybe_explain_implicit_delete (fn);
5602                   else
5603                     explain_invalid_constexpr_fn (fn);
5604                   break;
5605                 }
5606             }
5607         }
5608     }
5609   else
5610     {
5611       tree binfo, base_binfo, field; int i;
5612       for (binfo = TYPE_BINFO (t), i = 0;
5613            BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5614         {
5615           tree basetype = TREE_TYPE (base_binfo);
5616           if (!CLASSTYPE_LITERAL_P (basetype))
5617             {
5618               inform (0, "  base class %qT of %q+T is non-literal",
5619                       basetype, t);
5620               explain_non_literal_class (basetype);
5621               return;
5622             }
5623         }
5624       for (field = TYPE_FIELDS (t); field; field = TREE_CHAIN (field))
5625         {
5626           tree ftype;
5627           if (TREE_CODE (field) != FIELD_DECL)
5628             continue;
5629           ftype = TREE_TYPE (field);
5630           if (!literal_type_p (ftype))
5631             {
5632               inform (0, "  non-static data member %q+D has "
5633                       "non-literal type", field);
5634               if (CLASS_TYPE_P (ftype))
5635                 explain_non_literal_class (ftype);
5636             }
5637           if (CP_TYPE_VOLATILE_P (ftype))
5638             inform (0, "  non-static data member %q+D has "
5639                     "volatile type", field);
5640         }
5641     }
5642 }
5643
5644 /* Check the validity of the bases and members declared in T.  Add any
5645    implicitly-generated functions (like copy-constructors and
5646    assignment operators).  Compute various flag bits (like
5647    CLASSTYPE_NON_LAYOUT_POD_T) for T.  This routine works purely at the C++
5648    level: i.e., independently of the ABI in use.  */
5649
5650 static void
5651 check_bases_and_members (tree t)
5652 {
5653   /* Nonzero if the implicitly generated copy constructor should take
5654      a non-const reference argument.  */
5655   int cant_have_const_ctor;
5656   /* Nonzero if the implicitly generated assignment operator
5657      should take a non-const reference argument.  */
5658   int no_const_asn_ref;
5659   tree access_decls;
5660   bool saved_complex_asn_ref;
5661   bool saved_nontrivial_dtor;
5662   tree fn;
5663
5664   /* By default, we use const reference arguments and generate default
5665      constructors.  */
5666   cant_have_const_ctor = 0;
5667   no_const_asn_ref = 0;
5668
5669   /* Check all the base-classes.  */
5670   check_bases (t, &cant_have_const_ctor,
5671                &no_const_asn_ref);
5672
5673   /* Deduce noexcept on destructors.  This needs to happen after we've set
5674      triviality flags appropriately for our bases.  */
5675   if (cxx_dialect >= cxx11)
5676     deduce_noexcept_on_destructors (t);
5677
5678   /* Check all the method declarations.  */
5679   check_methods (t);
5680
5681   /* Save the initial values of these flags which only indicate whether
5682      or not the class has user-provided functions.  As we analyze the
5683      bases and members we can set these flags for other reasons.  */
5684   saved_complex_asn_ref = TYPE_HAS_COMPLEX_COPY_ASSIGN (t);
5685   saved_nontrivial_dtor = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t);
5686
5687   /* Check all the data member declarations.  We cannot call
5688      check_field_decls until we have called check_bases check_methods,
5689      as check_field_decls depends on TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5690      being set appropriately.  */
5691   check_field_decls (t, &access_decls,
5692                      &cant_have_const_ctor,
5693                      &no_const_asn_ref);
5694
5695   /* A nearly-empty class has to be vptr-containing; a nearly empty
5696      class contains just a vptr.  */
5697   if (!TYPE_CONTAINS_VPTR_P (t))
5698     CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
5699
5700   /* Do some bookkeeping that will guide the generation of implicitly
5701      declared member functions.  */
5702   TYPE_HAS_COMPLEX_COPY_CTOR (t) |= TYPE_CONTAINS_VPTR_P (t);
5703   TYPE_HAS_COMPLEX_MOVE_CTOR (t) |= TYPE_CONTAINS_VPTR_P (t);
5704   /* We need to call a constructor for this class if it has a
5705      user-provided constructor, or if the default constructor is going
5706      to initialize the vptr.  (This is not an if-and-only-if;
5707      TYPE_NEEDS_CONSTRUCTING is set elsewhere if bases or members
5708      themselves need constructing.)  */
5709   TYPE_NEEDS_CONSTRUCTING (t)
5710     |= (type_has_user_provided_constructor (t) || TYPE_CONTAINS_VPTR_P (t));
5711   /* [dcl.init.aggr]
5712
5713      An aggregate is an array or a class with no user-provided
5714      constructors ... and no virtual functions.  
5715
5716      Again, other conditions for being an aggregate are checked
5717      elsewhere.  */
5718   CLASSTYPE_NON_AGGREGATE (t)
5719     |= (type_has_user_provided_constructor (t) || TYPE_POLYMORPHIC_P (t));
5720   /* This is the C++98/03 definition of POD; it changed in C++0x, but we
5721      retain the old definition internally for ABI reasons.  */
5722   CLASSTYPE_NON_LAYOUT_POD_P (t)
5723     |= (CLASSTYPE_NON_AGGREGATE (t)
5724         || saved_nontrivial_dtor || saved_complex_asn_ref);
5725   CLASSTYPE_NON_STD_LAYOUT (t) |= TYPE_CONTAINS_VPTR_P (t);
5726   TYPE_HAS_COMPLEX_COPY_ASSIGN (t) |= TYPE_CONTAINS_VPTR_P (t);
5727   TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) |= TYPE_CONTAINS_VPTR_P (t);
5728   TYPE_HAS_COMPLEX_DFLT (t) |= TYPE_CONTAINS_VPTR_P (t);
5729
5730   /* If the only explicitly declared default constructor is user-provided,
5731      set TYPE_HAS_COMPLEX_DFLT.  */
5732   if (!TYPE_HAS_COMPLEX_DFLT (t)
5733       && TYPE_HAS_DEFAULT_CONSTRUCTOR (t)
5734       && !type_has_non_user_provided_default_constructor (t))
5735     TYPE_HAS_COMPLEX_DFLT (t) = true;
5736
5737   /* Warn if a public base of a polymorphic type has an accessible
5738      non-virtual destructor.  It is only now that we know the class is
5739      polymorphic.  Although a polymorphic base will have a already
5740      been diagnosed during its definition, we warn on use too.  */
5741   if (TYPE_POLYMORPHIC_P (t) && warn_nonvdtor)
5742     {
5743       tree binfo = TYPE_BINFO (t);
5744       vec<tree, va_gc> *accesses = BINFO_BASE_ACCESSES (binfo);
5745       tree base_binfo;
5746       unsigned i;
5747       
5748       for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5749         {
5750           tree basetype = TREE_TYPE (base_binfo);
5751
5752           if ((*accesses)[i] == access_public_node
5753               && (TYPE_POLYMORPHIC_P (basetype) || warn_ecpp)
5754               && accessible_nvdtor_p (basetype))
5755             warning (OPT_Wnon_virtual_dtor,
5756                      "base class %q#T has accessible non-virtual destructor",
5757                      basetype);
5758         }
5759     }
5760   
5761   /* If the class has no user-declared constructor, but does have
5762      non-static const or reference data members that can never be
5763      initialized, issue a warning.  */
5764   if (warn_uninitialized
5765       /* Classes with user-declared constructors are presumed to
5766          initialize these members.  */
5767       && !TYPE_HAS_USER_CONSTRUCTOR (t)
5768       /* Aggregates can be initialized with brace-enclosed
5769          initializers.  */
5770       && CLASSTYPE_NON_AGGREGATE (t))
5771     {
5772       tree field;
5773
5774       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5775         {
5776           tree type;
5777
5778           if (TREE_CODE (field) != FIELD_DECL
5779               || DECL_INITIAL (field) != NULL_TREE)
5780             continue;
5781
5782           type = TREE_TYPE (field);
5783           if (TREE_CODE (type) == REFERENCE_TYPE)
5784             warning (OPT_Wuninitialized, "non-static reference %q+#D "
5785                      "in class without a constructor", field);
5786           else if (CP_TYPE_CONST_P (type)
5787                    && (!CLASS_TYPE_P (type)
5788                        || !TYPE_HAS_DEFAULT_CONSTRUCTOR (type)))
5789             warning (OPT_Wuninitialized, "non-static const member %q+#D "
5790                      "in class without a constructor", field);
5791         }
5792     }
5793
5794   /* Synthesize any needed methods.  */
5795   add_implicitly_declared_members (t, &access_decls,
5796                                    cant_have_const_ctor,
5797                                    no_const_asn_ref);
5798
5799   /* Check defaulted declarations here so we have cant_have_const_ctor
5800      and don't need to worry about clones.  */
5801   for (fn = TYPE_METHODS (t); fn; fn = DECL_CHAIN (fn))
5802     if (!DECL_ARTIFICIAL (fn) && DECL_DEFAULTED_IN_CLASS_P (fn))
5803       {
5804         int copy = copy_fn_p (fn);
5805         if (copy > 0)
5806           {
5807             bool imp_const_p
5808               = (DECL_CONSTRUCTOR_P (fn) ? !cant_have_const_ctor
5809                  : !no_const_asn_ref);
5810             bool fn_const_p = (copy == 2);
5811
5812             if (fn_const_p && !imp_const_p)
5813               /* If the function is defaulted outside the class, we just
5814                  give the synthesis error.  */
5815               error ("%q+D declared to take const reference, but implicit "
5816                      "declaration would take non-const", fn);
5817           }
5818         defaulted_late_check (fn);
5819       }
5820
5821   if (LAMBDA_TYPE_P (t))
5822     {
5823       /* "This class type is not an aggregate."  */
5824       CLASSTYPE_NON_AGGREGATE (t) = 1;
5825     }
5826
5827   /* Compute the 'literal type' property before we
5828      do anything with non-static member functions.  */
5829   finalize_literal_type_property (t);
5830
5831   /* Create the in-charge and not-in-charge variants of constructors
5832      and destructors.  */
5833   clone_constructors_and_destructors (t);
5834
5835   /* Process the using-declarations.  */
5836   for (; access_decls; access_decls = TREE_CHAIN (access_decls))
5837     handle_using_decl (TREE_VALUE (access_decls), t);
5838
5839   /* Build and sort the CLASSTYPE_METHOD_VEC.  */
5840   finish_struct_methods (t);
5841
5842   /* Figure out whether or not we will need a cookie when dynamically
5843      allocating an array of this type.  */
5844   TYPE_LANG_SPECIFIC (t)->u.c.vec_new_uses_cookie
5845     = type_requires_array_cookie (t);
5846 }
5847
5848 /* If T needs a pointer to its virtual function table, set TYPE_VFIELD
5849    accordingly.  If a new vfield was created (because T doesn't have a
5850    primary base class), then the newly created field is returned.  It
5851    is not added to the TYPE_FIELDS list; it is the caller's
5852    responsibility to do that.  Accumulate declared virtual functions
5853    on VIRTUALS_P.  */
5854
5855 static tree
5856 create_vtable_ptr (tree t, tree* virtuals_p)
5857 {
5858   tree fn;
5859
5860   /* Collect the virtual functions declared in T.  */
5861   for (fn = TYPE_METHODS (t); fn; fn = DECL_CHAIN (fn))
5862     if (TREE_CODE (fn) == FUNCTION_DECL
5863         && DECL_VINDEX (fn) && !DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (fn)
5864         && TREE_CODE (DECL_VINDEX (fn)) != INTEGER_CST)
5865       {
5866         tree new_virtual = make_node (TREE_LIST);
5867
5868         BV_FN (new_virtual) = fn;
5869         BV_DELTA (new_virtual) = integer_zero_node;
5870         BV_VCALL_INDEX (new_virtual) = NULL_TREE;
5871
5872         TREE_CHAIN (new_virtual) = *virtuals_p;
5873         *virtuals_p = new_virtual;
5874       }
5875
5876   /* If we couldn't find an appropriate base class, create a new field
5877      here.  Even if there weren't any new virtual functions, we might need a
5878      new virtual function table if we're supposed to include vptrs in
5879      all classes that need them.  */
5880   if (!TYPE_VFIELD (t) && (*virtuals_p || TYPE_CONTAINS_VPTR_P (t)))
5881     {
5882       /* We build this decl with vtbl_ptr_type_node, which is a
5883          `vtable_entry_type*'.  It might seem more precise to use
5884          `vtable_entry_type (*)[N]' where N is the number of virtual
5885          functions.  However, that would require the vtable pointer in
5886          base classes to have a different type than the vtable pointer
5887          in derived classes.  We could make that happen, but that
5888          still wouldn't solve all the problems.  In particular, the
5889          type-based alias analysis code would decide that assignments
5890          to the base class vtable pointer can't alias assignments to
5891          the derived class vtable pointer, since they have different
5892          types.  Thus, in a derived class destructor, where the base
5893          class constructor was inlined, we could generate bad code for
5894          setting up the vtable pointer.
5895
5896          Therefore, we use one type for all vtable pointers.  We still
5897          use a type-correct type; it's just doesn't indicate the array
5898          bounds.  That's better than using `void*' or some such; it's
5899          cleaner, and it let's the alias analysis code know that these
5900          stores cannot alias stores to void*!  */
5901       tree field;
5902
5903       field = build_decl (input_location, 
5904                           FIELD_DECL, get_vfield_name (t), vtbl_ptr_type_node);
5905       DECL_VIRTUAL_P (field) = 1;
5906       DECL_ARTIFICIAL (field) = 1;
5907       DECL_FIELD_CONTEXT (field) = t;
5908       DECL_FCONTEXT (field) = t;
5909       if (TYPE_PACKED (t))
5910         DECL_PACKED (field) = 1;
5911
5912       TYPE_VFIELD (t) = field;
5913
5914       /* This class is non-empty.  */
5915       CLASSTYPE_EMPTY_P (t) = 0;
5916
5917       return field;
5918     }
5919
5920   return NULL_TREE;
5921 }
5922
5923 /* Add OFFSET to all base types of BINFO which is a base in the
5924    hierarchy dominated by T.
5925
5926    OFFSET, which is a type offset, is number of bytes.  */
5927
5928 static void
5929 propagate_binfo_offsets (tree binfo, tree offset)
5930 {
5931   int i;
5932   tree primary_binfo;
5933   tree base_binfo;
5934
5935   /* Update BINFO's offset.  */
5936   BINFO_OFFSET (binfo)
5937     = convert (sizetype,
5938                size_binop (PLUS_EXPR,
5939                            convert (ssizetype, BINFO_OFFSET (binfo)),
5940                            offset));
5941
5942   /* Find the primary base class.  */
5943   primary_binfo = get_primary_binfo (binfo);
5944
5945   if (primary_binfo && BINFO_INHERITANCE_CHAIN (primary_binfo) == binfo)
5946     propagate_binfo_offsets (primary_binfo, offset);
5947
5948   /* Scan all of the bases, pushing the BINFO_OFFSET adjust
5949      downwards.  */
5950   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
5951     {
5952       /* Don't do the primary base twice.  */
5953       if (base_binfo == primary_binfo)
5954         continue;
5955
5956       if (BINFO_VIRTUAL_P (base_binfo))
5957         continue;
5958
5959       propagate_binfo_offsets (base_binfo, offset);
5960     }
5961 }
5962
5963 /* Set BINFO_OFFSET for all of the virtual bases for RLI->T.  Update
5964    TYPE_ALIGN and TYPE_SIZE for T.  OFFSETS gives the location of
5965    empty subobjects of T.  */
5966
5967 static void
5968 layout_virtual_bases (record_layout_info rli, splay_tree offsets)
5969 {
5970   tree vbase;
5971   tree t = rli->t;
5972   tree *next_field;
5973
5974   if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)) == 0)
5975     return;
5976
5977   /* Find the last field.  The artificial fields created for virtual
5978      bases will go after the last extant field to date.  */
5979   next_field = &TYPE_FIELDS (t);
5980   while (*next_field)
5981     next_field = &DECL_CHAIN (*next_field);
5982
5983   /* Go through the virtual bases, allocating space for each virtual
5984      base that is not already a primary base class.  These are
5985      allocated in inheritance graph order.  */
5986   for (vbase = TYPE_BINFO (t); vbase; vbase = TREE_CHAIN (vbase))
5987     {
5988       if (!BINFO_VIRTUAL_P (vbase))
5989         continue;
5990
5991       if (!BINFO_PRIMARY_P (vbase))
5992         {
5993           /* This virtual base is not a primary base of any class in the
5994              hierarchy, so we have to add space for it.  */
5995           next_field = build_base_field (rli, vbase,
5996                                          offsets, next_field);
5997         }
5998     }
5999 }
6000
6001 /* Returns the offset of the byte just past the end of the base class
6002    BINFO.  */
6003
6004 static tree
6005 end_of_base (tree binfo)
6006 {
6007   tree size;
6008
6009   if (!CLASSTYPE_AS_BASE (BINFO_TYPE (binfo)))
6010     size = TYPE_SIZE_UNIT (char_type_node);
6011   else if (is_empty_class (BINFO_TYPE (binfo)))
6012     /* An empty class has zero CLASSTYPE_SIZE_UNIT, but we need to
6013        allocate some space for it. It cannot have virtual bases, so
6014        TYPE_SIZE_UNIT is fine.  */
6015     size = TYPE_SIZE_UNIT (BINFO_TYPE (binfo));
6016   else
6017     size = CLASSTYPE_SIZE_UNIT (BINFO_TYPE (binfo));
6018
6019   return size_binop (PLUS_EXPR, BINFO_OFFSET (binfo), size);
6020 }
6021
6022 /* Returns the offset of the byte just past the end of the base class
6023    with the highest offset in T.  If INCLUDE_VIRTUALS_P is zero, then
6024    only non-virtual bases are included.  */
6025
6026 static tree
6027 end_of_class (tree t, int include_virtuals_p)
6028 {
6029   tree result = size_zero_node;
6030   vec<tree, va_gc> *vbases;
6031   tree binfo;
6032   tree base_binfo;
6033   tree offset;
6034   int i;
6035
6036   for (binfo = TYPE_BINFO (t), i = 0;
6037        BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
6038     {
6039       if (!include_virtuals_p
6040           && BINFO_VIRTUAL_P (base_binfo)
6041           && (!BINFO_PRIMARY_P (base_binfo)
6042               || BINFO_INHERITANCE_CHAIN (base_binfo) != TYPE_BINFO (t)))
6043         continue;
6044
6045       offset = end_of_base (base_binfo);
6046       if (tree_int_cst_lt (result, offset))
6047         result = offset;
6048     }
6049
6050   if (include_virtuals_p)
6051     for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
6052          vec_safe_iterate (vbases, i, &base_binfo); i++)
6053       {
6054         offset = end_of_base (base_binfo);
6055         if (tree_int_cst_lt (result, offset))
6056           result = offset;
6057       }
6058
6059   return result;
6060 }
6061
6062 /* Warn about bases of T that are inaccessible because they are
6063    ambiguous.  For example:
6064
6065      struct S {};
6066      struct T : public S {};
6067      struct U : public S, public T {};
6068
6069    Here, `(S*) new U' is not allowed because there are two `S'
6070    subobjects of U.  */
6071
6072 static void
6073 warn_about_ambiguous_bases (tree t)
6074 {
6075   int i;
6076   vec<tree, va_gc> *vbases;
6077   tree basetype;
6078   tree binfo;
6079   tree base_binfo;
6080
6081   /* If there are no repeated bases, nothing can be ambiguous.  */
6082   if (!CLASSTYPE_REPEATED_BASE_P (t))
6083     return;
6084
6085   /* Check direct bases.  */
6086   for (binfo = TYPE_BINFO (t), i = 0;
6087        BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
6088     {
6089       basetype = BINFO_TYPE (base_binfo);
6090
6091       if (!uniquely_derived_from_p (basetype, t))
6092         warning (0, "direct base %qT inaccessible in %qT due to ambiguity",
6093                  basetype, t);
6094     }
6095
6096   /* Check for ambiguous virtual bases.  */
6097   if (extra_warnings)
6098     for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
6099          vec_safe_iterate (vbases, i, &binfo); i++)
6100       {
6101         basetype = BINFO_TYPE (binfo);
6102
6103         if (!uniquely_derived_from_p (basetype, t))
6104           warning (OPT_Wextra, "virtual base %qT inaccessible in %qT due "
6105                    "to ambiguity", basetype, t);
6106       }
6107 }
6108
6109 /* Compare two INTEGER_CSTs K1 and K2.  */
6110
6111 static int
6112 splay_tree_compare_integer_csts (splay_tree_key k1, splay_tree_key k2)
6113 {
6114   return tree_int_cst_compare ((tree) k1, (tree) k2);
6115 }
6116
6117 /* Increase the size indicated in RLI to account for empty classes
6118    that are "off the end" of the class.  */
6119
6120 static void
6121 include_empty_classes (record_layout_info rli)
6122 {
6123   tree eoc;
6124   tree rli_size;
6125
6126   /* It might be the case that we grew the class to allocate a
6127      zero-sized base class.  That won't be reflected in RLI, yet,
6128      because we are willing to overlay multiple bases at the same
6129      offset.  However, now we need to make sure that RLI is big enough
6130      to reflect the entire class.  */
6131   eoc = end_of_class (rli->t,
6132                       CLASSTYPE_AS_BASE (rli->t) != NULL_TREE);
6133   rli_size = rli_size_unit_so_far (rli);
6134   if (TREE_CODE (rli_size) == INTEGER_CST
6135       && tree_int_cst_lt (rli_size, eoc))
6136     {
6137       /* The size should have been rounded to a whole byte.  */
6138       gcc_assert (tree_int_cst_equal
6139                   (rli->bitpos, round_down (rli->bitpos, BITS_PER_UNIT)));
6140       rli->bitpos
6141         = size_binop (PLUS_EXPR,
6142                       rli->bitpos,
6143                       size_binop (MULT_EXPR,
6144                                   convert (bitsizetype,
6145                                            size_binop (MINUS_EXPR,
6146                                                        eoc, rli_size)),
6147                                   bitsize_int (BITS_PER_UNIT)));
6148       normalize_rli (rli);
6149     }
6150 }
6151
6152 /* Calculate the TYPE_SIZE, TYPE_ALIGN, etc for T.  Calculate
6153    BINFO_OFFSETs for all of the base-classes.  Position the vtable
6154    pointer.  Accumulate declared virtual functions on VIRTUALS_P.  */
6155
6156 static void
6157 layout_class_type (tree t, tree *virtuals_p)
6158 {
6159   tree non_static_data_members;
6160   tree field;
6161   tree vptr;
6162   record_layout_info rli;
6163   /* Maps offsets (represented as INTEGER_CSTs) to a TREE_LIST of
6164      types that appear at that offset.  */
6165   splay_tree empty_base_offsets;
6166   /* True if the last field laid out was a bit-field.  */
6167   bool last_field_was_bitfield = false;
6168   /* The location at which the next field should be inserted.  */
6169   tree *next_field;
6170   /* T, as a base class.  */
6171   tree base_t;
6172
6173   /* Keep track of the first non-static data member.  */
6174   non_static_data_members = TYPE_FIELDS (t);
6175
6176   /* Start laying out the record.  */
6177   rli = start_record_layout (t);
6178
6179   /* Mark all the primary bases in the hierarchy.  */
6180   determine_primary_bases (t);
6181
6182   /* Create a pointer to our virtual function table.  */
6183   vptr = create_vtable_ptr (t, virtuals_p);
6184
6185   /* The vptr is always the first thing in the class.  */
6186   if (vptr)
6187     {
6188       DECL_CHAIN (vptr) = TYPE_FIELDS (t);
6189       TYPE_FIELDS (t) = vptr;
6190       next_field = &DECL_CHAIN (vptr);
6191       place_field (rli, vptr);
6192     }
6193   else
6194     next_field = &TYPE_FIELDS (t);
6195
6196   /* Build FIELD_DECLs for all of the non-virtual base-types.  */
6197   empty_base_offsets = splay_tree_new (splay_tree_compare_integer_csts,
6198                                        NULL, NULL);
6199   build_base_fields (rli, empty_base_offsets, next_field);
6200
6201   /* Layout the non-static data members.  */
6202   for (field = non_static_data_members; field; field = DECL_CHAIN (field))
6203     {
6204       tree type;
6205       tree padding;
6206
6207       /* We still pass things that aren't non-static data members to
6208          the back end, in case it wants to do something with them.  */
6209       if (TREE_CODE (field) != FIELD_DECL)
6210         {
6211           place_field (rli, field);
6212           /* If the static data member has incomplete type, keep track
6213              of it so that it can be completed later.  (The handling
6214              of pending statics in finish_record_layout is
6215              insufficient; consider:
6216
6217                struct S1;
6218                struct S2 { static S1 s1; };
6219
6220              At this point, finish_record_layout will be called, but
6221              S1 is still incomplete.)  */
6222           if (VAR_P (field))
6223             {
6224               maybe_register_incomplete_var (field);
6225               /* The visibility of static data members is determined
6226                  at their point of declaration, not their point of
6227                  definition.  */
6228               determine_visibility (field);
6229             }
6230           continue;
6231         }
6232
6233       type = TREE_TYPE (field);
6234       if (type == error_mark_node)
6235         continue;
6236
6237       padding = NULL_TREE;
6238
6239       /* If this field is a bit-field whose width is greater than its
6240          type, then there are some special rules for allocating
6241          it.  */
6242       if (DECL_C_BIT_FIELD (field)
6243           && tree_int_cst_lt (TYPE_SIZE (type), DECL_SIZE (field)))
6244         {
6245           unsigned int itk;
6246           tree integer_type;
6247           bool was_unnamed_p = false;
6248           /* We must allocate the bits as if suitably aligned for the
6249              longest integer type that fits in this many bits.  type
6250              of the field.  Then, we are supposed to use the left over
6251              bits as additional padding.  */
6252           for (itk = itk_char; itk != itk_none; ++itk)
6253             if (integer_types[itk] != NULL_TREE
6254                 && (tree_int_cst_lt (size_int (MAX_FIXED_MODE_SIZE),
6255                                      TYPE_SIZE (integer_types[itk]))
6256                     || tree_int_cst_lt (DECL_SIZE (field),
6257                                         TYPE_SIZE (integer_types[itk]))))
6258               break;
6259
6260           /* ITK now indicates a type that is too large for the
6261              field.  We have to back up by one to find the largest
6262              type that fits.  */
6263           do
6264           {
6265             --itk;
6266             integer_type = integer_types[itk];
6267           } while (itk > 0 && integer_type == NULL_TREE);
6268
6269           /* Figure out how much additional padding is required.  */
6270           if (tree_int_cst_lt (TYPE_SIZE (integer_type), DECL_SIZE (field)))
6271             {
6272               if (TREE_CODE (t) == UNION_TYPE)
6273                 /* In a union, the padding field must have the full width
6274                    of the bit-field; all fields start at offset zero.  */
6275                 padding = DECL_SIZE (field);
6276               else
6277                 padding = size_binop (MINUS_EXPR, DECL_SIZE (field),
6278                                       TYPE_SIZE (integer_type));
6279             }
6280 #ifdef PCC_BITFIELD_TYPE_MATTERS
6281           /* An unnamed bitfield does not normally affect the
6282              alignment of the containing class on a target where
6283              PCC_BITFIELD_TYPE_MATTERS.  But, the C++ ABI does not
6284              make any exceptions for unnamed bitfields when the
6285              bitfields are longer than their types.  Therefore, we
6286              temporarily give the field a name.  */
6287           if (PCC_BITFIELD_TYPE_MATTERS && !DECL_NAME (field))
6288             {
6289               was_unnamed_p = true;
6290               DECL_NAME (field) = make_anon_name ();
6291             }
6292 #endif
6293           DECL_SIZE (field) = TYPE_SIZE (integer_type);
6294           DECL_ALIGN (field) = TYPE_ALIGN (integer_type);
6295           DECL_USER_ALIGN (field) = TYPE_USER_ALIGN (integer_type);
6296           layout_nonempty_base_or_field (rli, field, NULL_TREE,
6297                                          empty_base_offsets);
6298           if (was_unnamed_p)
6299             DECL_NAME (field) = NULL_TREE;
6300           /* Now that layout has been performed, set the size of the
6301              field to the size of its declared type; the rest of the
6302              field is effectively invisible.  */
6303           DECL_SIZE (field) = TYPE_SIZE (type);
6304           /* We must also reset the DECL_MODE of the field.  */
6305           DECL_MODE (field) = TYPE_MODE (type);
6306         }
6307       else
6308         layout_nonempty_base_or_field (rli, field, NULL_TREE,
6309                                        empty_base_offsets);
6310
6311       /* Remember the location of any empty classes in FIELD.  */
6312       record_subobject_offsets (TREE_TYPE (field),
6313                                 byte_position(field),
6314                                 empty_base_offsets,
6315                                 /*is_data_member=*/true);
6316
6317       /* If a bit-field does not immediately follow another bit-field,
6318          and yet it starts in the middle of a byte, we have failed to
6319          comply with the ABI.  */
6320       if (warn_abi
6321           && DECL_C_BIT_FIELD (field)
6322           /* The TREE_NO_WARNING flag gets set by Objective-C when
6323              laying out an Objective-C class.  The ObjC ABI differs
6324              from the C++ ABI, and so we do not want a warning
6325              here.  */
6326           && !TREE_NO_WARNING (field)
6327           && !last_field_was_bitfield
6328           && !integer_zerop (size_binop (TRUNC_MOD_EXPR,
6329                                          DECL_FIELD_BIT_OFFSET (field),
6330                                          bitsize_unit_node)))
6331         warning (OPT_Wabi, "offset of %q+D is not ABI-compliant and may "
6332                  "change in a future version of GCC", field);
6333
6334       /* The middle end uses the type of expressions to determine the
6335          possible range of expression values.  In order to optimize
6336          "x.i > 7" to "false" for a 2-bit bitfield "i", the middle end
6337          must be made aware of the width of "i", via its type.
6338
6339          Because C++ does not have integer types of arbitrary width,
6340          we must (for the purposes of the front end) convert from the
6341          type assigned here to the declared type of the bitfield
6342          whenever a bitfield expression is used as an rvalue.
6343          Similarly, when assigning a value to a bitfield, the value
6344          must be converted to the type given the bitfield here.  */
6345       if (DECL_C_BIT_FIELD (field))
6346         {
6347           unsigned HOST_WIDE_INT width;
6348           tree ftype = TREE_TYPE (field);
6349           width = tree_to_uhwi (DECL_SIZE (field));
6350           if (width != TYPE_PRECISION (ftype))
6351             {
6352               TREE_TYPE (field)
6353                 = c_build_bitfield_integer_type (width,
6354                                                  TYPE_UNSIGNED (ftype));
6355               TREE_TYPE (field)
6356                 = cp_build_qualified_type (TREE_TYPE (field),
6357                                            cp_type_quals (ftype));
6358             }
6359         }
6360
6361       /* If we needed additional padding after this field, add it
6362          now.  */
6363       if (padding)
6364         {
6365           tree padding_field;
6366
6367           padding_field = build_decl (input_location,
6368                                       FIELD_DECL,
6369                                       NULL_TREE,
6370                                       char_type_node);
6371           DECL_BIT_FIELD (padding_field) = 1;
6372           DECL_SIZE (padding_field) = padding;
6373           DECL_CONTEXT (padding_field) = t;
6374           DECL_ARTIFICIAL (padding_field) = 1;
6375           DECL_IGNORED_P (padding_field) = 1;
6376           layout_nonempty_base_or_field (rli, padding_field,
6377                                          NULL_TREE,
6378                                          empty_base_offsets);
6379         }
6380
6381       last_field_was_bitfield = DECL_C_BIT_FIELD (field);
6382     }
6383
6384   if (!integer_zerop (rli->bitpos))
6385     {
6386       /* Make sure that we are on a byte boundary so that the size of
6387          the class without virtual bases will always be a round number
6388          of bytes.  */
6389       rli->bitpos = round_up_loc (input_location, rli->bitpos, BITS_PER_UNIT);
6390       normalize_rli (rli);
6391     }
6392
6393   /* Delete all zero-width bit-fields from the list of fields.  Now
6394      that the type is laid out they are no longer important.  */
6395   remove_zero_width_bit_fields (t);
6396
6397   /* Create the version of T used for virtual bases.  We do not use
6398      make_class_type for this version; this is an artificial type.  For
6399      a POD type, we just reuse T.  */
6400   if (CLASSTYPE_NON_LAYOUT_POD_P (t) || CLASSTYPE_EMPTY_P (t))
6401     {
6402       base_t = make_node (TREE_CODE (t));
6403
6404       /* Set the size and alignment for the new type.  */
6405       tree eoc;
6406
6407       /* If the ABI version is not at least two, and the last
6408          field was a bit-field, RLI may not be on a byte
6409          boundary.  In particular, rli_size_unit_so_far might
6410          indicate the last complete byte, while rli_size_so_far
6411          indicates the total number of bits used.  Therefore,
6412          rli_size_so_far, rather than rli_size_unit_so_far, is
6413          used to compute TYPE_SIZE_UNIT.  */
6414       eoc = end_of_class (t, /*include_virtuals_p=*/0);
6415       TYPE_SIZE_UNIT (base_t)
6416         = size_binop (MAX_EXPR,
6417                       convert (sizetype,
6418                                size_binop (CEIL_DIV_EXPR,
6419                                            rli_size_so_far (rli),
6420                                            bitsize_int (BITS_PER_UNIT))),
6421                       eoc);
6422       TYPE_SIZE (base_t)
6423         = size_binop (MAX_EXPR,
6424                       rli_size_so_far (rli),
6425                       size_binop (MULT_EXPR,
6426                                   convert (bitsizetype, eoc),
6427                                   bitsize_int (BITS_PER_UNIT)));
6428       TYPE_ALIGN (base_t) = rli->record_align;
6429       TYPE_USER_ALIGN (base_t) = TYPE_USER_ALIGN (t);
6430
6431       /* Copy the fields from T.  */
6432       next_field = &TYPE_FIELDS (base_t);
6433       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
6434         if (TREE_CODE (field) == FIELD_DECL)
6435           {
6436             *next_field = build_decl (input_location,
6437                                       FIELD_DECL,
6438                                       DECL_NAME (field),
6439                                       TREE_TYPE (field));
6440             DECL_CONTEXT (*next_field) = base_t;
6441             DECL_FIELD_OFFSET (*next_field) = DECL_FIELD_OFFSET (field);
6442             DECL_FIELD_BIT_OFFSET (*next_field)
6443               = DECL_FIELD_BIT_OFFSET (field);
6444             DECL_SIZE (*next_field) = DECL_SIZE (field);
6445             DECL_MODE (*next_field) = DECL_MODE (field);
6446             next_field = &DECL_CHAIN (*next_field);
6447           }
6448
6449       /* Record the base version of the type.  */
6450       CLASSTYPE_AS_BASE (t) = base_t;
6451       TYPE_CONTEXT (base_t) = t;
6452     }
6453   else
6454     CLASSTYPE_AS_BASE (t) = t;
6455
6456   /* Every empty class contains an empty class.  */
6457   if (CLASSTYPE_EMPTY_P (t))
6458     CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t) = 1;
6459
6460   /* Set the TYPE_DECL for this type to contain the right
6461      value for DECL_OFFSET, so that we can use it as part
6462      of a COMPONENT_REF for multiple inheritance.  */
6463   layout_decl (TYPE_MAIN_DECL (t), 0);
6464
6465   /* Now fix up any virtual base class types that we left lying
6466      around.  We must get these done before we try to lay out the
6467      virtual function table.  As a side-effect, this will remove the
6468      base subobject fields.  */
6469   layout_virtual_bases (rli, empty_base_offsets);
6470
6471   /* Make sure that empty classes are reflected in RLI at this
6472      point.  */
6473   include_empty_classes(rli);
6474
6475   /* Make sure not to create any structures with zero size.  */
6476   if (integer_zerop (rli_size_unit_so_far (rli)) && CLASSTYPE_EMPTY_P (t))
6477     place_field (rli,
6478                  build_decl (input_location,
6479                              FIELD_DECL, NULL_TREE, char_type_node));
6480
6481   /* If this is a non-POD, declaring it packed makes a difference to how it
6482      can be used as a field; don't let finalize_record_size undo it.  */
6483   if (TYPE_PACKED (t) && !layout_pod_type_p (t))
6484     rli->packed_maybe_necessary = true;
6485
6486   /* Let the back end lay out the type.  */
6487   finish_record_layout (rli, /*free_p=*/true);
6488
6489   if (TYPE_SIZE_UNIT (t)
6490       && TREE_CODE (TYPE_SIZE_UNIT (t)) == INTEGER_CST
6491       && !TREE_OVERFLOW (TYPE_SIZE_UNIT (t))
6492       && !valid_constant_size_p (TYPE_SIZE_UNIT (t)))
6493     error ("type %qT is too large", t);
6494
6495   /* Warn about bases that can't be talked about due to ambiguity.  */
6496   warn_about_ambiguous_bases (t);
6497
6498   /* Now that we're done with layout, give the base fields the real types.  */
6499   for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
6500     if (DECL_ARTIFICIAL (field) && IS_FAKE_BASE_TYPE (TREE_TYPE (field)))
6501       TREE_TYPE (field) = TYPE_CONTEXT (TREE_TYPE (field));
6502
6503   /* Clean up.  */
6504   splay_tree_delete (empty_base_offsets);
6505
6506   if (CLASSTYPE_EMPTY_P (t)
6507       && tree_int_cst_lt (sizeof_biggest_empty_class,
6508                           TYPE_SIZE_UNIT (t)))
6509     sizeof_biggest_empty_class = TYPE_SIZE_UNIT (t);
6510 }
6511
6512 /* Determine the "key method" for the class type indicated by TYPE,
6513    and set CLASSTYPE_KEY_METHOD accordingly.  */
6514
6515 void
6516 determine_key_method (tree type)
6517 {
6518   tree method;
6519
6520   if (TYPE_FOR_JAVA (type)
6521       || processing_template_decl
6522       || CLASSTYPE_TEMPLATE_INSTANTIATION (type)
6523       || CLASSTYPE_INTERFACE_KNOWN (type))
6524     return;
6525
6526   /* The key method is the first non-pure virtual function that is not
6527      inline at the point of class definition.  On some targets the
6528      key function may not be inline; those targets should not call
6529      this function until the end of the translation unit.  */
6530   for (method = TYPE_METHODS (type); method != NULL_TREE;
6531        method = DECL_CHAIN (method))
6532     if (TREE_CODE (method) == FUNCTION_DECL
6533         && DECL_VINDEX (method) != NULL_TREE
6534         && ! DECL_DECLARED_INLINE_P (method)
6535         && ! DECL_PURE_VIRTUAL_P (method))
6536       {
6537         CLASSTYPE_KEY_METHOD (type) = method;
6538         break;
6539       }
6540
6541   return;
6542 }
6543
6544
6545 /* Allocate and return an instance of struct sorted_fields_type with
6546    N fields.  */
6547
6548 static struct sorted_fields_type *
6549 sorted_fields_type_new (int n)
6550 {
6551   struct sorted_fields_type *sft;
6552   sft = (sorted_fields_type *) ggc_internal_alloc (sizeof (sorted_fields_type)
6553                                       + n * sizeof (tree));
6554   sft->len = n;
6555
6556   return sft;
6557 }
6558
6559
6560 /* Perform processing required when the definition of T (a class type)
6561    is complete.  */
6562
6563 void
6564 finish_struct_1 (tree t)
6565 {
6566   tree x;
6567   /* A TREE_LIST.  The TREE_VALUE of each node is a FUNCTION_DECL.  */
6568   tree virtuals = NULL_TREE;
6569
6570   if (COMPLETE_TYPE_P (t))
6571     {
6572       gcc_assert (MAYBE_CLASS_TYPE_P (t));
6573       error ("redefinition of %q#T", t);
6574       popclass ();
6575       return;
6576     }
6577
6578   /* If this type was previously laid out as a forward reference,
6579      make sure we lay it out again.  */
6580   TYPE_SIZE (t) = NULL_TREE;
6581   CLASSTYPE_PRIMARY_BINFO (t) = NULL_TREE;
6582
6583   /* Make assumptions about the class; we'll reset the flags if
6584      necessary.  */
6585   CLASSTYPE_EMPTY_P (t) = 1;
6586   CLASSTYPE_NEARLY_EMPTY_P (t) = 1;
6587   CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t) = 0;
6588   CLASSTYPE_LITERAL_P (t) = true;
6589
6590   /* Do end-of-class semantic processing: checking the validity of the
6591      bases and members and add implicitly generated methods.  */
6592   check_bases_and_members (t);
6593
6594   /* Find the key method.  */
6595   if (TYPE_CONTAINS_VPTR_P (t))
6596     {
6597       /* The Itanium C++ ABI permits the key method to be chosen when
6598          the class is defined -- even though the key method so
6599          selected may later turn out to be an inline function.  On
6600          some systems (such as ARM Symbian OS) the key method cannot
6601          be determined until the end of the translation unit.  On such
6602          systems, we leave CLASSTYPE_KEY_METHOD set to NULL, which
6603          will cause the class to be added to KEYED_CLASSES.  Then, in
6604          finish_file we will determine the key method.  */
6605       if (targetm.cxx.key_method_may_be_inline ())
6606         determine_key_method (t);
6607
6608       /* If a polymorphic class has no key method, we may emit the vtable
6609          in every translation unit where the class definition appears.  If
6610          we're devirtualizing, we can look into the vtable even if we
6611          aren't emitting it.  */
6612       if (CLASSTYPE_KEY_METHOD (t) == NULL_TREE)
6613         keyed_classes = tree_cons (NULL_TREE, t, keyed_classes);
6614     }
6615
6616   /* Layout the class itself.  */
6617   layout_class_type (t, &virtuals);
6618   if (CLASSTYPE_AS_BASE (t) != t)
6619     /* We use the base type for trivial assignments, and hence it
6620        needs a mode.  */
6621     compute_record_mode (CLASSTYPE_AS_BASE (t));
6622
6623   virtuals = modify_all_vtables (t, nreverse (virtuals));
6624
6625   /* If necessary, create the primary vtable for this class.  */
6626   if (virtuals || TYPE_CONTAINS_VPTR_P (t))
6627     {
6628       /* We must enter these virtuals into the table.  */
6629       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
6630         build_primary_vtable (NULL_TREE, t);
6631       else if (! BINFO_NEW_VTABLE_MARKED (TYPE_BINFO (t)))
6632         /* Here we know enough to change the type of our virtual
6633            function table, but we will wait until later this function.  */
6634         build_primary_vtable (CLASSTYPE_PRIMARY_BINFO (t), t);
6635
6636       /* If we're warning about ABI tags, check the types of the new
6637          virtual functions.  */
6638       if (warn_abi_tag)
6639         for (tree v = virtuals; v; v = TREE_CHAIN (v))
6640           check_abi_tags (t, TREE_VALUE (v));
6641     }
6642
6643   if (TYPE_CONTAINS_VPTR_P (t))
6644     {
6645       int vindex;
6646       tree fn;
6647
6648       if (BINFO_VTABLE (TYPE_BINFO (t)))
6649         gcc_assert (DECL_VIRTUAL_P (BINFO_VTABLE (TYPE_BINFO (t))));
6650       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
6651         gcc_assert (BINFO_VIRTUALS (TYPE_BINFO (t)) == NULL_TREE);
6652
6653       /* Add entries for virtual functions introduced by this class.  */
6654       BINFO_VIRTUALS (TYPE_BINFO (t))
6655         = chainon (BINFO_VIRTUALS (TYPE_BINFO (t)), virtuals);
6656
6657       /* Set DECL_VINDEX for all functions declared in this class.  */
6658       for (vindex = 0, fn = BINFO_VIRTUALS (TYPE_BINFO (t));
6659            fn;
6660            fn = TREE_CHAIN (fn),
6661              vindex += (TARGET_VTABLE_USES_DESCRIPTORS
6662                         ? TARGET_VTABLE_USES_DESCRIPTORS : 1))
6663         {
6664           tree fndecl = BV_FN (fn);
6665
6666           if (DECL_THUNK_P (fndecl))
6667             /* A thunk. We should never be calling this entry directly
6668                from this vtable -- we'd use the entry for the non
6669                thunk base function.  */
6670             DECL_VINDEX (fndecl) = NULL_TREE;
6671           else if (TREE_CODE (DECL_VINDEX (fndecl)) != INTEGER_CST)
6672             DECL_VINDEX (fndecl) = build_int_cst (NULL_TREE, vindex);
6673         }
6674     }
6675
6676   finish_struct_bits (t);
6677   set_method_tm_attributes (t);
6678
6679   /* Complete the rtl for any static member objects of the type we're
6680      working on.  */
6681   for (x = TYPE_FIELDS (t); x; x = DECL_CHAIN (x))
6682     if (VAR_P (x) && TREE_STATIC (x)
6683         && TREE_TYPE (x) != error_mark_node
6684         && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (x)), t))
6685       DECL_MODE (x) = TYPE_MODE (t);
6686
6687   /* Done with FIELDS...now decide whether to sort these for
6688      faster lookups later.
6689
6690      We use a small number because most searches fail (succeeding
6691      ultimately as the search bores through the inheritance
6692      hierarchy), and we want this failure to occur quickly.  */
6693
6694   insert_into_classtype_sorted_fields (TYPE_FIELDS (t), t, 8);
6695
6696   /* Complain if one of the field types requires lower visibility.  */
6697   constrain_class_visibility (t);
6698
6699   /* Make the rtl for any new vtables we have created, and unmark
6700      the base types we marked.  */
6701   finish_vtbls (t);
6702
6703   /* Build the VTT for T.  */
6704   build_vtt (t);
6705
6706   /* This warning does not make sense for Java classes, since they
6707      cannot have destructors.  */
6708   if (!TYPE_FOR_JAVA (t) && warn_nonvdtor
6709       && TYPE_POLYMORPHIC_P (t) && accessible_nvdtor_p (t)
6710       && !CLASSTYPE_FINAL (t))
6711     warning (OPT_Wnon_virtual_dtor,
6712              "%q#T has virtual functions and accessible"
6713              " non-virtual destructor", t);
6714
6715   complete_vars (t);
6716
6717   if (warn_overloaded_virtual)
6718     warn_hidden (t);
6719
6720   /* Class layout, assignment of virtual table slots, etc., is now
6721      complete.  Give the back end a chance to tweak the visibility of
6722      the class or perform any other required target modifications.  */
6723   targetm.cxx.adjust_class_at_definition (t);
6724
6725   maybe_suppress_debug_info (t);
6726
6727   if (flag_vtable_verify)
6728     vtv_save_class_info (t);
6729
6730   dump_class_hierarchy (t);
6731
6732   /* Finish debugging output for this type.  */
6733   rest_of_type_compilation (t, ! LOCAL_CLASS_P (t));
6734
6735   if (TYPE_TRANSPARENT_AGGR (t))
6736     {
6737       tree field = first_field (t);
6738       if (field == NULL_TREE || error_operand_p (field))
6739         {
6740           error ("type transparent %q#T does not have any fields", t);
6741           TYPE_TRANSPARENT_AGGR (t) = 0;
6742         }
6743       else if (DECL_ARTIFICIAL (field))
6744         {
6745           if (DECL_FIELD_IS_BASE (field))
6746             error ("type transparent class %qT has base classes", t);
6747           else
6748             {
6749               gcc_checking_assert (DECL_VIRTUAL_P (field));
6750               error ("type transparent class %qT has virtual functions", t);
6751             }
6752           TYPE_TRANSPARENT_AGGR (t) = 0;
6753         }
6754       else if (TYPE_MODE (t) != DECL_MODE (field))
6755         {
6756           error ("type transparent %q#T cannot be made transparent because "
6757                  "the type of the first field has a different ABI from the "
6758                  "class overall", t);
6759           TYPE_TRANSPARENT_AGGR (t) = 0;
6760         }
6761     }
6762 }
6763
6764 /* Insert FIELDS into T for the sorted case if the FIELDS count is
6765    equal to THRESHOLD or greater than THRESHOLD.  */
6766
6767 static void 
6768 insert_into_classtype_sorted_fields (tree fields, tree t, int threshold)
6769 {
6770   int n_fields = count_fields (fields);
6771   if (n_fields >= threshold)
6772     {
6773       struct sorted_fields_type *field_vec = sorted_fields_type_new (n_fields);
6774       add_fields_to_record_type (fields, field_vec, 0);
6775       qsort (field_vec->elts, n_fields, sizeof (tree), field_decl_cmp);
6776       CLASSTYPE_SORTED_FIELDS (t) = field_vec;
6777     }
6778 }
6779
6780 /* Insert lately defined enum ENUMTYPE into T for the sorted case.  */
6781
6782 void
6783 insert_late_enum_def_into_classtype_sorted_fields (tree enumtype, tree t)
6784 {
6785   struct sorted_fields_type *sorted_fields = CLASSTYPE_SORTED_FIELDS (t);
6786   if (sorted_fields)
6787     {
6788       int i;
6789       int n_fields
6790         = list_length (TYPE_VALUES (enumtype)) + sorted_fields->len;
6791       struct sorted_fields_type *field_vec = sorted_fields_type_new (n_fields);
6792       
6793       for (i = 0; i < sorted_fields->len; ++i)
6794         field_vec->elts[i] = sorted_fields->elts[i];
6795
6796       add_enum_fields_to_record_type (enumtype, field_vec,
6797                                       sorted_fields->len);
6798       qsort (field_vec->elts, n_fields, sizeof (tree), field_decl_cmp);
6799       CLASSTYPE_SORTED_FIELDS (t) = field_vec;
6800     }
6801 }
6802
6803 /* When T was built up, the member declarations were added in reverse
6804    order.  Rearrange them to declaration order.  */
6805
6806 void
6807 unreverse_member_declarations (tree t)
6808 {
6809   tree next;
6810   tree prev;
6811   tree x;
6812
6813   /* The following lists are all in reverse order.  Put them in
6814      declaration order now.  */
6815   TYPE_METHODS (t) = nreverse (TYPE_METHODS (t));
6816   CLASSTYPE_DECL_LIST (t) = nreverse (CLASSTYPE_DECL_LIST (t));
6817
6818   /* Actually, for the TYPE_FIELDS, only the non TYPE_DECLs are in
6819      reverse order, so we can't just use nreverse.  */
6820   prev = NULL_TREE;
6821   for (x = TYPE_FIELDS (t);
6822        x && TREE_CODE (x) != TYPE_DECL;
6823        x = next)
6824     {
6825       next = DECL_CHAIN (x);
6826       DECL_CHAIN (x) = prev;
6827       prev = x;
6828     }
6829   if (prev)
6830     {
6831       DECL_CHAIN (TYPE_FIELDS (t)) = x;
6832       if (prev)
6833         TYPE_FIELDS (t) = prev;
6834     }
6835 }
6836
6837 tree
6838 finish_struct (tree t, tree attributes)
6839 {
6840   location_t saved_loc = input_location;
6841
6842   /* Now that we've got all the field declarations, reverse everything
6843      as necessary.  */
6844   unreverse_member_declarations (t);
6845
6846   cplus_decl_attributes (&t, attributes, (int) ATTR_FLAG_TYPE_IN_PLACE);
6847   fixup_attribute_variants (t);
6848
6849   /* Nadger the current location so that diagnostics point to the start of
6850      the struct, not the end.  */
6851   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (t));
6852
6853   if (processing_template_decl)
6854     {
6855       tree x;
6856
6857       finish_struct_methods (t);
6858       TYPE_SIZE (t) = bitsize_zero_node;
6859       TYPE_SIZE_UNIT (t) = size_zero_node;
6860
6861       /* We need to emit an error message if this type was used as a parameter
6862          and it is an abstract type, even if it is a template. We construct
6863          a simple CLASSTYPE_PURE_VIRTUALS list without taking bases into
6864          account and we call complete_vars with this type, which will check
6865          the PARM_DECLS. Note that while the type is being defined,
6866          CLASSTYPE_PURE_VIRTUALS contains the list of the inline friends
6867          (see CLASSTYPE_INLINE_FRIENDS) so we need to clear it.  */
6868       CLASSTYPE_PURE_VIRTUALS (t) = NULL;
6869       for (x = TYPE_METHODS (t); x; x = DECL_CHAIN (x))
6870         if (DECL_PURE_VIRTUAL_P (x))
6871           vec_safe_push (CLASSTYPE_PURE_VIRTUALS (t), x);
6872       complete_vars (t);
6873       /* We need to add the target functions to the CLASSTYPE_METHOD_VEC if
6874          an enclosing scope is a template class, so that this function be
6875          found by lookup_fnfields_1 when the using declaration is not
6876          instantiated yet.  */
6877       for (x = TYPE_FIELDS (t); x; x = DECL_CHAIN (x))
6878         if (TREE_CODE (x) == USING_DECL)
6879           {
6880             tree fn = strip_using_decl (x);
6881             if (is_overloaded_fn (fn))
6882               for (; fn; fn = OVL_NEXT (fn))
6883                 add_method (t, OVL_CURRENT (fn), x);
6884           }
6885
6886       /* Remember current #pragma pack value.  */
6887       TYPE_PRECISION (t) = maximum_field_alignment;
6888
6889       /* Fix up any variants we've already built.  */
6890       for (x = TYPE_NEXT_VARIANT (t); x; x = TYPE_NEXT_VARIANT (x))
6891         {
6892           TYPE_SIZE (x) = TYPE_SIZE (t);
6893           TYPE_SIZE_UNIT (x) = TYPE_SIZE_UNIT (t);
6894           TYPE_FIELDS (x) = TYPE_FIELDS (t);
6895           TYPE_METHODS (x) = TYPE_METHODS (t);
6896         }
6897     }
6898   else
6899     finish_struct_1 (t);
6900
6901   if (is_std_init_list (t))
6902     {
6903       /* People keep complaining that the compiler crashes on an invalid
6904          definition of initializer_list, so I guess we should explicitly
6905          reject it.  What the compiler internals care about is that it's a
6906          template and has a pointer field followed by an integer field.  */
6907       bool ok = false;
6908       if (processing_template_decl)
6909         {
6910           tree f = next_initializable_field (TYPE_FIELDS (t));
6911           if (f && TREE_CODE (TREE_TYPE (f)) == POINTER_TYPE)
6912             {
6913               f = next_initializable_field (DECL_CHAIN (f));
6914               if (f && same_type_p (TREE_TYPE (f), size_type_node))
6915                 ok = true;
6916             }
6917         }
6918       if (!ok)
6919         fatal_error (input_location,
6920                      "definition of std::initializer_list does not match "
6921                      "#include <initializer_list>");
6922     }
6923
6924   input_location = saved_loc;
6925
6926   TYPE_BEING_DEFINED (t) = 0;
6927
6928   if (current_class_type)
6929     popclass ();
6930   else
6931     error ("trying to finish struct, but kicked out due to previous parse errors");
6932
6933   if (processing_template_decl && at_function_scope_p ()
6934       /* Lambdas are defined by the LAMBDA_EXPR.  */
6935       && !LAMBDA_TYPE_P (t))
6936     add_stmt (build_min (TAG_DEFN, t));
6937
6938   return t;
6939 }
6940 \f
6941 /* Hash table to avoid endless recursion when handling references.  */
6942 static hash_table<pointer_hash<tree_node> > *fixed_type_or_null_ref_ht;
6943
6944 /* Return the dynamic type of INSTANCE, if known.
6945    Used to determine whether the virtual function table is needed
6946    or not.
6947
6948    *NONNULL is set iff INSTANCE can be known to be nonnull, regardless
6949    of our knowledge of its type.  *NONNULL should be initialized
6950    before this function is called.  */
6951
6952 static tree
6953 fixed_type_or_null (tree instance, int *nonnull, int *cdtorp)
6954 {
6955 #define RECUR(T) fixed_type_or_null((T), nonnull, cdtorp)
6956
6957   switch (TREE_CODE (instance))
6958     {
6959     case INDIRECT_REF:
6960       if (POINTER_TYPE_P (TREE_TYPE (instance)))
6961         return NULL_TREE;
6962       else
6963         return RECUR (TREE_OPERAND (instance, 0));
6964
6965     case CALL_EXPR:
6966       /* This is a call to a constructor, hence it's never zero.  */
6967       if (TREE_HAS_CONSTRUCTOR (instance))
6968         {
6969           if (nonnull)
6970             *nonnull = 1;
6971           return TREE_TYPE (instance);
6972         }
6973       return NULL_TREE;
6974
6975     case SAVE_EXPR:
6976       /* This is a call to a constructor, hence it's never zero.  */
6977       if (TREE_HAS_CONSTRUCTOR (instance))
6978         {
6979           if (nonnull)
6980             *nonnull = 1;
6981           return TREE_TYPE (instance);
6982         }
6983       return RECUR (TREE_OPERAND (instance, 0));
6984
6985     case POINTER_PLUS_EXPR:
6986     case PLUS_EXPR:
6987     case MINUS_EXPR:
6988       if (TREE_CODE (TREE_OPERAND (instance, 0)) == ADDR_EXPR)
6989         return RECUR (TREE_OPERAND (instance, 0));
6990       if (TREE_CODE (TREE_OPERAND (instance, 1)) == INTEGER_CST)
6991         /* Propagate nonnull.  */
6992         return RECUR (TREE_OPERAND (instance, 0));
6993
6994       return NULL_TREE;
6995
6996     CASE_CONVERT:
6997       return RECUR (TREE_OPERAND (instance, 0));
6998
6999     case ADDR_EXPR:
7000       instance = TREE_OPERAND (instance, 0);
7001       if (nonnull)
7002         {
7003           /* Just because we see an ADDR_EXPR doesn't mean we're dealing
7004              with a real object -- given &p->f, p can still be null.  */
7005           tree t = get_base_address (instance);
7006           /* ??? Probably should check DECL_WEAK here.  */
7007           if (t && DECL_P (t))
7008             *nonnull = 1;
7009         }
7010       return RECUR (instance);
7011
7012     case COMPONENT_REF:
7013       /* If this component is really a base class reference, then the field
7014          itself isn't definitive.  */
7015       if (DECL_FIELD_IS_BASE (TREE_OPERAND (instance, 1)))
7016         return RECUR (TREE_OPERAND (instance, 0));
7017       return RECUR (TREE_OPERAND (instance, 1));
7018
7019     case VAR_DECL:
7020     case FIELD_DECL:
7021       if (TREE_CODE (TREE_TYPE (instance)) == ARRAY_TYPE
7022           && MAYBE_CLASS_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
7023         {
7024           if (nonnull)
7025             *nonnull = 1;
7026           return TREE_TYPE (TREE_TYPE (instance));
7027         }
7028       /* fall through...  */
7029     case TARGET_EXPR:
7030     case PARM_DECL:
7031     case RESULT_DECL:
7032       if (MAYBE_CLASS_TYPE_P (TREE_TYPE (instance)))
7033         {
7034           if (nonnull)
7035             *nonnull = 1;
7036           return TREE_TYPE (instance);
7037         }
7038       else if (instance == current_class_ptr)
7039         {
7040           if (nonnull)
7041             *nonnull = 1;
7042
7043           /* if we're in a ctor or dtor, we know our type.  If
7044              current_class_ptr is set but we aren't in a function, we're in
7045              an NSDMI (and therefore a constructor).  */
7046           if (current_scope () != current_function_decl
7047               || (DECL_LANG_SPECIFIC (current_function_decl)
7048                   && (DECL_CONSTRUCTOR_P (current_function_decl)
7049                       || DECL_DESTRUCTOR_P (current_function_decl))))
7050             {
7051               if (cdtorp)
7052                 *cdtorp = 1;
7053               return TREE_TYPE (TREE_TYPE (instance));
7054             }
7055         }
7056       else if (TREE_CODE (TREE_TYPE (instance)) == REFERENCE_TYPE)
7057         {
7058           /* We only need one hash table because it is always left empty.  */
7059           if (!fixed_type_or_null_ref_ht)
7060             fixed_type_or_null_ref_ht
7061               = new hash_table<pointer_hash<tree_node> > (37); 
7062
7063           /* Reference variables should be references to objects.  */
7064           if (nonnull)
7065             *nonnull = 1;
7066
7067           /* Enter the INSTANCE in a table to prevent recursion; a
7068              variable's initializer may refer to the variable
7069              itself.  */
7070           if (VAR_P (instance)
7071               && DECL_INITIAL (instance)
7072               && !type_dependent_expression_p_push (DECL_INITIAL (instance))
7073               && !fixed_type_or_null_ref_ht->find (instance))
7074             {
7075               tree type;
7076               tree_node **slot;
7077
7078               slot = fixed_type_or_null_ref_ht->find_slot (instance, INSERT);
7079               *slot = instance;
7080               type = RECUR (DECL_INITIAL (instance));
7081               fixed_type_or_null_ref_ht->remove_elt (instance);
7082
7083               return type;
7084             }
7085         }
7086       return NULL_TREE;
7087
7088     default:
7089       return NULL_TREE;
7090     }
7091 #undef RECUR
7092 }
7093
7094 /* Return nonzero if the dynamic type of INSTANCE is known, and
7095    equivalent to the static type.  We also handle the case where
7096    INSTANCE is really a pointer. Return negative if this is a
7097    ctor/dtor. There the dynamic type is known, but this might not be
7098    the most derived base of the original object, and hence virtual
7099    bases may not be laid out according to this type.
7100
7101    Used to determine whether the virtual function table is needed
7102    or not.
7103
7104    *NONNULL is set iff INSTANCE can be known to be nonnull, regardless
7105    of our knowledge of its type.  *NONNULL should be initialized
7106    before this function is called.  */
7107
7108 int
7109 resolves_to_fixed_type_p (tree instance, int* nonnull)
7110 {
7111   tree t = TREE_TYPE (instance);
7112   int cdtorp = 0;
7113   tree fixed;
7114
7115   /* processing_template_decl can be false in a template if we're in
7116      instantiate_non_dependent_expr, but we still want to suppress
7117      this check.  */
7118   if (in_template_function ())
7119     {
7120       /* In a template we only care about the type of the result.  */
7121       if (nonnull)
7122         *nonnull = true;
7123       return true;
7124     }
7125
7126   fixed = fixed_type_or_null (instance, nonnull, &cdtorp);
7127   if (fixed == NULL_TREE)
7128     return 0;
7129   if (POINTER_TYPE_P (t))
7130     t = TREE_TYPE (t);
7131   if (!same_type_ignoring_top_level_qualifiers_p (t, fixed))
7132     return 0;
7133   return cdtorp ? -1 : 1;
7134 }
7135
7136 \f
7137 void
7138 init_class_processing (void)
7139 {
7140   current_class_depth = 0;
7141   current_class_stack_size = 10;
7142   current_class_stack
7143     = XNEWVEC (struct class_stack_node, current_class_stack_size);
7144   vec_alloc (local_classes, 8);
7145   sizeof_biggest_empty_class = size_zero_node;
7146
7147   ridpointers[(int) RID_PUBLIC] = access_public_node;
7148   ridpointers[(int) RID_PRIVATE] = access_private_node;
7149   ridpointers[(int) RID_PROTECTED] = access_protected_node;
7150 }
7151
7152 /* Restore the cached PREVIOUS_CLASS_LEVEL.  */
7153
7154 static void
7155 restore_class_cache (void)
7156 {
7157   tree type;
7158
7159   /* We are re-entering the same class we just left, so we don't
7160      have to search the whole inheritance matrix to find all the
7161      decls to bind again.  Instead, we install the cached
7162      class_shadowed list and walk through it binding names.  */
7163   push_binding_level (previous_class_level);
7164   class_binding_level = previous_class_level;
7165   /* Restore IDENTIFIER_TYPE_VALUE.  */
7166   for (type = class_binding_level->type_shadowed;
7167        type;
7168        type = TREE_CHAIN (type))
7169     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (type), TREE_TYPE (type));
7170 }
7171
7172 /* Set global variables CURRENT_CLASS_NAME and CURRENT_CLASS_TYPE as
7173    appropriate for TYPE.
7174
7175    So that we may avoid calls to lookup_name, we cache the _TYPE
7176    nodes of local TYPE_DECLs in the TREE_TYPE field of the name.
7177
7178    For multiple inheritance, we perform a two-pass depth-first search
7179    of the type lattice.  */
7180
7181 void
7182 pushclass (tree type)
7183 {
7184   class_stack_node_t csn;
7185
7186   type = TYPE_MAIN_VARIANT (type);
7187
7188   /* Make sure there is enough room for the new entry on the stack.  */
7189   if (current_class_depth + 1 >= current_class_stack_size)
7190     {
7191       current_class_stack_size *= 2;
7192       current_class_stack
7193         = XRESIZEVEC (struct class_stack_node, current_class_stack,
7194                       current_class_stack_size);
7195     }
7196
7197   /* Insert a new entry on the class stack.  */
7198   csn = current_class_stack + current_class_depth;
7199   csn->name = current_class_name;
7200   csn->type = current_class_type;
7201   csn->access = current_access_specifier;
7202   csn->names_used = 0;
7203   csn->hidden = 0;
7204   current_class_depth++;
7205
7206   /* Now set up the new type.  */
7207   current_class_name = TYPE_NAME (type);
7208   if (TREE_CODE (current_class_name) == TYPE_DECL)
7209     current_class_name = DECL_NAME (current_class_name);
7210   current_class_type = type;
7211
7212   /* By default, things in classes are private, while things in
7213      structures or unions are public.  */
7214   current_access_specifier = (CLASSTYPE_DECLARED_CLASS (type)
7215                               ? access_private_node
7216                               : access_public_node);
7217
7218   if (previous_class_level
7219       && type != previous_class_level->this_entity
7220       && current_class_depth == 1)
7221     {
7222       /* Forcibly remove any old class remnants.  */
7223       invalidate_class_lookup_cache ();
7224     }
7225
7226   if (!previous_class_level
7227       || type != previous_class_level->this_entity
7228       || current_class_depth > 1)
7229     pushlevel_class ();
7230   else
7231     restore_class_cache ();
7232 }
7233
7234 /* When we exit a toplevel class scope, we save its binding level so
7235    that we can restore it quickly.  Here, we've entered some other
7236    class, so we must invalidate our cache.  */
7237
7238 void
7239 invalidate_class_lookup_cache (void)
7240 {
7241   previous_class_level = NULL;
7242 }
7243
7244 /* Get out of the current class scope. If we were in a class scope
7245    previously, that is the one popped to.  */
7246
7247 void
7248 popclass (void)
7249 {
7250   poplevel_class ();
7251
7252   current_class_depth--;
7253   current_class_name = current_class_stack[current_class_depth].name;
7254   current_class_type = current_class_stack[current_class_depth].type;
7255   current_access_specifier = current_class_stack[current_class_depth].access;
7256   if (current_class_stack[current_class_depth].names_used)
7257     splay_tree_delete (current_class_stack[current_class_depth].names_used);
7258 }
7259
7260 /* Mark the top of the class stack as hidden.  */
7261
7262 void
7263 push_class_stack (void)
7264 {
7265   if (current_class_depth)
7266     ++current_class_stack[current_class_depth - 1].hidden;
7267 }
7268
7269 /* Mark the top of the class stack as un-hidden.  */
7270
7271 void
7272 pop_class_stack (void)
7273 {
7274   if (current_class_depth)
7275     --current_class_stack[current_class_depth - 1].hidden;
7276 }
7277
7278 /* Returns 1 if the class type currently being defined is either T or
7279    a nested type of T.  */
7280
7281 bool
7282 currently_open_class (tree t)
7283 {
7284   int i;
7285
7286   if (!CLASS_TYPE_P (t))
7287     return false;
7288
7289   t = TYPE_MAIN_VARIANT (t);
7290
7291   /* We start looking from 1 because entry 0 is from global scope,
7292      and has no type.  */
7293   for (i = current_class_depth; i > 0; --i)
7294     {
7295       tree c;
7296       if (i == current_class_depth)
7297         c = current_class_type;
7298       else
7299         {
7300           if (current_class_stack[i].hidden)
7301             break;
7302           c = current_class_stack[i].type;
7303         }
7304       if (!c)
7305         continue;
7306       if (same_type_p (c, t))
7307         return true;
7308     }
7309   return false;
7310 }
7311
7312 /* If either current_class_type or one of its enclosing classes are derived
7313    from T, return the appropriate type.  Used to determine how we found
7314    something via unqualified lookup.  */
7315
7316 tree
7317 currently_open_derived_class (tree t)
7318 {
7319   int i;
7320
7321   /* The bases of a dependent type are unknown.  */
7322   if (dependent_type_p (t))
7323     return NULL_TREE;
7324
7325   if (!current_class_type)
7326     return NULL_TREE;
7327
7328   if (DERIVED_FROM_P (t, current_class_type))
7329     return current_class_type;
7330
7331   for (i = current_class_depth - 1; i > 0; --i)
7332     {
7333       if (current_class_stack[i].hidden)
7334         break;
7335       if (DERIVED_FROM_P (t, current_class_stack[i].type))
7336         return current_class_stack[i].type;
7337     }
7338
7339   return NULL_TREE;
7340 }
7341
7342 /* Return the outermost enclosing class type that is still open, or
7343    NULL_TREE.  */
7344
7345 tree
7346 outermost_open_class (void)
7347 {
7348   if (!current_class_type)
7349     return NULL_TREE;
7350   tree r = NULL_TREE;
7351   if (TYPE_BEING_DEFINED (current_class_type))
7352     r = current_class_type;
7353   for (int i = current_class_depth - 1; i > 0; --i)
7354     {
7355       if (current_class_stack[i].hidden)
7356         break;
7357       tree t = current_class_stack[i].type;
7358       if (!TYPE_BEING_DEFINED (t))
7359         break;
7360       r = t;
7361     }
7362   return r;
7363 }
7364
7365 /* Returns the innermost class type which is not a lambda closure type.  */
7366
7367 tree
7368 current_nonlambda_class_type (void)
7369 {
7370   int i;
7371
7372   /* We start looking from 1 because entry 0 is from global scope,
7373      and has no type.  */
7374   for (i = current_class_depth; i > 0; --i)
7375     {
7376       tree c;
7377       if (i == current_class_depth)
7378         c = current_class_type;
7379       else
7380         {
7381           if (current_class_stack[i].hidden)
7382             break;
7383           c = current_class_stack[i].type;
7384         }
7385       if (!c)
7386         continue;
7387       if (!LAMBDA_TYPE_P (c))
7388         return c;
7389     }
7390   return NULL_TREE;
7391 }
7392
7393 /* When entering a class scope, all enclosing class scopes' names with
7394    static meaning (static variables, static functions, types and
7395    enumerators) have to be visible.  This recursive function calls
7396    pushclass for all enclosing class contexts until global or a local
7397    scope is reached.  TYPE is the enclosed class.  */
7398
7399 void
7400 push_nested_class (tree type)
7401 {
7402   /* A namespace might be passed in error cases, like A::B:C.  */
7403   if (type == NULL_TREE
7404       || !CLASS_TYPE_P (type))
7405     return;
7406
7407   push_nested_class (DECL_CONTEXT (TYPE_MAIN_DECL (type)));
7408
7409   pushclass (type);
7410 }
7411
7412 /* Undoes a push_nested_class call.  */
7413
7414 void
7415 pop_nested_class (void)
7416 {
7417   tree context = DECL_CONTEXT (TYPE_MAIN_DECL (current_class_type));
7418
7419   popclass ();
7420   if (context && CLASS_TYPE_P (context))
7421     pop_nested_class ();
7422 }
7423
7424 /* Returns the number of extern "LANG" blocks we are nested within.  */
7425
7426 int
7427 current_lang_depth (void)
7428 {
7429   return vec_safe_length (current_lang_base);
7430 }
7431
7432 /* Set global variables CURRENT_LANG_NAME to appropriate value
7433    so that behavior of name-mangling machinery is correct.  */
7434
7435 void
7436 push_lang_context (tree name)
7437 {
7438   vec_safe_push (current_lang_base, current_lang_name);
7439
7440   if (name == lang_name_cplusplus)
7441     {
7442       current_lang_name = name;
7443     }
7444   else if (name == lang_name_java)
7445     {
7446       current_lang_name = name;
7447       /* DECL_IGNORED_P is initially set for these types, to avoid clutter.
7448          (See record_builtin_java_type in decl.c.)  However, that causes
7449          incorrect debug entries if these types are actually used.
7450          So we re-enable debug output after extern "Java".  */
7451       DECL_IGNORED_P (TYPE_NAME (java_byte_type_node)) = 0;
7452       DECL_IGNORED_P (TYPE_NAME (java_short_type_node)) = 0;
7453       DECL_IGNORED_P (TYPE_NAME (java_int_type_node)) = 0;
7454       DECL_IGNORED_P (TYPE_NAME (java_long_type_node)) = 0;
7455       DECL_IGNORED_P (TYPE_NAME (java_float_type_node)) = 0;
7456       DECL_IGNORED_P (TYPE_NAME (java_double_type_node)) = 0;
7457       DECL_IGNORED_P (TYPE_NAME (java_char_type_node)) = 0;
7458       DECL_IGNORED_P (TYPE_NAME (java_boolean_type_node)) = 0;
7459     }
7460   else if (name == lang_name_c)
7461     {
7462       current_lang_name = name;
7463     }
7464   else
7465     error ("language string %<\"%E\"%> not recognized", name);
7466 }
7467
7468 /* Get out of the current language scope.  */
7469
7470 void
7471 pop_lang_context (void)
7472 {
7473   current_lang_name = current_lang_base->pop ();
7474 }
7475 \f
7476 /* Type instantiation routines.  */
7477
7478 /* Given an OVERLOAD and a TARGET_TYPE, return the function that
7479    matches the TARGET_TYPE.  If there is no satisfactory match, return
7480    error_mark_node, and issue an error & warning messages under
7481    control of FLAGS.  Permit pointers to member function if FLAGS
7482    permits.  If TEMPLATE_ONLY, the name of the overloaded function was
7483    a template-id, and EXPLICIT_TARGS are the explicitly provided
7484    template arguments.  
7485
7486    If OVERLOAD is for one or more member functions, then ACCESS_PATH
7487    is the base path used to reference those member functions.  If
7488    the address is resolved to a member function, access checks will be
7489    performed and errors issued if appropriate.  */
7490
7491 static tree
7492 resolve_address_of_overloaded_function (tree target_type,
7493                                         tree overload,
7494                                         tsubst_flags_t flags,
7495                                         bool template_only,
7496                                         tree explicit_targs,
7497                                         tree access_path)
7498 {
7499   /* Here's what the standard says:
7500
7501        [over.over]
7502
7503        If the name is a function template, template argument deduction
7504        is done, and if the argument deduction succeeds, the deduced
7505        arguments are used to generate a single template function, which
7506        is added to the set of overloaded functions considered.
7507
7508        Non-member functions and static member functions match targets of
7509        type "pointer-to-function" or "reference-to-function."  Nonstatic
7510        member functions match targets of type "pointer-to-member
7511        function;" the function type of the pointer to member is used to
7512        select the member function from the set of overloaded member
7513        functions.  If a nonstatic member function is selected, the
7514        reference to the overloaded function name is required to have the
7515        form of a pointer to member as described in 5.3.1.
7516
7517        If more than one function is selected, any template functions in
7518        the set are eliminated if the set also contains a non-template
7519        function, and any given template function is eliminated if the
7520        set contains a second template function that is more specialized
7521        than the first according to the partial ordering rules 14.5.5.2.
7522        After such eliminations, if any, there shall remain exactly one
7523        selected function.  */
7524
7525   int is_ptrmem = 0;
7526   /* We store the matches in a TREE_LIST rooted here.  The functions
7527      are the TREE_PURPOSE, not the TREE_VALUE, in this list, for easy
7528      interoperability with most_specialized_instantiation.  */
7529   tree matches = NULL_TREE;
7530   tree fn;
7531   tree target_fn_type;
7532
7533   /* By the time we get here, we should be seeing only real
7534      pointer-to-member types, not the internal POINTER_TYPE to
7535      METHOD_TYPE representation.  */
7536   gcc_assert (!TYPE_PTR_P (target_type)
7537               || TREE_CODE (TREE_TYPE (target_type)) != METHOD_TYPE);
7538
7539   gcc_assert (is_overloaded_fn (overload));
7540
7541   /* Check that the TARGET_TYPE is reasonable.  */
7542   if (TYPE_PTRFN_P (target_type)
7543       || TYPE_REFFN_P (target_type))
7544     /* This is OK.  */;
7545   else if (TYPE_PTRMEMFUNC_P (target_type))
7546     /* This is OK, too.  */
7547     is_ptrmem = 1;
7548   else if (TREE_CODE (target_type) == FUNCTION_TYPE)
7549     /* This is OK, too.  This comes from a conversion to reference
7550        type.  */
7551     target_type = build_reference_type (target_type);
7552   else
7553     {
7554       if (flags & tf_error)
7555         error ("cannot resolve overloaded function %qD based on"
7556                " conversion to type %qT",
7557                DECL_NAME (OVL_FUNCTION (overload)), target_type);
7558       return error_mark_node;
7559     }
7560
7561   /* Non-member functions and static member functions match targets of type
7562      "pointer-to-function" or "reference-to-function."  Nonstatic member
7563      functions match targets of type "pointer-to-member-function;" the
7564      function type of the pointer to member is used to select the member
7565      function from the set of overloaded member functions.
7566
7567      So figure out the FUNCTION_TYPE that we want to match against.  */
7568   target_fn_type = static_fn_type (target_type);
7569
7570   /* If we can find a non-template function that matches, we can just
7571      use it.  There's no point in generating template instantiations
7572      if we're just going to throw them out anyhow.  But, of course, we
7573      can only do this when we don't *need* a template function.  */
7574   if (!template_only)
7575     {
7576       tree fns;
7577
7578       for (fns = overload; fns; fns = OVL_NEXT (fns))
7579         {
7580           tree fn = OVL_CURRENT (fns);
7581
7582           if (TREE_CODE (fn) == TEMPLATE_DECL)
7583             /* We're not looking for templates just yet.  */
7584             continue;
7585
7586           if ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
7587               != is_ptrmem)
7588             /* We're looking for a non-static member, and this isn't
7589                one, or vice versa.  */
7590             continue;
7591
7592           /* Ignore functions which haven't been explicitly
7593              declared.  */
7594           if (DECL_ANTICIPATED (fn))
7595             continue;
7596
7597           /* See if there's a match.  */
7598           if (same_type_p (target_fn_type, static_fn_type (fn)))
7599             matches = tree_cons (fn, NULL_TREE, matches);
7600         }
7601     }
7602
7603   /* Now, if we've already got a match (or matches), there's no need
7604      to proceed to the template functions.  But, if we don't have a
7605      match we need to look at them, too.  */
7606   if (!matches)
7607     {
7608       tree target_arg_types;
7609       tree target_ret_type;
7610       tree fns;
7611       tree *args;
7612       unsigned int nargs, ia;
7613       tree arg;
7614
7615       target_arg_types = TYPE_ARG_TYPES (target_fn_type);
7616       target_ret_type = TREE_TYPE (target_fn_type);
7617
7618       nargs = list_length (target_arg_types);
7619       args = XALLOCAVEC (tree, nargs);
7620       for (arg = target_arg_types, ia = 0;
7621            arg != NULL_TREE && arg != void_list_node;
7622            arg = TREE_CHAIN (arg), ++ia)
7623         args[ia] = TREE_VALUE (arg);
7624       nargs = ia;
7625
7626       for (fns = overload; fns; fns = OVL_NEXT (fns))
7627         {
7628           tree fn = OVL_CURRENT (fns);
7629           tree instantiation;
7630           tree targs;
7631
7632           if (TREE_CODE (fn) != TEMPLATE_DECL)
7633             /* We're only looking for templates.  */
7634             continue;
7635
7636           if ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
7637               != is_ptrmem)
7638             /* We're not looking for a non-static member, and this is
7639                one, or vice versa.  */
7640             continue;
7641
7642           tree ret = target_ret_type;
7643
7644           /* If the template has a deduced return type, don't expose it to
7645              template argument deduction.  */
7646           if (undeduced_auto_decl (fn))
7647             ret = NULL_TREE;
7648
7649           /* Try to do argument deduction.  */
7650           targs = make_tree_vec (DECL_NTPARMS (fn));
7651           instantiation = fn_type_unification (fn, explicit_targs, targs, args,
7652                                                nargs, ret,
7653                                               DEDUCE_EXACT, LOOKUP_NORMAL,
7654                                                false, false);
7655           if (instantiation == error_mark_node)
7656             /* Instantiation failed.  */
7657             continue;
7658
7659           /* And now force instantiation to do return type deduction.  */
7660           if (undeduced_auto_decl (instantiation))
7661             {
7662               ++function_depth;
7663               instantiate_decl (instantiation, /*defer*/false, /*class*/false);
7664               --function_depth;
7665
7666               require_deduced_type (instantiation);
7667             }
7668
7669           /* See if there's a match.  */
7670           if (same_type_p (target_fn_type, static_fn_type (instantiation)))
7671             matches = tree_cons (instantiation, fn, matches);
7672         }
7673
7674       /* Now, remove all but the most specialized of the matches.  */
7675       if (matches)
7676         {
7677           tree match = most_specialized_instantiation (matches);
7678
7679           if (match != error_mark_node)
7680             matches = tree_cons (TREE_PURPOSE (match),
7681                                  NULL_TREE,
7682                                  NULL_TREE);
7683         }
7684     }
7685
7686   /* Now we should have exactly one function in MATCHES.  */
7687   if (matches == NULL_TREE)
7688     {
7689       /* There were *no* matches.  */
7690       if (flags & tf_error)
7691         {
7692           error ("no matches converting function %qD to type %q#T",
7693                  DECL_NAME (OVL_CURRENT (overload)),
7694                  target_type);
7695
7696           print_candidates (overload);
7697         }
7698       return error_mark_node;
7699     }
7700   else if (TREE_CHAIN (matches))
7701     {
7702       /* There were too many matches.  First check if they're all
7703          the same function.  */
7704       tree match = NULL_TREE;
7705
7706       fn = TREE_PURPOSE (matches);
7707
7708       /* For multi-versioned functions, more than one match is just fine and
7709          decls_match will return false as they are different.  */
7710       for (match = TREE_CHAIN (matches); match; match = TREE_CHAIN (match))
7711         if (!decls_match (fn, TREE_PURPOSE (match))
7712             && !targetm.target_option.function_versions
7713                (fn, TREE_PURPOSE (match)))
7714           break;
7715
7716       if (match)
7717         {
7718           if (flags & tf_error)
7719             {
7720               error ("converting overloaded function %qD to type %q#T is ambiguous",
7721                      DECL_NAME (OVL_FUNCTION (overload)),
7722                      target_type);
7723
7724               /* Since print_candidates expects the functions in the
7725                  TREE_VALUE slot, we flip them here.  */
7726               for (match = matches; match; match = TREE_CHAIN (match))
7727                 TREE_VALUE (match) = TREE_PURPOSE (match);
7728
7729               print_candidates (matches);
7730             }
7731
7732           return error_mark_node;
7733         }
7734     }
7735
7736   /* Good, exactly one match.  Now, convert it to the correct type.  */
7737   fn = TREE_PURPOSE (matches);
7738
7739   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
7740       && !(flags & tf_ptrmem_ok) && !flag_ms_extensions)
7741     {
7742       static int explained;
7743
7744       if (!(flags & tf_error))
7745         return error_mark_node;
7746
7747       permerror (input_location, "assuming pointer to member %qD", fn);
7748       if (!explained)
7749         {
7750           inform (input_location, "(a pointer to member can only be formed with %<&%E%>)", fn);
7751           explained = 1;
7752         }
7753     }
7754
7755   /* If a pointer to a function that is multi-versioned is requested, the
7756      pointer to the dispatcher function is returned instead.  This works
7757      well because indirectly calling the function will dispatch the right
7758      function version at run-time.  */
7759   if (DECL_FUNCTION_VERSIONED (fn))
7760     {
7761       fn = get_function_version_dispatcher (fn);
7762       if (fn == NULL)
7763         return error_mark_node;
7764       /* Mark all the versions corresponding to the dispatcher as used.  */
7765       if (!(flags & tf_conv))
7766         mark_versions_used (fn);
7767     }
7768
7769   /* If we're doing overload resolution purely for the purpose of
7770      determining conversion sequences, we should not consider the
7771      function used.  If this conversion sequence is selected, the
7772      function will be marked as used at this point.  */
7773   if (!(flags & tf_conv))
7774     {
7775       /* Make =delete work with SFINAE.  */
7776       if (DECL_DELETED_FN (fn) && !(flags & tf_error))
7777         return error_mark_node;
7778       
7779       mark_used (fn);
7780     }
7781
7782   /* We could not check access to member functions when this
7783      expression was originally created since we did not know at that
7784      time to which function the expression referred.  */
7785   if (DECL_FUNCTION_MEMBER_P (fn))
7786     {
7787       gcc_assert (access_path);
7788       perform_or_defer_access_check (access_path, fn, fn, flags);
7789     }
7790
7791   if (TYPE_PTRFN_P (target_type) || TYPE_PTRMEMFUNC_P (target_type))
7792     return cp_build_addr_expr (fn, flags);
7793   else
7794     {
7795       /* The target must be a REFERENCE_TYPE.  Above, cp_build_unary_op
7796          will mark the function as addressed, but here we must do it
7797          explicitly.  */
7798       cxx_mark_addressable (fn);
7799
7800       return fn;
7801     }
7802 }
7803
7804 /* This function will instantiate the type of the expression given in
7805    RHS to match the type of LHSTYPE.  If errors exist, then return
7806    error_mark_node. FLAGS is a bit mask.  If TF_ERROR is set, then
7807    we complain on errors.  If we are not complaining, never modify rhs,
7808    as overload resolution wants to try many possible instantiations, in
7809    the hope that at least one will work.
7810
7811    For non-recursive calls, LHSTYPE should be a function, pointer to
7812    function, or a pointer to member function.  */
7813
7814 tree
7815 instantiate_type (tree lhstype, tree rhs, tsubst_flags_t flags)
7816 {
7817   tsubst_flags_t flags_in = flags;
7818   tree access_path = NULL_TREE;
7819
7820   flags &= ~tf_ptrmem_ok;
7821
7822   if (lhstype == unknown_type_node)
7823     {
7824       if (flags & tf_error)
7825         error ("not enough type information");
7826       return error_mark_node;
7827     }
7828
7829   if (TREE_TYPE (rhs) != NULL_TREE && ! (type_unknown_p (rhs)))
7830     {
7831       tree fntype = non_reference (lhstype);
7832       if (same_type_p (fntype, TREE_TYPE (rhs)))
7833         return rhs;
7834       if (flag_ms_extensions
7835           && TYPE_PTRMEMFUNC_P (fntype)
7836           && !TYPE_PTRMEMFUNC_P (TREE_TYPE (rhs)))
7837         /* Microsoft allows `A::f' to be resolved to a
7838            pointer-to-member.  */
7839         ;
7840       else
7841         {
7842           if (flags & tf_error)
7843             error ("cannot convert %qE from type %qT to type %qT",
7844                    rhs, TREE_TYPE (rhs), fntype);
7845           return error_mark_node;
7846         }
7847     }
7848
7849   if (BASELINK_P (rhs))
7850     {
7851       access_path = BASELINK_ACCESS_BINFO (rhs);
7852       rhs = BASELINK_FUNCTIONS (rhs);
7853     }
7854
7855   /* If we are in a template, and have a NON_DEPENDENT_EXPR, we cannot
7856      deduce any type information.  */
7857   if (TREE_CODE (rhs) == NON_DEPENDENT_EXPR)
7858     {
7859       if (flags & tf_error)
7860         error ("not enough type information");
7861       return error_mark_node;
7862     }
7863
7864   /* There only a few kinds of expressions that may have a type
7865      dependent on overload resolution.  */
7866   gcc_assert (TREE_CODE (rhs) == ADDR_EXPR
7867               || TREE_CODE (rhs) == COMPONENT_REF
7868               || is_overloaded_fn (rhs)
7869               || (flag_ms_extensions && TREE_CODE (rhs) == FUNCTION_DECL));
7870
7871   /* This should really only be used when attempting to distinguish
7872      what sort of a pointer to function we have.  For now, any
7873      arithmetic operation which is not supported on pointers
7874      is rejected as an error.  */
7875
7876   switch (TREE_CODE (rhs))
7877     {
7878     case COMPONENT_REF:
7879       {
7880         tree member = TREE_OPERAND (rhs, 1);
7881
7882         member = instantiate_type (lhstype, member, flags);
7883         if (member != error_mark_node
7884             && TREE_SIDE_EFFECTS (TREE_OPERAND (rhs, 0)))
7885           /* Do not lose object's side effects.  */
7886           return build2 (COMPOUND_EXPR, TREE_TYPE (member),
7887                          TREE_OPERAND (rhs, 0), member);
7888         return member;
7889       }
7890
7891     case OFFSET_REF:
7892       rhs = TREE_OPERAND (rhs, 1);
7893       if (BASELINK_P (rhs))
7894         return instantiate_type (lhstype, rhs, flags_in);
7895
7896       /* This can happen if we are forming a pointer-to-member for a
7897          member template.  */
7898       gcc_assert (TREE_CODE (rhs) == TEMPLATE_ID_EXPR);
7899
7900       /* Fall through.  */
7901
7902     case TEMPLATE_ID_EXPR:
7903       {
7904         tree fns = TREE_OPERAND (rhs, 0);
7905         tree args = TREE_OPERAND (rhs, 1);
7906
7907         return
7908           resolve_address_of_overloaded_function (lhstype, fns, flags_in,
7909                                                   /*template_only=*/true,
7910                                                   args, access_path);
7911       }
7912
7913     case OVERLOAD:
7914     case FUNCTION_DECL:
7915       return
7916         resolve_address_of_overloaded_function (lhstype, rhs, flags_in,
7917                                                 /*template_only=*/false,
7918                                                 /*explicit_targs=*/NULL_TREE,
7919                                                 access_path);
7920
7921     case ADDR_EXPR:
7922     {
7923       if (PTRMEM_OK_P (rhs))
7924         flags |= tf_ptrmem_ok;
7925
7926       return instantiate_type (lhstype, TREE_OPERAND (rhs, 0), flags);
7927     }
7928
7929     case ERROR_MARK:
7930       return error_mark_node;
7931
7932     default:
7933       gcc_unreachable ();
7934     }
7935   return error_mark_node;
7936 }
7937 \f
7938 /* Return the name of the virtual function pointer field
7939    (as an IDENTIFIER_NODE) for the given TYPE.  Note that
7940    this may have to look back through base types to find the
7941    ultimate field name.  (For single inheritance, these could
7942    all be the same name.  Who knows for multiple inheritance).  */
7943
7944 static tree
7945 get_vfield_name (tree type)
7946 {
7947   tree binfo, base_binfo;
7948   char *buf;
7949
7950   for (binfo = TYPE_BINFO (type);
7951        BINFO_N_BASE_BINFOS (binfo);
7952        binfo = base_binfo)
7953     {
7954       base_binfo = BINFO_BASE_BINFO (binfo, 0);
7955
7956       if (BINFO_VIRTUAL_P (base_binfo)
7957           || !TYPE_CONTAINS_VPTR_P (BINFO_TYPE (base_binfo)))
7958         break;
7959     }
7960
7961   type = BINFO_TYPE (binfo);
7962   buf = (char *) alloca (sizeof (VFIELD_NAME_FORMAT)
7963                          + TYPE_NAME_LENGTH (type) + 2);
7964   sprintf (buf, VFIELD_NAME_FORMAT,
7965            IDENTIFIER_POINTER (constructor_name (type)));
7966   return get_identifier (buf);
7967 }
7968
7969 void
7970 print_class_statistics (void)
7971 {
7972   if (! GATHER_STATISTICS)
7973     return;
7974
7975   fprintf (stderr, "convert_harshness = %d\n", n_convert_harshness);
7976   fprintf (stderr, "compute_conversion_costs = %d\n", n_compute_conversion_costs);
7977   if (n_vtables)
7978     {
7979       fprintf (stderr, "vtables = %d; vtable searches = %d\n",
7980                n_vtables, n_vtable_searches);
7981       fprintf (stderr, "vtable entries = %d; vtable elems = %d\n",
7982                n_vtable_entries, n_vtable_elems);
7983     }
7984 }
7985
7986 /* Build a dummy reference to ourselves so Derived::Base (and A::A) works,
7987    according to [class]:
7988                                           The class-name is also inserted
7989    into  the scope of the class itself.  For purposes of access checking,
7990    the inserted class name is treated as if it were a public member name.  */
7991
7992 void
7993 build_self_reference (void)
7994 {
7995   tree name = constructor_name (current_class_type);
7996   tree value = build_lang_decl (TYPE_DECL, name, current_class_type);
7997   tree saved_cas;
7998
7999   DECL_NONLOCAL (value) = 1;
8000   DECL_CONTEXT (value) = current_class_type;
8001   DECL_ARTIFICIAL (value) = 1;
8002   SET_DECL_SELF_REFERENCE_P (value);
8003   set_underlying_type (value);
8004
8005   if (processing_template_decl)
8006     value = push_template_decl (value);
8007
8008   saved_cas = current_access_specifier;
8009   current_access_specifier = access_public_node;
8010   finish_member_declaration (value);
8011   current_access_specifier = saved_cas;
8012 }
8013
8014 /* Returns 1 if TYPE contains only padding bytes.  */
8015
8016 int
8017 is_empty_class (tree type)
8018 {
8019   if (type == error_mark_node)
8020     return 0;
8021
8022   if (! CLASS_TYPE_P (type))
8023     return 0;
8024
8025   return CLASSTYPE_EMPTY_P (type);
8026 }
8027
8028 /* Returns true if TYPE contains no actual data, just various
8029    possible combinations of empty classes and possibly a vptr.  */
8030
8031 bool
8032 is_really_empty_class (tree type)
8033 {
8034   if (CLASS_TYPE_P (type))
8035     {
8036       tree field;
8037       tree binfo;
8038       tree base_binfo;
8039       int i;
8040
8041       /* CLASSTYPE_EMPTY_P isn't set properly until the class is actually laid
8042          out, but we'd like to be able to check this before then.  */
8043       if (COMPLETE_TYPE_P (type) && is_empty_class (type))
8044         return true;
8045
8046       for (binfo = TYPE_BINFO (type), i = 0;
8047            BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
8048         if (!is_really_empty_class (BINFO_TYPE (base_binfo)))
8049           return false;
8050       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8051         if (TREE_CODE (field) == FIELD_DECL
8052             && !DECL_ARTIFICIAL (field)
8053             && !is_really_empty_class (TREE_TYPE (field)))
8054           return false;
8055       return true;
8056     }
8057   else if (TREE_CODE (type) == ARRAY_TYPE)
8058     return is_really_empty_class (TREE_TYPE (type));
8059   return false;
8060 }
8061
8062 /* Note that NAME was looked up while the current class was being
8063    defined and that the result of that lookup was DECL.  */
8064
8065 void
8066 maybe_note_name_used_in_class (tree name, tree decl)
8067 {
8068   splay_tree names_used;
8069
8070   /* If we're not defining a class, there's nothing to do.  */
8071   if (!(innermost_scope_kind() == sk_class
8072         && TYPE_BEING_DEFINED (current_class_type)
8073         && !LAMBDA_TYPE_P (current_class_type)))
8074     return;
8075
8076   /* If there's already a binding for this NAME, then we don't have
8077      anything to worry about.  */
8078   if (lookup_member (current_class_type, name,
8079                      /*protect=*/0, /*want_type=*/false, tf_warning_or_error))
8080     return;
8081
8082   if (!current_class_stack[current_class_depth - 1].names_used)
8083     current_class_stack[current_class_depth - 1].names_used
8084       = splay_tree_new (splay_tree_compare_pointers, 0, 0);
8085   names_used = current_class_stack[current_class_depth - 1].names_used;
8086
8087   splay_tree_insert (names_used,
8088                      (splay_tree_key) name,
8089                      (splay_tree_value) decl);
8090 }
8091
8092 /* Note that NAME was declared (as DECL) in the current class.  Check
8093    to see that the declaration is valid.  */
8094
8095 void
8096 note_name_declared_in_class (tree name, tree decl)
8097 {
8098   splay_tree names_used;
8099   splay_tree_node n;
8100
8101   /* Look to see if we ever used this name.  */
8102   names_used
8103     = current_class_stack[current_class_depth - 1].names_used;
8104   if (!names_used)
8105     return;
8106   /* The C language allows members to be declared with a type of the same
8107      name, and the C++ standard says this diagnostic is not required.  So
8108      allow it in extern "C" blocks unless predantic is specified.
8109      Allow it in all cases if -ms-extensions is specified.  */
8110   if ((!pedantic && current_lang_name == lang_name_c)
8111       || flag_ms_extensions)
8112     return;
8113   n = splay_tree_lookup (names_used, (splay_tree_key) name);
8114   if (n)
8115     {
8116       /* [basic.scope.class]
8117
8118          A name N used in a class S shall refer to the same declaration
8119          in its context and when re-evaluated in the completed scope of
8120          S.  */
8121       permerror (input_location, "declaration of %q#D", decl);
8122       permerror (input_location, "changes meaning of %qD from %q+#D",
8123                DECL_NAME (OVL_CURRENT (decl)), (tree) n->value);
8124     }
8125 }
8126
8127 /* Returns the VAR_DECL for the complete vtable associated with BINFO.
8128    Secondary vtables are merged with primary vtables; this function
8129    will return the VAR_DECL for the primary vtable.  */
8130
8131 tree
8132 get_vtbl_decl_for_binfo (tree binfo)
8133 {
8134   tree decl;
8135
8136   decl = BINFO_VTABLE (binfo);
8137   if (decl && TREE_CODE (decl) == POINTER_PLUS_EXPR)
8138     {
8139       gcc_assert (TREE_CODE (TREE_OPERAND (decl, 0)) == ADDR_EXPR);
8140       decl = TREE_OPERAND (TREE_OPERAND (decl, 0), 0);
8141     }
8142   if (decl)
8143     gcc_assert (VAR_P (decl));
8144   return decl;
8145 }
8146
8147
8148 /* Returns the binfo for the primary base of BINFO.  If the resulting
8149    BINFO is a virtual base, and it is inherited elsewhere in the
8150    hierarchy, then the returned binfo might not be the primary base of
8151    BINFO in the complete object.  Check BINFO_PRIMARY_P or
8152    BINFO_LOST_PRIMARY_P to be sure.  */
8153
8154 static tree
8155 get_primary_binfo (tree binfo)
8156 {
8157   tree primary_base;
8158
8159   primary_base = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (binfo));
8160   if (!primary_base)
8161     return NULL_TREE;
8162
8163   return copied_binfo (primary_base, binfo);
8164 }
8165
8166 /* If INDENTED_P is zero, indent to INDENT. Return nonzero.  */
8167
8168 static int
8169 maybe_indent_hierarchy (FILE * stream, int indent, int indented_p)
8170 {
8171   if (!indented_p)
8172     fprintf (stream, "%*s", indent, "");
8173   return 1;
8174 }
8175
8176 /* Dump the offsets of all the bases rooted at BINFO to STREAM.
8177    INDENT should be zero when called from the top level; it is
8178    incremented recursively.  IGO indicates the next expected BINFO in
8179    inheritance graph ordering.  */
8180
8181 static tree
8182 dump_class_hierarchy_r (FILE *stream,
8183                         int flags,
8184                         tree binfo,
8185                         tree igo,
8186                         int indent)
8187 {
8188   int indented = 0;
8189   tree base_binfo;
8190   int i;
8191
8192   indented = maybe_indent_hierarchy (stream, indent, 0);
8193   fprintf (stream, "%s (0x" HOST_WIDE_INT_PRINT_HEX ") ",
8194            type_as_string (BINFO_TYPE (binfo), TFF_PLAIN_IDENTIFIER),
8195            (HOST_WIDE_INT) (uintptr_t) binfo);
8196   if (binfo != igo)
8197     {
8198       fprintf (stream, "alternative-path\n");
8199       return igo;
8200     }
8201   igo = TREE_CHAIN (binfo);
8202
8203   fprintf (stream, HOST_WIDE_INT_PRINT_DEC,
8204            tree_to_shwi (BINFO_OFFSET (binfo)));
8205   if (is_empty_class (BINFO_TYPE (binfo)))
8206     fprintf (stream, " empty");
8207   else if (CLASSTYPE_NEARLY_EMPTY_P (BINFO_TYPE (binfo)))
8208     fprintf (stream, " nearly-empty");
8209   if (BINFO_VIRTUAL_P (binfo))
8210     fprintf (stream, " virtual");
8211   fprintf (stream, "\n");
8212
8213   indented = 0;
8214   if (BINFO_PRIMARY_P (binfo))
8215     {
8216       indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8217       fprintf (stream, " primary-for %s (0x" HOST_WIDE_INT_PRINT_HEX ")",
8218                type_as_string (BINFO_TYPE (BINFO_INHERITANCE_CHAIN (binfo)),
8219                                TFF_PLAIN_IDENTIFIER),
8220                (HOST_WIDE_INT) (uintptr_t) BINFO_INHERITANCE_CHAIN (binfo));
8221     }
8222   if (BINFO_LOST_PRIMARY_P (binfo))
8223     {
8224       indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8225       fprintf (stream, " lost-primary");
8226     }
8227   if (indented)
8228     fprintf (stream, "\n");
8229
8230   if (!(flags & TDF_SLIM))
8231     {
8232       int indented = 0;
8233
8234       if (BINFO_SUBVTT_INDEX (binfo))
8235         {
8236           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8237           fprintf (stream, " subvttidx=%s",
8238                    expr_as_string (BINFO_SUBVTT_INDEX (binfo),
8239                                    TFF_PLAIN_IDENTIFIER));
8240         }
8241       if (BINFO_VPTR_INDEX (binfo))
8242         {
8243           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8244           fprintf (stream, " vptridx=%s",
8245                    expr_as_string (BINFO_VPTR_INDEX (binfo),
8246                                    TFF_PLAIN_IDENTIFIER));
8247         }
8248       if (BINFO_VPTR_FIELD (binfo))
8249         {
8250           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8251           fprintf (stream, " vbaseoffset=%s",
8252                    expr_as_string (BINFO_VPTR_FIELD (binfo),
8253                                    TFF_PLAIN_IDENTIFIER));
8254         }
8255       if (BINFO_VTABLE (binfo))
8256         {
8257           indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8258           fprintf (stream, " vptr=%s",
8259                    expr_as_string (BINFO_VTABLE (binfo),
8260                                    TFF_PLAIN_IDENTIFIER));
8261         }
8262
8263       if (indented)
8264         fprintf (stream, "\n");
8265     }
8266
8267   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8268     igo = dump_class_hierarchy_r (stream, flags, base_binfo, igo, indent + 2);
8269
8270   return igo;
8271 }
8272
8273 /* Dump the BINFO hierarchy for T.  */
8274
8275 static void
8276 dump_class_hierarchy_1 (FILE *stream, int flags, tree t)
8277 {
8278   fprintf (stream, "Class %s\n", type_as_string (t, TFF_PLAIN_IDENTIFIER));
8279   fprintf (stream, "   size=%lu align=%lu\n",
8280            (unsigned long)(tree_to_shwi (TYPE_SIZE (t)) / BITS_PER_UNIT),
8281            (unsigned long)(TYPE_ALIGN (t) / BITS_PER_UNIT));
8282   fprintf (stream, "   base size=%lu base align=%lu\n",
8283            (unsigned long)(tree_to_shwi (TYPE_SIZE (CLASSTYPE_AS_BASE (t)))
8284                            / BITS_PER_UNIT),
8285            (unsigned long)(TYPE_ALIGN (CLASSTYPE_AS_BASE (t))
8286                            / BITS_PER_UNIT));
8287   dump_class_hierarchy_r (stream, flags, TYPE_BINFO (t), TYPE_BINFO (t), 0);
8288   fprintf (stream, "\n");
8289 }
8290
8291 /* Debug interface to hierarchy dumping.  */
8292
8293 void
8294 debug_class (tree t)
8295 {
8296   dump_class_hierarchy_1 (stderr, TDF_SLIM, t);
8297 }
8298
8299 static void
8300 dump_class_hierarchy (tree t)
8301 {
8302   int flags;
8303   FILE *stream = get_dump_info (TDI_class, &flags);
8304
8305   if (stream)
8306     {
8307       dump_class_hierarchy_1 (stream, flags, t);
8308     }
8309 }
8310
8311 static void
8312 dump_array (FILE * stream, tree decl)
8313 {
8314   tree value;
8315   unsigned HOST_WIDE_INT ix;
8316   HOST_WIDE_INT elt;
8317   tree size = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (decl)));
8318
8319   elt = (tree_to_shwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (decl))))
8320          / BITS_PER_UNIT);
8321   fprintf (stream, "%s:", decl_as_string (decl, TFF_PLAIN_IDENTIFIER));
8322   fprintf (stream, " %s entries",
8323            expr_as_string (size_binop (PLUS_EXPR, size, size_one_node),
8324                            TFF_PLAIN_IDENTIFIER));
8325   fprintf (stream, "\n");
8326
8327   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
8328                               ix, value)
8329     fprintf (stream, "%-4ld  %s\n", (long)(ix * elt),
8330              expr_as_string (value, TFF_PLAIN_IDENTIFIER));
8331 }
8332
8333 static void
8334 dump_vtable (tree t, tree binfo, tree vtable)
8335 {
8336   int flags;
8337   FILE *stream = get_dump_info (TDI_class, &flags);
8338
8339   if (!stream)
8340     return;
8341
8342   if (!(flags & TDF_SLIM))
8343     {
8344       int ctor_vtbl_p = TYPE_BINFO (t) != binfo;
8345
8346       fprintf (stream, "%s for %s",
8347                ctor_vtbl_p ? "Construction vtable" : "Vtable",
8348                type_as_string (BINFO_TYPE (binfo), TFF_PLAIN_IDENTIFIER));
8349       if (ctor_vtbl_p)
8350         {
8351           if (!BINFO_VIRTUAL_P (binfo))
8352             fprintf (stream, " (0x" HOST_WIDE_INT_PRINT_HEX " instance)",
8353                      (HOST_WIDE_INT) (uintptr_t) binfo);
8354           fprintf (stream, " in %s", type_as_string (t, TFF_PLAIN_IDENTIFIER));
8355         }
8356       fprintf (stream, "\n");
8357       dump_array (stream, vtable);
8358       fprintf (stream, "\n");
8359     }
8360 }
8361
8362 static void
8363 dump_vtt (tree t, tree vtt)
8364 {
8365   int flags;
8366   FILE *stream = get_dump_info (TDI_class, &flags);
8367
8368   if (!stream)
8369     return;
8370
8371   if (!(flags & TDF_SLIM))
8372     {
8373       fprintf (stream, "VTT for %s\n",
8374                type_as_string (t, TFF_PLAIN_IDENTIFIER));
8375       dump_array (stream, vtt);
8376       fprintf (stream, "\n");
8377     }
8378 }
8379
8380 /* Dump a function or thunk and its thunkees.  */
8381
8382 static void
8383 dump_thunk (FILE *stream, int indent, tree thunk)
8384 {
8385   static const char spaces[] = "        ";
8386   tree name = DECL_NAME (thunk);
8387   tree thunks;
8388
8389   fprintf (stream, "%.*s%p %s %s", indent, spaces,
8390            (void *)thunk,
8391            !DECL_THUNK_P (thunk) ? "function"
8392            : DECL_THIS_THUNK_P (thunk) ? "this-thunk" : "covariant-thunk",
8393            name ? IDENTIFIER_POINTER (name) : "<unset>");
8394   if (DECL_THUNK_P (thunk))
8395     {
8396       HOST_WIDE_INT fixed_adjust = THUNK_FIXED_OFFSET (thunk);
8397       tree virtual_adjust = THUNK_VIRTUAL_OFFSET (thunk);
8398
8399       fprintf (stream, " fixed=" HOST_WIDE_INT_PRINT_DEC, fixed_adjust);
8400       if (!virtual_adjust)
8401         /*NOP*/;
8402       else if (DECL_THIS_THUNK_P (thunk))
8403         fprintf (stream, " vcall="  HOST_WIDE_INT_PRINT_DEC,
8404                  tree_to_shwi (virtual_adjust));
8405       else
8406         fprintf (stream, " vbase=" HOST_WIDE_INT_PRINT_DEC "(%s)",
8407                  tree_to_shwi (BINFO_VPTR_FIELD (virtual_adjust)),
8408                  type_as_string (BINFO_TYPE (virtual_adjust), TFF_SCOPE));
8409       if (THUNK_ALIAS (thunk))
8410         fprintf (stream, " alias to %p", (void *)THUNK_ALIAS (thunk));
8411     }
8412   fprintf (stream, "\n");
8413   for (thunks = DECL_THUNKS (thunk); thunks; thunks = TREE_CHAIN (thunks))
8414     dump_thunk (stream, indent + 2, thunks);
8415 }
8416
8417 /* Dump the thunks for FN.  */
8418
8419 void
8420 debug_thunks (tree fn)
8421 {
8422   dump_thunk (stderr, 0, fn);
8423 }
8424
8425 /* Virtual function table initialization.  */
8426
8427 /* Create all the necessary vtables for T and its base classes.  */
8428
8429 static void
8430 finish_vtbls (tree t)
8431 {
8432   tree vbase;
8433   vec<constructor_elt, va_gc> *v = NULL;
8434   tree vtable = BINFO_VTABLE (TYPE_BINFO (t));
8435
8436   /* We lay out the primary and secondary vtables in one contiguous
8437      vtable.  The primary vtable is first, followed by the non-virtual
8438      secondary vtables in inheritance graph order.  */
8439   accumulate_vtbl_inits (TYPE_BINFO (t), TYPE_BINFO (t), TYPE_BINFO (t),
8440                          vtable, t, &v);
8441
8442   /* Then come the virtual bases, also in inheritance graph order.  */
8443   for (vbase = TYPE_BINFO (t); vbase; vbase = TREE_CHAIN (vbase))
8444     {
8445       if (!BINFO_VIRTUAL_P (vbase))
8446         continue;
8447       accumulate_vtbl_inits (vbase, vbase, TYPE_BINFO (t), vtable, t, &v);
8448     }
8449
8450   if (BINFO_VTABLE (TYPE_BINFO (t)))
8451     initialize_vtable (TYPE_BINFO (t), v);
8452 }
8453
8454 /* Initialize the vtable for BINFO with the INITS.  */
8455
8456 static void
8457 initialize_vtable (tree binfo, vec<constructor_elt, va_gc> *inits)
8458 {
8459   tree decl;
8460
8461   layout_vtable_decl (binfo, vec_safe_length (inits));
8462   decl = get_vtbl_decl_for_binfo (binfo);
8463   initialize_artificial_var (decl, inits);
8464   dump_vtable (BINFO_TYPE (binfo), binfo, decl);
8465 }
8466
8467 /* Build the VTT (virtual table table) for T.
8468    A class requires a VTT if it has virtual bases.
8469
8470    This holds
8471    1 - primary virtual pointer for complete object T
8472    2 - secondary VTTs for each direct non-virtual base of T which requires a
8473        VTT
8474    3 - secondary virtual pointers for each direct or indirect base of T which
8475        has virtual bases or is reachable via a virtual path from T.
8476    4 - secondary VTTs for each direct or indirect virtual base of T.
8477
8478    Secondary VTTs look like complete object VTTs without part 4.  */
8479
8480 static void
8481 build_vtt (tree t)
8482 {
8483   tree type;
8484   tree vtt;
8485   tree index;
8486   vec<constructor_elt, va_gc> *inits;
8487
8488   /* Build up the initializers for the VTT.  */
8489   inits = NULL;
8490   index = size_zero_node;
8491   build_vtt_inits (TYPE_BINFO (t), t, &inits, &index);
8492
8493   /* If we didn't need a VTT, we're done.  */
8494   if (!inits)
8495     return;
8496
8497   /* Figure out the type of the VTT.  */
8498   type = build_array_of_n_type (const_ptr_type_node,
8499                                 inits->length ());
8500
8501   /* Now, build the VTT object itself.  */
8502   vtt = build_vtable (t, mangle_vtt_for_type (t), type);
8503   initialize_artificial_var (vtt, inits);
8504   /* Add the VTT to the vtables list.  */
8505   DECL_CHAIN (vtt) = DECL_CHAIN (CLASSTYPE_VTABLES (t));
8506   DECL_CHAIN (CLASSTYPE_VTABLES (t)) = vtt;
8507
8508   dump_vtt (t, vtt);
8509 }
8510
8511 /* When building a secondary VTT, BINFO_VTABLE is set to a TREE_LIST with
8512    PURPOSE the RTTI_BINFO, VALUE the real vtable pointer for this binfo,
8513    and CHAIN the vtable pointer for this binfo after construction is
8514    complete.  VALUE can also be another BINFO, in which case we recurse.  */
8515
8516 static tree
8517 binfo_ctor_vtable (tree binfo)
8518 {
8519   tree vt;
8520
8521   while (1)
8522     {
8523       vt = BINFO_VTABLE (binfo);
8524       if (TREE_CODE (vt) == TREE_LIST)
8525         vt = TREE_VALUE (vt);
8526       if (TREE_CODE (vt) == TREE_BINFO)
8527         binfo = vt;
8528       else
8529         break;
8530     }
8531
8532   return vt;
8533 }
8534
8535 /* Data for secondary VTT initialization.  */
8536 typedef struct secondary_vptr_vtt_init_data_s
8537 {
8538   /* Is this the primary VTT? */
8539   bool top_level_p;
8540
8541   /* Current index into the VTT.  */
8542   tree index;
8543
8544   /* Vector of initializers built up.  */
8545   vec<constructor_elt, va_gc> *inits;
8546
8547   /* The type being constructed by this secondary VTT.  */
8548   tree type_being_constructed;
8549 } secondary_vptr_vtt_init_data;
8550
8551 /* Recursively build the VTT-initializer for BINFO (which is in the
8552    hierarchy dominated by T).  INITS points to the end of the initializer
8553    list to date.  INDEX is the VTT index where the next element will be
8554    replaced.  Iff BINFO is the binfo for T, this is the top level VTT (i.e.
8555    not a subvtt for some base of T).  When that is so, we emit the sub-VTTs
8556    for virtual bases of T. When it is not so, we build the constructor
8557    vtables for the BINFO-in-T variant.  */
8558
8559 static void
8560 build_vtt_inits (tree binfo, tree t, vec<constructor_elt, va_gc> **inits,
8561                  tree *index)
8562 {
8563   int i;
8564   tree b;
8565   tree init;
8566   secondary_vptr_vtt_init_data data;
8567   int top_level_p = SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t);
8568
8569   /* We only need VTTs for subobjects with virtual bases.  */
8570   if (!CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo)))
8571     return;
8572
8573   /* We need to use a construction vtable if this is not the primary
8574      VTT.  */
8575   if (!top_level_p)
8576     {
8577       build_ctor_vtbl_group (binfo, t);
8578
8579       /* Record the offset in the VTT where this sub-VTT can be found.  */
8580       BINFO_SUBVTT_INDEX (binfo) = *index;
8581     }
8582
8583   /* Add the address of the primary vtable for the complete object.  */
8584   init = binfo_ctor_vtable (binfo);
8585   CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, init);
8586   if (top_level_p)
8587     {
8588       gcc_assert (!BINFO_VPTR_INDEX (binfo));
8589       BINFO_VPTR_INDEX (binfo) = *index;
8590     }
8591   *index = size_binop (PLUS_EXPR, *index, TYPE_SIZE_UNIT (ptr_type_node));
8592
8593   /* Recursively add the secondary VTTs for non-virtual bases.  */
8594   for (i = 0; BINFO_BASE_ITERATE (binfo, i, b); ++i)
8595     if (!BINFO_VIRTUAL_P (b))
8596       build_vtt_inits (b, t, inits, index);
8597
8598   /* Add secondary virtual pointers for all subobjects of BINFO with
8599      either virtual bases or reachable along a virtual path, except
8600      subobjects that are non-virtual primary bases.  */
8601   data.top_level_p = top_level_p;
8602   data.index = *index;
8603   data.inits = *inits;
8604   data.type_being_constructed = BINFO_TYPE (binfo);
8605
8606   dfs_walk_once (binfo, dfs_build_secondary_vptr_vtt_inits, NULL, &data);
8607
8608   *index = data.index;
8609
8610   /* data.inits might have grown as we added secondary virtual pointers.
8611      Make sure our caller knows about the new vector.  */
8612   *inits = data.inits;
8613
8614   if (top_level_p)
8615     /* Add the secondary VTTs for virtual bases in inheritance graph
8616        order.  */
8617     for (b = TYPE_BINFO (BINFO_TYPE (binfo)); b; b = TREE_CHAIN (b))
8618       {
8619         if (!BINFO_VIRTUAL_P (b))
8620           continue;
8621
8622         build_vtt_inits (b, t, inits, index);
8623       }
8624   else
8625     /* Remove the ctor vtables we created.  */
8626     dfs_walk_all (binfo, dfs_fixup_binfo_vtbls, NULL, binfo);
8627 }
8628
8629 /* Called from build_vtt_inits via dfs_walk.  BINFO is the binfo for the base
8630    in most derived. DATA is a SECONDARY_VPTR_VTT_INIT_DATA structure.  */
8631
8632 static tree
8633 dfs_build_secondary_vptr_vtt_inits (tree binfo, void *data_)
8634 {
8635   secondary_vptr_vtt_init_data *data = (secondary_vptr_vtt_init_data *)data_;
8636
8637   /* We don't care about bases that don't have vtables.  */
8638   if (!TYPE_VFIELD (BINFO_TYPE (binfo)))
8639     return dfs_skip_bases;
8640
8641   /* We're only interested in proper subobjects of the type being
8642      constructed.  */
8643   if (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), data->type_being_constructed))
8644     return NULL_TREE;
8645
8646   /* We're only interested in bases with virtual bases or reachable
8647      via a virtual path from the type being constructed.  */
8648   if (!(CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo))
8649         || binfo_via_virtual (binfo, data->type_being_constructed)))
8650     return dfs_skip_bases;
8651
8652   /* We're not interested in non-virtual primary bases.  */
8653   if (!BINFO_VIRTUAL_P (binfo) && BINFO_PRIMARY_P (binfo))
8654     return NULL_TREE;
8655
8656   /* Record the index where this secondary vptr can be found.  */
8657   if (data->top_level_p)
8658     {
8659       gcc_assert (!BINFO_VPTR_INDEX (binfo));
8660       BINFO_VPTR_INDEX (binfo) = data->index;
8661
8662       if (BINFO_VIRTUAL_P (binfo))
8663         {
8664           /* It's a primary virtual base, and this is not a
8665              construction vtable.  Find the base this is primary of in
8666              the inheritance graph, and use that base's vtable
8667              now.  */
8668           while (BINFO_PRIMARY_P (binfo))
8669             binfo = BINFO_INHERITANCE_CHAIN (binfo);
8670         }
8671     }
8672
8673   /* Add the initializer for the secondary vptr itself.  */
8674   CONSTRUCTOR_APPEND_ELT (data->inits, NULL_TREE, binfo_ctor_vtable (binfo));
8675
8676   /* Advance the vtt index.  */
8677   data->index = size_binop (PLUS_EXPR, data->index,
8678                             TYPE_SIZE_UNIT (ptr_type_node));
8679
8680   return NULL_TREE;
8681 }
8682
8683 /* Called from build_vtt_inits via dfs_walk. After building
8684    constructor vtables and generating the sub-vtt from them, we need
8685    to restore the BINFO_VTABLES that were scribbled on.  DATA is the
8686    binfo of the base whose sub vtt was generated.  */
8687
8688 static tree
8689 dfs_fixup_binfo_vtbls (tree binfo, void* data)
8690 {
8691   tree vtable = BINFO_VTABLE (binfo);
8692
8693   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
8694     /* If this class has no vtable, none of its bases do.  */
8695     return dfs_skip_bases;
8696
8697   if (!vtable)
8698     /* This might be a primary base, so have no vtable in this
8699        hierarchy.  */
8700     return NULL_TREE;
8701
8702   /* If we scribbled the construction vtable vptr into BINFO, clear it
8703      out now.  */
8704   if (TREE_CODE (vtable) == TREE_LIST
8705       && (TREE_PURPOSE (vtable) == (tree) data))
8706     BINFO_VTABLE (binfo) = TREE_CHAIN (vtable);
8707
8708   return NULL_TREE;
8709 }
8710
8711 /* Build the construction vtable group for BINFO which is in the
8712    hierarchy dominated by T.  */
8713
8714 static void
8715 build_ctor_vtbl_group (tree binfo, tree t)
8716 {
8717   tree type;
8718   tree vtbl;
8719   tree id;
8720   tree vbase;
8721   vec<constructor_elt, va_gc> *v;
8722
8723   /* See if we've already created this construction vtable group.  */
8724   id = mangle_ctor_vtbl_for_type (t, binfo);
8725   if (IDENTIFIER_GLOBAL_VALUE (id))
8726     return;
8727
8728   gcc_assert (!SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t));
8729   /* Build a version of VTBL (with the wrong type) for use in
8730      constructing the addresses of secondary vtables in the
8731      construction vtable group.  */
8732   vtbl = build_vtable (t, id, ptr_type_node);
8733   DECL_CONSTRUCTION_VTABLE_P (vtbl) = 1;
8734   /* Don't export construction vtables from shared libraries.  Even on
8735      targets that don't support hidden visibility, this tells
8736      can_refer_decl_in_current_unit_p not to assume that it's safe to
8737      access from a different compilation unit (bz 54314).  */
8738   DECL_VISIBILITY (vtbl) = VISIBILITY_HIDDEN;
8739   DECL_VISIBILITY_SPECIFIED (vtbl) = true;
8740
8741   v = NULL;
8742   accumulate_vtbl_inits (binfo, TYPE_BINFO (TREE_TYPE (binfo)),
8743                          binfo, vtbl, t, &v);
8744
8745   /* Add the vtables for each of our virtual bases using the vbase in T
8746      binfo.  */
8747   for (vbase = TYPE_BINFO (BINFO_TYPE (binfo));
8748        vbase;
8749        vbase = TREE_CHAIN (vbase))
8750     {
8751       tree b;
8752
8753       if (!BINFO_VIRTUAL_P (vbase))
8754         continue;
8755       b = copied_binfo (vbase, binfo);
8756
8757       accumulate_vtbl_inits (b, vbase, binfo, vtbl, t, &v);
8758     }
8759
8760   /* Figure out the type of the construction vtable.  */
8761   type = build_array_of_n_type (vtable_entry_type, v->length ());
8762   layout_type (type);
8763   TREE_TYPE (vtbl) = type;
8764   DECL_SIZE (vtbl) = DECL_SIZE_UNIT (vtbl) = NULL_TREE;
8765   layout_decl (vtbl, 0);
8766
8767   /* Initialize the construction vtable.  */
8768   CLASSTYPE_VTABLES (t) = chainon (CLASSTYPE_VTABLES (t), vtbl);
8769   initialize_artificial_var (vtbl, v);
8770   dump_vtable (t, binfo, vtbl);
8771 }
8772
8773 /* Add the vtbl initializers for BINFO (and its bases other than
8774    non-virtual primaries) to the list of INITS.  BINFO is in the
8775    hierarchy dominated by T.  RTTI_BINFO is the binfo within T of
8776    the constructor the vtbl inits should be accumulated for. (If this
8777    is the complete object vtbl then RTTI_BINFO will be TYPE_BINFO (T).)
8778    ORIG_BINFO is the binfo for this object within BINFO_TYPE (RTTI_BINFO).
8779    BINFO is the active base equivalent of ORIG_BINFO in the inheritance
8780    graph of T. Both BINFO and ORIG_BINFO will have the same BINFO_TYPE,
8781    but are not necessarily the same in terms of layout.  */
8782
8783 static void
8784 accumulate_vtbl_inits (tree binfo,
8785                        tree orig_binfo,
8786                        tree rtti_binfo,
8787                        tree vtbl,
8788                        tree t,
8789                        vec<constructor_elt, va_gc> **inits)
8790 {
8791   int i;
8792   tree base_binfo;
8793   int ctor_vtbl_p = !SAME_BINFO_TYPE_P (BINFO_TYPE (rtti_binfo), t);
8794
8795   gcc_assert (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), BINFO_TYPE (orig_binfo)));
8796
8797   /* If it doesn't have a vptr, we don't do anything.  */
8798   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
8799     return;
8800
8801   /* If we're building a construction vtable, we're not interested in
8802      subobjects that don't require construction vtables.  */
8803   if (ctor_vtbl_p
8804       && !CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo))
8805       && !binfo_via_virtual (orig_binfo, BINFO_TYPE (rtti_binfo)))
8806     return;
8807
8808   /* Build the initializers for the BINFO-in-T vtable.  */
8809   dfs_accumulate_vtbl_inits (binfo, orig_binfo, rtti_binfo, vtbl, t, inits);
8810
8811   /* Walk the BINFO and its bases.  We walk in preorder so that as we
8812      initialize each vtable we can figure out at what offset the
8813      secondary vtable lies from the primary vtable.  We can't use
8814      dfs_walk here because we need to iterate through bases of BINFO
8815      and RTTI_BINFO simultaneously.  */
8816   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
8817     {
8818       /* Skip virtual bases.  */
8819       if (BINFO_VIRTUAL_P (base_binfo))
8820         continue;
8821       accumulate_vtbl_inits (base_binfo,
8822                              BINFO_BASE_BINFO (orig_binfo, i),
8823                              rtti_binfo, vtbl, t,
8824                              inits);
8825     }
8826 }
8827
8828 /* Called from accumulate_vtbl_inits.  Adds the initializers for the
8829    BINFO vtable to L.  */
8830
8831 static void
8832 dfs_accumulate_vtbl_inits (tree binfo,
8833                            tree orig_binfo,
8834                            tree rtti_binfo,
8835                            tree orig_vtbl,
8836                            tree t,
8837                            vec<constructor_elt, va_gc> **l)
8838 {
8839   tree vtbl = NULL_TREE;
8840   int ctor_vtbl_p = !SAME_BINFO_TYPE_P (BINFO_TYPE (rtti_binfo), t);
8841   int n_inits;
8842
8843   if (ctor_vtbl_p
8844       && BINFO_VIRTUAL_P (orig_binfo) && BINFO_PRIMARY_P (orig_binfo))
8845     {
8846       /* In the hierarchy of BINFO_TYPE (RTTI_BINFO), this is a
8847          primary virtual base.  If it is not the same primary in
8848          the hierarchy of T, we'll need to generate a ctor vtable
8849          for it, to place at its location in T.  If it is the same
8850          primary, we still need a VTT entry for the vtable, but it
8851          should point to the ctor vtable for the base it is a
8852          primary for within the sub-hierarchy of RTTI_BINFO.
8853
8854          There are three possible cases:
8855
8856          1) We are in the same place.
8857          2) We are a primary base within a lost primary virtual base of
8858          RTTI_BINFO.
8859          3) We are primary to something not a base of RTTI_BINFO.  */
8860
8861       tree b;
8862       tree last = NULL_TREE;
8863
8864       /* First, look through the bases we are primary to for RTTI_BINFO
8865          or a virtual base.  */
8866       b = binfo;
8867       while (BINFO_PRIMARY_P (b))
8868         {
8869           b = BINFO_INHERITANCE_CHAIN (b);
8870           last = b;
8871           if (BINFO_VIRTUAL_P (b) || b == rtti_binfo)
8872             goto found;
8873         }
8874       /* If we run out of primary links, keep looking down our
8875          inheritance chain; we might be an indirect primary.  */
8876       for (b = last; b; b = BINFO_INHERITANCE_CHAIN (b))
8877         if (BINFO_VIRTUAL_P (b) || b == rtti_binfo)
8878           break;
8879     found:
8880
8881       /* If we found RTTI_BINFO, this is case 1.  If we found a virtual
8882          base B and it is a base of RTTI_BINFO, this is case 2.  In
8883          either case, we share our vtable with LAST, i.e. the
8884          derived-most base within B of which we are a primary.  */
8885       if (b == rtti_binfo
8886           || (b && binfo_for_vbase (BINFO_TYPE (b), BINFO_TYPE (rtti_binfo))))
8887         /* Just set our BINFO_VTABLE to point to LAST, as we may not have
8888            set LAST's BINFO_VTABLE yet.  We'll extract the actual vptr in
8889            binfo_ctor_vtable after everything's been set up.  */
8890         vtbl = last;
8891
8892       /* Otherwise, this is case 3 and we get our own.  */
8893     }
8894   else if (!BINFO_NEW_VTABLE_MARKED (orig_binfo))
8895     return;
8896
8897   n_inits = vec_safe_length (*l);
8898
8899   if (!vtbl)
8900     {
8901       tree index;
8902       int non_fn_entries;
8903
8904       /* Add the initializer for this vtable.  */
8905       build_vtbl_initializer (binfo, orig_binfo, t, rtti_binfo,
8906                               &non_fn_entries, l);
8907
8908       /* Figure out the position to which the VPTR should point.  */
8909       vtbl = build1 (ADDR_EXPR, vtbl_ptr_type_node, orig_vtbl);
8910       index = size_binop (MULT_EXPR,
8911                           TYPE_SIZE_UNIT (vtable_entry_type),
8912                           size_int (non_fn_entries + n_inits));
8913       vtbl = fold_build_pointer_plus (vtbl, index);
8914     }
8915
8916   if (ctor_vtbl_p)
8917     /* For a construction vtable, we can't overwrite BINFO_VTABLE.
8918        So, we make a TREE_LIST.  Later, dfs_fixup_binfo_vtbls will
8919        straighten this out.  */
8920     BINFO_VTABLE (binfo) = tree_cons (rtti_binfo, vtbl, BINFO_VTABLE (binfo));
8921   else if (BINFO_PRIMARY_P (binfo) && BINFO_VIRTUAL_P (binfo))
8922     /* Throw away any unneeded intializers.  */
8923     (*l)->truncate (n_inits);
8924   else
8925      /* For an ordinary vtable, set BINFO_VTABLE.  */
8926     BINFO_VTABLE (binfo) = vtbl;
8927 }
8928
8929 static GTY(()) tree abort_fndecl_addr;
8930
8931 /* Construct the initializer for BINFO's virtual function table.  BINFO
8932    is part of the hierarchy dominated by T.  If we're building a
8933    construction vtable, the ORIG_BINFO is the binfo we should use to
8934    find the actual function pointers to put in the vtable - but they
8935    can be overridden on the path to most-derived in the graph that
8936    ORIG_BINFO belongs.  Otherwise,
8937    ORIG_BINFO should be the same as BINFO.  The RTTI_BINFO is the
8938    BINFO that should be indicated by the RTTI information in the
8939    vtable; it will be a base class of T, rather than T itself, if we
8940    are building a construction vtable.
8941
8942    The value returned is a TREE_LIST suitable for wrapping in a
8943    CONSTRUCTOR to use as the DECL_INITIAL for a vtable.  If
8944    NON_FN_ENTRIES_P is not NULL, *NON_FN_ENTRIES_P is set to the
8945    number of non-function entries in the vtable.
8946
8947    It might seem that this function should never be called with a
8948    BINFO for which BINFO_PRIMARY_P holds, the vtable for such a
8949    base is always subsumed by a derived class vtable.  However, when
8950    we are building construction vtables, we do build vtables for
8951    primary bases; we need these while the primary base is being
8952    constructed.  */
8953
8954 static void
8955 build_vtbl_initializer (tree binfo,
8956                         tree orig_binfo,
8957                         tree t,
8958                         tree rtti_binfo,
8959                         int* non_fn_entries_p,
8960                         vec<constructor_elt, va_gc> **inits)
8961 {
8962   tree v;
8963   vtbl_init_data vid;
8964   unsigned ix, jx;
8965   tree vbinfo;
8966   vec<tree, va_gc> *vbases;
8967   constructor_elt *e;
8968
8969   /* Initialize VID.  */
8970   memset (&vid, 0, sizeof (vid));
8971   vid.binfo = binfo;
8972   vid.derived = t;
8973   vid.rtti_binfo = rtti_binfo;
8974   vid.primary_vtbl_p = SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t);
8975   vid.ctor_vtbl_p = !SAME_BINFO_TYPE_P (BINFO_TYPE (rtti_binfo), t);
8976   vid.generate_vcall_entries = true;
8977   /* The first vbase or vcall offset is at index -3 in the vtable.  */
8978   vid.index = ssize_int(-3 * TARGET_VTABLE_DATA_ENTRY_DISTANCE);
8979
8980   /* Add entries to the vtable for RTTI.  */
8981   build_rtti_vtbl_entries (binfo, &vid);
8982
8983   /* Create an array for keeping track of the functions we've
8984      processed.  When we see multiple functions with the same
8985      signature, we share the vcall offsets.  */
8986   vec_alloc (vid.fns, 32);
8987   /* Add the vcall and vbase offset entries.  */
8988   build_vcall_and_vbase_vtbl_entries (binfo, &vid);
8989
8990   /* Clear BINFO_VTABLE_PATH_MARKED; it's set by
8991      build_vbase_offset_vtbl_entries.  */
8992   for (vbases = CLASSTYPE_VBASECLASSES (t), ix = 0;
8993        vec_safe_iterate (vbases, ix, &vbinfo); ix++)
8994     BINFO_VTABLE_PATH_MARKED (vbinfo) = 0;
8995
8996   /* If the target requires padding between data entries, add that now.  */
8997   if (TARGET_VTABLE_DATA_ENTRY_DISTANCE > 1)
8998     {
8999       int n_entries = vec_safe_length (vid.inits);
9000
9001       vec_safe_grow (vid.inits, TARGET_VTABLE_DATA_ENTRY_DISTANCE * n_entries);
9002
9003       /* Move data entries into their new positions and add padding
9004          after the new positions.  Iterate backwards so we don't
9005          overwrite entries that we would need to process later.  */
9006       for (ix = n_entries - 1;
9007            vid.inits->iterate (ix, &e);
9008            ix--)
9009         {
9010           int j;
9011           int new_position = (TARGET_VTABLE_DATA_ENTRY_DISTANCE * ix
9012                               + (TARGET_VTABLE_DATA_ENTRY_DISTANCE - 1));
9013
9014           (*vid.inits)[new_position] = *e;
9015
9016           for (j = 1; j < TARGET_VTABLE_DATA_ENTRY_DISTANCE; ++j)
9017             {
9018               constructor_elt *f = &(*vid.inits)[new_position - j];
9019               f->index = NULL_TREE;
9020               f->value = build1 (NOP_EXPR, vtable_entry_type,
9021                                  null_pointer_node);
9022             }
9023         }
9024     }
9025
9026   if (non_fn_entries_p)
9027     *non_fn_entries_p = vec_safe_length (vid.inits);
9028
9029   /* The initializers for virtual functions were built up in reverse
9030      order.  Straighten them out and add them to the running list in one
9031      step.  */
9032   jx = vec_safe_length (*inits);
9033   vec_safe_grow (*inits, jx + vid.inits->length ());
9034
9035   for (ix = vid.inits->length () - 1;
9036        vid.inits->iterate (ix, &e);
9037        ix--, jx++)
9038     (**inits)[jx] = *e;
9039
9040   /* Go through all the ordinary virtual functions, building up
9041      initializers.  */
9042   for (v = BINFO_VIRTUALS (orig_binfo); v; v = TREE_CHAIN (v))
9043     {
9044       tree delta;
9045       tree vcall_index;
9046       tree fn, fn_original;
9047       tree init = NULL_TREE;
9048
9049       fn = BV_FN (v);
9050       fn_original = fn;
9051       if (DECL_THUNK_P (fn))
9052         {
9053           if (!DECL_NAME (fn))
9054             finish_thunk (fn);
9055           if (THUNK_ALIAS (fn))
9056             {
9057               fn = THUNK_ALIAS (fn);
9058               BV_FN (v) = fn;
9059             }
9060           fn_original = THUNK_TARGET (fn);
9061         }
9062
9063       /* If the only definition of this function signature along our
9064          primary base chain is from a lost primary, this vtable slot will
9065          never be used, so just zero it out.  This is important to avoid
9066          requiring extra thunks which cannot be generated with the function.
9067
9068          We first check this in update_vtable_entry_for_fn, so we handle
9069          restored primary bases properly; we also need to do it here so we
9070          zero out unused slots in ctor vtables, rather than filling them
9071          with erroneous values (though harmless, apart from relocation
9072          costs).  */
9073       if (BV_LOST_PRIMARY (v))
9074         init = size_zero_node;
9075
9076       if (! init)
9077         {
9078           /* Pull the offset for `this', and the function to call, out of
9079              the list.  */
9080           delta = BV_DELTA (v);
9081           vcall_index = BV_VCALL_INDEX (v);
9082
9083           gcc_assert (TREE_CODE (delta) == INTEGER_CST);
9084           gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9085
9086           /* You can't call an abstract virtual function; it's abstract.
9087              So, we replace these functions with __pure_virtual.  */
9088           if (DECL_PURE_VIRTUAL_P (fn_original))
9089             {
9090               fn = abort_fndecl;
9091               if (!TARGET_VTABLE_USES_DESCRIPTORS)
9092                 {
9093                   if (abort_fndecl_addr == NULL)
9094                     abort_fndecl_addr
9095                       = fold_convert (vfunc_ptr_type_node,
9096                                       build_fold_addr_expr (fn));
9097                   init = abort_fndecl_addr;
9098                 }
9099             }
9100           /* Likewise for deleted virtuals.  */
9101           else if (DECL_DELETED_FN (fn_original))
9102             {
9103               fn = get_identifier ("__cxa_deleted_virtual");
9104               if (!get_global_value_if_present (fn, &fn))
9105                 fn = push_library_fn (fn, (build_function_type_list
9106                                            (void_type_node, NULL_TREE)),
9107                                       NULL_TREE, ECF_NORETURN);
9108               if (!TARGET_VTABLE_USES_DESCRIPTORS)
9109                 init = fold_convert (vfunc_ptr_type_node,
9110                                      build_fold_addr_expr (fn));
9111             }
9112           else
9113             {
9114               if (!integer_zerop (delta) || vcall_index)
9115                 {
9116                   fn = make_thunk (fn, /*this_adjusting=*/1, delta, vcall_index);
9117                   if (!DECL_NAME (fn))
9118                     finish_thunk (fn);
9119                 }
9120               /* Take the address of the function, considering it to be of an
9121                  appropriate generic type.  */
9122               if (!TARGET_VTABLE_USES_DESCRIPTORS)
9123                 init = fold_convert (vfunc_ptr_type_node,
9124                                      build_fold_addr_expr (fn));
9125               /* Don't refer to a virtual destructor from a constructor
9126                  vtable or a vtable for an abstract class, since destroying
9127                  an object under construction is undefined behavior and we
9128                  don't want it to be considered a candidate for speculative
9129                  devirtualization.  But do create the thunk for ABI
9130                  compliance.  */
9131               if (DECL_DESTRUCTOR_P (fn_original)
9132                   && (CLASSTYPE_PURE_VIRTUALS (DECL_CONTEXT (fn_original))
9133                       || orig_binfo != binfo))
9134                 init = size_zero_node;
9135             }
9136         }
9137
9138       /* And add it to the chain of initializers.  */
9139       if (TARGET_VTABLE_USES_DESCRIPTORS)
9140         {
9141           int i;
9142           if (init == size_zero_node)
9143             for (i = 0; i < TARGET_VTABLE_USES_DESCRIPTORS; ++i)
9144               CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, init);
9145           else
9146             for (i = 0; i < TARGET_VTABLE_USES_DESCRIPTORS; ++i)
9147               {
9148                 tree fdesc = build2 (FDESC_EXPR, vfunc_ptr_type_node,
9149                                      fn, build_int_cst (NULL_TREE, i));
9150                 TREE_CONSTANT (fdesc) = 1;
9151
9152                 CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, fdesc);
9153               }
9154         }
9155       else
9156         CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, init);
9157     }
9158 }
9159
9160 /* Adds to vid->inits the initializers for the vbase and vcall
9161    offsets in BINFO, which is in the hierarchy dominated by T.  */
9162
9163 static void
9164 build_vcall_and_vbase_vtbl_entries (tree binfo, vtbl_init_data* vid)
9165 {
9166   tree b;
9167
9168   /* If this is a derived class, we must first create entries
9169      corresponding to the primary base class.  */
9170   b = get_primary_binfo (binfo);
9171   if (b)
9172     build_vcall_and_vbase_vtbl_entries (b, vid);
9173
9174   /* Add the vbase entries for this base.  */
9175   build_vbase_offset_vtbl_entries (binfo, vid);
9176   /* Add the vcall entries for this base.  */
9177   build_vcall_offset_vtbl_entries (binfo, vid);
9178 }
9179
9180 /* Returns the initializers for the vbase offset entries in the vtable
9181    for BINFO (which is part of the class hierarchy dominated by T), in
9182    reverse order.  VBASE_OFFSET_INDEX gives the vtable index
9183    where the next vbase offset will go.  */
9184
9185 static void
9186 build_vbase_offset_vtbl_entries (tree binfo, vtbl_init_data* vid)
9187 {
9188   tree vbase;
9189   tree t;
9190   tree non_primary_binfo;
9191
9192   /* If there are no virtual baseclasses, then there is nothing to
9193      do.  */
9194   if (!CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo)))
9195     return;
9196
9197   t = vid->derived;
9198
9199   /* We might be a primary base class.  Go up the inheritance hierarchy
9200      until we find the most derived class of which we are a primary base:
9201      it is the offset of that which we need to use.  */
9202   non_primary_binfo = binfo;
9203   while (BINFO_INHERITANCE_CHAIN (non_primary_binfo))
9204     {
9205       tree b;
9206
9207       /* If we have reached a virtual base, then it must be a primary
9208          base (possibly multi-level) of vid->binfo, or we wouldn't
9209          have called build_vcall_and_vbase_vtbl_entries for it.  But it
9210          might be a lost primary, so just skip down to vid->binfo.  */
9211       if (BINFO_VIRTUAL_P (non_primary_binfo))
9212         {
9213           non_primary_binfo = vid->binfo;
9214           break;
9215         }
9216
9217       b = BINFO_INHERITANCE_CHAIN (non_primary_binfo);
9218       if (get_primary_binfo (b) != non_primary_binfo)
9219         break;
9220       non_primary_binfo = b;
9221     }
9222
9223   /* Go through the virtual bases, adding the offsets.  */
9224   for (vbase = TYPE_BINFO (BINFO_TYPE (binfo));
9225        vbase;
9226        vbase = TREE_CHAIN (vbase))
9227     {
9228       tree b;
9229       tree delta;
9230
9231       if (!BINFO_VIRTUAL_P (vbase))
9232         continue;
9233
9234       /* Find the instance of this virtual base in the complete
9235          object.  */
9236       b = copied_binfo (vbase, binfo);
9237
9238       /* If we've already got an offset for this virtual base, we
9239          don't need another one.  */
9240       if (BINFO_VTABLE_PATH_MARKED (b))
9241         continue;
9242       BINFO_VTABLE_PATH_MARKED (b) = 1;
9243
9244       /* Figure out where we can find this vbase offset.  */
9245       delta = size_binop (MULT_EXPR,
9246                           vid->index,
9247                           convert (ssizetype,
9248                                    TYPE_SIZE_UNIT (vtable_entry_type)));
9249       if (vid->primary_vtbl_p)
9250         BINFO_VPTR_FIELD (b) = delta;
9251
9252       if (binfo != TYPE_BINFO (t))
9253         /* The vbase offset had better be the same.  */
9254         gcc_assert (tree_int_cst_equal (delta, BINFO_VPTR_FIELD (vbase)));
9255
9256       /* The next vbase will come at a more negative offset.  */
9257       vid->index = size_binop (MINUS_EXPR, vid->index,
9258                                ssize_int (TARGET_VTABLE_DATA_ENTRY_DISTANCE));
9259
9260       /* The initializer is the delta from BINFO to this virtual base.
9261          The vbase offsets go in reverse inheritance-graph order, and
9262          we are walking in inheritance graph order so these end up in
9263          the right order.  */
9264       delta = size_diffop_loc (input_location,
9265                            BINFO_OFFSET (b), BINFO_OFFSET (non_primary_binfo));
9266
9267       CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE,
9268                               fold_build1_loc (input_location, NOP_EXPR,
9269                                                vtable_entry_type, delta));
9270     }
9271 }
9272
9273 /* Adds the initializers for the vcall offset entries in the vtable
9274    for BINFO (which is part of the class hierarchy dominated by VID->DERIVED)
9275    to VID->INITS.  */
9276
9277 static void
9278 build_vcall_offset_vtbl_entries (tree binfo, vtbl_init_data* vid)
9279 {
9280   /* We only need these entries if this base is a virtual base.  We
9281      compute the indices -- but do not add to the vtable -- when
9282      building the main vtable for a class.  */
9283   if (binfo == TYPE_BINFO (vid->derived)
9284       || (BINFO_VIRTUAL_P (binfo) 
9285           /* If BINFO is RTTI_BINFO, then (since BINFO does not
9286              correspond to VID->DERIVED), we are building a primary
9287              construction virtual table.  Since this is a primary
9288              virtual table, we do not need the vcall offsets for
9289              BINFO.  */
9290           && binfo != vid->rtti_binfo))
9291     {
9292       /* We need a vcall offset for each of the virtual functions in this
9293          vtable.  For example:
9294
9295            class A { virtual void f (); };
9296            class B1 : virtual public A { virtual void f (); };
9297            class B2 : virtual public A { virtual void f (); };
9298            class C: public B1, public B2 { virtual void f (); };
9299
9300          A C object has a primary base of B1, which has a primary base of A.  A
9301          C also has a secondary base of B2, which no longer has a primary base
9302          of A.  So the B2-in-C construction vtable needs a secondary vtable for
9303          A, which will adjust the A* to a B2* to call f.  We have no way of
9304          knowing what (or even whether) this offset will be when we define B2,
9305          so we store this "vcall offset" in the A sub-vtable and look it up in
9306          a "virtual thunk" for B2::f.
9307
9308          We need entries for all the functions in our primary vtable and
9309          in our non-virtual bases' secondary vtables.  */
9310       vid->vbase = binfo;
9311       /* If we are just computing the vcall indices -- but do not need
9312          the actual entries -- not that.  */
9313       if (!BINFO_VIRTUAL_P (binfo))
9314         vid->generate_vcall_entries = false;
9315       /* Now, walk through the non-virtual bases, adding vcall offsets.  */
9316       add_vcall_offset_vtbl_entries_r (binfo, vid);
9317     }
9318 }
9319
9320 /* Build vcall offsets, starting with those for BINFO.  */
9321
9322 static void
9323 add_vcall_offset_vtbl_entries_r (tree binfo, vtbl_init_data* vid)
9324 {
9325   int i;
9326   tree primary_binfo;
9327   tree base_binfo;
9328
9329   /* Don't walk into virtual bases -- except, of course, for the
9330      virtual base for which we are building vcall offsets.  Any
9331      primary virtual base will have already had its offsets generated
9332      through the recursion in build_vcall_and_vbase_vtbl_entries.  */
9333   if (BINFO_VIRTUAL_P (binfo) && vid->vbase != binfo)
9334     return;
9335
9336   /* If BINFO has a primary base, process it first.  */
9337   primary_binfo = get_primary_binfo (binfo);
9338   if (primary_binfo)
9339     add_vcall_offset_vtbl_entries_r (primary_binfo, vid);
9340
9341   /* Add BINFO itself to the list.  */
9342   add_vcall_offset_vtbl_entries_1 (binfo, vid);
9343
9344   /* Scan the non-primary bases of BINFO.  */
9345   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
9346     if (base_binfo != primary_binfo)
9347       add_vcall_offset_vtbl_entries_r (base_binfo, vid);
9348 }
9349
9350 /* Called from build_vcall_offset_vtbl_entries_r.  */
9351
9352 static void
9353 add_vcall_offset_vtbl_entries_1 (tree binfo, vtbl_init_data* vid)
9354 {
9355   /* Make entries for the rest of the virtuals.  */
9356   tree orig_fn;
9357
9358   /* The ABI requires that the methods be processed in declaration
9359      order.  */
9360   for (orig_fn = TYPE_METHODS (BINFO_TYPE (binfo));
9361        orig_fn;
9362        orig_fn = DECL_CHAIN (orig_fn))
9363     if (TREE_CODE (orig_fn) == FUNCTION_DECL && DECL_VINDEX (orig_fn))
9364       add_vcall_offset (orig_fn, binfo, vid);
9365 }
9366
9367 /* Add a vcall offset entry for ORIG_FN to the vtable.  */
9368
9369 static void
9370 add_vcall_offset (tree orig_fn, tree binfo, vtbl_init_data *vid)
9371 {
9372   size_t i;
9373   tree vcall_offset;
9374   tree derived_entry;
9375
9376   /* If there is already an entry for a function with the same
9377      signature as FN, then we do not need a second vcall offset.
9378      Check the list of functions already present in the derived
9379      class vtable.  */
9380   FOR_EACH_VEC_SAFE_ELT (vid->fns, i, derived_entry)
9381     {
9382       if (same_signature_p (derived_entry, orig_fn)
9383           /* We only use one vcall offset for virtual destructors,
9384              even though there are two virtual table entries.  */
9385           || (DECL_DESTRUCTOR_P (derived_entry)
9386               && DECL_DESTRUCTOR_P (orig_fn)))
9387         return;
9388     }
9389
9390   /* If we are building these vcall offsets as part of building
9391      the vtable for the most derived class, remember the vcall
9392      offset.  */
9393   if (vid->binfo == TYPE_BINFO (vid->derived))
9394     {
9395       tree_pair_s elt = {orig_fn, vid->index};
9396       vec_safe_push (CLASSTYPE_VCALL_INDICES (vid->derived), elt);
9397     }
9398
9399   /* The next vcall offset will be found at a more negative
9400      offset.  */
9401   vid->index = size_binop (MINUS_EXPR, vid->index,
9402                            ssize_int (TARGET_VTABLE_DATA_ENTRY_DISTANCE));
9403
9404   /* Keep track of this function.  */
9405   vec_safe_push (vid->fns, orig_fn);
9406
9407   if (vid->generate_vcall_entries)
9408     {
9409       tree base;
9410       tree fn;
9411
9412       /* Find the overriding function.  */
9413       fn = find_final_overrider (vid->rtti_binfo, binfo, orig_fn);
9414       if (fn == error_mark_node)
9415         vcall_offset = build_zero_cst (vtable_entry_type);
9416       else
9417         {
9418           base = TREE_VALUE (fn);
9419
9420           /* The vbase we're working on is a primary base of
9421              vid->binfo.  But it might be a lost primary, so its
9422              BINFO_OFFSET might be wrong, so we just use the
9423              BINFO_OFFSET from vid->binfo.  */
9424           vcall_offset = size_diffop_loc (input_location,
9425                                       BINFO_OFFSET (base),
9426                                       BINFO_OFFSET (vid->binfo));
9427           vcall_offset = fold_build1_loc (input_location,
9428                                       NOP_EXPR, vtable_entry_type,
9429                                       vcall_offset);
9430         }
9431       /* Add the initializer to the vtable.  */
9432       CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE, vcall_offset);
9433     }
9434 }
9435
9436 /* Return vtbl initializers for the RTTI entries corresponding to the
9437    BINFO's vtable.  The RTTI entries should indicate the object given
9438    by VID->rtti_binfo.  */
9439
9440 static void
9441 build_rtti_vtbl_entries (tree binfo, vtbl_init_data* vid)
9442 {
9443   tree b;
9444   tree t;
9445   tree offset;
9446   tree decl;
9447   tree init;
9448
9449   t = BINFO_TYPE (vid->rtti_binfo);
9450
9451   /* To find the complete object, we will first convert to our most
9452      primary base, and then add the offset in the vtbl to that value.  */
9453   b = binfo;
9454   while (CLASSTYPE_HAS_PRIMARY_BASE_P (BINFO_TYPE (b))
9455          && !BINFO_LOST_PRIMARY_P (b))
9456     {
9457       tree primary_base;
9458
9459       primary_base = get_primary_binfo (b);
9460       gcc_assert (BINFO_PRIMARY_P (primary_base)
9461                   && BINFO_INHERITANCE_CHAIN (primary_base) == b);
9462       b = primary_base;
9463     }
9464   offset = size_diffop_loc (input_location,
9465                         BINFO_OFFSET (vid->rtti_binfo), BINFO_OFFSET (b));
9466
9467   /* The second entry is the address of the typeinfo object.  */
9468   if (flag_rtti)
9469     decl = build_address (get_tinfo_decl (t));
9470   else
9471     decl = integer_zero_node;
9472
9473   /* Convert the declaration to a type that can be stored in the
9474      vtable.  */
9475   init = build_nop (vfunc_ptr_type_node, decl);
9476   CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE, init);
9477
9478   /* Add the offset-to-top entry.  It comes earlier in the vtable than
9479      the typeinfo entry.  Convert the offset to look like a
9480      function pointer, so that we can put it in the vtable.  */
9481   init = build_nop (vfunc_ptr_type_node, offset);
9482   CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE, init);
9483 }
9484
9485 /* TRUE iff TYPE is uniquely derived from PARENT.  Ignores
9486    accessibility.  */
9487
9488 bool
9489 uniquely_derived_from_p (tree parent, tree type)
9490 {
9491   tree base = lookup_base (type, parent, ba_unique, NULL, tf_none);
9492   return base && base != error_mark_node;
9493 }
9494
9495 /* TRUE iff TYPE is publicly & uniquely derived from PARENT.  */
9496
9497 bool
9498 publicly_uniquely_derived_p (tree parent, tree type)
9499 {
9500   tree base = lookup_base (type, parent, ba_ignore_scope | ba_check,
9501                            NULL, tf_none);
9502   return base && base != error_mark_node;
9503 }
9504
9505 /* CTX1 and CTX2 are declaration contexts.  Return the innermost common
9506    class between them, if any.  */
9507
9508 tree
9509 common_enclosing_class (tree ctx1, tree ctx2)
9510 {
9511   if (!TYPE_P (ctx1) || !TYPE_P (ctx2))
9512     return NULL_TREE;
9513   gcc_assert (ctx1 == TYPE_MAIN_VARIANT (ctx1)
9514               && ctx2 == TYPE_MAIN_VARIANT (ctx2));
9515   if (ctx1 == ctx2)
9516     return ctx1;
9517   for (tree t = ctx1; TYPE_P (t); t = TYPE_CONTEXT (t))
9518     TYPE_MARKED_P (t) = true;
9519   tree found = NULL_TREE;
9520   for (tree t = ctx2; TYPE_P (t); t = TYPE_CONTEXT (t))
9521     if (TYPE_MARKED_P (t))
9522       {
9523         found = t;
9524         break;
9525       }
9526   for (tree t = ctx1; TYPE_P (t); t = TYPE_CONTEXT (t))
9527     TYPE_MARKED_P (t) = false;
9528   return found;
9529 }
9530
9531 #include "gt-cp-class.h"