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