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