1/* RunTime Type Identification
2   Copyright (C) 1995-2015 Free Software Foundation, Inc.
3   Mostly written by Jason Merrill (jason@cygnus.com).
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 3, or (at your option)
10any later version.
11
12GCC is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3.  If not see
19<http://www.gnu.org/licenses/>.  */
20
21#include "config.h"
22#include "system.h"
23#include "intl.h"
24#include "coretypes.h"
25#include "tm.h"
26#include "hash-set.h"
27#include "machmode.h"
28#include "vec.h"
29#include "double-int.h"
30#include "input.h"
31#include "alias.h"
32#include "symtab.h"
33#include "wide-int.h"
34#include "inchash.h"
35#include "tree.h"
36#include "tm_p.h"
37#include "stringpool.h"
38#include "stor-layout.h"
39#include "cp-tree.h"
40#include "flags.h"
41#include "convert.h"
42#include "target.h"
43#include "c-family/c-pragma.h"
44
45/* C++ returns type information to the user in struct type_info
46   objects. We also use type information to implement dynamic_cast and
47   exception handlers. Type information for a particular type is
48   indicated with an ABI defined structure derived from type_info.
49   This would all be very straight forward, but for the fact that the
50   runtime library provides the definitions of the type_info structure
51   and the ABI defined derived classes. We cannot build declarations
52   of them directly in the compiler, but we need to layout objects of
53   their type.  Somewhere we have to lie.
54
55   We define layout compatible POD-structs with compiler-defined names
56   and generate the appropriate initializations for them (complete
57   with explicit mention of their vtable). When we have to provide a
58   type_info to the user we reinterpret_cast the internal compiler
59   type to type_info.  A well formed program can only explicitly refer
60   to the type_infos of complete types (& cv void).  However, we chain
61   pointer type_infos to the pointed-to-type, and that can be
62   incomplete.  We only need the addresses of such incomplete
63   type_info objects for static initialization.
64
65   The type information VAR_DECL of a type is held on the
66   IDENTIFIER_GLOBAL_VALUE of the type's mangled name. That VAR_DECL
67   will be the internal type.  It will usually have the correct
68   internal type reflecting the kind of type it represents (pointer,
69   array, function, class, inherited class, etc).  When the type it
70   represents is incomplete, it will have the internal type
71   corresponding to type_info.  That will only happen at the end of
72   translation, when we are emitting the type info objects.  */
73
74/* Auxiliary data we hold for each type_info derived object we need.  */
75typedef struct GTY (()) tinfo_s {
76  tree type;  /* The RECORD_TYPE for this type_info object */
77
78  tree vtable; /* The VAR_DECL of the vtable.  Only filled at end of
79		  translation.  */
80
81  tree name;  /* IDENTIFIER_NODE for the ABI specified name of
82		 the type_info derived type.  */
83} tinfo_s;
84
85
86typedef enum tinfo_kind
87{
88  TK_TYPE_INFO_TYPE,    /* abi::__type_info_pseudo */
89  TK_BASE_TYPE,		/* abi::__base_class_type_info */
90  TK_BUILTIN_TYPE,	/* abi::__fundamental_type_info */
91  TK_ARRAY_TYPE,	/* abi::__array_type_info */
92  TK_FUNCTION_TYPE,	/* abi::__function_type_info */
93  TK_ENUMERAL_TYPE,	/* abi::__enum_type_info */
94  TK_POINTER_TYPE,	/* abi::__pointer_type_info */
95  TK_POINTER_MEMBER_TYPE, /* abi::__pointer_to_member_type_info */
96  TK_CLASS_TYPE,	/* abi::__class_type_info */
97  TK_SI_CLASS_TYPE,	/* abi::__si_class_type_info */
98  TK_FIXED		/* end of fixed descriptors. */
99  /* ...		   abi::__vmi_type_info<I> */
100} tinfo_kind;
101
102/* Helper macro to get maximum scalar-width of pointer or of the 'long'-type.
103   This of interest for llp64 targets.  */
104#define LONGPTR_T \
105  integer_types[(POINTER_SIZE <= TYPE_PRECISION (integer_types[itk_long]) \
106		 ? itk_long : itk_long_long)]
107
108/* A vector of all tinfo decls that haven't yet been emitted.  */
109vec<tree, va_gc> *unemitted_tinfo_decls;
110
111/* A vector of all type_info derived types we need.  The first few are
112   fixed and created early. The remainder are for multiple inheritance
113   and are generated as needed. */
114static GTY (()) vec<tinfo_s, va_gc> *tinfo_descs;
115
116static tree ifnonnull (tree, tree, tsubst_flags_t);
117static tree tinfo_name (tree, bool);
118static tree build_dynamic_cast_1 (tree, tree, tsubst_flags_t);
119static tree throw_bad_cast (void);
120static tree throw_bad_typeid (void);
121static tree get_tinfo_ptr (tree);
122static bool typeid_ok_p (void);
123static int qualifier_flags (tree);
124static bool target_incomplete_p (tree);
125static tree tinfo_base_init (tinfo_s *, tree);
126static tree generic_initializer (tinfo_s *, tree);
127static tree ptr_initializer (tinfo_s *, tree);
128static tree ptm_initializer (tinfo_s *, tree);
129static tree class_initializer (tinfo_s *, tree, unsigned, ...);
130static void create_pseudo_type_info (int, const char *, ...);
131static tree get_pseudo_ti_init (tree, unsigned);
132static unsigned get_pseudo_ti_index (tree);
133static void create_tinfo_types (void);
134static bool typeinfo_in_lib_p (tree);
135
136static int doing_runtime = 0;
137
138static void
139push_abi_namespace (void)
140{
141  push_nested_namespace (abi_node);
142  push_visibility ("default", 2);
143}
144
145static void
146pop_abi_namespace (void)
147{
148  pop_visibility (2);
149  pop_nested_namespace (abi_node);
150}
151
152/* Declare language defined type_info type and a pointer to const
153   type_info.  This is incomplete here, and will be completed when
154   the user #includes <typeinfo>.  There are language defined
155   restrictions on what can be done until that is included.  Create
156   the internal versions of the ABI types.  */
157
158void
159init_rtti_processing (void)
160{
161  tree type_info_type;
162
163  push_namespace (std_identifier);
164  type_info_type = xref_tag (class_type, get_identifier ("type_info"),
165			     /*tag_scope=*/ts_current, false);
166  pop_namespace ();
167  const_type_info_type_node
168    = cp_build_qualified_type (type_info_type, TYPE_QUAL_CONST);
169  type_info_ptr_type = build_pointer_type (const_type_info_type_node);
170
171  vec_alloc (unemitted_tinfo_decls, 124);
172
173  create_tinfo_types ();
174}
175
176/* Given the expression EXP of type `class *', return the head of the
177   object pointed to by EXP with type cv void*, if the class has any
178   virtual functions (TYPE_POLYMORPHIC_P), else just return the
179   expression.  */
180
181tree
182build_headof (tree exp)
183{
184  tree type = TREE_TYPE (exp);
185  tree offset;
186  tree index;
187
188  gcc_assert (TYPE_PTR_P (type));
189  type = TREE_TYPE (type);
190
191  if (!TYPE_POLYMORPHIC_P (type))
192    return exp;
193
194  /* We use this a couple of times below, protect it.  */
195  exp = save_expr (exp);
196
197  /* The offset-to-top field is at index -2 from the vptr.  */
198  index = build_int_cst (NULL_TREE,
199			 -2 * TARGET_VTABLE_DATA_ENTRY_DISTANCE);
200
201  offset = build_vtbl_ref (cp_build_indirect_ref (exp, RO_NULL,
202                                                  tf_warning_or_error),
203                           index);
204
205  type = cp_build_qualified_type (ptr_type_node,
206				  cp_type_quals (TREE_TYPE (exp)));
207  return fold_build_pointer_plus (exp, offset);
208}
209
210/* Get a bad_cast node for the program to throw...
211
212   See libstdc++/exception.cc for __throw_bad_cast */
213
214static tree
215throw_bad_cast (void)
216{
217  tree fn = get_identifier ("__cxa_bad_cast");
218  if (!get_global_value_if_present (fn, &fn))
219    fn = push_throw_library_fn (fn, build_function_type_list (ptr_type_node,
220							      NULL_TREE));
221
222  return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
223}
224
225/* Return an expression for "__cxa_bad_typeid()".  The expression
226   returned is an lvalue of type "const std::type_info".  */
227
228static tree
229throw_bad_typeid (void)
230{
231  tree fn = get_identifier ("__cxa_bad_typeid");
232  if (!get_global_value_if_present (fn, &fn))
233    {
234      tree t;
235
236      t = build_reference_type (const_type_info_type_node);
237      t = build_function_type_list (t, NULL_TREE);
238      fn = push_throw_library_fn (fn, t);
239    }
240
241  return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
242}
243
244/* Return an lvalue expression whose type is "const std::type_info"
245   and whose value indicates the type of the expression EXP.  If EXP
246   is a reference to a polymorphic class, return the dynamic type;
247   otherwise return the static type of the expression.  */
248
249static tree
250get_tinfo_decl_dynamic (tree exp, tsubst_flags_t complain)
251{
252  tree type;
253  tree t;
254
255  if (error_operand_p (exp))
256    return error_mark_node;
257
258  exp = resolve_nondeduced_context (exp, complain);
259
260  /* peel back references, so they match.  */
261  type = non_reference (TREE_TYPE (exp));
262
263  /* Peel off cv qualifiers.  */
264  type = TYPE_MAIN_VARIANT (type);
265
266  /* For UNKNOWN_TYPEs call complete_type_or_else to get diagnostics.  */
267  if (CLASS_TYPE_P (type) || type == unknown_type_node
268      || type == init_list_type_node)
269    type = complete_type_or_maybe_complain (type, exp, complain);
270
271  if (!type)
272    return error_mark_node;
273
274  /* If exp is a reference to polymorphic type, get the real type_info.  */
275  if (TYPE_POLYMORPHIC_P (type) && ! resolves_to_fixed_type_p (exp, 0))
276    {
277      /* build reference to type_info from vtable.  */
278      tree index;
279
280      /* The RTTI information is at index -1.  */
281      index = build_int_cst (NULL_TREE,
282			     -1 * TARGET_VTABLE_DATA_ENTRY_DISTANCE);
283      t = build_vtbl_ref (exp, index);
284      t = convert (type_info_ptr_type, t);
285    }
286  else
287    /* Otherwise return the type_info for the static type of the expr.  */
288    t = get_tinfo_ptr (TYPE_MAIN_VARIANT (type));
289
290  return cp_build_indirect_ref (t, RO_NULL, complain);
291}
292
293static bool
294typeid_ok_p (void)
295{
296  tree pseudo_type_info, type_info_type;
297
298  if (! flag_rtti)
299    {
300      error ("cannot use typeid with -fno-rtti");
301      return false;
302    }
303
304  if (!COMPLETE_TYPE_P (const_type_info_type_node))
305    {
306      error ("must #include <typeinfo> before using typeid");
307      return false;
308    }
309
310  pseudo_type_info = (*tinfo_descs)[TK_TYPE_INFO_TYPE].type;
311  type_info_type = TYPE_MAIN_VARIANT (const_type_info_type_node);
312
313  /* Make sure abi::__type_info_pseudo has the same alias set
314     as std::type_info.  */
315  if (! TYPE_ALIAS_SET_KNOWN_P (pseudo_type_info))
316    TYPE_ALIAS_SET (pseudo_type_info) = get_alias_set (type_info_type);
317  else
318    gcc_assert (TYPE_ALIAS_SET (pseudo_type_info)
319		== get_alias_set (type_info_type));
320
321  return true;
322}
323
324/* Return an expression for "typeid(EXP)".  The expression returned is
325   an lvalue of type "const std::type_info".  */
326
327tree
328build_typeid (tree exp, tsubst_flags_t complain)
329{
330  tree cond = NULL_TREE, initial_expr = exp;
331  int nonnull = 0;
332
333  if (exp == error_mark_node || !typeid_ok_p ())
334    return error_mark_node;
335
336  if (processing_template_decl)
337    return build_min (TYPEID_EXPR, const_type_info_type_node, exp);
338
339  /* FIXME when integrating with c_fully_fold, mark
340     resolves_to_fixed_type_p case as a non-constant expression.  */
341  if (TYPE_POLYMORPHIC_P (TREE_TYPE (exp))
342      && ! resolves_to_fixed_type_p (exp, &nonnull)
343      && ! nonnull)
344    {
345      /* So we need to look into the vtable of the type of exp.
346         Make sure it isn't a null lvalue.  */
347      exp = cp_build_addr_expr (exp, complain);
348      exp = save_expr (exp);
349      cond = cp_convert (boolean_type_node, exp, complain);
350      exp = cp_build_indirect_ref (exp, RO_NULL, complain);
351    }
352
353  exp = get_tinfo_decl_dynamic (exp, complain);
354
355  if (exp == error_mark_node)
356    return error_mark_node;
357
358  if (cond)
359    {
360      tree bad = throw_bad_typeid ();
361
362      exp = build3 (COND_EXPR, TREE_TYPE (exp), cond, exp, bad);
363    }
364  else
365    mark_type_use (initial_expr);
366
367  return exp;
368}
369
370/* Generate the NTBS name of a type.  If MARK_PRIVATE, put a '*' in front so that
371   comparisons will be done by pointer rather than string comparison.  */
372static tree
373tinfo_name (tree type, bool mark_private)
374{
375  const char *name;
376  int length;
377  tree name_string;
378
379  name = mangle_type_string (type);
380  length = strlen (name);
381
382  if (mark_private)
383    {
384      /* Inject '*' at beginning of name to force pointer comparison.  */
385      char* buf = (char*) XALLOCAVEC (char, length + 2);
386      buf[0] = '*';
387      memcpy (buf + 1, name, length + 1);
388      name_string = build_string (length + 2, buf);
389    }
390  else
391    name_string = build_string (length + 1, name);
392
393  return fix_string_type (name_string);
394}
395
396/* Return a VAR_DECL for the internal ABI defined type_info object for
397   TYPE. You must arrange that the decl is mark_used, if actually use
398   it --- decls in vtables are only used if the vtable is output.  */
399
400tree
401get_tinfo_decl (tree type)
402{
403  tree name;
404  tree d;
405
406  if (variably_modified_type_p (type, /*fn=*/NULL_TREE))
407    {
408      error ("cannot create type information for type %qT because "
409	     "it involves types of variable size",
410	     type);
411      return error_mark_node;
412    }
413
414  if (TREE_CODE (type) == METHOD_TYPE)
415    type = build_function_type (TREE_TYPE (type),
416				TREE_CHAIN (TYPE_ARG_TYPES (type)));
417
418  type = complete_type (type);
419
420  /* For a class type, the variable is cached in the type node
421     itself.  */
422  if (CLASS_TYPE_P (type))
423    {
424      d = CLASSTYPE_TYPEINFO_VAR (TYPE_MAIN_VARIANT (type));
425      if (d)
426	return d;
427    }
428
429  name = mangle_typeinfo_for_type (type);
430
431  d = IDENTIFIER_GLOBAL_VALUE (name);
432  if (!d)
433    {
434      int ix = get_pseudo_ti_index (type);
435      tinfo_s *ti = &(*tinfo_descs)[ix];
436
437      d = build_lang_decl (VAR_DECL, name, ti->type);
438      SET_DECL_ASSEMBLER_NAME (d, name);
439      /* Remember the type it is for.  */
440      TREE_TYPE (name) = type;
441      DECL_TINFO_P (d) = 1;
442      DECL_ARTIFICIAL (d) = 1;
443      DECL_IGNORED_P (d) = 1;
444      TREE_READONLY (d) = 1;
445      TREE_STATIC (d) = 1;
446      /* Mark the variable as undefined -- but remember that we can
447	 define it later if we need to do so.  */
448      DECL_EXTERNAL (d) = 1;
449      DECL_NOT_REALLY_EXTERN (d) = 1;
450      set_linkage_according_to_type (type, d);
451
452      d = pushdecl_top_level_and_finish (d, NULL_TREE);
453      if (CLASS_TYPE_P (type))
454	CLASSTYPE_TYPEINFO_VAR (TYPE_MAIN_VARIANT (type)) = d;
455
456      /* Add decl to the global array of tinfo decls.  */
457      vec_safe_push (unemitted_tinfo_decls, d);
458    }
459
460  return d;
461}
462
463/* Return a pointer to a type_info object describing TYPE, suitably
464   cast to the language defined type.  */
465
466static tree
467get_tinfo_ptr (tree type)
468{
469  tree decl = get_tinfo_decl (type);
470
471  mark_used (decl);
472  return build_nop (type_info_ptr_type,
473		    build_address (decl));
474}
475
476/* Return the type_info object for TYPE.  */
477
478tree
479get_typeid (tree type, tsubst_flags_t complain)
480{
481  if (type == error_mark_node || !typeid_ok_p ())
482    return error_mark_node;
483
484  if (processing_template_decl)
485    return build_min (TYPEID_EXPR, const_type_info_type_node, type);
486
487  /* If the type of the type-id is a reference type, the result of the
488     typeid expression refers to a type_info object representing the
489     referenced type.  */
490  type = non_reference (type);
491
492  /* This is not one of the uses of a qualified function type in 8.3.5.  */
493  if (TREE_CODE (type) == FUNCTION_TYPE
494      && (type_memfn_quals (type) != TYPE_UNQUALIFIED
495	  || type_memfn_rqual (type) != REF_QUAL_NONE))
496    {
497      if (complain & tf_error)
498	error ("typeid of qualified function type %qT", type);
499      return error_mark_node;
500    }
501
502  /* The top-level cv-qualifiers of the lvalue expression or the type-id
503     that is the operand of typeid are always ignored.  */
504  type = TYPE_MAIN_VARIANT (type);
505
506  /* For UNKNOWN_TYPEs call complete_type_or_else to get diagnostics.  */
507  if (CLASS_TYPE_P (type) || type == unknown_type_node
508      || type == init_list_type_node)
509    type = complete_type_or_maybe_complain (type, NULL_TREE, complain);
510
511  if (!type)
512    return error_mark_node;
513
514  return cp_build_indirect_ref (get_tinfo_ptr (type), RO_NULL, complain);
515}
516
517/* Check whether TEST is null before returning RESULT.  If TEST is used in
518   RESULT, it must have previously had a save_expr applied to it.  */
519
520static tree
521ifnonnull (tree test, tree result, tsubst_flags_t complain)
522{
523  return build3 (COND_EXPR, TREE_TYPE (result),
524		 build2 (EQ_EXPR, boolean_type_node, test,
525			 cp_convert (TREE_TYPE (test), nullptr_node,
526				     complain)),
527		 cp_convert (TREE_TYPE (result), nullptr_node, complain),
528		 result);
529}
530
531/* Execute a dynamic cast, as described in section 5.2.6 of the 9/93 working
532   paper.  */
533
534static tree
535build_dynamic_cast_1 (tree type, tree expr, tsubst_flags_t complain)
536{
537  enum tree_code tc = TREE_CODE (type);
538  tree exprtype;
539  tree dcast_fn;
540  tree old_expr = expr;
541  const char *errstr = NULL;
542
543  /* Save casted types in the function's used types hash table.  */
544  used_types_insert (type);
545
546  /* T shall be a pointer or reference to a complete class type, or
547     `pointer to cv void''.  */
548  switch (tc)
549    {
550    case POINTER_TYPE:
551      if (VOID_TYPE_P (TREE_TYPE (type)))
552	break;
553      /* Fall through.  */
554    case REFERENCE_TYPE:
555      if (! MAYBE_CLASS_TYPE_P (TREE_TYPE (type)))
556	{
557	  errstr = _("target is not pointer or reference to class");
558	  goto fail;
559	}
560      if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
561	{
562	  errstr = _("target is not pointer or reference to complete type");
563	  goto fail;
564	}
565      break;
566
567    default:
568      errstr = _("target is not pointer or reference");
569      goto fail;
570    }
571
572  if (tc == POINTER_TYPE)
573    {
574      expr = decay_conversion (expr, complain);
575      exprtype = TREE_TYPE (expr);
576
577      /* If T is a pointer type, v shall be an rvalue of a pointer to
578	 complete class type, and the result is an rvalue of type T.  */
579
580      expr = mark_rvalue_use (expr);
581
582      if (!TYPE_PTR_P (exprtype))
583	{
584	  errstr = _("source is not a pointer");
585	  goto fail;
586	}
587      if (! MAYBE_CLASS_TYPE_P (TREE_TYPE (exprtype)))
588	{
589	  errstr = _("source is not a pointer to class");
590	  goto fail;
591	}
592      if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (exprtype))))
593	{
594	  errstr = _("source is a pointer to incomplete type");
595	  goto fail;
596	}
597    }
598  else
599    {
600      expr = mark_lvalue_use (expr);
601
602      exprtype = build_reference_type (TREE_TYPE (expr));
603
604      /* T is a reference type, v shall be an lvalue of a complete class
605	 type, and the result is an lvalue of the type referred to by T.  */
606
607      if (! MAYBE_CLASS_TYPE_P (TREE_TYPE (exprtype)))
608	{
609	  errstr = _("source is not of class type");
610	  goto fail;
611	}
612      if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (exprtype))))
613	{
614	  errstr = _("source is of incomplete class type");
615	  goto fail;
616	}
617    }
618
619  /* The dynamic_cast operator shall not cast away constness.  */
620  if (!at_least_as_qualified_p (TREE_TYPE (type),
621				TREE_TYPE (exprtype)))
622    {
623      errstr = _("conversion casts away constness");
624      goto fail;
625    }
626
627  /* If *type is an unambiguous accessible base class of *exprtype,
628     convert statically.  */
629  {
630    tree binfo = lookup_base (TREE_TYPE (exprtype), TREE_TYPE (type),
631			      ba_check, NULL, complain);
632    if (binfo)
633      return build_static_cast (type, expr, complain);
634  }
635
636  /* Apply trivial conversion T -> T& for dereferenced ptrs.  */
637  if (tc == REFERENCE_TYPE)
638    expr = convert_to_reference (exprtype, expr, CONV_IMPLICIT,
639				 LOOKUP_NORMAL, NULL_TREE, complain);
640
641  /* Otherwise *exprtype must be a polymorphic class (have a vtbl).  */
642  if (TYPE_POLYMORPHIC_P (TREE_TYPE (exprtype)))
643    {
644      tree expr1;
645      /* if TYPE is `void *', return pointer to complete object.  */
646      if (tc == POINTER_TYPE && VOID_TYPE_P (TREE_TYPE (type)))
647	{
648	  /* if b is an object, dynamic_cast<void *>(&b) == (void *)&b.  */
649	  if (TREE_CODE (expr) == ADDR_EXPR
650	      && VAR_P (TREE_OPERAND (expr, 0))
651	      && TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == RECORD_TYPE)
652	    return build1 (NOP_EXPR, type, expr);
653
654	  /* Since expr is used twice below, save it.  */
655	  expr = save_expr (expr);
656
657	  expr1 = build_headof (expr);
658	  if (TREE_TYPE (expr1) != type)
659	    expr1 = build1 (NOP_EXPR, type, expr1);
660	  return ifnonnull (expr, expr1, complain);
661	}
662      else
663	{
664	  tree retval;
665	  tree result, td2, td3;
666	  tree elems[4];
667	  tree static_type, target_type, boff;
668
669	  /* If we got here, we can't convert statically.  Therefore,
670	     dynamic_cast<D&>(b) (b an object) cannot succeed.  */
671	  if (tc == REFERENCE_TYPE)
672	    {
673	      if (VAR_P (old_expr)
674		  && TREE_CODE (TREE_TYPE (old_expr)) == RECORD_TYPE)
675		{
676		  tree expr = throw_bad_cast ();
677                  if (complain & tf_warning)
678                    warning (0, "dynamic_cast of %q#D to %q#T can never succeed",
679                             old_expr, type);
680		  /* Bash it to the expected type.  */
681		  TREE_TYPE (expr) = type;
682		  return expr;
683		}
684	    }
685	  /* Ditto for dynamic_cast<D*>(&b).  */
686	  else if (TREE_CODE (expr) == ADDR_EXPR)
687	    {
688	      tree op = TREE_OPERAND (expr, 0);
689	      if (VAR_P (op)
690		  && TREE_CODE (TREE_TYPE (op)) == RECORD_TYPE)
691		{
692                  if (complain & tf_warning)
693                    warning (0, "dynamic_cast of %q#D to %q#T can never succeed",
694                             op, type);
695		  retval = build_int_cst (type, 0);
696		  return retval;
697		}
698	    }
699
700	  /* Use of dynamic_cast when -fno-rtti is prohibited.  */
701	  if (!flag_rtti)
702	    {
703              if (complain & tf_error)
704                error ("%<dynamic_cast%> not permitted with -fno-rtti");
705	      return error_mark_node;
706	    }
707
708	  target_type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
709	  static_type = TYPE_MAIN_VARIANT (TREE_TYPE (exprtype));
710	  td2 = get_tinfo_decl (target_type);
711	  if (!mark_used (td2, complain) && !(complain & tf_error))
712	    return error_mark_node;
713	  td2 = cp_build_addr_expr (td2, complain);
714	  td3 = get_tinfo_decl (static_type);
715	  if (!mark_used (td3, complain) && !(complain & tf_error))
716	    return error_mark_node;
717	  td3 = cp_build_addr_expr (td3, complain);
718
719	  /* Determine how T and V are related.  */
720	  boff = dcast_base_hint (static_type, target_type);
721
722	  /* Since expr is used twice below, save it.  */
723	  expr = save_expr (expr);
724
725	  expr1 = expr;
726	  if (tc == REFERENCE_TYPE)
727	    expr1 = cp_build_addr_expr (expr1, complain);
728
729	  elems[0] = expr1;
730	  elems[1] = td3;
731	  elems[2] = td2;
732	  elems[3] = boff;
733
734	  dcast_fn = dynamic_cast_node;
735	  if (!dcast_fn)
736	    {
737	      tree tmp;
738	      tree tinfo_ptr;
739	      const char *name;
740
741	      push_abi_namespace ();
742	      tinfo_ptr = xref_tag (class_type,
743				    get_identifier ("__class_type_info"),
744				    /*tag_scope=*/ts_current, false);
745
746	      tinfo_ptr = build_pointer_type
747		(cp_build_qualified_type
748		 (tinfo_ptr, TYPE_QUAL_CONST));
749	      name = "__dynamic_cast";
750	      tmp = build_function_type_list (ptr_type_node,
751					      const_ptr_type_node,
752					      tinfo_ptr, tinfo_ptr,
753					      ptrdiff_type_node, NULL_TREE);
754	      dcast_fn = build_library_fn_ptr (name, tmp,
755					       ECF_LEAF | ECF_PURE | ECF_NOTHROW);
756	      pop_abi_namespace ();
757	      dynamic_cast_node = dcast_fn;
758	    }
759	  result = build_cxx_call (dcast_fn, 4, elems, complain);
760
761	  if (tc == REFERENCE_TYPE)
762	    {
763	      tree bad = throw_bad_cast ();
764	      tree neq;
765
766	      result = save_expr (result);
767	      neq = cp_truthvalue_conversion (result);
768	      return cp_convert (type,
769				 build3 (COND_EXPR, TREE_TYPE (result),
770					 neq, result, bad), complain);
771	    }
772
773	  /* Now back to the type we want from a void*.  */
774	  result = cp_convert (type, result, complain);
775	  return ifnonnull (expr, result, complain);
776	}
777    }
778  else
779    errstr = _("source type is not polymorphic");
780
781 fail:
782  if (complain & tf_error)
783    error ("cannot dynamic_cast %qE (of type %q#T) to type %q#T (%s)",
784           old_expr, TREE_TYPE (old_expr), type, errstr);
785  return error_mark_node;
786}
787
788tree
789build_dynamic_cast (tree type, tree expr, tsubst_flags_t complain)
790{
791  tree r;
792
793  if (type == error_mark_node || expr == error_mark_node)
794    return error_mark_node;
795
796  if (processing_template_decl)
797    {
798      expr = build_min (DYNAMIC_CAST_EXPR, type, expr);
799      TREE_SIDE_EFFECTS (expr) = 1;
800      return convert_from_reference (expr);
801    }
802
803  r = convert_from_reference (build_dynamic_cast_1 (type, expr, complain));
804  if (r != error_mark_node)
805    maybe_warn_about_useless_cast (type, expr, complain);
806  return r;
807}
808
809/* Return the runtime bit mask encoding the qualifiers of TYPE.  */
810
811static int
812qualifier_flags (tree type)
813{
814  int flags = 0;
815  int quals = cp_type_quals (type);
816
817  if (quals & TYPE_QUAL_CONST)
818    flags |= 1;
819  if (quals & TYPE_QUAL_VOLATILE)
820    flags |= 2;
821  if (quals & TYPE_QUAL_RESTRICT)
822    flags |= 4;
823  return flags;
824}
825
826/* Return true, if the pointer chain TYPE ends at an incomplete type, or
827   contains a pointer to member of an incomplete class.  */
828
829static bool
830target_incomplete_p (tree type)
831{
832  while (true)
833    if (TYPE_PTRDATAMEM_P (type))
834      {
835	if (!COMPLETE_TYPE_P (TYPE_PTRMEM_CLASS_TYPE (type)))
836	  return true;
837	type = TYPE_PTRMEM_POINTED_TO_TYPE (type);
838      }
839    else if (TYPE_PTR_P (type))
840      type = TREE_TYPE (type);
841    else
842      return !COMPLETE_OR_VOID_TYPE_P (type);
843}
844
845/* Returns true if TYPE involves an incomplete class type; in that
846   case, typeinfo variables for TYPE should be emitted with internal
847   linkage.  */
848
849static bool
850involves_incomplete_p (tree type)
851{
852  switch (TREE_CODE (type))
853    {
854    case POINTER_TYPE:
855      return target_incomplete_p (TREE_TYPE (type));
856
857    case OFFSET_TYPE:
858    ptrmem:
859      return
860	(target_incomplete_p (TYPE_PTRMEM_POINTED_TO_TYPE (type))
861	 || !COMPLETE_TYPE_P (TYPE_PTRMEM_CLASS_TYPE (type)));
862
863    case RECORD_TYPE:
864      if (TYPE_PTRMEMFUNC_P (type))
865	goto ptrmem;
866      /* Fall through.  */
867    case UNION_TYPE:
868      if (!COMPLETE_TYPE_P (type))
869	return true;
870
871    default:
872      /* All other types do not involve incomplete class types.  */
873      return false;
874    }
875}
876
877/* Return a CONSTRUCTOR for the common part of the type_info objects. This
878   is the vtable pointer and NTBS name.  The NTBS name is emitted as a
879   comdat const char array, so it becomes a unique key for the type. Generate
880   and emit that VAR_DECL here.  (We can't always emit the type_info itself
881   as comdat, because of pointers to incomplete.) */
882
883static tree
884tinfo_base_init (tinfo_s *ti, tree target)
885{
886  tree init;
887  tree name_decl;
888  tree vtable_ptr;
889  vec<constructor_elt, va_gc> *v;
890
891  {
892    tree name_name, name_string;
893
894    /* Generate the NTBS array variable.  */
895    tree name_type = build_cplus_array_type
896		     (cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST),
897		     NULL_TREE);
898
899    /* Determine the name of the variable -- and remember with which
900       type it is associated.  */
901    name_name = mangle_typeinfo_string_for_type (target);
902    TREE_TYPE (name_name) = target;
903
904    name_decl = build_lang_decl (VAR_DECL, name_name, name_type);
905    SET_DECL_ASSEMBLER_NAME (name_decl, name_name);
906    DECL_ARTIFICIAL (name_decl) = 1;
907    DECL_IGNORED_P (name_decl) = 1;
908    TREE_READONLY (name_decl) = 1;
909    TREE_STATIC (name_decl) = 1;
910    DECL_EXTERNAL (name_decl) = 0;
911    DECL_TINFO_P (name_decl) = 1;
912    set_linkage_according_to_type (target, name_decl);
913    import_export_decl (name_decl);
914    name_string = tinfo_name (target, !TREE_PUBLIC (name_decl));
915    DECL_INITIAL (name_decl) = name_string;
916    mark_used (name_decl);
917    pushdecl_top_level_and_finish (name_decl, name_string);
918  }
919
920  vtable_ptr = ti->vtable;
921  if (!vtable_ptr)
922    {
923      tree real_type;
924      push_abi_namespace ();
925      real_type = xref_tag (class_type, ti->name,
926			    /*tag_scope=*/ts_current, false);
927      pop_abi_namespace ();
928
929      if (!COMPLETE_TYPE_P (real_type))
930	{
931	  /* We never saw a definition of this type, so we need to
932	     tell the compiler that this is an exported class, as
933	     indeed all of the __*_type_info classes are.  */
934	  SET_CLASSTYPE_INTERFACE_KNOWN (real_type);
935	  CLASSTYPE_INTERFACE_ONLY (real_type) = 1;
936	}
937
938      vtable_ptr = get_vtable_decl (real_type, /*complete=*/1);
939      vtable_ptr = cp_build_addr_expr (vtable_ptr, tf_warning_or_error);
940
941      /* We need to point into the middle of the vtable.  */
942      vtable_ptr = fold_build_pointer_plus
943	(vtable_ptr,
944	 size_binop (MULT_EXPR,
945		     size_int (2 * TARGET_VTABLE_DATA_ENTRY_DISTANCE),
946		     TYPE_SIZE_UNIT (vtable_entry_type)));
947
948      ti->vtable = vtable_ptr;
949    }
950
951  vec_alloc (v, 2);
952  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, vtable_ptr);
953  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
954			  decay_conversion (name_decl, tf_warning_or_error));
955
956  init = build_constructor (init_list_type_node, v);
957  TREE_CONSTANT (init) = 1;
958  TREE_STATIC (init) = 1;
959
960  return init;
961}
962
963/* Return the CONSTRUCTOR expr for a type_info of TYPE. TI provides the
964   information about the particular type_info derivation, which adds no
965   additional fields to the type_info base.  */
966
967static tree
968generic_initializer (tinfo_s *ti, tree target)
969{
970  tree init = tinfo_base_init (ti, target);
971
972  init = build_constructor_single (init_list_type_node, NULL_TREE, init);
973  TREE_CONSTANT (init) = 1;
974  TREE_STATIC (init) = 1;
975  return init;
976}
977
978/* Return the CONSTRUCTOR expr for a type_info of pointer TYPE.
979   TI provides information about the particular type_info derivation,
980   which adds target type and qualifier flags members to the type_info base.  */
981
982static tree
983ptr_initializer (tinfo_s *ti, tree target)
984{
985  tree init = tinfo_base_init (ti, target);
986  tree to = TREE_TYPE (target);
987  int flags = qualifier_flags (to);
988  bool incomplete = target_incomplete_p (to);
989  vec<constructor_elt, va_gc> *v;
990  vec_alloc (v, 3);
991
992  if (incomplete)
993    flags |= 8;
994  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
995  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, build_int_cst (NULL_TREE, flags));
996  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
997                          get_tinfo_ptr (TYPE_MAIN_VARIANT (to)));
998
999  init = build_constructor (init_list_type_node, v);
1000  TREE_CONSTANT (init) = 1;
1001  TREE_STATIC (init) = 1;
1002  return init;
1003}
1004
1005/* Return the CONSTRUCTOR expr for a type_info of pointer to member data TYPE.
1006   TI provides information about the particular type_info derivation,
1007   which adds class, target type and qualifier flags members to the type_info
1008   base.  */
1009
1010static tree
1011ptm_initializer (tinfo_s *ti, tree target)
1012{
1013  tree init = tinfo_base_init (ti, target);
1014  tree to = TYPE_PTRMEM_POINTED_TO_TYPE (target);
1015  tree klass = TYPE_PTRMEM_CLASS_TYPE (target);
1016  int flags = qualifier_flags (to);
1017  bool incomplete = target_incomplete_p (to);
1018  vec<constructor_elt, va_gc> *v;
1019  vec_alloc (v, 4);
1020
1021  if (incomplete)
1022    flags |= 0x8;
1023  if (!COMPLETE_TYPE_P (klass))
1024    flags |= 0x10;
1025  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
1026  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, build_int_cst (NULL_TREE, flags));
1027  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
1028                          get_tinfo_ptr (TYPE_MAIN_VARIANT (to)));
1029  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, get_tinfo_ptr (klass));
1030
1031  init = build_constructor (init_list_type_node, v);
1032  TREE_CONSTANT (init) = 1;
1033  TREE_STATIC (init) = 1;
1034  return init;
1035}
1036
1037/* Return the CONSTRUCTOR expr for a type_info of class TYPE.
1038   TI provides information about the particular __class_type_info derivation,
1039   which adds hint flags and N extra initializers to the type_info base.  */
1040
1041static tree
1042class_initializer (tinfo_s *ti, tree target, unsigned n, ...)
1043{
1044  tree init = tinfo_base_init (ti, target);
1045  va_list extra_inits;
1046  unsigned i;
1047  vec<constructor_elt, va_gc> *v;
1048  vec_alloc (v, n+1);
1049
1050  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
1051  va_start (extra_inits, n);
1052  for (i = 0; i < n; i++)
1053    CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, va_arg (extra_inits, tree));
1054  va_end (extra_inits);
1055
1056  init = build_constructor (init_list_type_node, v);
1057  TREE_CONSTANT (init) = 1;
1058  TREE_STATIC (init) = 1;
1059  return init;
1060}
1061
1062/* Returns true if the typeinfo for type should be placed in
1063   the runtime library.  */
1064
1065static bool
1066typeinfo_in_lib_p (tree type)
1067{
1068  /* The typeinfo objects for `T*' and `const T*' are in the runtime
1069     library for simple types T.  */
1070  if (TYPE_PTR_P (type)
1071      && (cp_type_quals (TREE_TYPE (type)) == TYPE_QUAL_CONST
1072	  || cp_type_quals (TREE_TYPE (type)) == TYPE_UNQUALIFIED))
1073    type = TREE_TYPE (type);
1074
1075  switch (TREE_CODE (type))
1076    {
1077    case INTEGER_TYPE:
1078    case BOOLEAN_TYPE:
1079    case REAL_TYPE:
1080    case VOID_TYPE:
1081    case NULLPTR_TYPE:
1082      return true;
1083
1084    case LANG_TYPE:
1085      /* fall through.  */
1086
1087    default:
1088      return false;
1089    }
1090}
1091
1092/* Generate the initializer for the type info describing TYPE.  TK_INDEX is
1093   the index of the descriptor in the tinfo_desc vector. */
1094
1095static tree
1096get_pseudo_ti_init (tree type, unsigned tk_index)
1097{
1098  tinfo_s *ti = &(*tinfo_descs)[tk_index];
1099
1100  gcc_assert (at_eof);
1101  switch (tk_index)
1102    {
1103    case TK_POINTER_MEMBER_TYPE:
1104      return ptm_initializer (ti, type);
1105
1106    case TK_POINTER_TYPE:
1107      return ptr_initializer (ti, type);
1108
1109    case TK_BUILTIN_TYPE:
1110    case TK_ENUMERAL_TYPE:
1111    case TK_FUNCTION_TYPE:
1112    case TK_ARRAY_TYPE:
1113      return generic_initializer (ti, type);
1114
1115    case TK_CLASS_TYPE:
1116      return class_initializer (ti, type, 0);
1117
1118    case TK_SI_CLASS_TYPE:
1119      {
1120	tree base_binfo = BINFO_BASE_BINFO (TYPE_BINFO (type), 0);
1121	tree tinfo = get_tinfo_ptr (BINFO_TYPE (base_binfo));
1122
1123	/* get_tinfo_ptr might have reallocated the tinfo_descs vector.  */
1124	ti = &(*tinfo_descs)[tk_index];
1125	return class_initializer (ti, type, 1, tinfo);
1126      }
1127
1128    default:
1129      {
1130	int hint = ((CLASSTYPE_REPEATED_BASE_P (type) << 0)
1131		    | (CLASSTYPE_DIAMOND_SHAPED_P (type) << 1));
1132	tree binfo = TYPE_BINFO (type);
1133	int nbases = BINFO_N_BASE_BINFOS (binfo);
1134	vec<tree, va_gc> *base_accesses = BINFO_BASE_ACCESSES (binfo);
1135	tree offset_type = LONGPTR_T;
1136	tree base_inits = NULL_TREE;
1137	int ix;
1138	vec<constructor_elt, va_gc> *init_vec = NULL;
1139	constructor_elt *e;
1140
1141	gcc_assert (tk_index >= TK_FIXED);
1142
1143	vec_safe_grow (init_vec, nbases);
1144	/* Generate the base information initializer.  */
1145	for (ix = nbases; ix--;)
1146	  {
1147	    tree base_binfo = BINFO_BASE_BINFO (binfo, ix);
1148	    tree base_init;
1149	    int flags = 0;
1150	    tree tinfo;
1151	    tree offset;
1152	    vec<constructor_elt, va_gc> *v;
1153
1154	    if ((*base_accesses)[ix] == access_public_node)
1155	      flags |= 2;
1156	    tinfo = get_tinfo_ptr (BINFO_TYPE (base_binfo));
1157	    if (BINFO_VIRTUAL_P (base_binfo))
1158	      {
1159		/* We store the vtable offset at which the virtual
1160		   base offset can be found.  */
1161		offset = BINFO_VPTR_FIELD (base_binfo);
1162		flags |= 1;
1163	      }
1164	    else
1165	      offset = BINFO_OFFSET (base_binfo);
1166
1167	    /* Combine offset and flags into one field.  */
1168	    offset = fold_convert (offset_type, offset);
1169	    offset = fold_build2_loc (input_location,
1170				  LSHIFT_EXPR, offset_type, offset,
1171				  build_int_cst (offset_type, 8));
1172	    offset = fold_build2_loc (input_location,
1173				  BIT_IOR_EXPR, offset_type, offset,
1174				  build_int_cst (offset_type, flags));
1175	    vec_alloc (v, 2);
1176	    CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, tinfo);
1177	    CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, offset);
1178	    base_init = build_constructor (init_list_type_node, v);
1179	    e = &(*init_vec)[ix];
1180	    e->index = NULL_TREE;
1181	    e->value = base_init;
1182	  }
1183	base_inits = build_constructor (init_list_type_node, init_vec);
1184
1185	/* get_tinfo_ptr might have reallocated the tinfo_descs vector.  */
1186	ti = &(*tinfo_descs)[tk_index];
1187	return class_initializer (ti, type, 3,
1188				  build_int_cst (NULL_TREE, hint),
1189				  build_int_cst (NULL_TREE, nbases),
1190				  base_inits);
1191      }
1192    }
1193}
1194
1195/* Generate the RECORD_TYPE containing the data layout of a type_info
1196   derivative as used by the runtime. This layout must be consistent with
1197   that defined in the runtime support. Also generate the VAR_DECL for the
1198   type's vtable. We explicitly manage the vtable member, and name it for
1199   real type as used in the runtime. The RECORD type has a different name,
1200   to avoid collisions.  Return a TREE_LIST who's TINFO_PSEUDO_TYPE
1201   is the generated type and TINFO_VTABLE_NAME is the name of the
1202   vtable.  We have to delay generating the VAR_DECL of the vtable
1203   until the end of the translation, when we'll have seen the library
1204   definition, if there was one.
1205
1206   REAL_NAME is the runtime's name of the type. Trailing arguments are
1207   additional FIELD_DECL's for the structure. The final argument must be
1208   NULL.  */
1209
1210static void
1211create_pseudo_type_info (int tk, const char *real_name, ...)
1212{
1213  tinfo_s *ti;
1214  tree pseudo_type;
1215  char *pseudo_name;
1216  tree fields;
1217  tree field_decl;
1218  va_list ap;
1219
1220  va_start (ap, real_name);
1221
1222  /* Generate the pseudo type name.  */
1223  pseudo_name = (char *) alloca (strlen (real_name) + 30);
1224  strcpy (pseudo_name, real_name);
1225  strcat (pseudo_name, "_pseudo");
1226  if (tk >= TK_FIXED)
1227    sprintf (pseudo_name + strlen (pseudo_name), "%d", tk - TK_FIXED);
1228
1229  /* First field is the pseudo type_info base class.  */
1230  fields = build_decl (input_location,
1231		       FIELD_DECL, NULL_TREE,
1232		       (*tinfo_descs)[TK_TYPE_INFO_TYPE].type);
1233
1234  /* Now add the derived fields.  */
1235  while ((field_decl = va_arg (ap, tree)))
1236    {
1237      DECL_CHAIN (field_decl) = fields;
1238      fields = field_decl;
1239    }
1240
1241  /* Create the pseudo type.  */
1242  pseudo_type = make_class_type (RECORD_TYPE);
1243  finish_builtin_struct (pseudo_type, pseudo_name, fields, NULL_TREE);
1244  CLASSTYPE_AS_BASE (pseudo_type) = pseudo_type;
1245
1246  ti = &(*tinfo_descs)[tk];
1247  ti->type = cp_build_qualified_type (pseudo_type, TYPE_QUAL_CONST);
1248  ti->name = get_identifier (real_name);
1249  ti->vtable = NULL_TREE;
1250
1251  /* Pretend this is public so determine_visibility doesn't give vtables
1252     internal linkage.  */
1253  TREE_PUBLIC (TYPE_MAIN_DECL (ti->type)) = 1;
1254
1255  va_end (ap);
1256}
1257
1258/* Return the index of a pseudo type info type node used to describe
1259   TYPE.  TYPE must be a complete type (or cv void), except at the end
1260   of the translation unit.  */
1261
1262static unsigned
1263get_pseudo_ti_index (tree type)
1264{
1265  unsigned ix;
1266
1267  switch (TREE_CODE (type))
1268    {
1269    case OFFSET_TYPE:
1270      ix = TK_POINTER_MEMBER_TYPE;
1271      break;
1272
1273    case POINTER_TYPE:
1274      ix = TK_POINTER_TYPE;
1275      break;
1276
1277    case ENUMERAL_TYPE:
1278      ix = TK_ENUMERAL_TYPE;
1279      break;
1280
1281    case FUNCTION_TYPE:
1282      ix = TK_FUNCTION_TYPE;
1283      break;
1284
1285    case ARRAY_TYPE:
1286      ix = TK_ARRAY_TYPE;
1287      break;
1288
1289    case UNION_TYPE:
1290    case RECORD_TYPE:
1291      if (TYPE_PTRMEMFUNC_P (type))
1292	{
1293	  ix = TK_POINTER_MEMBER_TYPE;
1294	  break;
1295	}
1296      else if (!COMPLETE_TYPE_P (type))
1297	{
1298	  if (!at_eof)
1299	    cxx_incomplete_type_error (NULL_TREE, type);
1300	  ix = TK_CLASS_TYPE;
1301	  break;
1302	}
1303      else if (!BINFO_N_BASE_BINFOS (TYPE_BINFO (type)))
1304	{
1305	  ix = TK_CLASS_TYPE;
1306	  break;
1307	}
1308      else
1309	{
1310	  tree binfo = TYPE_BINFO (type);
1311	  vec<tree, va_gc> *base_accesses = BINFO_BASE_ACCESSES (binfo);
1312	  tree base_binfo = BINFO_BASE_BINFO (binfo, 0);
1313	  int num_bases = BINFO_N_BASE_BINFOS (binfo);
1314
1315	  if (num_bases == 1
1316	      && (*base_accesses)[0] == access_public_node
1317	      && !BINFO_VIRTUAL_P (base_binfo)
1318	      && integer_zerop (BINFO_OFFSET (base_binfo)))
1319	    {
1320	      /* single non-virtual public.  */
1321	      ix = TK_SI_CLASS_TYPE;
1322	      break;
1323	    }
1324	  else
1325	    {
1326	      tinfo_s *ti;
1327	      tree array_domain, base_array;
1328
1329	      ix = TK_FIXED + num_bases;
1330	      if (vec_safe_length (tinfo_descs) <= ix)
1331		{
1332		  /* too short, extend.  */
1333		  unsigned len = vec_safe_length (tinfo_descs);
1334
1335		  vec_safe_grow (tinfo_descs, ix + 1);
1336		  while (tinfo_descs->iterate (len++, &ti))
1337		    ti->type = ti->vtable = ti->name = NULL_TREE;
1338		}
1339	      else if ((*tinfo_descs)[ix].type)
1340		/* already created.  */
1341		break;
1342
1343	      /* Create the array of __base_class_type_info entries.  */
1344	      array_domain = build_index_type (size_int (num_bases - 1));
1345	      base_array = build_array_type ((*tinfo_descs)[TK_BASE_TYPE].type,
1346					     array_domain);
1347
1348	      push_abi_namespace ();
1349	      create_pseudo_type_info
1350		(ix, "__vmi_class_type_info",
1351		 build_decl (input_location,
1352			     FIELD_DECL, NULL_TREE, integer_type_node),
1353		 build_decl (input_location,
1354			     FIELD_DECL, NULL_TREE, integer_type_node),
1355		 build_decl (input_location,
1356			     FIELD_DECL, NULL_TREE, base_array),
1357		 NULL);
1358	      pop_abi_namespace ();
1359	      break;
1360	    }
1361	}
1362    default:
1363      ix = TK_BUILTIN_TYPE;
1364      break;
1365    }
1366  return ix;
1367}
1368
1369/* Make sure the required builtin types exist for generating the type_info
1370   variable definitions.  */
1371
1372static void
1373create_tinfo_types (void)
1374{
1375  tinfo_s *ti;
1376
1377  gcc_assert (!tinfo_descs);
1378
1379  vec_safe_grow (tinfo_descs, TK_FIXED);
1380
1381  push_abi_namespace ();
1382
1383  /* Create the internal type_info structure. This is used as a base for
1384     the other structures.  */
1385  {
1386    tree field, fields;
1387
1388    field = build_decl (BUILTINS_LOCATION,
1389			FIELD_DECL, NULL_TREE, const_ptr_type_node);
1390    fields = field;
1391
1392    field = build_decl (BUILTINS_LOCATION,
1393			FIELD_DECL, NULL_TREE, const_string_type_node);
1394    DECL_CHAIN (field) = fields;
1395    fields = field;
1396
1397    ti = &(*tinfo_descs)[TK_TYPE_INFO_TYPE];
1398    ti->type = make_class_type (RECORD_TYPE);
1399    ti->vtable = NULL_TREE;
1400    ti->name = NULL_TREE;
1401    finish_builtin_struct (ti->type, "__type_info_pseudo",
1402			   fields, NULL_TREE);
1403  }
1404
1405  /* Fundamental type_info */
1406  create_pseudo_type_info (TK_BUILTIN_TYPE, "__fundamental_type_info", NULL);
1407
1408  /* Array, function and enum type_info. No additional fields.  */
1409  create_pseudo_type_info (TK_ARRAY_TYPE, "__array_type_info", NULL);
1410  create_pseudo_type_info (TK_FUNCTION_TYPE, "__function_type_info", NULL);
1411  create_pseudo_type_info (TK_ENUMERAL_TYPE, "__enum_type_info", NULL);
1412
1413  /* Class type_info.  No additional fields.  */
1414  create_pseudo_type_info (TK_CLASS_TYPE, "__class_type_info", NULL);
1415
1416  /* Single public non-virtual base class. Add pointer to base class.
1417     This is really a descendant of __class_type_info.  */
1418  create_pseudo_type_info (TK_SI_CLASS_TYPE, "__si_class_type_info",
1419	    build_decl (BUILTINS_LOCATION,
1420			FIELD_DECL, NULL_TREE, type_info_ptr_type),
1421	    NULL);
1422
1423  /* Base class internal helper. Pointer to base type, offset to base,
1424     flags.  */
1425  {
1426    tree field, fields;
1427
1428    field = build_decl (BUILTINS_LOCATION,
1429			FIELD_DECL, NULL_TREE, type_info_ptr_type);
1430    fields = field;
1431
1432    field = build_decl (BUILTINS_LOCATION,
1433			FIELD_DECL, NULL_TREE, LONGPTR_T);
1434    DECL_CHAIN (field) = fields;
1435    fields = field;
1436
1437    ti = &(*tinfo_descs)[TK_BASE_TYPE];
1438
1439    ti->type = make_class_type (RECORD_TYPE);
1440    ti->vtable = NULL_TREE;
1441    ti->name = NULL_TREE;
1442    finish_builtin_struct (ti->type, "__base_class_type_info_pseudo",
1443			   fields, NULL_TREE);
1444  }
1445
1446  /* Pointer type_info. Adds two fields, qualification mask
1447     and pointer to the pointed to type.  This is really a descendant of
1448     __pbase_type_info.  */
1449  create_pseudo_type_info (TK_POINTER_TYPE, "__pointer_type_info",
1450       build_decl (BUILTINS_LOCATION,
1451		   FIELD_DECL, NULL_TREE, integer_type_node),
1452       build_decl (BUILTINS_LOCATION,
1453		   FIELD_DECL, NULL_TREE, type_info_ptr_type),
1454       NULL);
1455
1456  /* Pointer to member data type_info.  Add qualifications flags,
1457     pointer to the member's type info and pointer to the class.
1458     This is really a descendant of __pbase_type_info.  */
1459  create_pseudo_type_info (TK_POINTER_MEMBER_TYPE,
1460       "__pointer_to_member_type_info",
1461	build_decl (BUILTINS_LOCATION,
1462		    FIELD_DECL, NULL_TREE, integer_type_node),
1463	build_decl (BUILTINS_LOCATION,
1464		    FIELD_DECL, NULL_TREE, type_info_ptr_type),
1465	build_decl (BUILTINS_LOCATION,
1466		    FIELD_DECL, NULL_TREE, type_info_ptr_type),
1467	NULL);
1468
1469  pop_abi_namespace ();
1470}
1471
1472/* Helper for emit_support_tinfos. Emits the type_info descriptor of
1473   a single type.  */
1474
1475void
1476emit_support_tinfo_1 (tree bltn)
1477{
1478  tree types[3];
1479
1480  if (bltn == NULL_TREE)
1481    return;
1482  types[0] = bltn;
1483  types[1] = build_pointer_type (bltn);
1484  types[2] = build_pointer_type (cp_build_qualified_type (bltn,
1485							  TYPE_QUAL_CONST));
1486
1487  for (int i = 0; i < 3; ++i)
1488    {
1489      tree tinfo = get_tinfo_decl (types[i]);
1490      TREE_USED (tinfo) = 1;
1491      mark_needed (tinfo);
1492      /* The C++ ABI requires that these objects be COMDAT.  But,
1493	 On systems without weak symbols, initialized COMDAT
1494	 objects are emitted with internal linkage.  (See
1495	 comdat_linkage for details.)  Since we want these objects
1496	 to have external linkage so that copies do not have to be
1497	 emitted in code outside the runtime library, we make them
1498	 non-COMDAT here.
1499
1500	 It might also not be necessary to follow this detail of the
1501	 ABI.  */
1502      if (!flag_weak || ! targetm.cxx.library_rtti_comdat ())
1503	{
1504	  gcc_assert (TREE_PUBLIC (tinfo) && !DECL_COMDAT (tinfo));
1505	  DECL_INTERFACE_KNOWN (tinfo) = 1;
1506	}
1507    }
1508}
1509
1510/* Emit the type_info descriptors which are guaranteed to be in the runtime
1511   support.  Generating them here guarantees consistency with the other
1512   structures.  We use the following heuristic to determine when the runtime
1513   is being generated.  If std::__fundamental_type_info is defined, and its
1514   destructor is defined, then the runtime is being built.  */
1515
1516void
1517emit_support_tinfos (void)
1518{
1519  /* Dummy static variable so we can put nullptr in the array; it will be
1520     set before we actually start to walk the array.  */
1521  static tree *const fundamentals[] =
1522  {
1523    &void_type_node,
1524    &boolean_type_node,
1525    &wchar_type_node, &char16_type_node, &char32_type_node,
1526    &char_type_node, &signed_char_type_node, &unsigned_char_type_node,
1527    &short_integer_type_node, &short_unsigned_type_node,
1528    &integer_type_node, &unsigned_type_node,
1529    &long_integer_type_node, &long_unsigned_type_node,
1530    &long_long_integer_type_node, &long_long_unsigned_type_node,
1531    &float_type_node, &double_type_node, &long_double_type_node,
1532    &dfloat32_type_node, &dfloat64_type_node, &dfloat128_type_node,
1533    &nullptr_type_node,
1534    0
1535  };
1536  int ix;
1537  tree bltn_type, dtor;
1538
1539  push_abi_namespace ();
1540  bltn_type = xref_tag (class_type,
1541			get_identifier ("__fundamental_type_info"),
1542			/*tag_scope=*/ts_current, false);
1543  pop_abi_namespace ();
1544  if (!COMPLETE_TYPE_P (bltn_type))
1545    return;
1546  dtor = CLASSTYPE_DESTRUCTORS (bltn_type);
1547  if (!dtor || DECL_EXTERNAL (dtor))
1548    return;
1549  doing_runtime = 1;
1550  for (ix = 0; fundamentals[ix]; ix++)
1551    emit_support_tinfo_1 (*fundamentals[ix]);
1552  for (ix = 0; ix < NUM_INT_N_ENTS; ix ++)
1553    if (int_n_enabled_p[ix])
1554      {
1555	emit_support_tinfo_1 (int_n_trees[ix].signed_type);
1556	emit_support_tinfo_1 (int_n_trees[ix].unsigned_type);
1557      }
1558  for (tree t = registered_builtin_types; t; t = TREE_CHAIN (t))
1559    emit_support_tinfo_1 (TREE_VALUE (t));
1560}
1561
1562/* Finish a type info decl. DECL_PTR is a pointer to an unemitted
1563   tinfo decl.  Determine whether it needs emitting, and if so
1564   generate the initializer.  */
1565
1566bool
1567emit_tinfo_decl (tree decl)
1568{
1569  tree type = TREE_TYPE (DECL_NAME (decl));
1570  int in_library = typeinfo_in_lib_p (type);
1571
1572  gcc_assert (DECL_TINFO_P (decl));
1573
1574  if (in_library)
1575    {
1576      if (doing_runtime)
1577	DECL_EXTERNAL (decl) = 0;
1578      else
1579	{
1580	  /* If we're not in the runtime, then DECL (which is already
1581	     DECL_EXTERNAL) will not be defined here.  */
1582	  DECL_INTERFACE_KNOWN (decl) = 1;
1583	  return false;
1584	}
1585    }
1586  else if (involves_incomplete_p (type))
1587    {
1588      if (!decl_needed_p (decl))
1589	return false;
1590      /* If TYPE involves an incomplete class type, then the typeinfo
1591	 object will be emitted with internal linkage.  There is no
1592	 way to know whether or not types are incomplete until the end
1593	 of the compilation, so this determination must be deferred
1594	 until this point.  */
1595      TREE_PUBLIC (decl) = 0;
1596      DECL_EXTERNAL (decl) = 0;
1597      DECL_INTERFACE_KNOWN (decl) = 1;
1598    }
1599
1600  import_export_decl (decl);
1601  if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
1602    {
1603      tree init;
1604
1605      DECL_EXTERNAL (decl) = 0;
1606      init = get_pseudo_ti_init (type, get_pseudo_ti_index (type));
1607      DECL_INITIAL (decl) = init;
1608      mark_used (decl);
1609      cp_finish_decl (decl, init, false, NULL_TREE, 0);
1610      /* Avoid targets optionally bumping up the alignment to improve
1611	 vector instruction accesses, tinfo are never accessed this way.  */
1612#ifdef DATA_ABI_ALIGNMENT
1613      DECL_ALIGN (decl) = DATA_ABI_ALIGNMENT (decl, TYPE_ALIGN (TREE_TYPE (decl)));
1614      DECL_USER_ALIGN (decl) = true;
1615#endif
1616      return true;
1617    }
1618  else
1619    return false;
1620}
1621
1622#include "gt-cp-rtti.h"
1623