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