1/* Process declarations and variables for C++ compiler.
2   Copyright (C) 1988-2015 Free Software Foundation, Inc.
3   Hacked by Michael Tiemann (tiemann@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
22/* Process declarations and symbol lookup for C++ front end.
23   Also constructs types; the standard scalar types at initialization,
24   and structure, union, array and enum types when they are declared.  */
25
26/* ??? not all decl nodes are given the most useful possible
27   line numbers.  For example, the CONST_DECLs for enum values.  */
28
29#include "config.h"
30#include "system.h"
31#include "coretypes.h"
32#include "tm.h"
33#include "hash-set.h"
34#include "machmode.h"
35#include "vec.h"
36#include "double-int.h"
37#include "input.h"
38#include "alias.h"
39#include "symtab.h"
40#include "wide-int.h"
41#include "inchash.h"
42#include "tree.h"
43#include "stringpool.h"
44#include "varasm.h"
45#include "attribs.h"
46#include "stor-layout.h"
47#include "calls.h"
48#include "flags.h"
49#include "cp-tree.h"
50#include "decl.h"
51#include "toplev.h"
52#include "timevar.h"
53#include "cpplib.h"
54#include "target.h"
55#include "c-family/c-common.h"
56#include "c-family/c-objc.h"
57#include "hash-map.h"
58#include "is-a.h"
59#include "plugin-api.h"
60#include "hard-reg-set.h"
61#include "input.h"
62#include "function.h"
63#include "ipa-ref.h"
64#include "cgraph.h"
65#include "tree-inline.h"
66#include "c-family/c-pragma.h"
67#include "dumpfile.h"
68#include "intl.h"
69#include "splay-tree.h"
70#include "langhooks.h"
71#include "c-family/c-ada-spec.h"
72#include "asan.h"
73
74extern cpp_reader *parse_in;
75
76/* This structure contains information about the initializations
77   and/or destructions required for a particular priority level.  */
78typedef struct priority_info_s {
79  /* Nonzero if there have been any initializations at this priority
80     throughout the translation unit.  */
81  int initializations_p;
82  /* Nonzero if there have been any destructions at this priority
83     throughout the translation unit.  */
84  int destructions_p;
85} *priority_info;
86
87static void mark_vtable_entries (tree);
88static bool maybe_emit_vtables (tree);
89static bool acceptable_java_type (tree);
90static tree start_objects (int, int);
91static void finish_objects (int, int, tree);
92static tree start_static_storage_duration_function (unsigned);
93static void finish_static_storage_duration_function (tree);
94static priority_info get_priority_info (int);
95static void do_static_initialization_or_destruction (tree, bool);
96static void one_static_initialization_or_destruction (tree, tree, bool);
97static void generate_ctor_or_dtor_function (bool, int, location_t *);
98static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
99							  void *);
100static tree prune_vars_needing_no_initialization (tree *);
101static void write_out_vars (tree);
102static void import_export_class (tree);
103static tree get_guard_bits (tree);
104static void determine_visibility_from_class (tree, tree);
105static bool determine_hidden_inline (tree);
106static bool decl_defined_p (tree);
107
108/* A list of static class variables.  This is needed, because a
109   static class variable can be declared inside the class without
110   an initializer, and then initialized, statically, outside the class.  */
111static GTY(()) vec<tree, va_gc> *pending_statics;
112
113/* A list of functions which were declared inline, but which we
114   may need to emit outline anyway.  */
115static GTY(()) vec<tree, va_gc> *deferred_fns;
116
117/* A list of decls that use types with no linkage, which we need to make
118   sure are defined.  */
119static GTY(()) vec<tree, va_gc> *no_linkage_decls;
120
121/* A vector of alternating decls and identifiers, where the latter
122   is to be an alias for the former if the former is defined.  */
123static GTY(()) vec<tree, va_gc> *mangling_aliases;
124
125/* Nonzero if we're done parsing and into end-of-file activities.  */
126
127int at_eof;
128
129/* True if note_mangling_alias should enqueue mangling aliases for
130   later generation, rather than emitting them right away.  */
131
132bool defer_mangling_aliases = true;
133
134
135/* Return a member function type (a METHOD_TYPE), given FNTYPE (a
136   FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
137   that apply to the function).  */
138
139tree
140build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
141		  cp_ref_qualifier rqual)
142{
143  tree raises;
144  tree attrs;
145  int type_quals;
146  bool late_return_type_p;
147
148  if (fntype == error_mark_node || ctype == error_mark_node)
149    return error_mark_node;
150
151  gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
152	      || TREE_CODE (fntype) == METHOD_TYPE);
153
154  type_quals = quals & ~TYPE_QUAL_RESTRICT;
155  ctype = cp_build_qualified_type (ctype, type_quals);
156  raises = TYPE_RAISES_EXCEPTIONS (fntype);
157  attrs = TYPE_ATTRIBUTES (fntype);
158  late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype);
159  fntype = build_method_type_directly (ctype, TREE_TYPE (fntype),
160				       (TREE_CODE (fntype) == METHOD_TYPE
161					? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
162					: TYPE_ARG_TYPES (fntype)));
163  if (attrs)
164    fntype = cp_build_type_attribute_variant (fntype, attrs);
165  if (rqual)
166    fntype = build_ref_qualified_type (fntype, rqual);
167  if (raises)
168    fntype = build_exception_variant (fntype, raises);
169  if (late_return_type_p)
170    TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
171
172  return fntype;
173}
174
175/* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
176   return type changed to NEW_RET.  */
177
178tree
179change_return_type (tree new_ret, tree fntype)
180{
181  tree newtype;
182  tree args = TYPE_ARG_TYPES (fntype);
183  tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
184  tree attrs = TYPE_ATTRIBUTES (fntype);
185  bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype);
186
187  if (new_ret == error_mark_node)
188    return fntype;
189
190  if (same_type_p (new_ret, TREE_TYPE (fntype)))
191    return fntype;
192
193  if (TREE_CODE (fntype) == FUNCTION_TYPE)
194    {
195      newtype = build_function_type (new_ret, args);
196      newtype = apply_memfn_quals (newtype,
197				   type_memfn_quals (fntype),
198				   type_memfn_rqual (fntype));
199    }
200  else
201    newtype = build_method_type_directly
202      (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
203  if (raises)
204    newtype = build_exception_variant (newtype, raises);
205  if (attrs)
206    newtype = cp_build_type_attribute_variant (newtype, attrs);
207  if (late_return_type_p)
208    TYPE_HAS_LATE_RETURN_TYPE (newtype) = 1;
209
210  return newtype;
211}
212
213/* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE
214   appropriately.  */
215
216tree
217cp_build_parm_decl (tree name, tree type)
218{
219  tree parm = build_decl (input_location,
220			  PARM_DECL, name, type);
221  /* DECL_ARG_TYPE is only used by the back end and the back end never
222     sees templates.  */
223  if (!processing_template_decl)
224    DECL_ARG_TYPE (parm) = type_passed_as (type);
225
226  return parm;
227}
228
229/* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
230   indicated NAME.  */
231
232tree
233build_artificial_parm (tree name, tree type)
234{
235  tree parm = cp_build_parm_decl (name, type);
236  DECL_ARTIFICIAL (parm) = 1;
237  /* All our artificial parms are implicitly `const'; they cannot be
238     assigned to.  */
239  TREE_READONLY (parm) = 1;
240  return parm;
241}
242
243/* Constructors for types with virtual baseclasses need an "in-charge" flag
244   saying whether this constructor is responsible for initialization of
245   virtual baseclasses or not.  All destructors also need this "in-charge"
246   flag, which additionally determines whether or not the destructor should
247   free the memory for the object.
248
249   This function adds the "in-charge" flag to member function FN if
250   appropriate.  It is called from grokclassfn and tsubst.
251   FN must be either a constructor or destructor.
252
253   The in-charge flag follows the 'this' parameter, and is followed by the
254   VTT parm (if any), then the user-written parms.  */
255
256void
257maybe_retrofit_in_chrg (tree fn)
258{
259  tree basetype, arg_types, parms, parm, fntype;
260
261  /* If we've already add the in-charge parameter don't do it again.  */
262  if (DECL_HAS_IN_CHARGE_PARM_P (fn))
263    return;
264
265  /* When processing templates we can't know, in general, whether or
266     not we're going to have virtual baseclasses.  */
267  if (processing_template_decl)
268    return;
269
270  /* We don't need an in-charge parameter for constructors that don't
271     have virtual bases.  */
272  if (DECL_CONSTRUCTOR_P (fn)
273      && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
274    return;
275
276  arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
277  basetype = TREE_TYPE (TREE_VALUE (arg_types));
278  arg_types = TREE_CHAIN (arg_types);
279
280  parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
281
282  /* If this is a subobject constructor or destructor, our caller will
283     pass us a pointer to our VTT.  */
284  if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
285    {
286      parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
287
288      /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
289      DECL_CHAIN (parm) = parms;
290      parms = parm;
291
292      /* ...and then to TYPE_ARG_TYPES.  */
293      arg_types = hash_tree_chain (vtt_parm_type, arg_types);
294
295      DECL_HAS_VTT_PARM_P (fn) = 1;
296    }
297
298  /* Then add the in-charge parm (before the VTT parm).  */
299  parm = build_artificial_parm (in_charge_identifier, integer_type_node);
300  DECL_CHAIN (parm) = parms;
301  parms = parm;
302  arg_types = hash_tree_chain (integer_type_node, arg_types);
303
304  /* Insert our new parameter(s) into the list.  */
305  DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
306
307  /* And rebuild the function type.  */
308  fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
309				       arg_types);
310  if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
311    fntype = build_exception_variant (fntype,
312				      TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
313  if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
314    fntype = (cp_build_type_attribute_variant
315	      (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
316  TREE_TYPE (fn) = fntype;
317
318  /* Now we've got the in-charge parameter.  */
319  DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
320}
321
322/* Classes overload their constituent function names automatically.
323   When a function name is declared in a record structure,
324   its name is changed to it overloaded name.  Since names for
325   constructors and destructors can conflict, we place a leading
326   '$' for destructors.
327
328   CNAME is the name of the class we are grokking for.
329
330   FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
331
332   FLAGS contains bits saying what's special about today's
333   arguments.  DTOR_FLAG == DESTRUCTOR.
334
335   If FUNCTION is a destructor, then we must add the `auto-delete' field
336   as a second parameter.  There is some hair associated with the fact
337   that we must "declare" this variable in the manner consistent with the
338   way the rest of the arguments were declared.
339
340   QUALS are the qualifiers for the this pointer.  */
341
342void
343grokclassfn (tree ctype, tree function, enum overload_flags flags)
344{
345  tree fn_name = DECL_NAME (function);
346
347  /* Even within an `extern "C"' block, members get C++ linkage.  See
348     [dcl.link] for details.  */
349  SET_DECL_LANGUAGE (function, lang_cplusplus);
350
351  if (fn_name == NULL_TREE)
352    {
353      error ("name missing for member function");
354      fn_name = get_identifier ("<anonymous>");
355      DECL_NAME (function) = fn_name;
356    }
357
358  DECL_CONTEXT (function) = ctype;
359
360  if (flags == DTOR_FLAG)
361    DECL_DESTRUCTOR_P (function) = 1;
362
363  if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
364    maybe_retrofit_in_chrg (function);
365}
366
367/* Create an ARRAY_REF, checking for the user doing things backwards
368   along the way.  DECLTYPE_P is for N3276, as in the parser.  */
369
370tree
371grok_array_decl (location_t loc, tree array_expr, tree index_exp,
372		 bool decltype_p)
373{
374  tree type;
375  tree expr;
376  tree orig_array_expr = array_expr;
377  tree orig_index_exp = index_exp;
378
379  if (error_operand_p (array_expr) || error_operand_p (index_exp))
380    return error_mark_node;
381
382  if (processing_template_decl)
383    {
384      if (type_dependent_expression_p (array_expr)
385	  || type_dependent_expression_p (index_exp))
386	return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
387				 NULL_TREE, NULL_TREE);
388      array_expr = build_non_dependent_expr (array_expr);
389      index_exp = build_non_dependent_expr (index_exp);
390    }
391
392  type = TREE_TYPE (array_expr);
393  gcc_assert (type);
394  type = non_reference (type);
395
396  /* If they have an `operator[]', use that.  */
397  if (MAYBE_CLASS_TYPE_P (type) || MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
398    {
399      tsubst_flags_t complain = tf_warning_or_error;
400      if (decltype_p)
401	complain |= tf_decltype;
402      expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
403			   index_exp, NULL_TREE, /*overload=*/NULL, complain);
404    }
405  else
406    {
407      tree p1, p2, i1, i2;
408
409      /* Otherwise, create an ARRAY_REF for a pointer or array type.
410	 It is a little-known fact that, if `a' is an array and `i' is
411	 an int, you can write `i[a]', which means the same thing as
412	 `a[i]'.  */
413      if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
414	p1 = array_expr;
415      else
416	p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
417
418      if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
419	p2 = index_exp;
420      else
421	p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
422
423      i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
424				       false);
425      i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
426				       false);
427
428      if ((p1 && i2) && (i1 && p2))
429	error ("ambiguous conversion for array subscript");
430
431      if (p1 && i2)
432	array_expr = p1, index_exp = i2;
433      else if (i1 && p2)
434	array_expr = p2, index_exp = i1;
435      else
436	{
437	  error ("invalid types %<%T[%T]%> for array subscript",
438		 type, TREE_TYPE (index_exp));
439	  return error_mark_node;
440	}
441
442      if (array_expr == error_mark_node || index_exp == error_mark_node)
443	error ("ambiguous conversion for array subscript");
444
445      expr = build_array_ref (input_location, array_expr, index_exp);
446    }
447  if (processing_template_decl && expr != error_mark_node)
448    return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp,
449			      NULL_TREE, NULL_TREE);
450  return expr;
451}
452
453/* Given the cast expression EXP, checking out its validity.   Either return
454   an error_mark_node if there was an unavoidable error, return a cast to
455   void for trying to delete a pointer w/ the value 0, or return the
456   call to delete.  If DOING_VEC is true, we handle things differently
457   for doing an array delete.
458   Implements ARM $5.3.4.  This is called from the parser.  */
459
460tree
461delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete,
462	       tsubst_flags_t complain)
463{
464  tree t, type;
465
466  if (exp == error_mark_node)
467    return exp;
468
469  if (processing_template_decl)
470    {
471      t = build_min (DELETE_EXPR, void_type_node, exp, size);
472      DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
473      DELETE_EXPR_USE_VEC (t) = doing_vec;
474      TREE_SIDE_EFFECTS (t) = 1;
475      return t;
476    }
477
478  /* An array can't have been allocated by new, so complain.  */
479  if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
480    warning (0, "deleting array %q#E", exp);
481
482  t = build_expr_type_conversion (WANT_POINTER, exp, true);
483
484  if (t == NULL_TREE || t == error_mark_node)
485    {
486      error ("type %q#T argument given to %<delete%>, expected pointer",
487	     TREE_TYPE (exp));
488      return error_mark_node;
489    }
490
491  type = TREE_TYPE (t);
492
493  /* As of Valley Forge, you can delete a pointer to const.  */
494
495  /* You can't delete functions.  */
496  if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
497    {
498      error ("cannot delete a function.  Only pointer-to-objects are "
499	     "valid arguments to %<delete%>");
500      return error_mark_node;
501    }
502
503  /* Deleting ptr to void is undefined behavior [expr.delete/3].  */
504  if (VOID_TYPE_P (TREE_TYPE (type)))
505    {
506      warning (OPT_Wdelete_incomplete, "deleting %qT is undefined", type);
507      doing_vec = 0;
508    }
509
510  /* Deleting a pointer with the value zero is valid and has no effect.  */
511  if (integer_zerop (t))
512    return build1 (NOP_EXPR, void_type_node, t);
513
514  if (doing_vec)
515    return build_vec_delete (t, /*maxindex=*/NULL_TREE,
516			     sfk_deleting_destructor,
517			     use_global_delete, complain);
518  else
519    return build_delete (type, t, sfk_deleting_destructor,
520			 LOOKUP_NORMAL, use_global_delete,
521			 complain);
522}
523
524/* Report an error if the indicated template declaration is not the
525   sort of thing that should be a member template.  */
526
527void
528check_member_template (tree tmpl)
529{
530  tree decl;
531
532  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
533  decl = DECL_TEMPLATE_RESULT (tmpl);
534
535  if (TREE_CODE (decl) == FUNCTION_DECL
536      || DECL_ALIAS_TEMPLATE_P (tmpl)
537      || (TREE_CODE (decl) == TYPE_DECL
538	  && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
539    {
540      /* The parser rejects template declarations in local classes
541	 (with the exception of generic lambdas).  */
542      gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
543      /* The parser rejects any use of virtual in a function template.  */
544      gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
545		    && DECL_VIRTUAL_P (decl)));
546
547      /* The debug-information generating code doesn't know what to do
548	 with member templates.  */
549      DECL_IGNORED_P (tmpl) = 1;
550    }
551  else if (variable_template_p (tmpl))
552    /* OK */;
553  else
554    error ("template declaration of %q#D", decl);
555}
556
557/* Return true iff TYPE is a valid Java parameter or return type.  */
558
559static bool
560acceptable_java_type (tree type)
561{
562  if (type == error_mark_node)
563    return false;
564
565  if (VOID_TYPE_P (type) || TYPE_FOR_JAVA (type))
566    return true;
567  if (TYPE_PTR_P (type) || TREE_CODE (type) == REFERENCE_TYPE)
568    {
569      type = TREE_TYPE (type);
570      if (TREE_CODE (type) == RECORD_TYPE)
571	{
572	  tree args;  int i;
573	  if (! TYPE_FOR_JAVA (type))
574	    return false;
575	  if (! CLASSTYPE_TEMPLATE_INFO (type))
576	    return true;
577	  args = CLASSTYPE_TI_ARGS (type);
578	  i = TREE_VEC_LENGTH (args);
579	  while (--i >= 0)
580	    {
581	      type = TREE_VEC_ELT (args, i);
582	      if (TYPE_PTR_P (type))
583		type = TREE_TYPE (type);
584	      if (! TYPE_FOR_JAVA (type))
585		return false;
586	    }
587	  return true;
588	}
589    }
590  return false;
591}
592
593/* For a METHOD in a Java class CTYPE, return true if
594   the parameter and return types are valid Java types.
595   Otherwise, print appropriate error messages, and return false.  */
596
597bool
598check_java_method (tree method)
599{
600  bool jerr = false;
601  tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
602  tree ret_type = TREE_TYPE (TREE_TYPE (method));
603
604  if (!acceptable_java_type (ret_type))
605    {
606      error ("Java method %qD has non-Java return type %qT",
607	     method, ret_type);
608      jerr = true;
609    }
610
611  arg_types = TREE_CHAIN (arg_types);
612  if (DECL_HAS_IN_CHARGE_PARM_P (method))
613    arg_types = TREE_CHAIN (arg_types);
614  if (DECL_HAS_VTT_PARM_P (method))
615    arg_types = TREE_CHAIN (arg_types);
616
617  for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
618    {
619      tree type = TREE_VALUE (arg_types);
620      if (!acceptable_java_type (type))
621	{
622          if (type != error_mark_node)
623	    error ("Java method %qD has non-Java parameter type %qT",
624		   method, type);
625	  jerr = true;
626	}
627    }
628  return !jerr;
629}
630
631/* Sanity check: report error if this function FUNCTION is not
632   really a member of the class (CTYPE) it is supposed to belong to.
633   TEMPLATE_PARMS is used to specify the template parameters of a member
634   template passed as FUNCTION_DECL. If the member template is passed as a
635   TEMPLATE_DECL, it can be NULL since the parameters can be extracted
636   from the declaration. If the function is not a function template, it
637   must be NULL.
638   It returns the original declaration for the function, NULL_TREE if
639   no declaration was found, error_mark_node if an error was emitted.  */
640
641tree
642check_classfn (tree ctype, tree function, tree template_parms)
643{
644  int ix;
645  bool is_template;
646  tree pushed_scope;
647
648  if (DECL_USE_TEMPLATE (function)
649      && !(TREE_CODE (function) == TEMPLATE_DECL
650	   && DECL_TEMPLATE_SPECIALIZATION (function))
651      && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
652    /* Since this is a specialization of a member template,
653       we're not going to find the declaration in the class.
654       For example, in:
655
656	 struct S { template <typename T> void f(T); };
657	 template <> void S::f(int);
658
659       we're not going to find `S::f(int)', but there's no
660       reason we should, either.  We let our callers know we didn't
661       find the method, but we don't complain.  */
662    return NULL_TREE;
663
664  /* Basic sanity check: for a template function, the template parameters
665     either were not passed, or they are the same of DECL_TEMPLATE_PARMS.  */
666  if (TREE_CODE (function) == TEMPLATE_DECL)
667    {
668      if (template_parms
669	  && !comp_template_parms (template_parms,
670				   DECL_TEMPLATE_PARMS (function)))
671	{
672	  error ("template parameter lists provided don%'t match the "
673		 "template parameters of %qD", function);
674	  return error_mark_node;
675	}
676      template_parms = DECL_TEMPLATE_PARMS (function);
677    }
678
679  /* OK, is this a definition of a member template?  */
680  is_template = (template_parms != NULL_TREE);
681
682  /* [temp.mem]
683
684     A destructor shall not be a member template.  */
685  if (DECL_DESTRUCTOR_P (function) && is_template)
686    {
687      error ("destructor %qD declared as member template", function);
688      return error_mark_node;
689    }
690
691  /* We must enter the scope here, because conversion operators are
692     named by target type, and type equivalence relies on typenames
693     resolving within the scope of CTYPE.  */
694  pushed_scope = push_scope (ctype);
695  ix = class_method_index_for_fn (complete_type (ctype), function);
696  if (ix >= 0)
697    {
698      vec<tree, va_gc> *methods = CLASSTYPE_METHOD_VEC (ctype);
699      tree fndecls, fndecl = 0;
700      bool is_conv_op;
701      const char *format = NULL;
702
703      for (fndecls = (*methods)[ix];
704	   fndecls; fndecls = OVL_NEXT (fndecls))
705	{
706	  tree p1, p2;
707
708	  fndecl = OVL_CURRENT (fndecls);
709	  p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
710	  p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
711
712	  /* We cannot simply call decls_match because this doesn't
713	     work for static member functions that are pretending to
714	     be methods, and because the name may have been changed by
715	     asm("new_name").  */
716
717	   /* Get rid of the this parameter on functions that become
718	      static.  */
719	  if (DECL_STATIC_FUNCTION_P (fndecl)
720	      && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
721	    p1 = TREE_CHAIN (p1);
722
723	  /* A member template definition only matches a member template
724	     declaration.  */
725	  if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
726	    continue;
727
728	  /* ref-qualifier or absence of same must match.  */
729	  if (type_memfn_rqual (TREE_TYPE (function))
730	      != type_memfn_rqual (TREE_TYPE (fndecl)))
731	    continue;
732
733	  /* While finding a match, same types and params are not enough
734	     if the function is versioned.  Also check version ("target")
735	     attributes.  */
736	  if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
737			   TREE_TYPE (TREE_TYPE (fndecl)))
738	      && compparms (p1, p2)
739	      && !targetm.target_option.function_versions (function, fndecl)
740	      && (!is_template
741		  || comp_template_parms (template_parms,
742					  DECL_TEMPLATE_PARMS (fndecl)))
743	      && (DECL_TEMPLATE_SPECIALIZATION (function)
744		  == DECL_TEMPLATE_SPECIALIZATION (fndecl))
745	      && (!DECL_TEMPLATE_SPECIALIZATION (function)
746		  || (DECL_TI_TEMPLATE (function)
747		      == DECL_TI_TEMPLATE (fndecl))))
748	    break;
749	}
750      if (fndecls)
751	{
752	  if (pushed_scope)
753	    pop_scope (pushed_scope);
754	  return OVL_CURRENT (fndecls);
755	}
756
757      error_at (DECL_SOURCE_LOCATION (function),
758		"prototype for %q#D does not match any in class %qT",
759		function, ctype);
760      is_conv_op = DECL_CONV_FN_P (fndecl);
761
762      if (is_conv_op)
763	ix = CLASSTYPE_FIRST_CONVERSION_SLOT;
764      fndecls = (*methods)[ix];
765      while (fndecls)
766	{
767	  fndecl = OVL_CURRENT (fndecls);
768	  fndecls = OVL_NEXT (fndecls);
769
770	  if (!fndecls && is_conv_op)
771	    {
772	      if (methods->length () > (size_t) ++ix)
773		{
774		  fndecls = (*methods)[ix];
775		  if (!DECL_CONV_FN_P (OVL_CURRENT (fndecls)))
776		    {
777		      fndecls = NULL_TREE;
778		      is_conv_op = false;
779		    }
780		}
781	      else
782		is_conv_op = false;
783	    }
784	  if (format)
785	    format = "                %+#D";
786	  else if (fndecls)
787	    format = N_("candidates are: %+#D");
788	  else
789	    format = N_("candidate is: %+#D");
790	  error (format, fndecl);
791	}
792    }
793  else if (!COMPLETE_TYPE_P (ctype))
794    cxx_incomplete_type_error (function, ctype);
795  else
796    error ("no %q#D member function declared in class %qT",
797	   function, ctype);
798
799  if (pushed_scope)
800    pop_scope (pushed_scope);
801  return error_mark_node;
802}
803
804/* DECL is a function with vague linkage.  Remember it so that at the
805   end of the translation unit we can decide whether or not to emit
806   it.  */
807
808void
809note_vague_linkage_fn (tree decl)
810{
811  DECL_DEFER_OUTPUT (decl) = 1;
812  vec_safe_push (deferred_fns, decl);
813}
814
815/* As above, but for variable template instantiations.  */
816
817void
818note_variable_template_instantiation (tree decl)
819{
820  vec_safe_push (pending_statics, decl);
821}
822
823/* We have just processed the DECL, which is a static data member.
824   The other parameters are as for cp_finish_decl.  */
825
826void
827finish_static_data_member_decl (tree decl,
828				tree init, bool init_const_expr_p,
829				tree asmspec_tree,
830				int flags)
831{
832  DECL_CONTEXT (decl) = current_class_type;
833
834  /* We cannot call pushdecl here, because that would fill in the
835     TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
836     the right thing, namely, to put this decl out straight away.  */
837
838  if (! processing_template_decl)
839    vec_safe_push (pending_statics, decl);
840
841  if (LOCAL_CLASS_P (current_class_type)
842      /* We already complained about the template definition.  */
843      && !DECL_TEMPLATE_INSTANTIATION (decl))
844    permerror (input_location, "local class %q#T shall not have static data member %q#D",
845	       current_class_type, decl);
846  else
847    for (tree t = current_class_type; TYPE_P (t);
848	 t = CP_TYPE_CONTEXT (t))
849      if (TYPE_ANONYMOUS_P (t))
850	{
851	  if (permerror (DECL_SOURCE_LOCATION (decl),
852			 "static data member %qD in unnamed class", decl))
853	    inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
854		    "unnamed class defined here");
855	  break;
856	}
857
858  DECL_IN_AGGR_P (decl) = 1;
859
860  if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
861      && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
862    SET_VAR_HAD_UNKNOWN_BOUND (decl);
863
864  cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
865}
866
867/* DECLARATOR and DECLSPECS correspond to a class member.  The other
868   parameters are as for cp_finish_decl.  Return the DECL for the
869   class member declared.  */
870
871tree
872grokfield (const cp_declarator *declarator,
873	   cp_decl_specifier_seq *declspecs,
874	   tree init, bool init_const_expr_p,
875	   tree asmspec_tree,
876	   tree attrlist)
877{
878  tree value;
879  const char *asmspec = 0;
880  int flags;
881  tree name;
882
883  if (init
884      && TREE_CODE (init) == TREE_LIST
885      && TREE_VALUE (init) == error_mark_node
886      && TREE_CHAIN (init) == NULL_TREE)
887    init = NULL_TREE;
888
889  value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
890  if (! value || value == error_mark_node)
891    /* friend or constructor went bad.  */
892    return error_mark_node;
893  if (TREE_TYPE (value) == error_mark_node)
894    return value;
895
896  if (TREE_CODE (value) == TYPE_DECL && init)
897    {
898      error ("typedef %qD is initialized (use decltype instead)", value);
899      init = NULL_TREE;
900    }
901
902  /* Pass friendly classes back.  */
903  if (value == void_type_node)
904    return value;
905
906
907  name = DECL_NAME (value);
908
909  if (name != NULL_TREE)
910    {
911      if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
912	{
913	  error ("explicit template argument list not allowed");
914	  return error_mark_node;
915	}
916
917      if (IDENTIFIER_POINTER (name)[0] == '_'
918	  && ! strcmp (IDENTIFIER_POINTER (name), "_vptr"))
919	error ("member %qD conflicts with virtual function table field name",
920	       value);
921    }
922
923  /* Stash away type declarations.  */
924  if (TREE_CODE (value) == TYPE_DECL)
925    {
926      DECL_NONLOCAL (value) = 1;
927      DECL_CONTEXT (value) = current_class_type;
928
929      if (attrlist)
930	{
931	  int attrflags = 0;
932
933	  /* If this is a typedef that names the class for linkage purposes
934	     (7.1.3p8), apply any attributes directly to the type.  */
935	  if (OVERLOAD_TYPE_P (TREE_TYPE (value))
936	      && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
937	    attrflags = ATTR_FLAG_TYPE_IN_PLACE;
938
939	  cplus_decl_attributes (&value, attrlist, attrflags);
940	}
941
942      if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
943          && TREE_TYPE (value) != error_mark_node
944          && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
945	set_underlying_type (value);
946
947      /* It's important that push_template_decl below follows
948	 set_underlying_type above so that the created template
949	 carries the properly set type of VALUE.  */
950      if (processing_template_decl)
951	value = push_template_decl (value);
952
953      record_locally_defined_typedef (value);
954      return value;
955    }
956
957  int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
958
959  if (!friendp && DECL_IN_AGGR_P (value))
960    {
961      error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
962      return void_type_node;
963    }
964
965  if (asmspec_tree && asmspec_tree != error_mark_node)
966    asmspec = TREE_STRING_POINTER (asmspec_tree);
967
968  if (init)
969    {
970      if (TREE_CODE (value) == FUNCTION_DECL)
971	{
972	  if (init == ridpointers[(int)RID_DELETE])
973	    {
974	      DECL_DELETED_FN (value) = 1;
975	      DECL_DECLARED_INLINE_P (value) = 1;
976	      DECL_INITIAL (value) = error_mark_node;
977	    }
978	  else if (init == ridpointers[(int)RID_DEFAULT])
979	    {
980	      if (defaultable_fn_check (value))
981		{
982		  DECL_DEFAULTED_FN (value) = 1;
983		  DECL_INITIALIZED_IN_CLASS_P (value) = 1;
984		  DECL_DECLARED_INLINE_P (value) = 1;
985		}
986	    }
987	  else if (TREE_CODE (init) == DEFAULT_ARG)
988	    error ("invalid initializer for member function %qD", value);
989	  else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
990	    {
991	      if (integer_zerop (init))
992		DECL_PURE_VIRTUAL_P (value) = 1;
993	      else if (error_operand_p (init))
994		; /* An error has already been reported.  */
995	      else
996		error ("invalid initializer for member function %qD",
997		       value);
998	    }
999	  else
1000	    {
1001	      gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
1002	      if (friendp)
1003		error ("initializer specified for friend function %qD",
1004		       value);
1005	      else
1006		error ("initializer specified for static member function %qD",
1007		       value);
1008	    }
1009	}
1010      else if (TREE_CODE (value) == FIELD_DECL)
1011	/* C++11 NSDMI, keep going.  */;
1012      else if (!VAR_P (value))
1013	gcc_unreachable ();
1014    }
1015
1016  /* Pass friend decls back.  */
1017  if ((TREE_CODE (value) == FUNCTION_DECL
1018       || TREE_CODE (value) == TEMPLATE_DECL)
1019      && DECL_CONTEXT (value) != current_class_type)
1020    return value;
1021
1022  /* Need to set this before push_template_decl.  */
1023  if (TREE_CODE (value) == VAR_DECL)
1024    DECL_CONTEXT (value) = current_class_type;
1025
1026  if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
1027    {
1028      value = push_template_decl (value);
1029      if (error_operand_p (value))
1030	return error_mark_node;
1031    }
1032
1033  if (attrlist)
1034    cplus_decl_attributes (&value, attrlist, 0);
1035
1036  if (init && DIRECT_LIST_INIT_P (init))
1037    flags = LOOKUP_NORMAL;
1038  else
1039    flags = LOOKUP_IMPLICIT;
1040
1041  switch (TREE_CODE (value))
1042    {
1043    case VAR_DECL:
1044      finish_static_data_member_decl (value, init, init_const_expr_p,
1045				      asmspec_tree, flags);
1046      return value;
1047
1048    case FIELD_DECL:
1049      if (asmspec)
1050	error ("%<asm%> specifiers are not permitted on non-static data members");
1051      if (DECL_INITIAL (value) == error_mark_node)
1052	init = error_mark_node;
1053      cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1054		      NULL_TREE, flags);
1055      DECL_IN_AGGR_P (value) = 1;
1056      return value;
1057
1058    case  FUNCTION_DECL:
1059      if (asmspec)
1060	set_user_assembler_name (value, asmspec);
1061
1062      cp_finish_decl (value,
1063		      /*init=*/NULL_TREE,
1064		      /*init_const_expr_p=*/false,
1065		      asmspec_tree, flags);
1066
1067      /* Pass friends back this way.  */
1068      if (DECL_FRIEND_P (value))
1069	return void_type_node;
1070
1071      DECL_IN_AGGR_P (value) = 1;
1072      return value;
1073
1074    default:
1075      gcc_unreachable ();
1076    }
1077  return NULL_TREE;
1078}
1079
1080/* Like `grokfield', but for bitfields.
1081   WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
1082
1083tree
1084grokbitfield (const cp_declarator *declarator,
1085	      cp_decl_specifier_seq *declspecs, tree width,
1086	      tree attrlist)
1087{
1088  tree value = grokdeclarator (declarator, declspecs, BITFIELD, 0, &attrlist);
1089
1090  if (value == error_mark_node)
1091    return NULL_TREE; /* friends went bad.  */
1092  if (TREE_TYPE (value) == error_mark_node)
1093    return value;
1094
1095  /* Pass friendly classes back.  */
1096  if (VOID_TYPE_P (value))
1097    return void_type_node;
1098
1099  if (!INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (value))
1100      && (POINTER_TYPE_P (value)
1101          || !dependent_type_p (TREE_TYPE (value))))
1102    {
1103      error ("bit-field %qD with non-integral type", value);
1104      return error_mark_node;
1105    }
1106
1107  if (TREE_CODE (value) == TYPE_DECL)
1108    {
1109      error ("cannot declare %qD to be a bit-field type", value);
1110      return NULL_TREE;
1111    }
1112
1113  /* Usually, finish_struct_1 catches bitfields with invalid types.
1114     But, in the case of bitfields with function type, we confuse
1115     ourselves into thinking they are member functions, so we must
1116     check here.  */
1117  if (TREE_CODE (value) == FUNCTION_DECL)
1118    {
1119      error ("cannot declare bit-field %qD with function type",
1120	     DECL_NAME (value));
1121      return NULL_TREE;
1122    }
1123
1124  if (DECL_IN_AGGR_P (value))
1125    {
1126      error ("%qD is already defined in the class %qT", value,
1127	     DECL_CONTEXT (value));
1128      return void_type_node;
1129    }
1130
1131  if (TREE_STATIC (value))
1132    {
1133      error ("static member %qD cannot be a bit-field", value);
1134      return NULL_TREE;
1135    }
1136  cp_finish_decl (value, NULL_TREE, false, NULL_TREE, 0);
1137
1138  if (width != error_mark_node)
1139    {
1140      /* The width must be an integer type.  */
1141      if (!type_dependent_expression_p (width)
1142	  && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1143	error ("width of bit-field %qD has non-integral type %qT", value,
1144	       TREE_TYPE (width));
1145      DECL_INITIAL (value) = width;
1146      SET_DECL_C_BIT_FIELD (value);
1147    }
1148
1149  DECL_IN_AGGR_P (value) = 1;
1150
1151  if (attrlist)
1152    cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1153
1154  return value;
1155}
1156
1157
1158/* Returns true iff ATTR is an attribute which needs to be applied at
1159   instantiation time rather than template definition time.  */
1160
1161static bool
1162is_late_template_attribute (tree attr, tree decl)
1163{
1164  tree name = get_attribute_name (attr);
1165  tree args = TREE_VALUE (attr);
1166  const struct attribute_spec *spec = lookup_attribute_spec (name);
1167  tree arg;
1168
1169  if (!spec)
1170    /* Unknown attribute.  */
1171    return false;
1172
1173  /* Attribute weak handling wants to write out assembly right away.  */
1174  if (is_attribute_p ("weak", name))
1175    return true;
1176
1177  /* Attribute unused is applied directly, as it appertains to
1178     decls. */
1179  if (is_attribute_p ("unused", name))
1180    return false;
1181
1182  /* #pragma omp declare simd attribute needs to be always deferred.  */
1183  if (flag_openmp
1184      && is_attribute_p ("omp declare simd", name))
1185    return true;
1186
1187  /* An attribute pack is clearly dependent.  */
1188  if (args && PACK_EXPANSION_P (args))
1189    return true;
1190
1191  /* If any of the arguments are dependent expressions, we can't evaluate
1192     the attribute until instantiation time.  */
1193  for (arg = args; arg; arg = TREE_CHAIN (arg))
1194    {
1195      tree t = TREE_VALUE (arg);
1196
1197      /* If the first attribute argument is an identifier, only consider
1198	 second and following arguments.  Attributes like mode, format,
1199	 cleanup and several target specific attributes aren't late
1200	 just because they have an IDENTIFIER_NODE as first argument.  */
1201      if (arg == args && identifier_p (t))
1202	continue;
1203
1204      if (value_dependent_expression_p (t)
1205	  || type_dependent_expression_p (t))
1206	return true;
1207    }
1208
1209  if (TREE_CODE (decl) == TYPE_DECL
1210      || TYPE_P (decl)
1211      || spec->type_required)
1212    {
1213      tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1214
1215      /* We can't apply any attributes to a completely unknown type until
1216	 instantiation time.  */
1217      enum tree_code code = TREE_CODE (type);
1218      if (code == TEMPLATE_TYPE_PARM
1219	  || code == BOUND_TEMPLATE_TEMPLATE_PARM
1220	  || code == TYPENAME_TYPE)
1221	return true;
1222      /* Also defer most attributes on dependent types.  This is not
1223	 necessary in all cases, but is the better default.  */
1224      else if (dependent_type_p (type)
1225	       /* But some attributes specifically apply to templates.  */
1226	       && !is_attribute_p ("abi_tag", name)
1227	       && !is_attribute_p ("deprecated", name)
1228	       && !is_attribute_p ("visibility", name))
1229	return true;
1230      else
1231	return false;
1232    }
1233  else
1234    return false;
1235}
1236
1237/* ATTR_P is a list of attributes.  Remove any attributes which need to be
1238   applied at instantiation time and return them.  If IS_DEPENDENT is true,
1239   the declaration itself is dependent, so all attributes should be applied
1240   at instantiation time.  */
1241
1242static tree
1243splice_template_attributes (tree *attr_p, tree decl)
1244{
1245  tree *p = attr_p;
1246  tree late_attrs = NULL_TREE;
1247  tree *q = &late_attrs;
1248
1249  if (!p)
1250    return NULL_TREE;
1251
1252  for (; *p; )
1253    {
1254      if (is_late_template_attribute (*p, decl))
1255	{
1256	  ATTR_IS_DEPENDENT (*p) = 1;
1257	  *q = *p;
1258	  *p = TREE_CHAIN (*p);
1259	  q = &TREE_CHAIN (*q);
1260	  *q = NULL_TREE;
1261	}
1262      else
1263	p = &TREE_CHAIN (*p);
1264    }
1265
1266  return late_attrs;
1267}
1268
1269/* Remove any late attributes from the list in ATTR_P and attach them to
1270   DECL_P.  */
1271
1272static void
1273save_template_attributes (tree *attr_p, tree *decl_p)
1274{
1275  tree *q;
1276
1277  if (attr_p && *attr_p == error_mark_node)
1278    return;
1279
1280  tree late_attrs = splice_template_attributes (attr_p, *decl_p);
1281  if (!late_attrs)
1282    return;
1283
1284  if (DECL_P (*decl_p))
1285    q = &DECL_ATTRIBUTES (*decl_p);
1286  else
1287    q = &TYPE_ATTRIBUTES (*decl_p);
1288
1289  tree old_attrs = *q;
1290
1291  /* Merge the late attributes at the beginning with the attribute
1292     list.  */
1293  late_attrs = merge_attributes (late_attrs, *q);
1294  *q = late_attrs;
1295
1296  if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1297    {
1298      /* We've added new attributes directly to the main variant, so
1299	 now we need to update all of the other variants to include
1300	 these new attributes.  */
1301      tree variant;
1302      for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1303	   variant = TYPE_NEXT_VARIANT (variant))
1304	{
1305	  gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1306	  TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1307	}
1308    }
1309}
1310
1311/* Return true iff ATTRS are acceptable attributes to be applied in-place
1312   to a typedef which gives a previously anonymous class or enum a name for
1313   linkage purposes.  */
1314
1315bool
1316attributes_naming_typedef_ok (tree attrs)
1317{
1318  for (; attrs; attrs = TREE_CHAIN (attrs))
1319    {
1320      tree name = get_attribute_name (attrs);
1321      if (is_attribute_p ("vector_size", name))
1322	return false;
1323    }
1324  return true;
1325}
1326
1327/* Like reconstruct_complex_type, but handle also template trees.  */
1328
1329tree
1330cp_reconstruct_complex_type (tree type, tree bottom)
1331{
1332  tree inner, outer;
1333  bool late_return_type_p = false;
1334
1335  if (TYPE_PTR_P (type))
1336    {
1337      inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1338      outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1339					   TYPE_REF_CAN_ALIAS_ALL (type));
1340    }
1341  else if (TREE_CODE (type) == REFERENCE_TYPE)
1342    {
1343      inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1344      outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1345					     TYPE_REF_CAN_ALIAS_ALL (type));
1346    }
1347  else if (TREE_CODE (type) == ARRAY_TYPE)
1348    {
1349      inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1350      outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1351      /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1352	 element type qualification will be handled by the recursive
1353	 cp_reconstruct_complex_type call and cp_build_qualified_type
1354	 for ARRAY_TYPEs changes the element type.  */
1355      return outer;
1356    }
1357  else if (TREE_CODE (type) == FUNCTION_TYPE)
1358    {
1359      late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type);
1360      inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1361      outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1362      outer = apply_memfn_quals (outer,
1363				 type_memfn_quals (type),
1364				 type_memfn_rqual (type));
1365    }
1366  else if (TREE_CODE (type) == METHOD_TYPE)
1367    {
1368      late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type);
1369      inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1370      /* The build_method_type_directly() routine prepends 'this' to argument list,
1371	 so we must compensate by getting rid of it.  */
1372      outer
1373	= build_method_type_directly
1374	    (class_of_this_parm (type), inner,
1375	     TREE_CHAIN (TYPE_ARG_TYPES (type)));
1376    }
1377  else if (TREE_CODE (type) == OFFSET_TYPE)
1378    {
1379      inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1380      outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1381    }
1382  else
1383    return bottom;
1384
1385  if (TYPE_ATTRIBUTES (type))
1386    outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1387  outer = cp_build_qualified_type (outer, cp_type_quals (type));
1388
1389  if (late_return_type_p)
1390    TYPE_HAS_LATE_RETURN_TYPE (outer) = 1;
1391
1392  return outer;
1393}
1394
1395/* Replaces any constexpr expression that may be into the attributes
1396   arguments with their reduced value.  */
1397
1398static void
1399cp_check_const_attributes (tree attributes)
1400{
1401  if (attributes == error_mark_node)
1402    return;
1403
1404  tree attr;
1405  for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1406    {
1407      tree arg;
1408      for (arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg))
1409	{
1410	  tree expr = TREE_VALUE (arg);
1411	  if (EXPR_P (expr))
1412	    TREE_VALUE (arg) = maybe_constant_value (expr);
1413	}
1414    }
1415}
1416
1417/* Return true if TYPE is an OpenMP mappable type.  */
1418bool
1419cp_omp_mappable_type (tree type)
1420{
1421  /* Mappable type has to be complete.  */
1422  if (type == error_mark_node || !COMPLETE_TYPE_P (type))
1423    return false;
1424  /* Arrays have mappable type if the elements have mappable type.  */
1425  while (TREE_CODE (type) == ARRAY_TYPE)
1426    type = TREE_TYPE (type);
1427  /* A mappable type cannot contain virtual members.  */
1428  if (CLASS_TYPE_P (type) && CLASSTYPE_VTABLES (type))
1429    return false;
1430  /* All data members must be non-static.  */
1431  if (CLASS_TYPE_P (type))
1432    {
1433      tree field;
1434      for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1435	if (TREE_CODE (field) == VAR_DECL)
1436	  return false;
1437	/* All fields must have mappable types.  */
1438	else if (TREE_CODE (field) == FIELD_DECL
1439		 && !cp_omp_mappable_type (TREE_TYPE (field)))
1440	  return false;
1441    }
1442  return true;
1443}
1444
1445/* Like decl_attributes, but handle C++ complexity.  */
1446
1447void
1448cplus_decl_attributes (tree *decl, tree attributes, int flags)
1449{
1450  if (*decl == NULL_TREE || *decl == void_type_node
1451      || *decl == error_mark_node)
1452    return;
1453
1454  /* Add implicit "omp declare target" attribute if requested.  */
1455  if (scope_chain->omp_declare_target_attribute
1456      && ((TREE_CODE (*decl) == VAR_DECL
1457	   && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1458	  || TREE_CODE (*decl) == FUNCTION_DECL))
1459    {
1460      if (TREE_CODE (*decl) == VAR_DECL
1461	  && DECL_CLASS_SCOPE_P (*decl))
1462	error ("%q+D static data member inside of declare target directive",
1463	       *decl);
1464      else if (TREE_CODE (*decl) == VAR_DECL
1465	       && (DECL_FUNCTION_SCOPE_P (*decl)
1466		   || (current_function_decl && !DECL_EXTERNAL (*decl))))
1467	error ("%q+D in block scope inside of declare target directive",
1468	       *decl);
1469      else if (!processing_template_decl
1470	       && TREE_CODE (*decl) == VAR_DECL
1471	       && !cp_omp_mappable_type (TREE_TYPE (*decl)))
1472	error ("%q+D in declare target directive does not have mappable type",
1473	       *decl);
1474      else
1475	attributes = tree_cons (get_identifier ("omp declare target"),
1476				NULL_TREE, attributes);
1477    }
1478
1479  if (processing_template_decl)
1480    {
1481      if (check_for_bare_parameter_packs (attributes))
1482	return;
1483
1484      save_template_attributes (&attributes, decl);
1485    }
1486
1487  cp_check_const_attributes (attributes);
1488
1489  if (TREE_CODE (*decl) == TEMPLATE_DECL)
1490    decl = &DECL_TEMPLATE_RESULT (*decl);
1491
1492  if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1493    {
1494      attributes
1495	= decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1496      decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1497		       attributes, flags);
1498    }
1499  else
1500    decl_attributes (decl, attributes, flags);
1501
1502  if (TREE_CODE (*decl) == TYPE_DECL)
1503    SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1504
1505  /* Propagate deprecation out to the template.  */
1506  if (TREE_DEPRECATED (*decl))
1507    if (tree ti = get_template_info (*decl))
1508      {
1509	tree tmpl = TI_TEMPLATE (ti);
1510	tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1511			: DECL_TEMPLATE_RESULT (tmpl));
1512	if (*decl == pattern)
1513	  TREE_DEPRECATED (tmpl) = true;
1514      }
1515}
1516
1517/* Walks through the namespace- or function-scope anonymous union
1518   OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1519   Returns one of the fields for use in the mangled name.  */
1520
1521static tree
1522build_anon_union_vars (tree type, tree object)
1523{
1524  tree main_decl = NULL_TREE;
1525  tree field;
1526
1527  /* Rather than write the code to handle the non-union case,
1528     just give an error.  */
1529  if (TREE_CODE (type) != UNION_TYPE)
1530    {
1531      error ("anonymous struct not inside named type");
1532      return error_mark_node;
1533    }
1534
1535  for (field = TYPE_FIELDS (type);
1536       field != NULL_TREE;
1537       field = DECL_CHAIN (field))
1538    {
1539      tree decl;
1540      tree ref;
1541
1542      if (DECL_ARTIFICIAL (field))
1543	continue;
1544      if (TREE_CODE (field) != FIELD_DECL)
1545	{
1546	  permerror (input_location, "%q+#D invalid; an anonymous union can only "
1547		     "have non-static data members", field);
1548	  continue;
1549	}
1550
1551      if (TREE_PRIVATE (field))
1552	permerror (input_location, "private member %q+#D in anonymous union", field);
1553      else if (TREE_PROTECTED (field))
1554	permerror (input_location, "protected member %q+#D in anonymous union", field);
1555
1556      if (processing_template_decl)
1557	ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1558				DECL_NAME (field), NULL_TREE);
1559      else
1560	ref = build_class_member_access_expr (object, field, NULL_TREE,
1561					      false, tf_warning_or_error);
1562
1563      if (DECL_NAME (field))
1564	{
1565	  tree base;
1566
1567	  decl = build_decl (input_location,
1568			     VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1569	  DECL_ANON_UNION_VAR_P (decl) = 1;
1570	  DECL_ARTIFICIAL (decl) = 1;
1571
1572	  base = get_base_address (object);
1573	  TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1574	  TREE_STATIC (decl) = TREE_STATIC (base);
1575	  DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1576
1577	  SET_DECL_VALUE_EXPR (decl, ref);
1578	  DECL_HAS_VALUE_EXPR_P (decl) = 1;
1579
1580	  decl = pushdecl (decl);
1581	}
1582      else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1583	decl = build_anon_union_vars (TREE_TYPE (field), ref);
1584      else
1585	decl = 0;
1586
1587      if (main_decl == NULL_TREE)
1588	main_decl = decl;
1589    }
1590
1591  return main_decl;
1592}
1593
1594/* Finish off the processing of a UNION_TYPE structure.  If the union is an
1595   anonymous union, then all members must be laid out together.  PUBLIC_P
1596   is nonzero if this union is not declared static.  */
1597
1598void
1599finish_anon_union (tree anon_union_decl)
1600{
1601  tree type;
1602  tree main_decl;
1603  bool public_p;
1604
1605  if (anon_union_decl == error_mark_node)
1606    return;
1607
1608  type = TREE_TYPE (anon_union_decl);
1609  public_p = TREE_PUBLIC (anon_union_decl);
1610
1611  /* The VAR_DECL's context is the same as the TYPE's context.  */
1612  DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1613
1614  if (TYPE_FIELDS (type) == NULL_TREE)
1615    return;
1616
1617  if (public_p)
1618    {
1619      error ("namespace-scope anonymous aggregates must be static");
1620      return;
1621    }
1622
1623  main_decl = build_anon_union_vars (type, anon_union_decl);
1624  if (main_decl == error_mark_node)
1625    return;
1626  if (main_decl == NULL_TREE)
1627    {
1628      warning (0, "anonymous union with no members");
1629      return;
1630    }
1631
1632  if (!processing_template_decl)
1633    {
1634      /* Use main_decl to set the mangled name.  */
1635      DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1636      maybe_commonize_var (anon_union_decl);
1637      if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1638	mangle_decl (anon_union_decl);
1639      DECL_NAME (anon_union_decl) = NULL_TREE;
1640    }
1641
1642  pushdecl (anon_union_decl);
1643  cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1644}
1645
1646/* Auxiliary functions to make type signatures for
1647   `operator new' and `operator delete' correspond to
1648   what compiler will be expecting.  */
1649
1650tree
1651coerce_new_type (tree type)
1652{
1653  int e = 0;
1654  tree args = TYPE_ARG_TYPES (type);
1655
1656  gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1657
1658  if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1659    {
1660      e = 1;
1661      error ("%<operator new%> must return type %qT", ptr_type_node);
1662    }
1663
1664  if (args && args != void_list_node)
1665    {
1666      if (TREE_PURPOSE (args))
1667	{
1668	  /* [basic.stc.dynamic.allocation]
1669
1670	     The first parameter shall not have an associated default
1671	     argument.  */
1672	  error ("the first parameter of %<operator new%> cannot "
1673		 "have a default argument");
1674	  /* Throw away the default argument.  */
1675	  TREE_PURPOSE (args) = NULL_TREE;
1676	}
1677
1678      if (!same_type_p (TREE_VALUE (args), size_type_node))
1679	{
1680	  e = 2;
1681	  args = TREE_CHAIN (args);
1682	}
1683    }
1684  else
1685    e = 2;
1686
1687  if (e == 2)
1688    permerror (input_location, "%<operator new%> takes type %<size_t%> (%qT) "
1689	       "as first parameter", size_type_node);
1690
1691  switch (e)
1692  {
1693    case 2:
1694      args = tree_cons (NULL_TREE, size_type_node, args);
1695      /* Fall through.  */
1696    case 1:
1697      type = build_exception_variant
1698	      (build_function_type (ptr_type_node, args),
1699	       TYPE_RAISES_EXCEPTIONS (type));
1700      /* Fall through.  */
1701    default:;
1702  }
1703  return type;
1704}
1705
1706tree
1707coerce_delete_type (tree type)
1708{
1709  int e = 0;
1710  tree args = TYPE_ARG_TYPES (type);
1711
1712  gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1713
1714  if (!same_type_p (TREE_TYPE (type), void_type_node))
1715    {
1716      e = 1;
1717      error ("%<operator delete%> must return type %qT", void_type_node);
1718    }
1719
1720  if (!args || args == void_list_node
1721      || !same_type_p (TREE_VALUE (args), ptr_type_node))
1722    {
1723      e = 2;
1724      if (args && args != void_list_node)
1725	args = TREE_CHAIN (args);
1726      error ("%<operator delete%> takes type %qT as first parameter",
1727	     ptr_type_node);
1728    }
1729  switch (e)
1730  {
1731    case 2:
1732      args = tree_cons (NULL_TREE, ptr_type_node, args);
1733      /* Fall through.  */
1734    case 1:
1735      type = build_exception_variant
1736	      (build_function_type (void_type_node, args),
1737	       TYPE_RAISES_EXCEPTIONS (type));
1738      /* Fall through.  */
1739    default:;
1740  }
1741
1742  return type;
1743}
1744
1745/* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
1746   and mark them as needed.  */
1747
1748static void
1749mark_vtable_entries (tree decl)
1750{
1751  tree fnaddr;
1752  unsigned HOST_WIDE_INT idx;
1753
1754  /* It's OK for the vtable to refer to deprecated virtual functions.  */
1755  warning_sentinel w(warn_deprecated_decl);
1756
1757  FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
1758			      idx, fnaddr)
1759    {
1760      tree fn;
1761
1762      STRIP_NOPS (fnaddr);
1763
1764      if (TREE_CODE (fnaddr) != ADDR_EXPR
1765	  && TREE_CODE (fnaddr) != FDESC_EXPR)
1766	/* This entry is an offset: a virtual base class offset, a
1767	   virtual call offset, an RTTI offset, etc.  */
1768	continue;
1769
1770      fn = TREE_OPERAND (fnaddr, 0);
1771      TREE_ADDRESSABLE (fn) = 1;
1772      /* When we don't have vcall offsets, we output thunks whenever
1773	 we output the vtables that contain them.  With vcall offsets,
1774	 we know all the thunks we'll need when we emit a virtual
1775	 function, so we emit the thunks there instead.  */
1776      if (DECL_THUNK_P (fn))
1777	use_thunk (fn, /*emit_p=*/0);
1778      mark_used (fn);
1779    }
1780}
1781
1782/* Set DECL up to have the closest approximation of "initialized common"
1783   linkage available.  */
1784
1785void
1786comdat_linkage (tree decl)
1787{
1788  if (flag_weak)
1789    make_decl_one_only (decl, cxx_comdat_group (decl));
1790  else if (TREE_CODE (decl) == FUNCTION_DECL
1791	   || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
1792    /* We can just emit function and compiler-generated variables
1793       statically; having multiple copies is (for the most part) only
1794       a waste of space.
1795
1796       There are two correctness issues, however: the address of a
1797       template instantiation with external linkage should be the
1798       same, independent of what translation unit asks for the
1799       address, and this will not hold when we emit multiple copies of
1800       the function.  However, there's little else we can do.
1801
1802       Also, by default, the typeinfo implementation assumes that
1803       there will be only one copy of the string used as the name for
1804       each type.  Therefore, if weak symbols are unavailable, the
1805       run-time library should perform a more conservative check; it
1806       should perform a string comparison, rather than an address
1807       comparison.  */
1808    TREE_PUBLIC (decl) = 0;
1809  else
1810    {
1811      /* Static data member template instantiations, however, cannot
1812	 have multiple copies.  */
1813      if (DECL_INITIAL (decl) == 0
1814	  || DECL_INITIAL (decl) == error_mark_node)
1815	DECL_COMMON (decl) = 1;
1816      else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1817	{
1818	  DECL_COMMON (decl) = 1;
1819	  DECL_INITIAL (decl) = error_mark_node;
1820	}
1821      else if (!DECL_EXPLICIT_INSTANTIATION (decl))
1822	{
1823	  /* We can't do anything useful; leave vars for explicit
1824	     instantiation.  */
1825	  DECL_EXTERNAL (decl) = 1;
1826	  DECL_NOT_REALLY_EXTERN (decl) = 0;
1827	}
1828    }
1829
1830  DECL_COMDAT (decl) = 1;
1831}
1832
1833/* For win32 we also want to put explicit instantiations in
1834   linkonce sections, so that they will be merged with implicit
1835   instantiations; otherwise we get duplicate symbol errors.
1836   For Darwin we do not want explicit instantiations to be
1837   linkonce.  */
1838
1839void
1840maybe_make_one_only (tree decl)
1841{
1842  /* We used to say that this was not necessary on targets that support weak
1843     symbols, because the implicit instantiations will defer to the explicit
1844     one.  However, that's not actually the case in SVR4; a strong definition
1845     after a weak one is an error.  Also, not making explicit
1846     instantiations one_only means that we can end up with two copies of
1847     some template instantiations.  */
1848  if (! flag_weak)
1849    return;
1850
1851  /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
1852     we can get away with not emitting them if they aren't used.  We need
1853     to for variables so that cp_finish_decl will update their linkage,
1854     because their DECL_INITIAL may not have been set properly yet.  */
1855
1856  if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
1857      || (! DECL_EXPLICIT_INSTANTIATION (decl)
1858	  && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
1859    {
1860      make_decl_one_only (decl, cxx_comdat_group (decl));
1861
1862      if (VAR_P (decl))
1863	{
1864	  varpool_node *node = varpool_node::get_create (decl);
1865	  DECL_COMDAT (decl) = 1;
1866	  /* Mark it needed so we don't forget to emit it.  */
1867          node->forced_by_abi = true;
1868	  TREE_USED (decl) = 1;
1869	}
1870    }
1871}
1872
1873/* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
1874   This predicate will give the right answer during parsing of the
1875   function, which other tests may not.  */
1876
1877bool
1878vague_linkage_p (tree decl)
1879{
1880  /* Unfortunately, import_export_decl has not always been called
1881     before the function is processed, so we cannot simply check
1882     DECL_COMDAT.  */
1883  if (DECL_COMDAT (decl)
1884      || (((TREE_CODE (decl) == FUNCTION_DECL
1885	    && DECL_DECLARED_INLINE_P (decl))
1886	   || (DECL_LANG_SPECIFIC (decl)
1887	       && DECL_TEMPLATE_INSTANTIATION (decl)))
1888	  && TREE_PUBLIC (decl)))
1889    return true;
1890  else if (DECL_FUNCTION_SCOPE_P (decl))
1891    /* A local static in an inline effectively has vague linkage.  */
1892    return (TREE_STATIC (decl)
1893	    && vague_linkage_p (DECL_CONTEXT (decl)));
1894  else
1895    return false;
1896}
1897
1898/* Determine whether or not we want to specifically import or export CTYPE,
1899   using various heuristics.  */
1900
1901static void
1902import_export_class (tree ctype)
1903{
1904  /* -1 for imported, 1 for exported.  */
1905  int import_export = 0;
1906
1907  /* It only makes sense to call this function at EOF.  The reason is
1908     that this function looks at whether or not the first non-inline
1909     non-abstract virtual member function has been defined in this
1910     translation unit.  But, we can't possibly know that until we've
1911     seen the entire translation unit.  */
1912  gcc_assert (at_eof);
1913
1914  if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1915    return;
1916
1917  /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
1918     we will have CLASSTYPE_INTERFACE_ONLY set but not
1919     CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
1920     heuristic because someone will supply a #pragma implementation
1921     elsewhere, and deducing it here would produce a conflict.  */
1922  if (CLASSTYPE_INTERFACE_ONLY (ctype))
1923    return;
1924
1925  if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
1926    import_export = -1;
1927  else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
1928    import_export = 1;
1929  else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
1930	   && !flag_implicit_templates)
1931    /* For a template class, without -fimplicit-templates, check the
1932       repository.  If the virtual table is assigned to this
1933       translation unit, then export the class; otherwise, import
1934       it.  */
1935      import_export = repo_export_class_p (ctype) ? 1 : -1;
1936  else if (TYPE_POLYMORPHIC_P (ctype))
1937    {
1938      /* The ABI specifies that the virtual table and associated
1939	 information are emitted with the key method, if any.  */
1940      tree method = CLASSTYPE_KEY_METHOD (ctype);
1941      /* If weak symbol support is not available, then we must be
1942	 careful not to emit the vtable when the key function is
1943	 inline.  An inline function can be defined in multiple
1944	 translation units.  If we were to emit the vtable in each
1945	 translation unit containing a definition, we would get
1946	 multiple definition errors at link-time.  */
1947      if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
1948	import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
1949    }
1950
1951  /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
1952     a definition anywhere else.  */
1953  if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
1954    import_export = 0;
1955
1956  /* Allow back ends the chance to overrule the decision.  */
1957  if (targetm.cxx.import_export_class)
1958    import_export = targetm.cxx.import_export_class (ctype, import_export);
1959
1960  if (import_export)
1961    {
1962      SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
1963      CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
1964    }
1965}
1966
1967/* Return true if VAR has already been provided to the back end; in that
1968   case VAR should not be modified further by the front end.  */
1969static bool
1970var_finalized_p (tree var)
1971{
1972  return varpool_node::get_create (var)->definition;
1973}
1974
1975/* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
1976   must be emitted in this translation unit.  Mark it as such.  */
1977
1978void
1979mark_needed (tree decl)
1980{
1981  TREE_USED (decl) = 1;
1982  if (TREE_CODE (decl) == FUNCTION_DECL)
1983    {
1984      /* Extern inline functions don't become needed when referenced.
1985	 If we know a method will be emitted in other TU and no new
1986	 functions can be marked reachable, just use the external
1987	 definition.  */
1988      struct cgraph_node *node = cgraph_node::get_create (decl);
1989      node->forced_by_abi = true;
1990
1991      /* #pragma interface and -frepo code can call mark_needed for
1992          maybe-in-charge 'tors; mark the clones as well.  */
1993      tree clone;
1994      FOR_EACH_CLONE (clone, decl)
1995	mark_needed (clone);
1996    }
1997  else if (TREE_CODE (decl) == VAR_DECL)
1998    {
1999      varpool_node *node = varpool_node::get_create (decl);
2000      /* C++ frontend use mark_decl_references to force COMDAT variables
2001         to be output that might appear dead otherwise.  */
2002      node->forced_by_abi = true;
2003    }
2004}
2005
2006/* DECL is either a FUNCTION_DECL or a VAR_DECL.  This function
2007   returns true if a definition of this entity should be provided in
2008   this object file.  Callers use this function to determine whether
2009   or not to let the back end know that a definition of DECL is
2010   available in this translation unit.  */
2011
2012bool
2013decl_needed_p (tree decl)
2014{
2015  gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2016  /* This function should only be called at the end of the translation
2017     unit.  We cannot be sure of whether or not something will be
2018     COMDAT until that point.  */
2019  gcc_assert (at_eof);
2020
2021  /* All entities with external linkage that are not COMDAT/EXTERN should be
2022     emitted; they may be referred to from other object files.  */
2023  if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2024    return true;
2025  /* Functions marked "dllexport" must be emitted so that they are
2026     visible to other DLLs.  */
2027  if (flag_keep_inline_dllexport
2028      && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2029    return true;
2030
2031  /* When not optimizing, do not bother to produce definitions for extern
2032     symbols.  */
2033  if (DECL_REALLY_EXTERN (decl)
2034      && ((TREE_CODE (decl) != FUNCTION_DECL
2035	   && !optimize)
2036	  || (TREE_CODE (decl) == FUNCTION_DECL
2037	      && !opt_for_fn (decl, optimize)))
2038      && !lookup_attribute ("always_inline", decl))
2039    return false;
2040
2041  /* If this entity was used, let the back end see it; it will decide
2042     whether or not to emit it into the object file.  */
2043  if (TREE_USED (decl))
2044      return true;
2045  /* Virtual functions might be needed for devirtualization.  */
2046  if (flag_devirtualize
2047      && TREE_CODE (decl) == FUNCTION_DECL
2048      && DECL_VIRTUAL_P (decl))
2049    return true;
2050  /* Otherwise, DECL does not need to be emitted -- yet.  A subsequent
2051     reference to DECL might cause it to be emitted later.  */
2052  return false;
2053}
2054
2055/* If necessary, write out the vtables for the dynamic class CTYPE.
2056   Returns true if any vtables were emitted.  */
2057
2058static bool
2059maybe_emit_vtables (tree ctype)
2060{
2061  tree vtbl;
2062  tree primary_vtbl;
2063  int needed = 0;
2064  varpool_node *current = NULL, *last = NULL;
2065
2066  /* If the vtables for this class have already been emitted there is
2067     nothing more to do.  */
2068  primary_vtbl = CLASSTYPE_VTABLES (ctype);
2069  if (var_finalized_p (primary_vtbl))
2070    return false;
2071  /* Ignore dummy vtables made by get_vtable_decl.  */
2072  if (TREE_TYPE (primary_vtbl) == void_type_node)
2073    return false;
2074
2075  /* On some targets, we cannot determine the key method until the end
2076     of the translation unit -- which is when this function is
2077     called.  */
2078  if (!targetm.cxx.key_method_may_be_inline ())
2079    determine_key_method (ctype);
2080
2081  /* See if any of the vtables are needed.  */
2082  for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2083    {
2084      import_export_decl (vtbl);
2085      if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2086	needed = 1;
2087    }
2088  if (!needed)
2089    {
2090      /* If the references to this class' vtables are optimized away,
2091	 still emit the appropriate debugging information.  See
2092	 dfs_debug_mark.  */
2093      if (DECL_COMDAT (primary_vtbl)
2094	  && CLASSTYPE_DEBUG_REQUESTED (ctype))
2095	note_debug_info_needed (ctype);
2096      return false;
2097    }
2098
2099  /* The ABI requires that we emit all of the vtables if we emit any
2100     of them.  */
2101  for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2102    {
2103      /* Mark entities references from the virtual table as used.  */
2104      mark_vtable_entries (vtbl);
2105
2106      if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2107	{
2108	  vec<tree, va_gc> *cleanups = NULL;
2109	  tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2110					LOOKUP_NORMAL);
2111
2112	  /* It had better be all done at compile-time.  */
2113	  gcc_assert (!expr && !cleanups);
2114	}
2115
2116      /* Write it out.  */
2117      DECL_EXTERNAL (vtbl) = 0;
2118      rest_of_decl_compilation (vtbl, 1, 1);
2119
2120      /* Because we're only doing syntax-checking, we'll never end up
2121	 actually marking the variable as written.  */
2122      if (flag_syntax_only)
2123	TREE_ASM_WRITTEN (vtbl) = 1;
2124      else if (DECL_ONE_ONLY (vtbl))
2125	{
2126	  current = varpool_node::get_create (vtbl);
2127	  if (last)
2128	    current->add_to_same_comdat_group (last);
2129	  last = current;
2130	}
2131    }
2132
2133  /* Since we're writing out the vtable here, also write the debug
2134     info.  */
2135  note_debug_info_needed (ctype);
2136
2137  return true;
2138}
2139
2140/* A special return value from type_visibility meaning internal
2141   linkage.  */
2142
2143enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2144
2145/* walk_tree helper function for type_visibility.  */
2146
2147static tree
2148min_vis_r (tree *tp, int *walk_subtrees, void *data)
2149{
2150  int *vis_p = (int *)data;
2151  if (! TYPE_P (*tp))
2152    {
2153      *walk_subtrees = 0;
2154    }
2155  else if (OVERLOAD_TYPE_P (*tp)
2156	   && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2157    {
2158      *vis_p = VISIBILITY_ANON;
2159      return *tp;
2160    }
2161  else if (CLASS_TYPE_P (*tp)
2162	   && CLASSTYPE_VISIBILITY (*tp) > *vis_p)
2163    *vis_p = CLASSTYPE_VISIBILITY (*tp);
2164  return NULL;
2165}
2166
2167/* Returns the visibility of TYPE, which is the minimum visibility of its
2168   component types.  */
2169
2170static int
2171type_visibility (tree type)
2172{
2173  int vis = VISIBILITY_DEFAULT;
2174  cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2175  return vis;
2176}
2177
2178/* Limit the visibility of DECL to VISIBILITY, if not explicitly
2179   specified (or if VISIBILITY is static).  If TMPL is true, this
2180   constraint is for a template argument, and takes precedence
2181   over explicitly-specified visibility on the template.  */
2182
2183static void
2184constrain_visibility (tree decl, int visibility, bool tmpl)
2185{
2186  if (visibility == VISIBILITY_ANON)
2187    {
2188      /* extern "C" declarations aren't affected by the anonymous
2189	 namespace.  */
2190      if (!DECL_EXTERN_C_P (decl))
2191	{
2192	  TREE_PUBLIC (decl) = 0;
2193	  DECL_WEAK (decl) = 0;
2194	  DECL_COMMON (decl) = 0;
2195	  DECL_COMDAT (decl) = false;
2196	  if (TREE_CODE (decl) == FUNCTION_DECL
2197	      || TREE_CODE (decl) == VAR_DECL)
2198	    {
2199	      struct symtab_node *snode = symtab_node::get (decl);
2200
2201	      if (snode)
2202	        snode->set_comdat_group (NULL);
2203	    }
2204	  DECL_INTERFACE_KNOWN (decl) = 1;
2205	  if (DECL_LANG_SPECIFIC (decl))
2206	    DECL_NOT_REALLY_EXTERN (decl) = 1;
2207	}
2208    }
2209  else if (visibility > DECL_VISIBILITY (decl)
2210	   && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2211    {
2212      DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2213      /* This visibility was not specified.  */
2214      DECL_VISIBILITY_SPECIFIED (decl) = false;
2215    }
2216}
2217
2218/* Constrain the visibility of DECL based on the visibility of its template
2219   arguments.  */
2220
2221static void
2222constrain_visibility_for_template (tree decl, tree targs)
2223{
2224  /* If this is a template instantiation, check the innermost
2225     template args for visibility constraints.  The outer template
2226     args are covered by the class check.  */
2227  tree args = INNERMOST_TEMPLATE_ARGS (targs);
2228  int i;
2229  for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2230    {
2231      int vis = 0;
2232
2233      tree arg = TREE_VEC_ELT (args, i-1);
2234      if (TYPE_P (arg))
2235	vis = type_visibility (arg);
2236      else
2237	{
2238	  if (REFERENCE_REF_P (arg))
2239	    arg = TREE_OPERAND (arg, 0);
2240	  if (TREE_TYPE (arg))
2241	    STRIP_NOPS (arg);
2242	  if (TREE_CODE (arg) == ADDR_EXPR)
2243	    arg = TREE_OPERAND (arg, 0);
2244	  if (VAR_OR_FUNCTION_DECL_P (arg))
2245	    {
2246	      if (! TREE_PUBLIC (arg))
2247		vis = VISIBILITY_ANON;
2248	      else
2249		vis = DECL_VISIBILITY (arg);
2250	    }
2251	}
2252      if (vis)
2253	constrain_visibility (decl, vis, true);
2254    }
2255}
2256
2257/* Like c_determine_visibility, but with additional C++-specific
2258   behavior.
2259
2260   Function-scope entities can rely on the function's visibility because
2261   it is set in start_preparsed_function.
2262
2263   Class-scope entities cannot rely on the class's visibility until the end
2264   of the enclosing class definition.
2265
2266   Note that because namespaces have multiple independent definitions,
2267   namespace visibility is handled elsewhere using the #pragma visibility
2268   machinery rather than by decorating the namespace declaration.
2269
2270   The goal is for constraints from the type to give a diagnostic, and
2271   other constraints to be applied silently.  */
2272
2273void
2274determine_visibility (tree decl)
2275{
2276  tree class_type = NULL_TREE;
2277  bool use_template;
2278  bool orig_visibility_specified;
2279  enum symbol_visibility orig_visibility;
2280
2281  /* Remember that all decls get VISIBILITY_DEFAULT when built.  */
2282
2283  /* Only relevant for names with external linkage.  */
2284  if (!TREE_PUBLIC (decl))
2285    return;
2286
2287  /* Cloned constructors and destructors get the same visibility as
2288     the underlying function.  That should be set up in
2289     maybe_clone_body.  */
2290  gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2291
2292  orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2293  orig_visibility = DECL_VISIBILITY (decl);
2294
2295  if (TREE_CODE (decl) == TYPE_DECL)
2296    {
2297      if (CLASS_TYPE_P (TREE_TYPE (decl)))
2298	use_template = CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl));
2299      else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2300	use_template = 1;
2301      else
2302	use_template = 0;
2303    }
2304  else if (DECL_LANG_SPECIFIC (decl))
2305    use_template = DECL_USE_TEMPLATE (decl);
2306  else
2307    use_template = 0;
2308
2309  /* If DECL is a member of a class, visibility specifiers on the
2310     class can influence the visibility of the DECL.  */
2311  if (DECL_CLASS_SCOPE_P (decl))
2312    class_type = DECL_CONTEXT (decl);
2313  else
2314    {
2315      /* Not a class member.  */
2316
2317      /* Virtual tables have DECL_CONTEXT set to their associated class,
2318	 so they are automatically handled above.  */
2319      gcc_assert (!VAR_P (decl)
2320		  || !DECL_VTABLE_OR_VTT_P (decl));
2321
2322      if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2323	{
2324	  /* Local statics and classes get the visibility of their
2325	     containing function by default, except that
2326	     -fvisibility-inlines-hidden doesn't affect them.  */
2327	  tree fn = DECL_CONTEXT (decl);
2328	  if (DECL_VISIBILITY_SPECIFIED (fn))
2329	    {
2330	      DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2331	      DECL_VISIBILITY_SPECIFIED (decl) =
2332		DECL_VISIBILITY_SPECIFIED (fn);
2333	    }
2334	  else
2335	    {
2336	      if (DECL_CLASS_SCOPE_P (fn))
2337		determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2338	      else if (determine_hidden_inline (fn))
2339		{
2340		  DECL_VISIBILITY (decl) = default_visibility;
2341		  DECL_VISIBILITY_SPECIFIED (decl) =
2342		    visibility_options.inpragma;
2343		}
2344	      else
2345		{
2346	          DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2347	          DECL_VISIBILITY_SPECIFIED (decl) =
2348		    DECL_VISIBILITY_SPECIFIED (fn);
2349		}
2350	    }
2351
2352	  /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2353	     but have no TEMPLATE_INFO, so don't try to check it.  */
2354	  use_template = 0;
2355	}
2356      else if (VAR_P (decl) && DECL_TINFO_P (decl)
2357	       && flag_visibility_ms_compat)
2358	{
2359	  /* Under -fvisibility-ms-compat, types are visible by default,
2360	     even though their contents aren't.  */
2361	  tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2362	  int underlying_vis = type_visibility (underlying_type);
2363	  if (underlying_vis == VISIBILITY_ANON
2364	      || (CLASS_TYPE_P (underlying_type)
2365		  && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2366	    constrain_visibility (decl, underlying_vis, false);
2367	  else
2368	    DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2369	}
2370      else if (VAR_P (decl) && DECL_TINFO_P (decl))
2371	{
2372	  /* tinfo visibility is based on the type it's for.  */
2373	  constrain_visibility
2374	    (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2375
2376	  /* Give the target a chance to override the visibility associated
2377	     with DECL.  */
2378	  if (TREE_PUBLIC (decl)
2379	      && !DECL_REALLY_EXTERN (decl)
2380	      && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2381	      && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2382	    targetm.cxx.determine_class_data_visibility (decl);
2383	}
2384      else if (use_template)
2385	/* Template instantiations and specializations get visibility based
2386	   on their template unless they override it with an attribute.  */;
2387      else if (! DECL_VISIBILITY_SPECIFIED (decl))
2388	{
2389          if (determine_hidden_inline (decl))
2390	    DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2391	  else
2392            {
2393	      /* Set default visibility to whatever the user supplied with
2394	         #pragma GCC visibility or a namespace visibility attribute.  */
2395	      DECL_VISIBILITY (decl) = default_visibility;
2396	      DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2397            }
2398	}
2399    }
2400
2401  if (use_template)
2402    {
2403      /* If the specialization doesn't specify visibility, use the
2404	 visibility from the template.  */
2405      tree tinfo = (TREE_CODE (decl) == TYPE_DECL
2406		    ? TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2407		    : DECL_TEMPLATE_INFO (decl));
2408      tree args = TI_ARGS (tinfo);
2409      tree attribs = (TREE_CODE (decl) == TYPE_DECL
2410		      ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2411		      : DECL_ATTRIBUTES (decl));
2412
2413      if (args != error_mark_node)
2414	{
2415	  tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2416
2417	  if (!DECL_VISIBILITY_SPECIFIED (decl))
2418	    {
2419	      if (!DECL_VISIBILITY_SPECIFIED (pattern)
2420		  && determine_hidden_inline (decl))
2421		DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2422	      else
2423		{
2424	          DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2425	          DECL_VISIBILITY_SPECIFIED (decl)
2426		    = DECL_VISIBILITY_SPECIFIED (pattern);
2427		}
2428	    }
2429
2430	  if (args
2431	      /* Template argument visibility outweighs #pragma or namespace
2432		 visibility, but not an explicit attribute.  */
2433	      && !lookup_attribute ("visibility", attribs))
2434	    {
2435	      int depth = TMPL_ARGS_DEPTH (args);
2436	      if (DECL_VISIBILITY_SPECIFIED (decl))
2437		{
2438		  /* A class template member with explicit visibility
2439		     overrides the class visibility, so we need to apply
2440		     all the levels of template args directly.  */
2441		  int i;
2442		  for (i = 1; i <= depth; ++i)
2443		    {
2444		      tree lev = TMPL_ARGS_LEVEL (args, i);
2445		      constrain_visibility_for_template (decl, lev);
2446		    }
2447		}
2448	      else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2449		/* Limit visibility based on its template arguments.  */
2450		constrain_visibility_for_template (decl, args);
2451	    }
2452	}
2453    }
2454
2455  if (class_type)
2456    determine_visibility_from_class (decl, class_type);
2457
2458  if (decl_anon_ns_mem_p (decl))
2459    /* Names in an anonymous namespace get internal linkage.
2460       This might change once we implement export.  */
2461    constrain_visibility (decl, VISIBILITY_ANON, false);
2462  else if (TREE_CODE (decl) != TYPE_DECL)
2463    {
2464      /* Propagate anonymity from type to decl.  */
2465      int tvis = type_visibility (TREE_TYPE (decl));
2466      if (tvis == VISIBILITY_ANON
2467	  || ! DECL_VISIBILITY_SPECIFIED (decl))
2468	constrain_visibility (decl, tvis, false);
2469    }
2470  else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2471    /* DR 757: A type without linkage shall not be used as the type of a
2472       variable or function with linkage, unless
2473       o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2474       o the variable or function is not used (3.2 [basic.def.odr]) or is
2475       defined in the same translation unit.
2476
2477       Since non-extern "C" decls need to be defined in the same
2478       translation unit, we can make the type internal.  */
2479    constrain_visibility (decl, VISIBILITY_ANON, false);
2480
2481  /* If visibility changed and DECL already has DECL_RTL, ensure
2482     symbol flags are updated.  */
2483  if ((DECL_VISIBILITY (decl) != orig_visibility
2484       || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2485      && ((VAR_P (decl) && TREE_STATIC (decl))
2486	  || TREE_CODE (decl) == FUNCTION_DECL)
2487      && DECL_RTL_SET_P (decl))
2488    make_decl_rtl (decl);
2489}
2490
2491/* By default, static data members and function members receive
2492   the visibility of their containing class.  */
2493
2494static void
2495determine_visibility_from_class (tree decl, tree class_type)
2496{
2497  if (DECL_VISIBILITY_SPECIFIED (decl))
2498    return;
2499
2500  if (determine_hidden_inline (decl))
2501    DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2502  else
2503    {
2504      /* Default to the class visibility.  */
2505      DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2506      DECL_VISIBILITY_SPECIFIED (decl)
2507	= CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2508    }
2509
2510  /* Give the target a chance to override the visibility associated
2511     with DECL.  */
2512  if (VAR_P (decl)
2513      && (DECL_TINFO_P (decl)
2514	  || (DECL_VTABLE_OR_VTT_P (decl)
2515	      /* Construction virtual tables are not exported because
2516		 they cannot be referred to from other object files;
2517		 their name is not standardized by the ABI.  */
2518	      && !DECL_CONSTRUCTION_VTABLE_P (decl)))
2519      && TREE_PUBLIC (decl)
2520      && !DECL_REALLY_EXTERN (decl)
2521      && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2522    targetm.cxx.determine_class_data_visibility (decl);
2523}
2524
2525/* Returns true iff DECL is an inline that should get hidden visibility
2526   because of -fvisibility-inlines-hidden.  */
2527
2528static bool
2529determine_hidden_inline (tree decl)
2530{
2531  return (visibility_options.inlines_hidden
2532	  /* Don't do this for inline templates; specializations might not be
2533	     inline, and we don't want them to inherit the hidden
2534	     visibility.  We'll set it here for all inline instantiations.  */
2535	  && !processing_template_decl
2536	  && TREE_CODE (decl) == FUNCTION_DECL
2537	  && DECL_DECLARED_INLINE_P (decl)
2538	  && (! DECL_LANG_SPECIFIC (decl)
2539	      || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2540}
2541
2542/* Constrain the visibility of a class TYPE based on the visibility of its
2543   field types.  Warn if any fields require lesser visibility.  */
2544
2545void
2546constrain_class_visibility (tree type)
2547{
2548  tree binfo;
2549  tree t;
2550  int i;
2551
2552  int vis = type_visibility (type);
2553
2554  if (vis == VISIBILITY_ANON
2555      || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2556    return;
2557
2558  /* Don't warn about visibility if the class has explicit visibility.  */
2559  if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2560    vis = VISIBILITY_INTERNAL;
2561
2562  for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2563    if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node)
2564      {
2565	tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2566	int subvis = type_visibility (ftype);
2567
2568	if (subvis == VISIBILITY_ANON)
2569	  {
2570	    if (!in_main_input_context ())
2571	      warning (0, "\
2572%qT has a field %qD whose type uses the anonymous namespace",
2573		       type, t);
2574	  }
2575	else if (MAYBE_CLASS_TYPE_P (ftype)
2576		 && vis < VISIBILITY_HIDDEN
2577		 && subvis >= VISIBILITY_HIDDEN)
2578	  warning (OPT_Wattributes, "\
2579%qT declared with greater visibility than the type of its field %qD",
2580		   type, t);
2581      }
2582
2583  binfo = TYPE_BINFO (type);
2584  for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
2585    {
2586      int subvis = type_visibility (TREE_TYPE (t));
2587
2588      if (subvis == VISIBILITY_ANON)
2589        {
2590	  if (!in_main_input_context())
2591	    warning (0, "\
2592%qT has a base %qT whose type uses the anonymous namespace",
2593		     type, TREE_TYPE (t));
2594	}
2595      else if (vis < VISIBILITY_HIDDEN
2596	       && subvis >= VISIBILITY_HIDDEN)
2597	warning (OPT_Wattributes, "\
2598%qT declared with greater visibility than its base %qT",
2599		 type, TREE_TYPE (t));
2600    }
2601}
2602
2603/* Functions for adjusting the visibility of a tagged type and its nested
2604   types and declarations when it gets a name for linkage purposes from a
2605   typedef.  */
2606
2607static void bt_reset_linkage_1 (binding_entry, void *);
2608static void bt_reset_linkage_2 (binding_entry, void *);
2609
2610/* First reset the visibility of all the types.  */
2611
2612static void
2613reset_type_linkage_1 (tree type)
2614{
2615  set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
2616  if (CLASS_TYPE_P (type))
2617    binding_table_foreach (CLASSTYPE_NESTED_UTDS (type),
2618			   bt_reset_linkage_1, NULL);
2619}
2620static void
2621bt_reset_linkage_1 (binding_entry b, void */*data*/)
2622{
2623  reset_type_linkage_1 (b->type);
2624}
2625
2626/* Then reset the visibility of any static data members or member
2627   functions that use those types.  */
2628
2629static void
2630reset_decl_linkage (tree decl)
2631{
2632  if (TREE_PUBLIC (decl))
2633    return;
2634  if (DECL_CLONED_FUNCTION_P (decl))
2635    return;
2636  TREE_PUBLIC (decl) = true;
2637  DECL_INTERFACE_KNOWN (decl) = false;
2638  determine_visibility (decl);
2639  tentative_decl_linkage (decl);
2640}
2641static void
2642reset_type_linkage_2 (tree type)
2643{
2644  if (CLASS_TYPE_P (type))
2645    {
2646      if (tree vt = CLASSTYPE_VTABLES (type))
2647	{
2648	  tree name = mangle_vtbl_for_type (type);
2649	  DECL_NAME (vt) = name;
2650	  SET_DECL_ASSEMBLER_NAME (vt, name);
2651	  reset_decl_linkage (vt);
2652	}
2653      if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
2654	{
2655	  tree name = mangle_typeinfo_for_type (type);
2656	  DECL_NAME (ti) = name;
2657	  SET_DECL_ASSEMBLER_NAME (ti, name);
2658	  TREE_TYPE (name) = type;
2659	  reset_decl_linkage (ti);
2660	}
2661      for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
2662	{
2663	  tree mem = STRIP_TEMPLATE (m);
2664	  if (VAR_P (mem))
2665	    reset_decl_linkage (mem);
2666	}
2667      for (tree m = TYPE_METHODS (type); m; m = DECL_CHAIN (m))
2668	{
2669	  tree mem = STRIP_TEMPLATE (m);
2670	  reset_decl_linkage (mem);
2671	}
2672      binding_table_foreach (CLASSTYPE_NESTED_UTDS (type),
2673			     bt_reset_linkage_2, NULL);
2674    }
2675}
2676static void
2677bt_reset_linkage_2 (binding_entry b, void */*data*/)
2678{
2679  reset_type_linkage_2 (b->type);
2680}
2681void
2682reset_type_linkage (tree type)
2683{
2684  reset_type_linkage_1 (type);
2685  reset_type_linkage_2 (type);
2686}
2687
2688/* Set up our initial idea of what the linkage of DECL should be.  */
2689
2690void
2691tentative_decl_linkage (tree decl)
2692{
2693  if (DECL_INTERFACE_KNOWN (decl))
2694    /* We've already made a decision as to how this function will
2695       be handled.  */;
2696  else if (vague_linkage_p (decl))
2697    {
2698      if (TREE_CODE (decl) == FUNCTION_DECL
2699	  && decl_defined_p (decl))
2700	{
2701	  DECL_EXTERNAL (decl) = 1;
2702	  DECL_NOT_REALLY_EXTERN (decl) = 1;
2703	  note_vague_linkage_fn (decl);
2704	  /* A non-template inline function with external linkage will
2705	     always be COMDAT.  As we must eventually determine the
2706	     linkage of all functions, and as that causes writes to
2707	     the data mapped in from the PCH file, it's advantageous
2708	     to mark the functions at this point.  */
2709	  if (DECL_DECLARED_INLINE_P (decl)
2710	      && (!DECL_IMPLICIT_INSTANTIATION (decl)
2711		  || DECL_DEFAULTED_FN (decl)))
2712	    {
2713	      /* This function must have external linkage, as
2714		 otherwise DECL_INTERFACE_KNOWN would have been
2715		 set.  */
2716	      gcc_assert (TREE_PUBLIC (decl));
2717	      comdat_linkage (decl);
2718	      DECL_INTERFACE_KNOWN (decl) = 1;
2719	    }
2720	}
2721      else if (TREE_CODE (decl) == VAR_DECL)
2722	maybe_commonize_var (decl);
2723    }
2724}
2725
2726/* DECL is a FUNCTION_DECL or VAR_DECL.  If the object file linkage
2727   for DECL has not already been determined, do so now by setting
2728   DECL_EXTERNAL, DECL_COMDAT and other related flags.  Until this
2729   function is called entities with vague linkage whose definitions
2730   are available must have TREE_PUBLIC set.
2731
2732   If this function decides to place DECL in COMDAT, it will set
2733   appropriate flags -- but will not clear DECL_EXTERNAL.  It is up to
2734   the caller to decide whether or not to clear DECL_EXTERNAL.  Some
2735   callers defer that decision until it is clear that DECL is actually
2736   required.  */
2737
2738void
2739import_export_decl (tree decl)
2740{
2741  int emit_p;
2742  bool comdat_p;
2743  bool import_p;
2744  tree class_type = NULL_TREE;
2745
2746  if (DECL_INTERFACE_KNOWN (decl))
2747    return;
2748
2749  /* We cannot determine what linkage to give to an entity with vague
2750     linkage until the end of the file.  For example, a virtual table
2751     for a class will be defined if and only if the key method is
2752     defined in this translation unit.  As a further example, consider
2753     that when compiling a translation unit that uses PCH file with
2754     "-frepo" it would be incorrect to make decisions about what
2755     entities to emit when building the PCH; those decisions must be
2756     delayed until the repository information has been processed.  */
2757  gcc_assert (at_eof);
2758  /* Object file linkage for explicit instantiations is handled in
2759     mark_decl_instantiated.  For static variables in functions with
2760     vague linkage, maybe_commonize_var is used.
2761
2762     Therefore, the only declarations that should be provided to this
2763     function are those with external linkage that are:
2764
2765     * implicit instantiations of function templates
2766
2767     * inline function
2768
2769     * implicit instantiations of static data members of class
2770       templates
2771
2772     * virtual tables
2773
2774     * typeinfo objects
2775
2776     Furthermore, all entities that reach this point must have a
2777     definition available in this translation unit.
2778
2779     The following assertions check these conditions.  */
2780  gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2781  /* Any code that creates entities with TREE_PUBLIC cleared should
2782     also set DECL_INTERFACE_KNOWN.  */
2783  gcc_assert (TREE_PUBLIC (decl));
2784  if (TREE_CODE (decl) == FUNCTION_DECL)
2785    gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2786		|| DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
2787		|| DECL_DECLARED_INLINE_P (decl));
2788  else
2789    gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2790		|| DECL_VTABLE_OR_VTT_P (decl)
2791		|| DECL_TINFO_P (decl));
2792  /* Check that a definition of DECL is available in this translation
2793     unit.  */
2794  gcc_assert (!DECL_REALLY_EXTERN (decl));
2795
2796  /* Assume that DECL will not have COMDAT linkage.  */
2797  comdat_p = false;
2798  /* Assume that DECL will not be imported into this translation
2799     unit.  */
2800  import_p = false;
2801
2802  /* See if the repository tells us whether or not to emit DECL in
2803     this translation unit.  */
2804  emit_p = repo_emit_p (decl);
2805  if (emit_p == 0)
2806    import_p = true;
2807  else if (emit_p == 1)
2808    {
2809      /* The repository indicates that this entity should be defined
2810	 here.  Make sure the back end honors that request.  */
2811      mark_needed (decl);
2812      /* Output the definition as an ordinary strong definition.  */
2813      DECL_EXTERNAL (decl) = 0;
2814      DECL_INTERFACE_KNOWN (decl) = 1;
2815      return;
2816    }
2817
2818  if (import_p)
2819    /* We have already decided what to do with this DECL; there is no
2820       need to check anything further.  */
2821    ;
2822  else if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
2823    {
2824      class_type = DECL_CONTEXT (decl);
2825      import_export_class (class_type);
2826      if (TYPE_FOR_JAVA (class_type))
2827	import_p = true;
2828      else if (CLASSTYPE_INTERFACE_KNOWN (class_type)
2829	       && CLASSTYPE_INTERFACE_ONLY (class_type))
2830	import_p = true;
2831      else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
2832	       && !CLASSTYPE_USE_TEMPLATE (class_type)
2833	       && CLASSTYPE_KEY_METHOD (class_type)
2834	       && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
2835	/* The ABI requires that all virtual tables be emitted with
2836	   COMDAT linkage.  However, on systems where COMDAT symbols
2837	   don't show up in the table of contents for a static
2838	   archive, or on systems without weak symbols (where we
2839	   approximate COMDAT linkage by using internal linkage), the
2840	   linker will report errors about undefined symbols because
2841	   it will not see the virtual table definition.  Therefore,
2842	   in the case that we know that the virtual table will be
2843	   emitted in only one translation unit, we make the virtual
2844	   table an ordinary definition with external linkage.  */
2845	DECL_EXTERNAL (decl) = 0;
2846      else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
2847	{
2848	  /* CLASS_TYPE is being exported from this translation unit,
2849	     so DECL should be defined here.  */
2850	  if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
2851	    /* If a class is declared in a header with the "extern
2852	       template" extension, then it will not be instantiated,
2853	       even in translation units that would normally require
2854	       it.  Often such classes are explicitly instantiated in
2855	       one translation unit.  Therefore, the explicit
2856	       instantiation must be made visible to other translation
2857	       units.  */
2858	    DECL_EXTERNAL (decl) = 0;
2859	  else
2860	    {
2861	      /* The generic C++ ABI says that class data is always
2862		 COMDAT, even if there is a key function.  Some
2863		 variants (e.g., the ARM EABI) says that class data
2864		 only has COMDAT linkage if the class data might be
2865		 emitted in more than one translation unit.  When the
2866		 key method can be inline and is inline, we still have
2867		 to arrange for comdat even though
2868		 class_data_always_comdat is false.  */
2869	      if (!CLASSTYPE_KEY_METHOD (class_type)
2870		  || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
2871		  || targetm.cxx.class_data_always_comdat ())
2872		{
2873		  /* The ABI requires COMDAT linkage.  Normally, we
2874		     only emit COMDAT things when they are needed;
2875		     make sure that we realize that this entity is
2876		     indeed needed.  */
2877		  comdat_p = true;
2878		  mark_needed (decl);
2879		}
2880	    }
2881	}
2882      else if (!flag_implicit_templates
2883	       && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
2884	import_p = true;
2885      else
2886	comdat_p = true;
2887    }
2888  else if (VAR_P (decl) && DECL_TINFO_P (decl))
2889    {
2890      tree type = TREE_TYPE (DECL_NAME (decl));
2891      if (CLASS_TYPE_P (type))
2892	{
2893	  class_type = type;
2894	  import_export_class (type);
2895	  if (CLASSTYPE_INTERFACE_KNOWN (type)
2896	      && TYPE_POLYMORPHIC_P (type)
2897	      && CLASSTYPE_INTERFACE_ONLY (type)
2898	      /* If -fno-rtti was specified, then we cannot be sure
2899		 that RTTI information will be emitted with the
2900		 virtual table of the class, so we must emit it
2901		 wherever it is used.  */
2902	      && flag_rtti)
2903	    import_p = true;
2904	  else
2905	    {
2906	      if (CLASSTYPE_INTERFACE_KNOWN (type)
2907		  && !CLASSTYPE_INTERFACE_ONLY (type))
2908		{
2909		  comdat_p = (targetm.cxx.class_data_always_comdat ()
2910			      || (CLASSTYPE_KEY_METHOD (type)
2911				  && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
2912		  mark_needed (decl);
2913		  if (!flag_weak)
2914		    {
2915		      comdat_p = false;
2916		      DECL_EXTERNAL (decl) = 0;
2917		    }
2918		}
2919	      else
2920		comdat_p = true;
2921	    }
2922	}
2923      else
2924	comdat_p = true;
2925    }
2926  else if (DECL_TEMPLOID_INSTANTIATION (decl))
2927    {
2928      /* DECL is an implicit instantiation of a function or static
2929	 data member.  */
2930      if ((flag_implicit_templates
2931	   && !flag_use_repository)
2932	  || (flag_implicit_inline_templates
2933	      && TREE_CODE (decl) == FUNCTION_DECL
2934	      && DECL_DECLARED_INLINE_P (decl)))
2935	comdat_p = true;
2936      else
2937	/* If we are not implicitly generating templates, then mark
2938	   this entity as undefined in this translation unit.  */
2939	import_p = true;
2940    }
2941  else if (DECL_FUNCTION_MEMBER_P (decl))
2942    {
2943      if (!DECL_DECLARED_INLINE_P (decl))
2944	{
2945	  tree ctype = DECL_CONTEXT (decl);
2946	  import_export_class (ctype);
2947	  if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2948	    {
2949	      DECL_NOT_REALLY_EXTERN (decl)
2950		= ! (CLASSTYPE_INTERFACE_ONLY (ctype)
2951		     || (DECL_DECLARED_INLINE_P (decl)
2952			 && ! flag_implement_inlines
2953			 && !DECL_VINDEX (decl)));
2954
2955	      if (!DECL_NOT_REALLY_EXTERN (decl))
2956		DECL_EXTERNAL (decl) = 1;
2957
2958	      /* Always make artificials weak.  */
2959	      if (DECL_ARTIFICIAL (decl) && flag_weak)
2960		comdat_p = true;
2961	      else
2962		maybe_make_one_only (decl);
2963	    }
2964	}
2965      else
2966	comdat_p = true;
2967    }
2968  else
2969    comdat_p = true;
2970
2971  if (import_p)
2972    {
2973      /* If we are importing DECL into this translation unit, mark is
2974	 an undefined here.  */
2975      DECL_EXTERNAL (decl) = 1;
2976      DECL_NOT_REALLY_EXTERN (decl) = 0;
2977    }
2978  else if (comdat_p)
2979    {
2980      /* If we decided to put DECL in COMDAT, mark it accordingly at
2981	 this point.  */
2982      comdat_linkage (decl);
2983    }
2984
2985  DECL_INTERFACE_KNOWN (decl) = 1;
2986}
2987
2988/* Return an expression that performs the destruction of DECL, which
2989   must be a VAR_DECL whose type has a non-trivial destructor, or is
2990   an array whose (innermost) elements have a non-trivial destructor.  */
2991
2992tree
2993build_cleanup (tree decl)
2994{
2995  tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
2996  gcc_assert (clean != NULL_TREE);
2997  return clean;
2998}
2999
3000/* Returns the initialization guard variable for the variable DECL,
3001   which has static storage duration.  */
3002
3003tree
3004get_guard (tree decl)
3005{
3006  tree sname;
3007  tree guard;
3008
3009  sname = mangle_guard_variable (decl);
3010  guard = IDENTIFIER_GLOBAL_VALUE (sname);
3011  if (! guard)
3012    {
3013      tree guard_type;
3014
3015      /* We use a type that is big enough to contain a mutex as well
3016	 as an integer counter.  */
3017      guard_type = targetm.cxx.guard_type ();
3018      guard = build_decl (DECL_SOURCE_LOCATION (decl),
3019			  VAR_DECL, sname, guard_type);
3020
3021      /* The guard should have the same linkage as what it guards.  */
3022      TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3023      TREE_STATIC (guard) = TREE_STATIC (decl);
3024      DECL_COMMON (guard) = DECL_COMMON (decl);
3025      DECL_COMDAT (guard) = DECL_COMDAT (decl);
3026      set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3027      if (DECL_ONE_ONLY (decl))
3028	make_decl_one_only (guard, cxx_comdat_group (guard));
3029      if (TREE_PUBLIC (decl))
3030	DECL_WEAK (guard) = DECL_WEAK (decl);
3031      DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3032      DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3033
3034      DECL_ARTIFICIAL (guard) = 1;
3035      DECL_IGNORED_P (guard) = 1;
3036      TREE_USED (guard) = 1;
3037      pushdecl_top_level_and_finish (guard, NULL_TREE);
3038    }
3039  return guard;
3040}
3041
3042/* Return those bits of the GUARD variable that should be set when the
3043   guarded entity is actually initialized.  */
3044
3045static tree
3046get_guard_bits (tree guard)
3047{
3048  if (!targetm.cxx.guard_mask_bit ())
3049    {
3050      /* We only set the first byte of the guard, in order to leave room
3051	 for a mutex in the high-order bits.  */
3052      guard = build1 (ADDR_EXPR,
3053		      build_pointer_type (TREE_TYPE (guard)),
3054		      guard);
3055      guard = build1 (NOP_EXPR,
3056		      build_pointer_type (char_type_node),
3057		      guard);
3058      guard = build1 (INDIRECT_REF, char_type_node, guard);
3059    }
3060
3061  return guard;
3062}
3063
3064/* Return an expression which determines whether or not the GUARD
3065   variable has already been initialized.  */
3066
3067tree
3068get_guard_cond (tree guard)
3069{
3070  tree guard_value;
3071
3072  /* Check to see if the GUARD is zero.  */
3073  guard = get_guard_bits (guard);
3074
3075  /* Mask off all but the low bit.  */
3076  if (targetm.cxx.guard_mask_bit ())
3077    {
3078      guard_value = integer_one_node;
3079      if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3080	guard_value = convert (TREE_TYPE (guard), guard_value);
3081      guard = cp_build_binary_op (input_location,
3082				  BIT_AND_EXPR, guard, guard_value,
3083				  tf_warning_or_error);
3084    }
3085
3086  guard_value = integer_zero_node;
3087  if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3088    guard_value = convert (TREE_TYPE (guard), guard_value);
3089  return cp_build_binary_op (input_location,
3090			     EQ_EXPR, guard, guard_value,
3091			     tf_warning_or_error);
3092}
3093
3094/* Return an expression which sets the GUARD variable, indicating that
3095   the variable being guarded has been initialized.  */
3096
3097tree
3098set_guard (tree guard)
3099{
3100  tree guard_init;
3101
3102  /* Set the GUARD to one.  */
3103  guard = get_guard_bits (guard);
3104  guard_init = integer_one_node;
3105  if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3106    guard_init = convert (TREE_TYPE (guard), guard_init);
3107  return cp_build_modify_expr (guard, NOP_EXPR, guard_init,
3108			       tf_warning_or_error);
3109}
3110
3111/* Returns true iff we can tell that VAR does not have a dynamic
3112   initializer.  */
3113
3114static bool
3115var_defined_without_dynamic_init (tree var)
3116{
3117  /* If it's defined in another TU, we can't tell.  */
3118  if (DECL_EXTERNAL (var))
3119    return false;
3120  /* If it has a non-trivial destructor, registering the destructor
3121     counts as dynamic initialization.  */
3122  if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3123    return false;
3124  /* If it's in this TU, its initializer has been processed, unless
3125     it's a case of self-initialization, then DECL_INITIALIZED_P is
3126     false while the initializer is handled by finish_id_expression.  */
3127  if (!DECL_INITIALIZED_P (var))
3128    return false;
3129  /* If it has no initializer or a constant one, it's not dynamic.  */
3130  return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3131	  || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3132}
3133
3134/* Returns true iff VAR is a variable that needs uses to be
3135   wrapped for possible dynamic initialization.  */
3136
3137static bool
3138var_needs_tls_wrapper (tree var)
3139{
3140  return (!error_operand_p (var)
3141	  && DECL_THREAD_LOCAL_P (var)
3142	  && !DECL_GNU_TLS_P (var)
3143	  && !DECL_FUNCTION_SCOPE_P (var)
3144	  && !var_defined_without_dynamic_init (var));
3145}
3146
3147/* Get the FUNCTION_DECL for the shared TLS init function for this
3148   translation unit.  */
3149
3150static tree
3151get_local_tls_init_fn (void)
3152{
3153  tree sname = get_identifier ("__tls_init");
3154  tree fn = IDENTIFIER_GLOBAL_VALUE (sname);
3155  if (!fn)
3156    {
3157      fn = build_lang_decl (FUNCTION_DECL, sname,
3158			     build_function_type (void_type_node,
3159						  void_list_node));
3160      SET_DECL_LANGUAGE (fn, lang_c);
3161      TREE_PUBLIC (fn) = false;
3162      DECL_ARTIFICIAL (fn) = true;
3163      mark_used (fn);
3164      SET_IDENTIFIER_GLOBAL_VALUE (sname, fn);
3165    }
3166  return fn;
3167}
3168
3169/* Get a FUNCTION_DECL for the init function for the thread_local
3170   variable VAR.  The init function will be an alias to the function
3171   that initializes all the non-local TLS variables in the translation
3172   unit.  The init function is only used by the wrapper function.  */
3173
3174static tree
3175get_tls_init_fn (tree var)
3176{
3177  /* Only C++11 TLS vars need this init fn.  */
3178  if (!var_needs_tls_wrapper (var))
3179    return NULL_TREE;
3180
3181  /* If -fno-extern-tls-init, assume that we don't need to call
3182     a tls init function for a variable defined in another TU.  */
3183  if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3184    return NULL_TREE;
3185
3186#ifdef ASM_OUTPUT_DEF
3187  /* If the variable is internal, or if we can't generate aliases,
3188     call the local init function directly.  */
3189  if (!TREE_PUBLIC (var))
3190#endif
3191    return get_local_tls_init_fn ();
3192
3193  tree sname = mangle_tls_init_fn (var);
3194  tree fn = IDENTIFIER_GLOBAL_VALUE (sname);
3195  if (!fn)
3196    {
3197      fn = build_lang_decl (FUNCTION_DECL, sname,
3198			    build_function_type (void_type_node,
3199						 void_list_node));
3200      SET_DECL_LANGUAGE (fn, lang_c);
3201      TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3202      DECL_ARTIFICIAL (fn) = true;
3203      DECL_COMDAT (fn) = DECL_COMDAT (var);
3204      DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3205      if (DECL_ONE_ONLY (var))
3206	make_decl_one_only (fn, cxx_comdat_group (fn));
3207      if (TREE_PUBLIC (var))
3208	{
3209	  tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3210	  /* If the variable is defined somewhere else and might have static
3211	     initialization, make the init function a weak reference.  */
3212	  if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3213	       || TYPE_HAS_CONSTEXPR_CTOR (obtype))
3214	      && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3215	      && DECL_EXTERNAL (var))
3216	    declare_weak (fn);
3217	  else
3218	    DECL_WEAK (fn) = DECL_WEAK (var);
3219	}
3220      DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3221      DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3222      DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3223      DECL_IGNORED_P (fn) = 1;
3224      mark_used (fn);
3225
3226      DECL_BEFRIENDING_CLASSES (fn) = var;
3227
3228      SET_IDENTIFIER_GLOBAL_VALUE (sname, fn);
3229    }
3230  return fn;
3231}
3232
3233/* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3234   variable VAR.  The wrapper function calls the init function (if any) for
3235   VAR and then returns a reference to VAR.  The wrapper function is used
3236   in place of VAR everywhere VAR is mentioned.  */
3237
3238tree
3239get_tls_wrapper_fn (tree var)
3240{
3241  /* Only C++11 TLS vars need this wrapper fn.  */
3242  if (!var_needs_tls_wrapper (var))
3243    return NULL_TREE;
3244
3245  tree sname = mangle_tls_wrapper_fn (var);
3246  tree fn = IDENTIFIER_GLOBAL_VALUE (sname);
3247  if (!fn)
3248    {
3249      /* A named rvalue reference is an lvalue, so the wrapper should
3250	 always return an lvalue reference.  */
3251      tree type = non_reference (TREE_TYPE (var));
3252      type = build_reference_type (type);
3253      tree fntype = build_function_type (type, void_list_node);
3254      fn = build_lang_decl (FUNCTION_DECL, sname, fntype);
3255      SET_DECL_LANGUAGE (fn, lang_c);
3256      TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3257      DECL_ARTIFICIAL (fn) = true;
3258      DECL_IGNORED_P (fn) = 1;
3259      /* The wrapper is inline and emitted everywhere var is used.  */
3260      DECL_DECLARED_INLINE_P (fn) = true;
3261      if (TREE_PUBLIC (var))
3262	{
3263	  comdat_linkage (fn);
3264#ifdef HAVE_GAS_HIDDEN
3265	  /* Make the wrapper bind locally; there's no reason to share
3266	     the wrapper between multiple shared objects.  */
3267	  DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3268	  DECL_VISIBILITY_SPECIFIED (fn) = true;
3269#endif
3270	}
3271      if (!TREE_PUBLIC (fn))
3272	DECL_INTERFACE_KNOWN (fn) = true;
3273      mark_used (fn);
3274      note_vague_linkage_fn (fn);
3275
3276#if 0
3277      /* We want CSE to commonize calls to the wrapper, but marking it as
3278	 pure is unsafe since it has side-effects.  I guess we need a new
3279	 ECF flag even weaker than ECF_PURE.  FIXME!  */
3280      DECL_PURE_P (fn) = true;
3281#endif
3282
3283      DECL_BEFRIENDING_CLASSES (fn) = var;
3284
3285      SET_IDENTIFIER_GLOBAL_VALUE (sname, fn);
3286    }
3287  return fn;
3288}
3289
3290/* At EOF, generate the definition for the TLS wrapper function FN:
3291
3292   T& var_wrapper() {
3293     if (init_fn) init_fn();
3294     return var;
3295   }  */
3296
3297static void
3298generate_tls_wrapper (tree fn)
3299{
3300  tree var = DECL_BEFRIENDING_CLASSES (fn);
3301
3302  start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3303  tree body = begin_function_body ();
3304  /* Only call the init fn if there might be one.  */
3305  if (tree init_fn = get_tls_init_fn (var))
3306    {
3307      tree if_stmt = NULL_TREE;
3308      /* If init_fn is a weakref, make sure it exists before calling.  */
3309      if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3310	{
3311	  if_stmt = begin_if_stmt ();
3312	  tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3313	  tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3314					  NE_EXPR, addr, nullptr_node,
3315					  tf_warning_or_error);
3316	  finish_if_stmt_cond (cond, if_stmt);
3317	}
3318      finish_expr_stmt (build_cxx_call
3319			(init_fn, 0, NULL, tf_warning_or_error));
3320      if (if_stmt)
3321	{
3322	  finish_then_clause (if_stmt);
3323	  finish_if_stmt (if_stmt);
3324	}
3325    }
3326  else
3327    /* If there's no initialization, the wrapper is a constant function.  */
3328    TREE_READONLY (fn) = true;
3329  finish_return_stmt (convert_from_reference (var));
3330  finish_function_body (body);
3331  expand_or_defer_fn (finish_function (0));
3332}
3333
3334/* Start the process of running a particular set of global constructors
3335   or destructors.  Subroutine of do_[cd]tors.  Also called from
3336   vtv_start_verification_constructor_init_function.  */
3337
3338static tree
3339start_objects (int method_type, int initp)
3340{
3341  tree body;
3342  tree fndecl;
3343  char type[14];
3344
3345  /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
3346
3347  if (initp != DEFAULT_INIT_PRIORITY)
3348    {
3349      char joiner;
3350
3351#ifdef JOINER
3352      joiner = JOINER;
3353#else
3354      joiner = '_';
3355#endif
3356
3357      sprintf (type, "sub_%c%c%.5u", method_type, joiner, initp);
3358    }
3359  else
3360    sprintf (type, "sub_%c", method_type);
3361
3362  fndecl = build_lang_decl (FUNCTION_DECL,
3363			    get_file_function_name (type),
3364			    build_function_type_list (void_type_node,
3365						      NULL_TREE));
3366  start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3367
3368  TREE_PUBLIC (current_function_decl) = 0;
3369
3370  /* Mark as artificial because it's not explicitly in the user's
3371     source code.  */
3372  DECL_ARTIFICIAL (current_function_decl) = 1;
3373
3374  /* Mark this declaration as used to avoid spurious warnings.  */
3375  TREE_USED (current_function_decl) = 1;
3376
3377  /* Mark this function as a global constructor or destructor.  */
3378  if (method_type == 'I')
3379    DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3380  else
3381    DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3382
3383  body = begin_compound_stmt (BCS_FN_BODY);
3384
3385  return body;
3386}
3387
3388/* Finish the process of running a particular set of global constructors
3389   or destructors.  Subroutine of do_[cd]tors.  */
3390
3391static void
3392finish_objects (int method_type, int initp, tree body)
3393{
3394  tree fn;
3395
3396  /* Finish up.  */
3397  finish_compound_stmt (body);
3398  fn = finish_function (0);
3399
3400  if (method_type == 'I')
3401    {
3402      DECL_STATIC_CONSTRUCTOR (fn) = 1;
3403      decl_init_priority_insert (fn, initp);
3404    }
3405  else
3406    {
3407      DECL_STATIC_DESTRUCTOR (fn) = 1;
3408      decl_fini_priority_insert (fn, initp);
3409    }
3410
3411  expand_or_defer_fn (fn);
3412}
3413
3414/* The names of the parameters to the function created to handle
3415   initializations and destructions for objects with static storage
3416   duration.  */
3417#define INITIALIZE_P_IDENTIFIER "__initialize_p"
3418#define PRIORITY_IDENTIFIER "__priority"
3419
3420/* The name of the function we create to handle initializations and
3421   destructions for objects with static storage duration.  */
3422#define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3423
3424/* The declaration for the __INITIALIZE_P argument.  */
3425static GTY(()) tree initialize_p_decl;
3426
3427/* The declaration for the __PRIORITY argument.  */
3428static GTY(()) tree priority_decl;
3429
3430/* The declaration for the static storage duration function.  */
3431static GTY(()) tree ssdf_decl;
3432
3433/* All the static storage duration functions created in this
3434   translation unit.  */
3435static GTY(()) vec<tree, va_gc> *ssdf_decls;
3436
3437/* A map from priority levels to information about that priority
3438   level.  There may be many such levels, so efficient lookup is
3439   important.  */
3440static splay_tree priority_info_map;
3441
3442/* Begins the generation of the function that will handle all
3443   initialization and destruction of objects with static storage
3444   duration.  The function generated takes two parameters of type
3445   `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
3446   nonzero, it performs initializations.  Otherwise, it performs
3447   destructions.  It only performs those initializations or
3448   destructions with the indicated __PRIORITY.  The generated function
3449   returns no value.
3450
3451   It is assumed that this function will only be called once per
3452   translation unit.  */
3453
3454static tree
3455start_static_storage_duration_function (unsigned count)
3456{
3457  tree type;
3458  tree body;
3459  char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3460
3461  /* Create the identifier for this function.  It will be of the form
3462     SSDF_IDENTIFIER_<number>.  */
3463  sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3464
3465  type = build_function_type_list (void_type_node,
3466				   integer_type_node, integer_type_node,
3467				   NULL_TREE);
3468
3469  /* Create the FUNCTION_DECL itself.  */
3470  ssdf_decl = build_lang_decl (FUNCTION_DECL,
3471			       get_identifier (id),
3472			       type);
3473  TREE_PUBLIC (ssdf_decl) = 0;
3474  DECL_ARTIFICIAL (ssdf_decl) = 1;
3475
3476  /* Put this function in the list of functions to be called from the
3477     static constructors and destructors.  */
3478  if (!ssdf_decls)
3479    {
3480      vec_alloc (ssdf_decls, 32);
3481
3482      /* Take this opportunity to initialize the map from priority
3483	 numbers to information about that priority level.  */
3484      priority_info_map = splay_tree_new (splay_tree_compare_ints,
3485					  /*delete_key_fn=*/0,
3486					  /*delete_value_fn=*/
3487					  (splay_tree_delete_value_fn) &free);
3488
3489      /* We always need to generate functions for the
3490	 DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
3491	 priorities later, we'll be sure to find the
3492	 DEFAULT_INIT_PRIORITY.  */
3493      get_priority_info (DEFAULT_INIT_PRIORITY);
3494    }
3495
3496  vec_safe_push (ssdf_decls, ssdf_decl);
3497
3498  /* Create the argument list.  */
3499  initialize_p_decl = cp_build_parm_decl
3500    (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
3501  DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
3502  TREE_USED (initialize_p_decl) = 1;
3503  priority_decl = cp_build_parm_decl
3504    (get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
3505  DECL_CONTEXT (priority_decl) = ssdf_decl;
3506  TREE_USED (priority_decl) = 1;
3507
3508  DECL_CHAIN (initialize_p_decl) = priority_decl;
3509  DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
3510
3511  /* Put the function in the global scope.  */
3512  pushdecl (ssdf_decl);
3513
3514  /* Start the function itself.  This is equivalent to declaring the
3515     function as:
3516
3517       static void __ssdf (int __initialize_p, init __priority_p);
3518
3519     It is static because we only need to call this function from the
3520     various constructor and destructor functions for this module.  */
3521  start_preparsed_function (ssdf_decl,
3522			    /*attrs=*/NULL_TREE,
3523			    SF_PRE_PARSED);
3524
3525  /* Set up the scope of the outermost block in the function.  */
3526  body = begin_compound_stmt (BCS_FN_BODY);
3527
3528  return body;
3529}
3530
3531/* Finish the generation of the function which performs initialization
3532   and destruction of objects with static storage duration.  After
3533   this point, no more such objects can be created.  */
3534
3535static void
3536finish_static_storage_duration_function (tree body)
3537{
3538  /* Close out the function.  */
3539  finish_compound_stmt (body);
3540  expand_or_defer_fn (finish_function (0));
3541}
3542
3543/* Return the information about the indicated PRIORITY level.  If no
3544   code to handle this level has yet been generated, generate the
3545   appropriate prologue.  */
3546
3547static priority_info
3548get_priority_info (int priority)
3549{
3550  priority_info pi;
3551  splay_tree_node n;
3552
3553  n = splay_tree_lookup (priority_info_map,
3554			 (splay_tree_key) priority);
3555  if (!n)
3556    {
3557      /* Create a new priority information structure, and insert it
3558	 into the map.  */
3559      pi = XNEW (struct priority_info_s);
3560      pi->initializations_p = 0;
3561      pi->destructions_p = 0;
3562      splay_tree_insert (priority_info_map,
3563			 (splay_tree_key) priority,
3564			 (splay_tree_value) pi);
3565    }
3566  else
3567    pi = (priority_info) n->value;
3568
3569  return pi;
3570}
3571
3572/* The effective initialization priority of a DECL.  */
3573
3574#define DECL_EFFECTIVE_INIT_PRIORITY(decl)				      \
3575	((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
3576	 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
3577
3578/* Whether a DECL needs a guard to protect it against multiple
3579   initialization.  */
3580
3581#define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl)      \
3582						    || DECL_ONE_ONLY (decl) \
3583						    || DECL_WEAK (decl)))
3584
3585/* Called from one_static_initialization_or_destruction(),
3586   via walk_tree.
3587   Walks the initializer list of a global variable and looks for
3588   temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
3589   and that have their DECL_CONTEXT() == NULL.
3590   For each such temporary variable, set their DECL_CONTEXT() to
3591   the current function. This is necessary because otherwise
3592   some optimizers (enabled by -O2 -fprofile-arcs) might crash
3593   when trying to refer to a temporary variable that does not have
3594   it's DECL_CONTECT() properly set.  */
3595static tree
3596fix_temporary_vars_context_r (tree *node,
3597			      int  * /*unused*/,
3598			      void * /*unused1*/)
3599{
3600  gcc_assert (current_function_decl);
3601
3602  if (TREE_CODE (*node) == BIND_EXPR)
3603    {
3604      tree var;
3605
3606      for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
3607	if (VAR_P (var)
3608	  && !DECL_NAME (var)
3609	  && DECL_ARTIFICIAL (var)
3610	  && !DECL_CONTEXT (var))
3611	  DECL_CONTEXT (var) = current_function_decl;
3612    }
3613
3614  return NULL_TREE;
3615}
3616
3617/* Set up to handle the initialization or destruction of DECL.  If
3618   INITP is nonzero, we are initializing the variable.  Otherwise, we
3619   are destroying it.  */
3620
3621static void
3622one_static_initialization_or_destruction (tree decl, tree init, bool initp)
3623{
3624  tree guard_if_stmt = NULL_TREE;
3625  tree guard;
3626
3627  /* If we are supposed to destruct and there's a trivial destructor,
3628     nothing has to be done.  */
3629  if (!initp
3630      && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3631    return;
3632
3633  /* Trick the compiler into thinking we are at the file and line
3634     where DECL was declared so that error-messages make sense, and so
3635     that the debugger will show somewhat sensible file and line
3636     information.  */
3637  input_location = DECL_SOURCE_LOCATION (decl);
3638
3639  /* Make sure temporary variables in the initialiser all have
3640     their DECL_CONTEXT() set to a value different from NULL_TREE.
3641     This can happen when global variables initialisers are built.
3642     In that case, the DECL_CONTEXT() of the global variables _AND_ of all
3643     the temporary variables that might have been generated in the
3644     accompagning initialisers is NULL_TREE, meaning the variables have been
3645     declared in the global namespace.
3646     What we want to do here is to fix that and make sure the DECL_CONTEXT()
3647     of the temporaries are set to the current function decl.  */
3648  cp_walk_tree_without_duplicates (&init,
3649				   fix_temporary_vars_context_r,
3650				   NULL);
3651
3652  /* Because of:
3653
3654       [class.access.spec]
3655
3656       Access control for implicit calls to the constructors,
3657       the conversion functions, or the destructor called to
3658       create and destroy a static data member is performed as
3659       if these calls appeared in the scope of the member's
3660       class.
3661
3662     we pretend we are in a static member function of the class of
3663     which the DECL is a member.  */
3664  if (member_p (decl))
3665    {
3666      DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
3667      DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
3668    }
3669
3670  /* Assume we don't need a guard.  */
3671  guard = NULL_TREE;
3672  /* We need a guard if this is an object with external linkage that
3673     might be initialized in more than one place.  (For example, a
3674     static data member of a template, when the data member requires
3675     construction.)  */
3676  if (NEEDS_GUARD_P (decl))
3677    {
3678      tree guard_cond;
3679
3680      guard = get_guard (decl);
3681
3682      /* When using __cxa_atexit, we just check the GUARD as we would
3683	 for a local static.  */
3684      if (flag_use_cxa_atexit)
3685	{
3686	  /* When using __cxa_atexit, we never try to destroy
3687	     anything from a static destructor.  */
3688	  gcc_assert (initp);
3689	  guard_cond = get_guard_cond (guard);
3690	}
3691      /* If we don't have __cxa_atexit, then we will be running
3692	 destructors from .fini sections, or their equivalents.  So,
3693	 we need to know how many times we've tried to initialize this
3694	 object.  We do initializations only if the GUARD is zero,
3695	 i.e., if we are the first to initialize the variable.  We do
3696	 destructions only if the GUARD is one, i.e., if we are the
3697	 last to destroy the variable.  */
3698      else if (initp)
3699	guard_cond
3700	  = cp_build_binary_op (input_location,
3701				EQ_EXPR,
3702				cp_build_unary_op (PREINCREMENT_EXPR,
3703						   guard,
3704						   /*noconvert=*/1,
3705						   tf_warning_or_error),
3706				integer_one_node,
3707				tf_warning_or_error);
3708      else
3709	guard_cond
3710	  = cp_build_binary_op (input_location,
3711				EQ_EXPR,
3712				cp_build_unary_op (PREDECREMENT_EXPR,
3713						   guard,
3714						   /*noconvert=*/1,
3715						   tf_warning_or_error),
3716				integer_zero_node,
3717				tf_warning_or_error);
3718
3719      guard_if_stmt = begin_if_stmt ();
3720      finish_if_stmt_cond (guard_cond, guard_if_stmt);
3721    }
3722
3723
3724  /* If we're using __cxa_atexit, we have not already set the GUARD,
3725     so we must do so now.  */
3726  if (guard && initp && flag_use_cxa_atexit)
3727    finish_expr_stmt (set_guard (guard));
3728
3729  /* Perform the initialization or destruction.  */
3730  if (initp)
3731    {
3732      if (init)
3733	{
3734	  finish_expr_stmt (init);
3735	  if (flag_sanitize & SANITIZE_ADDRESS)
3736	    {
3737	      varpool_node *vnode = varpool_node::get (decl);
3738	      if (vnode)
3739		vnode->dynamically_initialized = 1;
3740	    }
3741	}
3742
3743      /* If we're using __cxa_atexit, register a function that calls the
3744	 destructor for the object.  */
3745      if (flag_use_cxa_atexit)
3746	finish_expr_stmt (register_dtor_fn (decl));
3747    }
3748  else
3749    finish_expr_stmt (build_cleanup (decl));
3750
3751  /* Finish the guard if-stmt, if necessary.  */
3752  if (guard)
3753    {
3754      finish_then_clause (guard_if_stmt);
3755      finish_if_stmt (guard_if_stmt);
3756    }
3757
3758  /* Now that we're done with DECL we don't need to pretend to be a
3759     member of its class any longer.  */
3760  DECL_CONTEXT (current_function_decl) = NULL_TREE;
3761  DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
3762}
3763
3764/* Generate code to do the initialization or destruction of the decls in VARS,
3765   a TREE_LIST of VAR_DECL with static storage duration.
3766   Whether initialization or destruction is performed is specified by INITP.  */
3767
3768static void
3769do_static_initialization_or_destruction (tree vars, bool initp)
3770{
3771  tree node, init_if_stmt, cond;
3772
3773  /* Build the outer if-stmt to check for initialization or destruction.  */
3774  init_if_stmt = begin_if_stmt ();
3775  cond = initp ? integer_one_node : integer_zero_node;
3776  cond = cp_build_binary_op (input_location,
3777			     EQ_EXPR,
3778			     initialize_p_decl,
3779			     cond,
3780			     tf_warning_or_error);
3781  finish_if_stmt_cond (cond, init_if_stmt);
3782
3783  /* To make sure dynamic construction doesn't access globals from other
3784     compilation units where they might not be yet constructed, for
3785     -fsanitize=address insert __asan_before_dynamic_init call that
3786     prevents access to either all global variables that need construction
3787     in other compilation units, or at least those that haven't been
3788     initialized yet.  Variables that need dynamic construction in
3789     the current compilation unit are kept accessible.  */
3790  if (flag_sanitize & SANITIZE_ADDRESS)
3791    finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
3792
3793  node = vars;
3794  do {
3795    tree decl = TREE_VALUE (node);
3796    tree priority_if_stmt;
3797    int priority;
3798    priority_info pi;
3799
3800    /* If we don't need a destructor, there's nothing to do.  Avoid
3801       creating a possibly empty if-stmt.  */
3802    if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3803      {
3804	node = TREE_CHAIN (node);
3805	continue;
3806      }
3807
3808    /* Remember that we had an initialization or finalization at this
3809       priority.  */
3810    priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
3811    pi = get_priority_info (priority);
3812    if (initp)
3813      pi->initializations_p = 1;
3814    else
3815      pi->destructions_p = 1;
3816
3817    /* Conditionalize this initialization on being in the right priority
3818       and being initializing/finalizing appropriately.  */
3819    priority_if_stmt = begin_if_stmt ();
3820    cond = cp_build_binary_op (input_location,
3821			       EQ_EXPR,
3822			       priority_decl,
3823			       build_int_cst (NULL_TREE, priority),
3824			       tf_warning_or_error);
3825    finish_if_stmt_cond (cond, priority_if_stmt);
3826
3827    /* Process initializers with same priority.  */
3828    for (; node
3829	   && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
3830	 node = TREE_CHAIN (node))
3831      /* Do one initialization or destruction.  */
3832      one_static_initialization_or_destruction (TREE_VALUE (node),
3833						TREE_PURPOSE (node), initp);
3834
3835    /* Finish up the priority if-stmt body.  */
3836    finish_then_clause (priority_if_stmt);
3837    finish_if_stmt (priority_if_stmt);
3838
3839  } while (node);
3840
3841  /* Revert what __asan_before_dynamic_init did by calling
3842     __asan_after_dynamic_init.  */
3843  if (flag_sanitize & SANITIZE_ADDRESS)
3844    finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
3845
3846  /* Finish up the init/destruct if-stmt body.  */
3847  finish_then_clause (init_if_stmt);
3848  finish_if_stmt (init_if_stmt);
3849}
3850
3851/* VARS is a list of variables with static storage duration which may
3852   need initialization and/or finalization.  Remove those variables
3853   that don't really need to be initialized or finalized, and return
3854   the resulting list.  The order in which the variables appear in
3855   VARS is in reverse order of the order in which they should actually
3856   be initialized.  The list we return is in the unreversed order;
3857   i.e., the first variable should be initialized first.  */
3858
3859static tree
3860prune_vars_needing_no_initialization (tree *vars)
3861{
3862  tree *var = vars;
3863  tree result = NULL_TREE;
3864
3865  while (*var)
3866    {
3867      tree t = *var;
3868      tree decl = TREE_VALUE (t);
3869      tree init = TREE_PURPOSE (t);
3870
3871      /* Deal gracefully with error.  */
3872      if (decl == error_mark_node)
3873	{
3874	  var = &TREE_CHAIN (t);
3875	  continue;
3876	}
3877
3878      /* The only things that can be initialized are variables.  */
3879      gcc_assert (VAR_P (decl));
3880
3881      /* If this object is not defined, we don't need to do anything
3882	 here.  */
3883      if (DECL_EXTERNAL (decl))
3884	{
3885	  var = &TREE_CHAIN (t);
3886	  continue;
3887	}
3888
3889      /* Also, if the initializer already contains errors, we can bail
3890	 out now.  */
3891      if (init && TREE_CODE (init) == TREE_LIST
3892	  && value_member (error_mark_node, init))
3893	{
3894	  var = &TREE_CHAIN (t);
3895	  continue;
3896	}
3897
3898      /* This variable is going to need initialization and/or
3899	 finalization, so we add it to the list.  */
3900      *var = TREE_CHAIN (t);
3901      TREE_CHAIN (t) = result;
3902      result = t;
3903    }
3904
3905  return result;
3906}
3907
3908/* Make sure we have told the back end about all the variables in
3909   VARS.  */
3910
3911static void
3912write_out_vars (tree vars)
3913{
3914  tree v;
3915
3916  for (v = vars; v; v = TREE_CHAIN (v))
3917    {
3918      tree var = TREE_VALUE (v);
3919      if (!var_finalized_p (var))
3920	{
3921	  import_export_decl (var);
3922	  rest_of_decl_compilation (var, 1, 1);
3923	}
3924    }
3925}
3926
3927/* Generate a static constructor (if CONSTRUCTOR_P) or destructor
3928   (otherwise) that will initialize all global objects with static
3929   storage duration having the indicated PRIORITY.  */
3930
3931static void
3932generate_ctor_or_dtor_function (bool constructor_p, int priority,
3933				location_t *locus)
3934{
3935  char function_key;
3936  tree fndecl;
3937  tree body;
3938  size_t i;
3939
3940  input_location = *locus;
3941  /* ??? */
3942  /* Was: locus->line++; */
3943
3944  /* We use `I' to indicate initialization and `D' to indicate
3945     destruction.  */
3946  function_key = constructor_p ? 'I' : 'D';
3947
3948  /* We emit the function lazily, to avoid generating empty
3949     global constructors and destructors.  */
3950  body = NULL_TREE;
3951
3952  /* For Objective-C++, we may need to initialize metadata found in this module.
3953     This must be done _before_ any other static initializations.  */
3954  if (c_dialect_objc () && (priority == DEFAULT_INIT_PRIORITY)
3955      && constructor_p && objc_static_init_needed_p ())
3956    {
3957      body = start_objects (function_key, priority);
3958      objc_generate_static_init_call (NULL_TREE);
3959    }
3960
3961  /* Call the static storage duration function with appropriate
3962     arguments.  */
3963  FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl)
3964    {
3965      /* Calls to pure or const functions will expand to nothing.  */
3966      if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
3967	{
3968	  tree call;
3969
3970	  if (! body)
3971	    body = start_objects (function_key, priority);
3972
3973	  call = cp_build_function_call_nary (fndecl, tf_warning_or_error,
3974					      build_int_cst (NULL_TREE,
3975							     constructor_p),
3976					      build_int_cst (NULL_TREE,
3977							     priority),
3978					      NULL_TREE);
3979	  finish_expr_stmt (call);
3980	}
3981    }
3982
3983  /* Close out the function.  */
3984  if (body)
3985    finish_objects (function_key, priority, body);
3986}
3987
3988/* Generate constructor and destructor functions for the priority
3989   indicated by N.  */
3990
3991static int
3992generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
3993{
3994  location_t *locus = (location_t *) data;
3995  int priority = (int) n->key;
3996  priority_info pi = (priority_info) n->value;
3997
3998  /* Generate the functions themselves, but only if they are really
3999     needed.  */
4000  if (pi->initializations_p)
4001    generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
4002  if (pi->destructions_p)
4003    generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
4004
4005  /* Keep iterating.  */
4006  return 0;
4007}
4008
4009/* Java requires that we be able to reference a local address for a
4010   method, and not be confused by PLT entries.  If hidden aliases are
4011   supported, collect and return all the functions for which we should
4012   emit a hidden alias.  */
4013
4014static hash_set<tree> *
4015collect_candidates_for_java_method_aliases (void)
4016{
4017  struct cgraph_node *node;
4018  hash_set<tree> *candidates = NULL;
4019
4020#ifndef HAVE_GAS_HIDDEN
4021  return candidates;
4022#endif
4023
4024  FOR_EACH_FUNCTION (node)
4025    {
4026      tree fndecl = node->decl;
4027
4028      if (DECL_CLASS_SCOPE_P (fndecl)
4029	  && TYPE_FOR_JAVA (DECL_CONTEXT (fndecl))
4030	  && TARGET_USE_LOCAL_THUNK_ALIAS_P (fndecl))
4031	{
4032	  if (candidates == NULL)
4033	    candidates = new hash_set<tree>;
4034	  candidates->add (fndecl);
4035	}
4036    }
4037
4038  return candidates;
4039}
4040
4041
4042/* Java requires that we be able to reference a local address for a
4043   method, and not be confused by PLT entries.  If hidden aliases are
4044   supported, emit one for each java function that we've emitted.
4045   CANDIDATES is the set of FUNCTION_DECLs that were gathered
4046   by collect_candidates_for_java_method_aliases.  */
4047
4048static void
4049build_java_method_aliases (hash_set<tree> *candidates)
4050{
4051  struct cgraph_node *node;
4052
4053#ifndef HAVE_GAS_HIDDEN
4054  return;
4055#endif
4056
4057  FOR_EACH_FUNCTION (node)
4058    {
4059      tree fndecl = node->decl;
4060
4061      if (TREE_ASM_WRITTEN (fndecl)
4062	  && candidates->contains (fndecl))
4063	{
4064	  /* Mangle the name in a predictable way; we need to reference
4065	     this from a java compiled object file.  */
4066	  tree oid, nid, alias;
4067	  const char *oname;
4068	  char *nname;
4069
4070	  oid = DECL_ASSEMBLER_NAME (fndecl);
4071	  oname = IDENTIFIER_POINTER (oid);
4072	  gcc_assert (oname[0] == '_' && oname[1] == 'Z');
4073	  nname = ACONCAT (("_ZGA", oname+2, NULL));
4074	  nid = get_identifier (nname);
4075
4076	  alias = make_alias_for (fndecl, nid);
4077	  TREE_PUBLIC (alias) = 1;
4078	  DECL_VISIBILITY (alias) = VISIBILITY_HIDDEN;
4079
4080	  assemble_alias (alias, oid);
4081	}
4082    }
4083}
4084
4085/* Return C++ property of T, based on given operation OP.  */
4086
4087static int
4088cpp_check (tree t, cpp_operation op)
4089{
4090  switch (op)
4091    {
4092      case IS_ABSTRACT:
4093	return DECL_PURE_VIRTUAL_P (t);
4094      case IS_CONSTRUCTOR:
4095	return DECL_CONSTRUCTOR_P (t);
4096      case IS_DESTRUCTOR:
4097	return DECL_DESTRUCTOR_P (t);
4098      case IS_COPY_CONSTRUCTOR:
4099	return DECL_COPY_CONSTRUCTOR_P (t);
4100      case IS_TEMPLATE:
4101	return TREE_CODE (t) == TEMPLATE_DECL;
4102      case IS_TRIVIAL:
4103	return trivial_type_p (t);
4104      default:
4105        return 0;
4106    }
4107}
4108
4109/* Collect source file references recursively, starting from NAMESPC.  */
4110
4111static void
4112collect_source_refs (tree namespc)
4113{
4114  tree t;
4115
4116  if (!namespc)
4117    return;
4118
4119  /* Iterate over names in this name space.  */
4120  for (t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4121    if (!DECL_IS_BUILTIN (t) )
4122      collect_source_ref (DECL_SOURCE_FILE (t));
4123
4124  /* Dump siblings, if any */
4125  collect_source_refs (TREE_CHAIN (namespc));
4126
4127  /* Dump children, if any */
4128  collect_source_refs (NAMESPACE_LEVEL (namespc)->namespaces);
4129}
4130
4131/* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4132   starting from NAMESPC.  */
4133
4134static void
4135collect_ada_namespace (tree namespc, const char *source_file)
4136{
4137  if (!namespc)
4138    return;
4139
4140  /* Collect decls from this namespace */
4141  collect_ada_nodes (NAMESPACE_LEVEL (namespc)->names, source_file);
4142
4143  /* Collect siblings, if any */
4144  collect_ada_namespace (TREE_CHAIN (namespc), source_file);
4145
4146  /* Collect children, if any */
4147  collect_ada_namespace (NAMESPACE_LEVEL (namespc)->namespaces, source_file);
4148}
4149
4150/* Returns true iff there is a definition available for variable or
4151   function DECL.  */
4152
4153static bool
4154decl_defined_p (tree decl)
4155{
4156  if (TREE_CODE (decl) == FUNCTION_DECL)
4157    return (DECL_INITIAL (decl) != NULL_TREE);
4158  else
4159    {
4160      gcc_assert (VAR_P (decl));
4161      return !DECL_EXTERNAL (decl);
4162    }
4163}
4164
4165/* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4166
4167      [expr.const]
4168
4169      An integral constant-expression can only involve ... const
4170      variables of integral or enumeration types initialized with
4171      constant expressions ...
4172
4173      C++0x also allows constexpr variables and temporaries initialized
4174      with constant expressions.  We handle the former here, but the latter
4175      are just folded away in cxx_eval_constant_expression.
4176
4177   The standard does not require that the expression be non-volatile.
4178   G++ implements the proposed correction in DR 457.  */
4179
4180bool
4181decl_constant_var_p (tree decl)
4182{
4183  if (!decl_maybe_constant_var_p (decl))
4184    return false;
4185
4186  /* We don't know if a template static data member is initialized with
4187     a constant expression until we instantiate its initializer.  Even
4188     in the case of a constexpr variable, we can't treat it as a
4189     constant until its initializer is complete in case it's used in
4190     its own initializer.  */
4191  mark_used (decl);
4192  return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4193}
4194
4195/* Returns true if DECL could be a symbolic constant variable, depending on
4196   its initializer.  */
4197
4198bool
4199decl_maybe_constant_var_p (tree decl)
4200{
4201  tree type = TREE_TYPE (decl);
4202  if (!VAR_P (decl))
4203    return false;
4204  if (DECL_DECLARED_CONSTEXPR_P (decl))
4205    return true;
4206  if (DECL_HAS_VALUE_EXPR_P (decl))
4207    /* A proxy isn't constant.  */
4208    return false;
4209  return (CP_TYPE_CONST_NON_VOLATILE_P (type)
4210	  && INTEGRAL_OR_ENUMERATION_TYPE_P (type));
4211}
4212
4213/* Complain that DECL uses a type with no linkage.  In C++98 mode this is
4214   called from grokfndecl and grokvardecl; in all modes it is called from
4215   cp_write_global_declarations.  */
4216
4217void
4218no_linkage_error (tree decl)
4219{
4220  if (cxx_dialect >= cxx11 && decl_defined_p (decl))
4221    /* In C++11 it's ok if the decl is defined.  */
4222    return;
4223  tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4224  if (t == NULL_TREE)
4225    /* The type that got us on no_linkage_decls must have gotten a name for
4226       linkage purposes.  */;
4227  else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4228    /* The type might end up having a typedef name for linkage purposes.  */
4229    vec_safe_push (no_linkage_decls, decl);
4230  else if (TYPE_ANONYMOUS_P (t))
4231    {
4232      bool d = false;
4233      if (cxx_dialect >= cxx11)
4234	d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4235		       "anonymous type, is used but never defined", decl);
4236      else if (DECL_EXTERN_C_P (decl))
4237	/* Allow this; it's pretty common in C.  */;
4238      else if (TREE_CODE (decl) == VAR_DECL)
4239	/* DRs 132, 319 and 389 seem to indicate types with
4240	   no linkage can only be used to declare extern "C"
4241	   entities.  Since it's not always an error in the
4242	   ISO C++ 90 Standard, we only issue a warning.  */
4243	d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "anonymous type "
4244			"with no linkage used to declare variable %q#D with "
4245			"linkage", decl);
4246      else
4247	d = permerror (DECL_SOURCE_LOCATION (decl), "anonymous type with no "
4248		       "linkage used to declare function %q#D with linkage",
4249		       decl);
4250      if (d && is_typedef_decl (TYPE_NAME (t)))
4251	inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4252		"to the unqualified type, so it is not used for linkage",
4253		TYPE_NAME (t));
4254    }
4255  else if (cxx_dialect >= cxx11)
4256    {
4257      if (TREE_CODE (decl) == VAR_DECL || !DECL_PURE_VIRTUAL_P (decl))
4258	permerror (DECL_SOURCE_LOCATION (decl),
4259		   "%q#D, declared using local type "
4260		   "%qT, is used but never defined", decl, t);
4261    }
4262  else if (TREE_CODE (decl) == VAR_DECL)
4263    warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4264		"used to declare variable %q#D with linkage", t, decl);
4265  else
4266    permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4267	       "to declare function %q#D with linkage", t, decl);
4268}
4269
4270/* Collect declarations from all namespaces relevant to SOURCE_FILE.  */
4271
4272static void
4273collect_all_refs (const char *source_file)
4274{
4275  collect_ada_namespace (global_namespace, source_file);
4276}
4277
4278/* Clear DECL_EXTERNAL for NODE.  */
4279
4280static bool
4281clear_decl_external (struct cgraph_node *node, void * /*data*/)
4282{
4283  DECL_EXTERNAL (node->decl) = 0;
4284  return false;
4285}
4286
4287/* Build up the function to run dynamic initializers for thread_local
4288   variables in this translation unit and alias the init functions for the
4289   individual variables to it.  */
4290
4291static void
4292handle_tls_init (void)
4293{
4294  tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4295  if (vars == NULL_TREE)
4296    return;
4297
4298  location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4299
4300  write_out_vars (vars);
4301
4302  tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4303			   boolean_type_node);
4304  TREE_PUBLIC (guard) = false;
4305  TREE_STATIC (guard) = true;
4306  DECL_ARTIFICIAL (guard) = true;
4307  DECL_IGNORED_P (guard) = true;
4308  TREE_USED (guard) = true;
4309  set_decl_tls_model (guard, decl_default_tls_model (guard));
4310  pushdecl_top_level_and_finish (guard, NULL_TREE);
4311
4312  tree fn = get_local_tls_init_fn ();
4313  start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4314  tree body = begin_function_body ();
4315  tree if_stmt = begin_if_stmt ();
4316  tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4317				 tf_warning_or_error);
4318  finish_if_stmt_cond (cond, if_stmt);
4319  finish_expr_stmt (cp_build_modify_expr (guard, NOP_EXPR, boolean_true_node,
4320					  tf_warning_or_error));
4321  for (; vars; vars = TREE_CHAIN (vars))
4322    {
4323      tree var = TREE_VALUE (vars);
4324      tree init = TREE_PURPOSE (vars);
4325      one_static_initialization_or_destruction (var, init, true);
4326
4327#ifdef ASM_OUTPUT_DEF
4328      /* Output init aliases even with -fno-extern-tls-init.  */
4329      if (TREE_PUBLIC (var))
4330	{
4331          tree single_init_fn = get_tls_init_fn (var);
4332	  if (single_init_fn == NULL_TREE)
4333	    continue;
4334	  cgraph_node *alias
4335	    = cgraph_node::get_create (fn)->create_same_body_alias
4336		(single_init_fn, fn);
4337	  gcc_assert (alias != NULL);
4338	}
4339#endif
4340    }
4341
4342  finish_then_clause (if_stmt);
4343  finish_if_stmt (if_stmt);
4344  finish_function_body (body);
4345  expand_or_defer_fn (finish_function (0));
4346}
4347
4348/* We're at the end of compilation, so generate any mangling aliases that
4349   we've been saving up, if DECL is going to be output and ID2 isn't
4350   already taken by another declaration.  */
4351
4352static void
4353generate_mangling_alias (tree decl, tree id2)
4354{
4355  /* If there's a declaration already using this mangled name,
4356     don't create a compatibility alias that conflicts.  */
4357  if (IDENTIFIER_GLOBAL_VALUE (id2))
4358    return;
4359
4360  struct cgraph_node *n = NULL;
4361  if (TREE_CODE (decl) == FUNCTION_DECL
4362      && !(n = cgraph_node::get (decl)))
4363    /* Don't create an alias to an unreferenced function.  */
4364    return;
4365
4366  tree alias = make_alias_for (decl, id2);
4367  SET_IDENTIFIER_GLOBAL_VALUE (id2, alias);
4368  DECL_IGNORED_P (alias) = 1;
4369  TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4370  DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4371  if (vague_linkage_p (decl))
4372    DECL_WEAK (alias) = 1;
4373  if (TREE_CODE (decl) == FUNCTION_DECL)
4374    n->create_same_body_alias (alias, decl);
4375  else
4376    varpool_node::create_extra_name_alias (alias, decl);
4377}
4378
4379/* Note that we might want to emit an alias with the symbol ID2 for DECL at
4380   the end of translation, for compatibility across bugs in the mangling
4381   implementation.  */
4382
4383void
4384note_mangling_alias (tree decl ATTRIBUTE_UNUSED, tree id2 ATTRIBUTE_UNUSED)
4385{
4386#ifdef ASM_OUTPUT_DEF
4387  if (!defer_mangling_aliases)
4388    generate_mangling_alias (decl, id2);
4389  else
4390    {
4391      vec_safe_push (mangling_aliases, decl);
4392      vec_safe_push (mangling_aliases, id2);
4393    }
4394#endif
4395}
4396
4397/* Emit all mangling aliases that were deferred up to this point.  */
4398
4399void
4400generate_mangling_aliases ()
4401{
4402  while (!vec_safe_is_empty (mangling_aliases))
4403    {
4404      tree id2 = mangling_aliases->pop();
4405      tree decl = mangling_aliases->pop();
4406      generate_mangling_alias (decl, id2);
4407    }
4408  defer_mangling_aliases = false;
4409}
4410
4411/* The entire file is now complete.  If requested, dump everything
4412   to a file.  */
4413
4414static void
4415dump_tu (void)
4416{
4417  int flags;
4418  FILE *stream = dump_begin (TDI_tu, &flags);
4419
4420  if (stream)
4421    {
4422      dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4423      dump_end (TDI_tu, stream);
4424    }
4425}
4426
4427/* Check the deallocation functions for CODE to see if we want to warn that
4428   only one was defined.  */
4429
4430static void
4431maybe_warn_sized_delete (enum tree_code code)
4432{
4433  tree sized = NULL_TREE;
4434  tree unsized = NULL_TREE;
4435
4436  for (tree ovl = IDENTIFIER_GLOBAL_VALUE (ansi_opname (code));
4437       ovl; ovl = OVL_NEXT (ovl))
4438    {
4439      tree fn = OVL_CURRENT (ovl);
4440      /* We're only interested in usual deallocation functions.  */
4441      if (!non_placement_deallocation_fn_p (fn))
4442	continue;
4443      if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4444	unsized = fn;
4445      else
4446	sized = fn;
4447    }
4448  if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
4449    warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
4450		"the program should also define %qD", sized);
4451  else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
4452    warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
4453		"the program should also define %qD", unsized);
4454}
4455
4456/* Check the global deallocation functions to see if we want to warn about
4457   defining unsized without sized (or vice versa).  */
4458
4459static void
4460maybe_warn_sized_delete ()
4461{
4462  if (!flag_sized_deallocation || !warn_sized_deallocation)
4463    return;
4464  maybe_warn_sized_delete (DELETE_EXPR);
4465  maybe_warn_sized_delete (VEC_DELETE_EXPR);
4466}
4467
4468/* This routine is called at the end of compilation.
4469   Its job is to create all the code needed to initialize and
4470   destroy the global aggregates.  We do the destruction
4471   first, since that way we only need to reverse the decls once.  */
4472
4473void
4474cp_write_global_declarations (void)
4475{
4476  tree vars;
4477  bool reconsider;
4478  size_t i;
4479  location_t locus;
4480  unsigned ssdf_count = 0;
4481  int retries = 0;
4482  tree decl;
4483  hash_set<tree> *candidates;
4484
4485  locus = input_location;
4486  at_eof = 1;
4487
4488  /* Bad parse errors.  Just forget about it.  */
4489  if (! global_bindings_p () || current_class_type
4490      || !vec_safe_is_empty (decl_namespace_list))
4491    return;
4492
4493  /* This is the point to write out a PCH if we're doing that.
4494     In that case we do not want to do anything else.  */
4495  if (pch_file)
4496    {
4497      c_common_write_pch ();
4498      dump_tu ();
4499      return;
4500    }
4501
4502  symtab->process_same_body_aliases ();
4503
4504  /* Handle -fdump-ada-spec[-slim] */
4505  if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
4506    {
4507      if (flag_dump_ada_spec_slim)
4508	collect_source_ref (main_input_filename);
4509      else
4510	collect_source_refs (global_namespace);
4511
4512      dump_ada_specs (collect_all_refs, cpp_check);
4513    }
4514
4515  /* FIXME - huh?  was  input_line -= 1;*/
4516
4517  timevar_start (TV_PHASE_DEFERRED);
4518
4519  /* We now have to write out all the stuff we put off writing out.
4520     These include:
4521
4522       o Template specializations that we have not yet instantiated,
4523	 but which are needed.
4524       o Initialization and destruction for non-local objects with
4525	 static storage duration.  (Local objects with static storage
4526	 duration are initialized when their scope is first entered,
4527	 and are cleaned up via atexit.)
4528       o Virtual function tables.
4529
4530     All of these may cause others to be needed.  For example,
4531     instantiating one function may cause another to be needed, and
4532     generating the initializer for an object may cause templates to be
4533     instantiated, etc., etc.  */
4534
4535  emit_support_tinfos ();
4536
4537  do
4538    {
4539      tree t;
4540      tree decl;
4541
4542      reconsider = false;
4543
4544      /* If there are templates that we've put off instantiating, do
4545	 them now.  */
4546      instantiate_pending_templates (retries);
4547      ggc_collect ();
4548
4549      /* Write out virtual tables as required.  Note that writing out
4550	 the virtual table for a template class may cause the
4551	 instantiation of members of that class.  If we write out
4552	 vtables then we remove the class from our list so we don't
4553	 have to look at it again.  */
4554
4555      while (keyed_classes != NULL_TREE
4556	     && maybe_emit_vtables (TREE_VALUE (keyed_classes)))
4557	{
4558	  reconsider = true;
4559	  keyed_classes = TREE_CHAIN (keyed_classes);
4560	}
4561
4562      t = keyed_classes;
4563      if (t != NULL_TREE)
4564	{
4565	  tree next = TREE_CHAIN (t);
4566
4567	  while (next)
4568	    {
4569	      if (maybe_emit_vtables (TREE_VALUE (next)))
4570		{
4571		  reconsider = true;
4572		  TREE_CHAIN (t) = TREE_CHAIN (next);
4573		}
4574	      else
4575		t = next;
4576
4577	      next = TREE_CHAIN (t);
4578	    }
4579	}
4580
4581      /* Write out needed type info variables.  We have to be careful
4582	 looping through unemitted decls, because emit_tinfo_decl may
4583	 cause other variables to be needed. New elements will be
4584	 appended, and we remove from the vector those that actually
4585	 get emitted.  */
4586      for (i = unemitted_tinfo_decls->length ();
4587	   unemitted_tinfo_decls->iterate (--i, &t);)
4588	if (emit_tinfo_decl (t))
4589	  {
4590	    reconsider = true;
4591	    unemitted_tinfo_decls->unordered_remove (i);
4592	  }
4593
4594      /* The list of objects with static storage duration is built up
4595	 in reverse order.  We clear STATIC_AGGREGATES so that any new
4596	 aggregates added during the initialization of these will be
4597	 initialized in the correct order when we next come around the
4598	 loop.  */
4599      vars = prune_vars_needing_no_initialization (&static_aggregates);
4600
4601      if (vars)
4602	{
4603	  /* We need to start a new initialization function each time
4604	     through the loop.  That's because we need to know which
4605	     vtables have been referenced, and TREE_SYMBOL_REFERENCED
4606	     isn't computed until a function is finished, and written
4607	     out.  That's a deficiency in the back end.  When this is
4608	     fixed, these initialization functions could all become
4609	     inline, with resulting performance improvements.  */
4610	  tree ssdf_body;
4611
4612	  /* Set the line and file, so that it is obviously not from
4613	     the source file.  */
4614	  input_location = locus;
4615	  ssdf_body = start_static_storage_duration_function (ssdf_count);
4616
4617	  /* Make sure the back end knows about all the variables.  */
4618	  write_out_vars (vars);
4619
4620	  /* First generate code to do all the initializations.  */
4621	  if (vars)
4622	    do_static_initialization_or_destruction (vars, /*initp=*/true);
4623
4624	  /* Then, generate code to do all the destructions.  Do these
4625	     in reverse order so that the most recently constructed
4626	     variable is the first destroyed.  If we're using
4627	     __cxa_atexit, then we don't need to do this; functions
4628	     were registered at initialization time to destroy the
4629	     local statics.  */
4630	  if (!flag_use_cxa_atexit && vars)
4631	    {
4632	      vars = nreverse (vars);
4633	      do_static_initialization_or_destruction (vars, /*initp=*/false);
4634	    }
4635	  else
4636	    vars = NULL_TREE;
4637
4638	  /* Finish up the static storage duration function for this
4639	     round.  */
4640	  input_location = locus;
4641	  finish_static_storage_duration_function (ssdf_body);
4642
4643	  /* All those initializations and finalizations might cause
4644	     us to need more inline functions, more template
4645	     instantiations, etc.  */
4646	  reconsider = true;
4647	  ssdf_count++;
4648	  /* ??? was:  locus.line++; */
4649	}
4650
4651      /* Now do the same for thread_local variables.  */
4652      handle_tls_init ();
4653
4654      /* Go through the set of inline functions whose bodies have not
4655	 been emitted yet.  If out-of-line copies of these functions
4656	 are required, emit them.  */
4657      FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
4658	{
4659	  /* Does it need synthesizing?  */
4660	  if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
4661	      && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
4662	    {
4663	      /* Even though we're already at the top-level, we push
4664		 there again.  That way, when we pop back a few lines
4665		 hence, all of our state is restored.  Otherwise,
4666		 finish_function doesn't clean things up, and we end
4667		 up with CURRENT_FUNCTION_DECL set.  */
4668	      push_to_top_level ();
4669	      /* The decl's location will mark where it was first
4670		 needed.  Save that so synthesize method can indicate
4671		 where it was needed from, in case of error  */
4672	      input_location = DECL_SOURCE_LOCATION (decl);
4673	      synthesize_method (decl);
4674	      pop_from_top_level ();
4675	      reconsider = true;
4676	    }
4677
4678	  if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
4679	    generate_tls_wrapper (decl);
4680
4681	  if (!DECL_SAVED_TREE (decl))
4682	    continue;
4683
4684	  /* We lie to the back end, pretending that some functions
4685	     are not defined when they really are.  This keeps these
4686	     functions from being put out unnecessarily.  But, we must
4687	     stop lying when the functions are referenced, or if they
4688	     are not comdat since they need to be put out now.  If
4689	     DECL_INTERFACE_KNOWN, then we have already set
4690	     DECL_EXTERNAL appropriately, so there's no need to check
4691	     again, and we do not want to clear DECL_EXTERNAL if a
4692	     previous call to import_export_decl set it.
4693
4694	     This is done in a separate for cycle, because if some
4695	     deferred function is contained in another deferred
4696	     function later in deferred_fns varray,
4697	     rest_of_compilation would skip this function and we
4698	     really cannot expand the same function twice.  */
4699	  import_export_decl (decl);
4700	  if (DECL_NOT_REALLY_EXTERN (decl)
4701	      && DECL_INITIAL (decl)
4702	      && decl_needed_p (decl))
4703	    {
4704	      struct cgraph_node *node, *next;
4705
4706	      node = cgraph_node::get (decl);
4707	      if (node->cpp_implicit_alias)
4708		node = node->get_alias_target ();
4709
4710	      node->call_for_symbol_thunks_and_aliases (clear_decl_external,
4711						      NULL, true);
4712	      /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
4713		 group, we need to mark all symbols in the same comdat group
4714		 that way.  */
4715	      if (node->same_comdat_group)
4716		for (next = dyn_cast<cgraph_node *> (node->same_comdat_group);
4717		     next != node;
4718		     next = dyn_cast<cgraph_node *> (next->same_comdat_group))
4719		  next->call_for_symbol_thunks_and_aliases (clear_decl_external,
4720							  NULL, true);
4721	    }
4722
4723	  /* If we're going to need to write this function out, and
4724	     there's already a body for it, create RTL for it now.
4725	     (There might be no body if this is a method we haven't
4726	     gotten around to synthesizing yet.)  */
4727	  if (!DECL_EXTERNAL (decl)
4728	      && decl_needed_p (decl)
4729	      && !TREE_ASM_WRITTEN (decl)
4730	      && !cgraph_node::get (decl)->definition)
4731	    {
4732	      /* We will output the function; no longer consider it in this
4733		 loop.  */
4734	      DECL_DEFER_OUTPUT (decl) = 0;
4735	      /* Generate RTL for this function now that we know we
4736		 need it.  */
4737	      expand_or_defer_fn (decl);
4738	      /* If we're compiling -fsyntax-only pretend that this
4739		 function has been written out so that we don't try to
4740		 expand it again.  */
4741	      if (flag_syntax_only)
4742		TREE_ASM_WRITTEN (decl) = 1;
4743	      reconsider = true;
4744	    }
4745	}
4746
4747      if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
4748	reconsider = true;
4749
4750      /* Static data members are just like namespace-scope globals.  */
4751      FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
4752	{
4753	  if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
4754	      /* Don't write it out if we haven't seen a definition.  */
4755	      || DECL_IN_AGGR_P (decl))
4756	    continue;
4757	  import_export_decl (decl);
4758	  /* If this static data member is needed, provide it to the
4759	     back end.  */
4760	  if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
4761	    DECL_EXTERNAL (decl) = 0;
4762	}
4763      if (vec_safe_length (pending_statics) != 0
4764	  && wrapup_global_declarations (pending_statics->address (),
4765					 pending_statics->length ()))
4766	reconsider = true;
4767
4768      retries++;
4769    }
4770  while (reconsider);
4771
4772  generate_mangling_aliases ();
4773
4774  /* All used inline functions must have a definition at this point.  */
4775  FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
4776    {
4777      if (/* Check online inline functions that were actually used.  */
4778	  DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
4779	  /* If the definition actually was available here, then the
4780	     fact that the function was not defined merely represents
4781	     that for some reason (use of a template repository,
4782	     #pragma interface, etc.) we decided not to emit the
4783	     definition here.  */
4784	  && !DECL_INITIAL (decl)
4785	  /* Don't complain if the template was defined.  */
4786	  && !(DECL_TEMPLATE_INSTANTIATION (decl)
4787	       && DECL_INITIAL (DECL_TEMPLATE_RESULT
4788				(template_for_substitution (decl)))))
4789	{
4790	  warning (0, "inline function %q+D used but never defined", decl);
4791	  /* Avoid a duplicate warning from check_global_declaration_1.  */
4792	  TREE_NO_WARNING (decl) = 1;
4793	}
4794    }
4795
4796  /* So must decls that use a type with no linkage.  */
4797  FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
4798    no_linkage_error (decl);
4799
4800  maybe_warn_sized_delete ();
4801
4802  /* Then, do the Objective-C stuff.  This is where all the
4803     Objective-C module stuff gets generated (symtab,
4804     class/protocol/selector lists etc).  This must be done after C++
4805     templates, destructors etc. so that selectors used in C++
4806     templates are properly allocated.  */
4807  if (c_dialect_objc ())
4808    objc_write_global_declarations ();
4809
4810  /* We give C linkage to static constructors and destructors.  */
4811  push_lang_context (lang_name_c);
4812
4813  /* Generate initialization and destruction functions for all
4814     priorities for which they are required.  */
4815  if (priority_info_map)
4816    splay_tree_foreach (priority_info_map,
4817			generate_ctor_and_dtor_functions_for_priority,
4818			/*data=*/&locus);
4819  else if (c_dialect_objc () && objc_static_init_needed_p ())
4820    /* If this is obj-c++ and we need a static init, call
4821       generate_ctor_or_dtor_function.  */
4822    generate_ctor_or_dtor_function (/*constructor_p=*/true,
4823				    DEFAULT_INIT_PRIORITY, &locus);
4824
4825  /* We're done with the splay-tree now.  */
4826  if (priority_info_map)
4827    splay_tree_delete (priority_info_map);
4828
4829  /* Generate any missing aliases.  */
4830  maybe_apply_pending_pragma_weaks ();
4831
4832  /* We're done with static constructors, so we can go back to "C++"
4833     linkage now.  */
4834  pop_lang_context ();
4835
4836  /* Collect candidates for Java hidden aliases.  */
4837  candidates = collect_candidates_for_java_method_aliases ();
4838
4839  timevar_stop (TV_PHASE_DEFERRED);
4840  timevar_start (TV_PHASE_OPT_GEN);
4841
4842  if (flag_vtable_verify)
4843    {
4844      vtv_recover_class_info ();
4845      vtv_compute_class_hierarchy_transitive_closure ();
4846      vtv_build_vtable_verify_fndecl ();
4847    }
4848
4849  symtab->finalize_compilation_unit ();
4850
4851  if (flag_vtable_verify)
4852    {
4853      /* Generate the special constructor initialization function that
4854         calls __VLTRegisterPairs, and give it a very high
4855         initialization priority.  This must be done after
4856         finalize_compilation_unit so that we have accurate
4857         information about which vtable will actually be emitted.  */
4858      vtv_generate_init_routine ();
4859    }
4860
4861  timevar_stop (TV_PHASE_OPT_GEN);
4862  timevar_start (TV_PHASE_CHECK_DBGINFO);
4863
4864  /* Now, issue warnings about static, but not defined, functions,
4865     etc., and emit debugging information.  */
4866  walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
4867  if (vec_safe_length (pending_statics) != 0)
4868    {
4869      check_global_declarations (pending_statics->address (),
4870				 pending_statics->length ());
4871      emit_debug_global_declarations (pending_statics->address (),
4872				      pending_statics->length ());
4873    }
4874
4875  perform_deferred_noexcept_checks ();
4876
4877  /* Generate hidden aliases for Java.  */
4878  if (candidates)
4879    {
4880      build_java_method_aliases (candidates);
4881      delete candidates;
4882    }
4883
4884  finish_repo ();
4885
4886  /* The entire file is now complete.  If requested, dump everything
4887     to a file.  */
4888  dump_tu ();
4889
4890  if (flag_detailed_statistics)
4891    {
4892      dump_tree_statistics ();
4893      dump_time_statistics ();
4894    }
4895  input_location = locus;
4896
4897#ifdef ENABLE_CHECKING
4898  validate_conversion_obstack ();
4899#endif /* ENABLE_CHECKING */
4900
4901  timevar_stop (TV_PHASE_CHECK_DBGINFO);
4902}
4903
4904/* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
4905   function to call in parse-tree form; it has not yet been
4906   semantically analyzed.  ARGS are the arguments to the function.
4907   They have already been semantically analyzed.  This may change
4908   ARGS.  */
4909
4910tree
4911build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
4912				 tsubst_flags_t complain)
4913{
4914  tree orig_fn;
4915  vec<tree, va_gc> *orig_args = NULL;
4916  tree expr;
4917  tree object;
4918
4919  orig_fn = fn;
4920  object = TREE_OPERAND (fn, 0);
4921
4922  if (processing_template_decl)
4923    {
4924      gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
4925		  || TREE_CODE (fn) == MEMBER_REF);
4926      if (type_dependent_expression_p (fn)
4927	  || any_type_dependent_arguments_p (*args))
4928	return build_nt_call_vec (fn, *args);
4929
4930      orig_args = make_tree_vector_copy (*args);
4931
4932      /* Transform the arguments and add the implicit "this"
4933	 parameter.  That must be done before the FN is transformed
4934	 because we depend on the form of FN.  */
4935      make_args_non_dependent (*args);
4936      object = build_non_dependent_expr (object);
4937      if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
4938	{
4939	  if (TREE_CODE (fn) == DOTSTAR_EXPR)
4940	    object = cp_build_addr_expr (object, complain);
4941	  vec_safe_insert (*args, 0, object);
4942	}
4943      /* Now that the arguments are done, transform FN.  */
4944      fn = build_non_dependent_expr (fn);
4945    }
4946
4947  /* A qualified name corresponding to a bound pointer-to-member is
4948     represented as an OFFSET_REF:
4949
4950	struct B { void g(); };
4951	void (B::*p)();
4952	void B::g() { (this->*p)(); }  */
4953  if (TREE_CODE (fn) == OFFSET_REF)
4954    {
4955      tree object_addr = cp_build_addr_expr (object, complain);
4956      fn = TREE_OPERAND (fn, 1);
4957      fn = get_member_function_from_ptrfunc (&object_addr, fn,
4958					     complain);
4959      vec_safe_insert (*args, 0, object_addr);
4960    }
4961
4962  if (CLASS_TYPE_P (TREE_TYPE (fn)))
4963    expr = build_op_call (fn, args, complain);
4964  else
4965    expr = cp_build_function_call_vec (fn, args, complain);
4966  if (processing_template_decl && expr != error_mark_node)
4967    expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
4968
4969  if (orig_args != NULL)
4970    release_tree_vector (orig_args);
4971
4972  return expr;
4973}
4974
4975
4976void
4977check_default_args (tree x)
4978{
4979  tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
4980  bool saw_def = false;
4981  int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
4982  for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
4983    {
4984      if (TREE_PURPOSE (arg))
4985	saw_def = true;
4986      else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
4987	{
4988	  error ("default argument missing for parameter %P of %q+#D", i, x);
4989	  TREE_PURPOSE (arg) = error_mark_node;
4990	}
4991    }
4992}
4993
4994/* Return true if function DECL can be inlined.  This is used to force
4995   instantiation of methods that might be interesting for inlining.  */
4996bool
4997possibly_inlined_p (tree decl)
4998{
4999  gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5000  if (DECL_UNINLINABLE (decl))
5001    return false;
5002  if (!optimize || pragma_java_exceptions)
5003    return DECL_DECLARED_INLINE_P (decl);
5004  /* When optimizing, we might inline everything when flatten
5005     attribute or heuristics inlining for size or autoinlining
5006     is used.  */
5007  return true;
5008}
5009
5010/* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5011   If DECL is a specialization or implicitly declared class member,
5012   generate the actual definition.  Return false if something goes
5013   wrong, true otherwise.  */
5014
5015bool
5016mark_used (tree decl, tsubst_flags_t complain)
5017{
5018  /* If DECL is a BASELINK for a single function, then treat it just
5019     like the DECL for the function.  Otherwise, if the BASELINK is
5020     for an overloaded function, we don't know which function was
5021     actually used until after overload resolution.  */
5022  if (BASELINK_P (decl))
5023    {
5024      decl = BASELINK_FUNCTIONS (decl);
5025      if (really_overloaded_fn (decl))
5026	return true;
5027      decl = OVL_CURRENT (decl);
5028    }
5029
5030  /* Set TREE_USED for the benefit of -Wunused.  */
5031  TREE_USED (decl) = 1;
5032  if (DECL_CLONED_FUNCTION_P (decl))
5033    TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5034
5035  /* Mark enumeration types as used.  */
5036  if (TREE_CODE (decl) == CONST_DECL)
5037    used_types_insert (DECL_CONTEXT (decl));
5038
5039  if (TREE_CODE (decl) == FUNCTION_DECL)
5040    maybe_instantiate_noexcept (decl);
5041
5042  if (TREE_CODE (decl) == FUNCTION_DECL
5043      && DECL_DELETED_FN (decl))
5044    {
5045      if (DECL_ARTIFICIAL (decl))
5046	{
5047	  if (DECL_OVERLOADED_OPERATOR_P (decl) == TYPE_EXPR
5048	      && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5049	    {
5050	      /* We mark a lambda conversion op as deleted if we can't
5051		 generate it properly; see maybe_add_lambda_conv_op.  */
5052	      sorry ("converting lambda which uses %<...%> to "
5053		     "function pointer");
5054	      return false;
5055	    }
5056	}
5057      if (complain & tf_error)
5058	{
5059	  error ("use of deleted function %qD", decl);
5060	  if (!maybe_explain_implicit_delete (decl))
5061	    inform (DECL_SOURCE_LOCATION (decl), "declared here");
5062	}
5063      return false;
5064    }
5065
5066  if (TREE_DEPRECATED (decl) && (complain & tf_warning)
5067      && deprecated_state != DEPRECATED_SUPPRESS)
5068    warn_deprecated_use (decl, NULL_TREE);
5069
5070  /* We can only check DECL_ODR_USED on variables or functions with
5071     DECL_LANG_SPECIFIC set, and these are also the only decls that we
5072     might need special handling for.  */
5073  if (!VAR_OR_FUNCTION_DECL_P (decl)
5074      || DECL_LANG_SPECIFIC (decl) == NULL
5075      || DECL_THUNK_P (decl))
5076    {
5077      if (!processing_template_decl && type_uses_auto (TREE_TYPE (decl)))
5078	{
5079	  if (complain & tf_error)
5080	    error ("use of %qD before deduction of %<auto%>", decl);
5081	  return false;
5082	}
5083      return true;
5084    }
5085
5086  /* We only want to do this processing once.  We don't need to keep trying
5087     to instantiate inline templates, because unit-at-a-time will make sure
5088     we get them compiled before functions that want to inline them.  */
5089  if (DECL_ODR_USED (decl))
5090    return true;
5091
5092  /* If within finish_function, defer the rest until that function
5093     finishes, otherwise it might recurse.  */
5094  if (defer_mark_used_calls)
5095    {
5096      vec_safe_push (deferred_mark_used_calls, decl);
5097      return true;
5098    }
5099
5100  /* Normally, we can wait until instantiation-time to synthesize DECL.
5101     However, if DECL is a static data member initialized with a constant
5102     or a constexpr function, we need it right now because a reference to
5103     such a data member or a call to such function is not value-dependent.
5104     For a function that uses auto in the return type, we need to instantiate
5105     it to find out its type.  For OpenMP user defined reductions, we need
5106     them instantiated for reduction clauses which inline them by hand
5107     directly.  */
5108  if (DECL_LANG_SPECIFIC (decl)
5109      && DECL_TEMPLATE_INFO (decl)
5110      && (decl_maybe_constant_var_p (decl)
5111	  || (TREE_CODE (decl) == FUNCTION_DECL
5112	      && DECL_OMP_DECLARE_REDUCTION_P (decl))
5113	  || undeduced_auto_decl (decl))
5114      && !uses_template_parms (DECL_TI_ARGS (decl)))
5115    {
5116      /* Instantiating a function will result in garbage collection.  We
5117	 must treat this situation as if we were within the body of a
5118	 function so as to avoid collecting live data only referenced from
5119	 the stack (such as overload resolution candidates).  */
5120      ++function_depth;
5121      instantiate_decl (decl, /*defer_ok=*/false,
5122			/*expl_inst_class_mem_p=*/false);
5123      --function_depth;
5124    }
5125
5126  if (processing_template_decl || in_template_function ())
5127    return true;
5128
5129  /* Check this too in case we're within instantiate_non_dependent_expr.  */
5130  if (DECL_TEMPLATE_INFO (decl)
5131      && uses_template_parms (DECL_TI_ARGS (decl)))
5132    return true;
5133
5134  if (undeduced_auto_decl (decl))
5135    {
5136      if (complain & tf_error)
5137	error ("use of %qD before deduction of %<auto%>", decl);
5138      return false;
5139    }
5140
5141  /* If we don't need a value, then we don't need to synthesize DECL.  */
5142  if (cp_unevaluated_operand != 0)
5143    return true;
5144
5145  DECL_ODR_USED (decl) = 1;
5146  if (DECL_CLONED_FUNCTION_P (decl))
5147    DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5148
5149  /* DR 757: A type without linkage shall not be used as the type of a
5150     variable or function with linkage, unless
5151   o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5152   o the variable or function is not used (3.2 [basic.def.odr]) or is
5153   defined in the same translation unit.  */
5154  if (cxx_dialect > cxx98
5155      && decl_linkage (decl) != lk_none
5156      && !DECL_EXTERN_C_P (decl)
5157      && !DECL_ARTIFICIAL (decl)
5158      && !decl_defined_p (decl)
5159      && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5160    {
5161      if (is_local_extern (decl))
5162	/* There's no way to define a local extern, and adding it to
5163	   the vector interferes with GC, so give an error now.  */
5164	no_linkage_error (decl);
5165      else
5166	vec_safe_push (no_linkage_decls, decl);
5167    }
5168
5169  if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
5170      && !DECL_INITIAL (decl) && !DECL_ARTIFICIAL (decl))
5171    /* Remember it, so we can check it was defined.  */
5172    note_vague_linkage_fn (decl);
5173
5174  /* Is it a synthesized method that needs to be synthesized?  */
5175  if (TREE_CODE (decl) == FUNCTION_DECL
5176      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5177      && DECL_DEFAULTED_FN (decl)
5178      /* A function defaulted outside the class is synthesized either by
5179	 cp_finish_decl or instantiate_decl.  */
5180      && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5181      && ! DECL_INITIAL (decl))
5182    {
5183      /* Defer virtual destructors so that thunks get the right
5184	 linkage.  */
5185      if (DECL_VIRTUAL_P (decl) && !at_eof)
5186	{
5187	  note_vague_linkage_fn (decl);
5188	  return true;
5189	}
5190
5191      /* Remember the current location for a function we will end up
5192	 synthesizing.  Then we can inform the user where it was
5193	 required in the case of error.  */
5194      DECL_SOURCE_LOCATION (decl) = input_location;
5195
5196      /* Synthesizing an implicitly defined member function will result in
5197	 garbage collection.  We must treat this situation as if we were
5198	 within the body of a function so as to avoid collecting live data
5199	 on the stack (such as overload resolution candidates).
5200
5201         We could just let cp_write_global_declarations handle synthesizing
5202         this function by adding it to deferred_fns, but doing
5203         it at the use site produces better error messages.  */
5204      ++function_depth;
5205      synthesize_method (decl);
5206      --function_depth;
5207      /* If this is a synthesized method we don't need to
5208	 do the instantiation test below.  */
5209    }
5210  else if (VAR_OR_FUNCTION_DECL_P (decl)
5211	   && DECL_TEMPLATE_INFO (decl)
5212	   && (!DECL_EXPLICIT_INSTANTIATION (decl)
5213	       || always_instantiate_p (decl)))
5214    /* If this is a function or variable that is an instance of some
5215       template, we now know that we will need to actually do the
5216       instantiation. We check that DECL is not an explicit
5217       instantiation because that is not checked in instantiate_decl.
5218
5219       We put off instantiating functions in order to improve compile
5220       times.  Maintaining a stack of active functions is expensive,
5221       and the inliner knows to instantiate any functions it might
5222       need.  Therefore, we always try to defer instantiation.  */
5223    {
5224      ++function_depth;
5225      instantiate_decl (decl, /*defer_ok=*/true,
5226			/*expl_inst_class_mem_p=*/false);
5227      --function_depth;
5228    }
5229
5230  return true;
5231}
5232
5233bool
5234mark_used (tree decl)
5235{
5236  return mark_used (decl, tf_warning_or_error);
5237}
5238
5239tree
5240vtv_start_verification_constructor_init_function (void)
5241{
5242  return start_objects ('I', MAX_RESERVED_INIT_PRIORITY - 1);
5243}
5244
5245tree
5246vtv_finish_verification_constructor_init_function (tree function_body)
5247{
5248  tree fn;
5249
5250  finish_compound_stmt (function_body);
5251  fn = finish_function (0);
5252  DECL_STATIC_CONSTRUCTOR (fn) = 1;
5253  decl_init_priority_insert (fn, MAX_RESERVED_INIT_PRIORITY - 1);
5254
5255  return fn;
5256}
5257
5258#include "gt-cp-decl2.h"
5259