c++: deduction from auto fn [PR105623]
[official-gcc.git] / gcc / cp / decl2.cc
blobe72fdf05382722c43932b6616a852164f31a80b0
1 /* Process declarations and variables for C++ compiler.
2 Copyright (C) 1988-2022 Free Software Foundation, Inc.
3 Hacked by Michael Tiemann (tiemann@cygnus.com)
5 This file is part of GCC.
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.
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.
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/>. */
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. */
26 /* ??? not all decl nodes are given the most useful possible
27 line numbers. For example, the CONST_DECLs for enum values. */
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 #include "optabs-query.h"
53 /* Id for dumping the raw trees. */
54 int raw_dump_id;
56 extern cpp_reader *parse_in;
58 /* This structure contains information about the initializations
59 and/or destructions required for a particular priority level. */
60 typedef struct priority_info_s {
61 /* Nonzero if there have been any initializations at this priority
62 throughout the translation unit. */
63 int initializations_p;
64 /* Nonzero if there have been any destructions at this priority
65 throughout the translation unit. */
66 int destructions_p;
67 } *priority_info;
69 static tree start_objects (int, int);
70 static void finish_objects (int, int, tree);
71 static tree start_static_storage_duration_function (unsigned);
72 static void finish_static_storage_duration_function (tree);
73 static priority_info get_priority_info (int);
74 static void do_static_initialization_or_destruction (tree, bool);
75 static void one_static_initialization_or_destruction (tree, tree, bool);
76 static void generate_ctor_or_dtor_function (bool, int, location_t *);
77 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
78 void *);
79 static tree prune_vars_needing_no_initialization (tree *);
80 static void write_out_vars (tree);
81 static void import_export_class (tree);
82 static tree get_guard_bits (tree);
83 static void determine_visibility_from_class (tree, tree);
84 static bool determine_hidden_inline (tree);
86 /* A list of static class variables. This is needed, because a
87 static class variable can be declared inside the class without
88 an initializer, and then initialized, statically, outside the class. */
89 static GTY(()) vec<tree, va_gc> *pending_statics;
91 /* A list of functions which were declared inline, but which we
92 may need to emit outline anyway. */
93 static GTY(()) vec<tree, va_gc> *deferred_fns;
95 /* A list of decls that use types with no linkage, which we need to make
96 sure are defined. */
97 static GTY(()) vec<tree, va_gc> *no_linkage_decls;
99 /* A vector of alternating decls and identifiers, where the latter
100 is to be an alias for the former if the former is defined. */
101 static GTY(()) vec<tree, va_gc> *mangling_aliases;
103 /* hash traits for declarations. Hashes single decls via
104 DECL_ASSEMBLER_NAME_RAW. */
106 struct mangled_decl_hash : ggc_remove <tree>
108 typedef tree value_type; /* A DECL. */
109 typedef tree compare_type; /* An identifier. */
111 static hashval_t hash (const value_type decl)
113 return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME_RAW (decl));
115 static bool equal (const value_type existing, compare_type candidate)
117 tree name = DECL_ASSEMBLER_NAME_RAW (existing);
118 return candidate == name;
121 static const bool empty_zero_p = true;
122 static inline void mark_empty (value_type &p) {p = NULL_TREE;}
123 static inline bool is_empty (value_type p) {return !p;}
125 static bool is_deleted (value_type e)
127 return e == reinterpret_cast <value_type> (1);
129 static void mark_deleted (value_type &e)
131 e = reinterpret_cast <value_type> (1);
135 /* A hash table of decls keyed by mangled name. Used to figure out if
136 we need compatibility aliases. */
137 static GTY(()) hash_table<mangled_decl_hash> *mangled_decls;
139 /* Nonzero if we're done parsing and into end-of-file activities. */
141 int at_eof;
143 /* True if note_mangling_alias should enqueue mangling aliases for
144 later generation, rather than emitting them right away. */
146 bool defer_mangling_aliases = true;
149 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
150 FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
151 that apply to the function). */
153 tree
154 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
155 cp_ref_qualifier rqual)
157 if (fntype == error_mark_node || ctype == error_mark_node)
158 return error_mark_node;
160 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
162 cp_cv_quals type_quals = quals & ~TYPE_QUAL_RESTRICT;
163 ctype = cp_build_qualified_type (ctype, type_quals);
165 tree newtype
166 = build_method_type_directly (ctype, TREE_TYPE (fntype),
167 (TREE_CODE (fntype) == METHOD_TYPE
168 ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
169 : TYPE_ARG_TYPES (fntype)));
170 if (tree attrs = TYPE_ATTRIBUTES (fntype))
171 newtype = cp_build_type_attribute_variant (newtype, attrs);
172 newtype = build_cp_fntype_variant (newtype, rqual,
173 TYPE_RAISES_EXCEPTIONS (fntype),
174 TYPE_HAS_LATE_RETURN_TYPE (fntype));
176 return newtype;
179 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
180 return type changed to NEW_RET. */
182 tree
183 change_return_type (tree new_ret, tree fntype)
185 if (new_ret == error_mark_node)
186 return fntype;
188 if (same_type_p (new_ret, TREE_TYPE (fntype)))
189 return fntype;
191 tree newtype;
192 tree args = TYPE_ARG_TYPES (fntype);
194 if (TREE_CODE (fntype) == FUNCTION_TYPE)
196 newtype = build_function_type (new_ret, args);
197 newtype = apply_memfn_quals (newtype,
198 type_memfn_quals (fntype));
200 else
201 newtype = build_method_type_directly
202 (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
204 if (tree attrs = TYPE_ATTRIBUTES (fntype))
205 newtype = cp_build_type_attribute_variant (newtype, attrs);
206 newtype = cxx_copy_lang_qualifiers (newtype, fntype);
208 return newtype;
211 /* Build a PARM_DECL of FN with NAME and TYPE, and set DECL_ARG_TYPE
212 appropriately. */
214 tree
215 cp_build_parm_decl (tree fn, tree name, tree type)
217 tree parm = build_decl (input_location,
218 PARM_DECL, name, type);
219 DECL_CONTEXT (parm) = fn;
221 /* DECL_ARG_TYPE is only used by the back end and the back end never
222 sees templates. */
223 if (!processing_template_decl)
224 DECL_ARG_TYPE (parm) = type_passed_as (type);
226 return parm;
229 /* Returns a PARM_DECL of FN for a parameter of the indicated TYPE, with the
230 indicated NAME. */
232 tree
233 build_artificial_parm (tree fn, tree name, tree type)
235 tree parm = cp_build_parm_decl (fn, name, type);
236 DECL_ARTIFICIAL (parm) = 1;
237 /* All our artificial parms are implicitly `const'; they cannot be
238 assigned to. */
239 TREE_READONLY (parm) = 1;
240 return parm;
243 /* Constructors for types with virtual baseclasses need an "in-charge" flag
244 saying whether this constructor is responsible for initialization of
245 virtual baseclasses or not. All destructors also need this "in-charge"
246 flag, which additionally determines whether or not the destructor should
247 free the memory for the object.
249 This function adds the "in-charge" flag to member function FN if
250 appropriate. It is called from grokclassfn and tsubst.
251 FN must be either a constructor or destructor.
253 The in-charge flag follows the 'this' parameter, and is followed by the
254 VTT parm (if any), then the user-written parms. */
256 void
257 maybe_retrofit_in_chrg (tree fn)
259 tree basetype, arg_types, parms, parm, fntype;
261 /* If we've already add the in-charge parameter don't do it again. */
262 if (DECL_HAS_IN_CHARGE_PARM_P (fn))
263 return;
265 /* When processing templates we can't know, in general, whether or
266 not we're going to have virtual baseclasses. */
267 if (processing_template_decl)
268 return;
270 /* We don't need an in-charge parameter for constructors that don't
271 have virtual bases. */
272 if (DECL_CONSTRUCTOR_P (fn)
273 && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
274 return;
276 arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
277 basetype = TREE_TYPE (TREE_VALUE (arg_types));
278 arg_types = TREE_CHAIN (arg_types);
280 parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
282 /* If this is a subobject constructor or destructor, our caller will
283 pass us a pointer to our VTT. */
284 if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
286 parm = build_artificial_parm (fn, vtt_parm_identifier, vtt_parm_type);
288 /* First add it to DECL_ARGUMENTS between 'this' and the real args... */
289 DECL_CHAIN (parm) = parms;
290 parms = parm;
292 /* ...and then to TYPE_ARG_TYPES. */
293 arg_types = hash_tree_chain (vtt_parm_type, arg_types);
295 DECL_HAS_VTT_PARM_P (fn) = 1;
298 /* Then add the in-charge parm (before the VTT parm). */
299 parm = build_artificial_parm (fn, in_charge_identifier, integer_type_node);
300 DECL_CHAIN (parm) = parms;
301 parms = parm;
302 arg_types = hash_tree_chain (integer_type_node, arg_types);
304 /* Insert our new parameter(s) into the list. */
305 DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
307 /* And rebuild the function type. */
308 fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
309 arg_types);
310 if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
311 fntype = (cp_build_type_attribute_variant
312 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
313 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (fn));
314 TREE_TYPE (fn) = fntype;
316 /* Now we've got the in-charge parameter. */
317 DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
320 /* Classes overload their constituent function names automatically.
321 When a function name is declared in a record structure,
322 its name is changed to it overloaded name. Since names for
323 constructors and destructors can conflict, we place a leading
324 '$' for destructors.
326 CNAME is the name of the class we are grokking for.
328 FUNCTION is a FUNCTION_DECL. It was created by `grokdeclarator'.
330 FLAGS contains bits saying what's special about today's
331 arguments. DTOR_FLAG == DESTRUCTOR.
333 If FUNCTION is a destructor, then we must add the `auto-delete' field
334 as a second parameter. There is some hair associated with the fact
335 that we must "declare" this variable in the manner consistent with the
336 way the rest of the arguments were declared.
338 QUALS are the qualifiers for the this pointer. */
340 void
341 grokclassfn (tree ctype, tree function, enum overload_flags flags)
343 tree fn_name = DECL_NAME (function);
345 /* Even within an `extern "C"' block, members get C++ linkage. See
346 [dcl.link] for details. */
347 SET_DECL_LANGUAGE (function, lang_cplusplus);
349 if (fn_name == NULL_TREE)
351 error ("name missing for member function");
352 fn_name = get_identifier ("<anonymous>");
353 DECL_NAME (function) = fn_name;
356 DECL_CONTEXT (function) = ctype;
358 if (flags == DTOR_FLAG)
359 DECL_CXX_DESTRUCTOR_P (function) = 1;
361 if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
362 maybe_retrofit_in_chrg (function);
365 /* Create an ARRAY_REF, checking for the user doing things backwards
366 along the way.
367 If INDEX_EXP is non-NULL, then that is the index expression,
368 otherwise INDEX_EXP_LIST is the list of index expressions. */
370 tree
371 grok_array_decl (location_t loc, tree array_expr, tree index_exp,
372 vec<tree, va_gc> **index_exp_list, tsubst_flags_t complain)
374 tree type;
375 tree expr;
376 tree orig_array_expr = array_expr;
377 tree orig_index_exp = index_exp;
378 vec<tree, va_gc> *orig_index_exp_list
379 = index_exp_list ? *index_exp_list : NULL;
380 tree overload = NULL_TREE;
382 if (error_operand_p (array_expr) || error_operand_p (index_exp))
383 return error_mark_node;
385 if (processing_template_decl)
387 if (type_dependent_expression_p (array_expr)
388 || (index_exp ? type_dependent_expression_p (index_exp)
389 : any_type_dependent_arguments_p (*index_exp_list)))
391 if (index_exp == NULL)
392 index_exp = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
393 *index_exp_list);
394 return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
395 NULL_TREE, NULL_TREE);
397 array_expr = build_non_dependent_expr (array_expr);
398 if (index_exp)
399 index_exp = build_non_dependent_expr (index_exp);
400 else
402 orig_index_exp_list = make_tree_vector_copy (*index_exp_list);
403 make_args_non_dependent (*index_exp_list);
407 type = TREE_TYPE (array_expr);
408 gcc_assert (type);
409 type = non_reference (type);
411 /* If they have an `operator[]', use that. */
412 if (MAYBE_CLASS_TYPE_P (type)
413 || (index_exp && MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
414 || (index_exp == NULL_TREE
415 && !(*index_exp_list)->is_empty ()
416 && MAYBE_CLASS_TYPE_P (TREE_TYPE ((*index_exp_list)->last ()))))
418 if (index_exp)
419 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
420 index_exp, NULL_TREE, NULL_TREE,
421 &overload, complain);
422 else if ((*index_exp_list)->is_empty ())
423 expr = build_op_subscript (loc, array_expr, index_exp_list, &overload,
424 complain);
425 else
427 expr = build_op_subscript (loc, array_expr, index_exp_list,
428 &overload, complain & tf_decltype);
429 if (expr == error_mark_node)
431 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
432 tf_none);
433 if (idx != error_mark_node)
434 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
435 idx, NULL_TREE, NULL_TREE, &overload,
436 complain & tf_decltype);
437 if (expr == error_mark_node)
439 overload = NULL_TREE;
440 expr = build_op_subscript (loc, array_expr, index_exp_list,
441 &overload, complain);
443 else
444 /* If it would be valid albeit deprecated expression in C++20,
445 just pedwarn on it and treat it as if wrapped in (). */
446 pedwarn (loc, OPT_Wcomma_subscript,
447 "top-level comma expression in array subscript "
448 "changed meaning in C++23");
452 else
454 tree p1, p2, i1, i2;
455 bool swapped = false;
457 /* Otherwise, create an ARRAY_REF for a pointer or array type.
458 It is a little-known fact that, if `a' is an array and `i' is
459 an int, you can write `i[a]', which means the same thing as
460 `a[i]'. */
461 if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
462 p1 = array_expr;
463 else
464 p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
466 if (index_exp == NULL_TREE)
468 if ((*index_exp_list)->is_empty ())
470 error_at (loc, "built-in subscript operator without expression "
471 "list");
472 return error_mark_node;
474 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
475 tf_none);
476 if (idx != error_mark_node)
477 /* If it would be valid albeit deprecated expression in C++20,
478 just pedwarn on it and treat it as if wrapped in (). */
479 pedwarn (loc, OPT_Wcomma_subscript,
480 "top-level comma expression in array subscript "
481 "changed meaning in C++23");
482 else
484 error_at (loc, "built-in subscript operator with more than one "
485 "expression in expression list");
486 return error_mark_node;
488 index_exp = idx;
491 if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
492 p2 = index_exp;
493 else
494 p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
496 i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
497 false);
498 i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
499 false);
501 if ((p1 && i2) && (i1 && p2))
502 error ("ambiguous conversion for array subscript");
504 if (p1 && i2)
505 array_expr = p1, index_exp = i2;
506 else if (i1 && p2)
507 swapped = true, array_expr = p2, index_exp = i1;
508 else
510 error_at (loc, "invalid types %<%T[%T]%> for array subscript",
511 type, TREE_TYPE (index_exp));
512 return error_mark_node;
515 if (array_expr == error_mark_node || index_exp == error_mark_node)
516 error ("ambiguous conversion for array subscript");
518 if (TYPE_PTR_P (TREE_TYPE (array_expr)))
519 array_expr = mark_rvalue_use (array_expr);
520 else
521 array_expr = mark_lvalue_use_nonread (array_expr);
522 index_exp = mark_rvalue_use (index_exp);
523 if (swapped
524 && flag_strong_eval_order == 2
525 && (TREE_SIDE_EFFECTS (array_expr) || TREE_SIDE_EFFECTS (index_exp)))
526 expr = build_array_ref (input_location, index_exp, array_expr);
527 else
528 expr = build_array_ref (input_location, array_expr, index_exp);
530 if (processing_template_decl && expr != error_mark_node)
532 if (overload != NULL_TREE)
534 if (orig_index_exp == NULL_TREE)
536 expr = build_min_non_dep_op_overload (expr, overload,
537 orig_array_expr,
538 orig_index_exp_list);
539 release_tree_vector (orig_index_exp_list);
540 return expr;
542 return build_min_non_dep_op_overload (ARRAY_REF, expr, overload,
543 orig_array_expr,
544 orig_index_exp);
547 if (orig_index_exp == NULL_TREE)
549 orig_index_exp
550 = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
551 orig_index_exp_list);
552 release_tree_vector (orig_index_exp_list);
555 return build_min_non_dep (ARRAY_REF, expr, orig_array_expr,
556 orig_index_exp, NULL_TREE, NULL_TREE);
558 return expr;
561 /* Given the cast expression EXP, checking out its validity. Either return
562 an error_mark_node if there was an unavoidable error, return a cast to
563 void for trying to delete a pointer w/ the value 0, or return the
564 call to delete. If DOING_VEC is true, we handle things differently
565 for doing an array delete.
566 Implements ARM $5.3.4. This is called from the parser. */
568 tree
569 delete_sanity (location_t loc, tree exp, tree size, bool doing_vec,
570 int use_global_delete, tsubst_flags_t complain)
572 tree t, type;
574 if (exp == error_mark_node)
575 return exp;
577 if (processing_template_decl)
579 t = build_min (DELETE_EXPR, void_type_node, exp, size);
580 DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
581 DELETE_EXPR_USE_VEC (t) = doing_vec;
582 TREE_SIDE_EFFECTS (t) = 1;
583 SET_EXPR_LOCATION (t, loc);
584 return t;
587 location_t exp_loc = cp_expr_loc_or_loc (exp, loc);
589 /* An array can't have been allocated by new, so complain. */
590 if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
591 && (complain & tf_warning))
592 warning_at (exp_loc, 0, "deleting array %q#E", exp);
594 t = build_expr_type_conversion (WANT_POINTER, exp, true);
596 if (t == NULL_TREE || t == error_mark_node)
598 if (complain & tf_error)
599 error_at (exp_loc,
600 "type %q#T argument given to %<delete%>, expected pointer",
601 TREE_TYPE (exp));
602 return error_mark_node;
605 type = TREE_TYPE (t);
607 /* As of Valley Forge, you can delete a pointer to const. */
609 /* You can't delete functions. */
610 if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
612 if (complain & tf_error)
613 error_at (exp_loc,
614 "cannot delete a function. Only pointer-to-objects are "
615 "valid arguments to %<delete%>");
616 return error_mark_node;
619 /* Deleting ptr to void is undefined behavior [expr.delete/3]. */
620 if (VOID_TYPE_P (TREE_TYPE (type)))
622 if (complain & tf_warning)
623 warning_at (exp_loc, OPT_Wdelete_incomplete,
624 "deleting %qT is undefined", type);
625 doing_vec = 0;
628 /* Deleting a pointer with the value zero is valid and has no effect. */
629 if (integer_zerop (t))
630 return build1_loc (loc, NOP_EXPR, void_type_node, t);
632 if (doing_vec)
633 return build_vec_delete (loc, t, /*maxindex=*/NULL_TREE,
634 sfk_deleting_destructor,
635 use_global_delete, complain);
636 else
637 return build_delete (loc, type, t, sfk_deleting_destructor,
638 LOOKUP_NORMAL, use_global_delete,
639 complain);
642 /* Report an error if the indicated template declaration is not the
643 sort of thing that should be a member template. */
645 void
646 check_member_template (tree tmpl)
648 tree decl;
650 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
651 decl = DECL_TEMPLATE_RESULT (tmpl);
653 if (TREE_CODE (decl) == FUNCTION_DECL
654 || DECL_ALIAS_TEMPLATE_P (tmpl)
655 || (TREE_CODE (decl) == TYPE_DECL
656 && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
658 /* The parser rejects template declarations in local classes
659 (with the exception of generic lambdas). */
660 gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
661 /* The parser rejects any use of virtual in a function template. */
662 gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
663 && DECL_VIRTUAL_P (decl)));
665 /* The debug-information generating code doesn't know what to do
666 with member templates. */
667 DECL_IGNORED_P (tmpl) = 1;
669 else if (variable_template_p (tmpl))
670 /* OK */;
671 else
672 error ("template declaration of %q#D", decl);
675 /* Sanity check: report error if this function FUNCTION is not
676 really a member of the class (CTYPE) it is supposed to belong to.
677 TEMPLATE_PARMS is used to specify the template parameters of a member
678 template passed as FUNCTION_DECL. If the member template is passed as a
679 TEMPLATE_DECL, it can be NULL since the parameters can be extracted
680 from the declaration. If the function is not a function template, it
681 must be NULL.
682 It returns the original declaration for the function, NULL_TREE if
683 no declaration was found, error_mark_node if an error was emitted. */
685 tree
686 check_classfn (tree ctype, tree function, tree template_parms)
688 if (DECL_USE_TEMPLATE (function)
689 && !(TREE_CODE (function) == TEMPLATE_DECL
690 && DECL_TEMPLATE_SPECIALIZATION (function))
691 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
692 /* Since this is a specialization of a member template,
693 we're not going to find the declaration in the class.
694 For example, in:
696 struct S { template <typename T> void f(T); };
697 template <> void S::f(int);
699 we're not going to find `S::f(int)', but there's no
700 reason we should, either. We let our callers know we didn't
701 find the method, but we don't complain. */
702 return NULL_TREE;
704 /* Basic sanity check: for a template function, the template parameters
705 either were not passed, or they are the same of DECL_TEMPLATE_PARMS. */
706 if (TREE_CODE (function) == TEMPLATE_DECL)
708 if (template_parms
709 && !comp_template_parms (template_parms,
710 DECL_TEMPLATE_PARMS (function)))
712 error ("template parameter lists provided don%'t match the "
713 "template parameters of %qD", function);
714 return error_mark_node;
716 template_parms = DECL_TEMPLATE_PARMS (function);
719 /* OK, is this a definition of a member template? */
720 bool is_template = (template_parms != NULL_TREE);
722 /* [temp.mem]
724 A destructor shall not be a member template. */
725 if (DECL_DESTRUCTOR_P (function) && is_template)
727 error ("destructor %qD declared as member template", function);
728 return error_mark_node;
731 /* We must enter the scope here, because conversion operators are
732 named by target type, and type equivalence relies on typenames
733 resolving within the scope of CTYPE. */
734 tree pushed_scope = push_scope (ctype);
735 tree matched = NULL_TREE;
736 tree fns = get_class_binding (ctype, DECL_NAME (function));
737 bool saw_template = false;
739 for (ovl_iterator iter (fns); !matched && iter; ++iter)
741 tree fndecl = *iter;
743 if (TREE_CODE (fndecl) == TEMPLATE_DECL)
744 saw_template = true;
746 /* A member template definition only matches a member template
747 declaration. */
748 if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
749 continue;
751 if (!DECL_DECLARES_FUNCTION_P (fndecl))
752 continue;
754 tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
755 tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
757 /* We cannot simply call decls_match because this doesn't work
758 for static member functions that are pretending to be
759 methods, and because the name may have been changed by
760 asm("new_name"). */
762 /* Get rid of the this parameter on functions that become
763 static. */
764 if (DECL_STATIC_FUNCTION_P (fndecl)
765 && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
766 p1 = TREE_CHAIN (p1);
768 /* ref-qualifier or absence of same must match. */
769 if (type_memfn_rqual (TREE_TYPE (function))
770 != type_memfn_rqual (TREE_TYPE (fndecl)))
771 continue;
773 // Include constraints in the match.
774 tree c1 = get_constraints (function);
775 tree c2 = get_constraints (fndecl);
777 /* While finding a match, same types and params are not enough
778 if the function is versioned. Also check version ("target")
779 attributes. */
780 if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
781 TREE_TYPE (TREE_TYPE (fndecl)))
782 && compparms (p1, p2)
783 && !targetm.target_option.function_versions (function, fndecl)
784 && (!is_template
785 || comp_template_parms (template_parms,
786 DECL_TEMPLATE_PARMS (fndecl)))
787 && equivalent_constraints (c1, c2)
788 && (DECL_TEMPLATE_SPECIALIZATION (function)
789 == DECL_TEMPLATE_SPECIALIZATION (fndecl))
790 && (!DECL_TEMPLATE_SPECIALIZATION (function)
791 || (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl))))
792 matched = fndecl;
795 if (!matched && !is_template && saw_template
796 && !processing_template_decl && DECL_UNIQUE_FRIEND_P (function))
798 /* "[if no non-template match is found,] each remaining function template
799 is replaced with the specialization chosen by deduction from the
800 friend declaration or discarded if deduction fails."
802 So tell check_explicit_specialization to look for a match. */
803 SET_DECL_IMPLICIT_INSTANTIATION (function);
804 matched = function;
807 if (!matched)
809 if (!COMPLETE_TYPE_P (ctype))
810 cxx_incomplete_type_error (DECL_SOURCE_LOCATION (function),
811 function, ctype);
812 else
814 if (DECL_CONV_FN_P (function))
815 fns = get_class_binding (ctype, conv_op_identifier);
817 error_at (DECL_SOURCE_LOCATION (function),
818 "no declaration matches %q#D", function);
819 if (fns)
820 print_candidates (fns);
821 else if (DECL_CONV_FN_P (function))
822 inform (DECL_SOURCE_LOCATION (function),
823 "no conversion operators declared");
824 else
825 inform (DECL_SOURCE_LOCATION (function),
826 "no functions named %qD", function);
827 inform (DECL_SOURCE_LOCATION (TYPE_NAME (ctype)),
828 "%#qT defined here", ctype);
830 matched = error_mark_node;
833 if (pushed_scope)
834 pop_scope (pushed_scope);
836 return matched;
839 /* DECL is a function with vague linkage. Remember it so that at the
840 end of the translation unit we can decide whether or not to emit
841 it. */
843 void
844 note_vague_linkage_fn (tree decl)
846 if (processing_template_decl)
847 return;
849 DECL_DEFER_OUTPUT (decl) = 1;
850 vec_safe_push (deferred_fns, decl);
853 /* As above, but for variable template instantiations. */
855 void
856 note_variable_template_instantiation (tree decl)
858 vec_safe_push (pending_statics, decl);
861 /* We have just processed the DECL, which is a static data member.
862 The other parameters are as for cp_finish_decl. */
864 void
865 finish_static_data_member_decl (tree decl,
866 tree init, bool init_const_expr_p,
867 tree asmspec_tree,
868 int flags)
870 if (DECL_TEMPLATE_INSTANTIATED (decl))
871 /* We already needed to instantiate this, so the processing in this
872 function is unnecessary/wrong. */
873 return;
875 DECL_CONTEXT (decl) = current_class_type;
877 /* We cannot call pushdecl here, because that would fill in the
878 TREE_CHAIN of our decl. Instead, we modify cp_finish_decl to do
879 the right thing, namely, to put this decl out straight away. */
881 if (! processing_template_decl)
882 vec_safe_push (pending_statics, decl);
884 if (LOCAL_CLASS_P (current_class_type)
885 /* We already complained about the template definition. */
886 && !DECL_TEMPLATE_INSTANTIATION (decl))
887 permerror (DECL_SOURCE_LOCATION (decl),
888 "local class %q#T shall not have static data member %q#D",
889 current_class_type, decl);
890 else
891 for (tree t = current_class_type; TYPE_P (t);
892 t = CP_TYPE_CONTEXT (t))
893 if (TYPE_UNNAMED_P (t))
895 auto_diagnostic_group d;
896 if (permerror (DECL_SOURCE_LOCATION (decl),
897 "static data member %qD in unnamed class", decl))
898 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
899 "unnamed class defined here");
900 break;
903 if (DECL_INLINE_VAR_P (decl) && !DECL_TEMPLATE_INSTANTIATION (decl))
904 /* An inline variable is immediately defined, so don't set DECL_IN_AGGR_P.
905 Except that if decl is a template instantiation, it isn't defined until
906 instantiate_decl. */;
907 else
908 DECL_IN_AGGR_P (decl) = 1;
910 if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
911 && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
912 SET_VAR_HAD_UNKNOWN_BOUND (decl);
914 if (init)
916 /* Similarly to start_decl_1, we want to complete the type in order
917 to do the right thing in cp_apply_type_quals_to_decl, possibly
918 clear TYPE_QUAL_CONST (c++/65579). */
919 tree type = TREE_TYPE (decl) = complete_type (TREE_TYPE (decl));
920 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
923 cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
926 /* DECLARATOR and DECLSPECS correspond to a class member. The other
927 parameters are as for cp_finish_decl. Return the DECL for the
928 class member declared. */
930 tree
931 grokfield (const cp_declarator *declarator,
932 cp_decl_specifier_seq *declspecs,
933 tree init, bool init_const_expr_p,
934 tree asmspec_tree,
935 tree attrlist)
937 tree value;
938 const char *asmspec = 0;
939 int flags;
941 if (init
942 && TREE_CODE (init) == TREE_LIST
943 && TREE_VALUE (init) == error_mark_node
944 && TREE_CHAIN (init) == NULL_TREE)
945 init = NULL_TREE;
947 int initialized;
948 if (init == ridpointers[(int)RID_DELETE])
949 initialized = SD_DELETED;
950 else if (init == ridpointers[(int)RID_DEFAULT])
951 initialized = SD_DEFAULTED;
952 else if (init)
953 initialized = SD_INITIALIZED;
954 else
955 initialized = SD_UNINITIALIZED;
957 value = grokdeclarator (declarator, declspecs, FIELD, initialized, &attrlist);
958 if (! value || value == error_mark_node)
959 /* friend or constructor went bad. */
960 return error_mark_node;
961 if (TREE_TYPE (value) == error_mark_node)
962 return value;
964 if (TREE_CODE (value) == TYPE_DECL && init)
966 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value)),
967 "typedef %qD is initialized (use %qs instead)",
968 value, "decltype");
969 init = NULL_TREE;
972 /* Pass friendly classes back. */
973 if (value == void_type_node)
974 return value;
976 if (DECL_NAME (value)
977 && TREE_CODE (DECL_NAME (value)) == TEMPLATE_ID_EXPR)
979 error_at (declarator->id_loc,
980 "explicit template argument list not allowed");
981 return error_mark_node;
984 /* Stash away type declarations. */
985 if (TREE_CODE (value) == TYPE_DECL)
987 DECL_NONLOCAL (value) = 1;
988 DECL_CONTEXT (value) = current_class_type;
990 if (attrlist)
992 int attrflags = 0;
994 /* If this is a typedef that names the class for linkage purposes
995 (7.1.3p8), apply any attributes directly to the type. */
996 if (OVERLOAD_TYPE_P (TREE_TYPE (value))
997 && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
998 attrflags = ATTR_FLAG_TYPE_IN_PLACE;
1000 cplus_decl_attributes (&value, attrlist, attrflags);
1003 if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
1004 && TREE_TYPE (value) != error_mark_node
1005 && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
1006 set_underlying_type (value);
1008 /* It's important that push_template_decl below follows
1009 set_underlying_type above so that the created template
1010 carries the properly set type of VALUE. */
1011 if (processing_template_decl)
1012 value = push_template_decl (value);
1014 record_locally_defined_typedef (value);
1015 return value;
1018 int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
1020 if (!friendp && DECL_IN_AGGR_P (value))
1022 error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
1023 return void_type_node;
1026 if (asmspec_tree && asmspec_tree != error_mark_node)
1027 asmspec = TREE_STRING_POINTER (asmspec_tree);
1029 if (init)
1031 if (TREE_CODE (value) == FUNCTION_DECL)
1033 if (init == ridpointers[(int)RID_DELETE])
1035 DECL_DELETED_FN (value) = 1;
1036 DECL_DECLARED_INLINE_P (value) = 1;
1038 else if (init == ridpointers[(int)RID_DEFAULT])
1040 if (defaultable_fn_check (value))
1042 DECL_DEFAULTED_FN (value) = 1;
1043 DECL_INITIALIZED_IN_CLASS_P (value) = 1;
1044 DECL_DECLARED_INLINE_P (value) = 1;
1045 /* grokfndecl set this to error_mark_node, but we want to
1046 leave it unset until synthesize_method. */
1047 DECL_INITIAL (value) = NULL_TREE;
1050 else if (TREE_CODE (init) == DEFERRED_PARSE)
1051 error ("invalid initializer for member function %qD", value);
1052 else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
1054 if (integer_zerop (init))
1055 DECL_PURE_VIRTUAL_P (value) = 1;
1056 else if (error_operand_p (init))
1057 ; /* An error has already been reported. */
1058 else
1059 error ("invalid initializer for member function %qD",
1060 value);
1062 else
1064 gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
1065 location_t iloc
1066 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value));
1067 if (friendp)
1068 error_at (iloc, "initializer specified for friend "
1069 "function %qD", value);
1070 else
1071 error_at (iloc, "initializer specified for static "
1072 "member function %qD", value);
1075 else if (TREE_CODE (value) == FIELD_DECL)
1076 /* C++11 NSDMI, keep going. */;
1077 else if (!VAR_P (value))
1078 gcc_unreachable ();
1081 /* Pass friend decls back. */
1082 if ((TREE_CODE (value) == FUNCTION_DECL
1083 || TREE_CODE (value) == TEMPLATE_DECL)
1084 && DECL_CONTEXT (value) != current_class_type)
1086 if (attrlist)
1087 cplus_decl_attributes (&value, attrlist, 0);
1088 return value;
1091 /* Need to set this before push_template_decl. */
1092 if (VAR_P (value))
1093 DECL_CONTEXT (value) = current_class_type;
1095 if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
1097 value = push_template_decl (value);
1098 if (error_operand_p (value))
1099 return error_mark_node;
1102 if (attrlist)
1103 cplus_decl_attributes (&value, attrlist, 0);
1105 if (init && DIRECT_LIST_INIT_P (init))
1106 flags = LOOKUP_NORMAL;
1107 else
1108 flags = LOOKUP_IMPLICIT;
1110 switch (TREE_CODE (value))
1112 case VAR_DECL:
1113 finish_static_data_member_decl (value, init, init_const_expr_p,
1114 asmspec_tree, flags);
1115 return value;
1117 case FIELD_DECL:
1118 if (asmspec)
1119 error ("%<asm%> specifiers are not permitted on non-static data members");
1120 if (DECL_INITIAL (value) == error_mark_node)
1121 init = error_mark_node;
1122 cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1123 NULL_TREE, flags);
1124 DECL_IN_AGGR_P (value) = 1;
1125 return value;
1127 case FUNCTION_DECL:
1128 if (asmspec)
1129 set_user_assembler_name (value, asmspec);
1131 cp_finish_decl (value,
1132 /*init=*/NULL_TREE,
1133 /*init_const_expr_p=*/false,
1134 asmspec_tree, flags);
1136 /* Pass friends back this way. */
1137 if (DECL_UNIQUE_FRIEND_P (value))
1138 return void_type_node;
1140 DECL_IN_AGGR_P (value) = 1;
1141 return value;
1143 default:
1144 gcc_unreachable ();
1146 return NULL_TREE;
1149 /* Like `grokfield', but for bitfields.
1150 WIDTH is the width of the bitfield, a constant expression.
1151 The other parameters are as for grokfield. */
1153 tree
1154 grokbitfield (const cp_declarator *declarator,
1155 cp_decl_specifier_seq *declspecs, tree width, tree init,
1156 tree attrlist)
1158 tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1159 init != NULL_TREE, &attrlist);
1161 if (value == error_mark_node)
1162 return NULL_TREE; /* friends went bad. */
1164 tree type = TREE_TYPE (value);
1165 if (type == error_mark_node)
1166 return value;
1168 /* Pass friendly classes back. */
1169 if (VOID_TYPE_P (value))
1170 return void_type_node;
1172 if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type)
1173 && (INDIRECT_TYPE_P (type) || !dependent_type_p (type)))
1175 error_at (DECL_SOURCE_LOCATION (value),
1176 "bit-field %qD with non-integral type %qT",
1177 value, type);
1178 return error_mark_node;
1181 if (TREE_CODE (value) == TYPE_DECL)
1183 error_at (DECL_SOURCE_LOCATION (value),
1184 "cannot declare %qD to be a bit-field type", value);
1185 return NULL_TREE;
1188 /* Usually, finish_struct_1 catches bitfields with invalid types.
1189 But, in the case of bitfields with function type, we confuse
1190 ourselves into thinking they are member functions, so we must
1191 check here. */
1192 if (TREE_CODE (value) == FUNCTION_DECL)
1194 error_at (DECL_SOURCE_LOCATION (value),
1195 "cannot declare bit-field %qD with function type", value);
1196 return NULL_TREE;
1199 if (TYPE_WARN_IF_NOT_ALIGN (type))
1201 error_at (DECL_SOURCE_LOCATION (value), "cannot declare bit-field "
1202 "%qD with %<warn_if_not_aligned%> type", value);
1203 return NULL_TREE;
1206 if (DECL_IN_AGGR_P (value))
1208 error ("%qD is already defined in the class %qT", value,
1209 DECL_CONTEXT (value));
1210 return void_type_node;
1213 if (TREE_STATIC (value))
1215 error_at (DECL_SOURCE_LOCATION (value),
1216 "static member %qD cannot be a bit-field", value);
1217 return NULL_TREE;
1220 int flags = LOOKUP_IMPLICIT;
1221 if (init && DIRECT_LIST_INIT_P (init))
1222 flags = LOOKUP_NORMAL;
1223 cp_finish_decl (value, init, false, NULL_TREE, flags);
1225 if (width != error_mark_node)
1227 /* The width must be an integer type. */
1228 if (!type_dependent_expression_p (width)
1229 && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1230 error ("width of bit-field %qD has non-integral type %qT", value,
1231 TREE_TYPE (width));
1232 else if (!check_for_bare_parameter_packs (width))
1234 /* Temporarily stash the width in DECL_BIT_FIELD_REPRESENTATIVE.
1235 check_bitfield_decl picks it from there later and sets DECL_SIZE
1236 accordingly. */
1237 DECL_BIT_FIELD_REPRESENTATIVE (value) = width;
1238 SET_DECL_C_BIT_FIELD (value);
1242 DECL_IN_AGGR_P (value) = 1;
1244 if (attrlist)
1245 cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1247 return value;
1251 /* Returns true iff ATTR is an attribute which needs to be applied at
1252 instantiation time rather than template definition time. */
1254 static bool
1255 is_late_template_attribute (tree attr, tree decl)
1257 tree name = get_attribute_name (attr);
1258 tree args = TREE_VALUE (attr);
1259 const struct attribute_spec *spec = lookup_attribute_spec (name);
1260 tree arg;
1262 if (!spec)
1263 /* Unknown attribute. */
1264 return false;
1266 /* Attribute weak handling wants to write out assembly right away. */
1267 if (is_attribute_p ("weak", name))
1268 return true;
1270 /* Attributes used and unused are applied directly to typedefs for the
1271 benefit of maybe_warn_unused_local_typedefs. */
1272 if (TREE_CODE (decl) == TYPE_DECL
1273 && (is_attribute_p ("unused", name)
1274 || is_attribute_p ("used", name)))
1275 return false;
1277 /* Attribute tls_model wants to modify the symtab. */
1278 if (is_attribute_p ("tls_model", name))
1279 return true;
1281 /* #pragma omp declare simd attribute needs to be always deferred. */
1282 if (flag_openmp
1283 && is_attribute_p ("omp declare simd", name))
1284 return true;
1286 if (args == error_mark_node)
1287 return false;
1289 /* An attribute pack is clearly dependent. */
1290 if (args && PACK_EXPANSION_P (args))
1291 return true;
1293 /* If any of the arguments are dependent expressions, we can't evaluate
1294 the attribute until instantiation time. */
1295 for (arg = args; arg; arg = TREE_CHAIN (arg))
1297 tree t = TREE_VALUE (arg);
1299 /* If the first attribute argument is an identifier, only consider
1300 second and following arguments. Attributes like mode, format,
1301 cleanup and several target specific attributes aren't late
1302 just because they have an IDENTIFIER_NODE as first argument. */
1303 if (arg == args && attribute_takes_identifier_p (name)
1304 && identifier_p (t))
1305 continue;
1307 if (value_dependent_expression_p (t))
1308 return true;
1311 if (TREE_CODE (decl) == TYPE_DECL
1312 || TYPE_P (decl)
1313 || spec->type_required)
1315 tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1317 if (!type)
1318 return true;
1320 /* We can't apply any attributes to a completely unknown type until
1321 instantiation time. */
1322 enum tree_code code = TREE_CODE (type);
1323 if (code == TEMPLATE_TYPE_PARM
1324 || code == BOUND_TEMPLATE_TEMPLATE_PARM
1325 || code == TYPENAME_TYPE)
1326 return true;
1327 /* Also defer most attributes on dependent types. This is not
1328 necessary in all cases, but is the better default. */
1329 else if (dependent_type_p (type)
1330 /* But some attributes specifically apply to templates. */
1331 && !is_attribute_p ("abi_tag", name)
1332 && !is_attribute_p ("deprecated", name)
1333 && !is_attribute_p ("unavailable", name)
1334 && !is_attribute_p ("visibility", name))
1335 return true;
1336 else
1337 return false;
1339 else
1340 return false;
1343 /* ATTR_P is a list of attributes. Remove any attributes which need to be
1344 applied at instantiation time and return them. If IS_DEPENDENT is true,
1345 the declaration itself is dependent, so all attributes should be applied
1346 at instantiation time. */
1348 tree
1349 splice_template_attributes (tree *attr_p, tree decl)
1351 tree *p = attr_p;
1352 tree late_attrs = NULL_TREE;
1353 tree *q = &late_attrs;
1355 if (!p || *p == error_mark_node)
1356 return NULL_TREE;
1358 for (; *p; )
1360 if (is_late_template_attribute (*p, decl))
1362 ATTR_IS_DEPENDENT (*p) = 1;
1363 *q = *p;
1364 *p = TREE_CHAIN (*p);
1365 q = &TREE_CHAIN (*q);
1366 *q = NULL_TREE;
1368 else
1369 p = &TREE_CHAIN (*p);
1372 return late_attrs;
1375 /* Attach any LATE_ATTRS to DECL_P, after the non-dependent attributes have
1376 been applied by a previous call to decl_attributes. */
1378 static void
1379 save_template_attributes (tree late_attrs, tree *decl_p, int flags)
1381 tree *q;
1383 if (!late_attrs)
1384 return;
1386 if (DECL_P (*decl_p))
1387 q = &DECL_ATTRIBUTES (*decl_p);
1388 else
1389 q = &TYPE_ATTRIBUTES (*decl_p);
1391 tree old_attrs = *q;
1393 /* Place the late attributes at the beginning of the attribute
1394 list. */
1395 late_attrs = chainon (late_attrs, *q);
1396 if (*q != late_attrs
1397 && !DECL_P (*decl_p)
1398 && !(flags & ATTR_FLAG_TYPE_IN_PLACE))
1400 if (!dependent_type_p (*decl_p))
1401 *decl_p = cp_build_type_attribute_variant (*decl_p, late_attrs);
1402 else
1404 *decl_p = build_variant_type_copy (*decl_p);
1405 TYPE_ATTRIBUTES (*decl_p) = late_attrs;
1408 else
1409 *q = late_attrs;
1411 if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1413 /* We've added new attributes directly to the main variant, so
1414 now we need to update all of the other variants to include
1415 these new attributes. */
1416 tree variant;
1417 for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1418 variant = TYPE_NEXT_VARIANT (variant))
1420 gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1421 TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1426 /* True if ATTRS contains any dependent attributes that affect type
1427 identity. */
1429 bool
1430 any_dependent_type_attributes_p (tree attrs)
1432 for (tree a = attrs; a; a = TREE_CHAIN (a))
1433 if (ATTR_IS_DEPENDENT (a))
1435 const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (a));
1436 if (as && as->affects_type_identity)
1437 return true;
1439 return false;
1442 /* Return true iff ATTRS are acceptable attributes to be applied in-place
1443 to a typedef which gives a previously unnamed class or enum a name for
1444 linkage purposes. */
1446 bool
1447 attributes_naming_typedef_ok (tree attrs)
1449 for (; attrs; attrs = TREE_CHAIN (attrs))
1451 tree name = get_attribute_name (attrs);
1452 if (is_attribute_p ("vector_size", name))
1453 return false;
1455 return true;
1458 /* Like reconstruct_complex_type, but handle also template trees. */
1460 tree
1461 cp_reconstruct_complex_type (tree type, tree bottom)
1463 tree inner, outer;
1465 if (TYPE_PTR_P (type))
1467 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1468 outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1469 TYPE_REF_CAN_ALIAS_ALL (type));
1471 else if (TYPE_REF_P (type))
1473 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1474 outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1475 TYPE_REF_CAN_ALIAS_ALL (type));
1477 else if (TREE_CODE (type) == ARRAY_TYPE)
1479 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1480 outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1481 /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1482 element type qualification will be handled by the recursive
1483 cp_reconstruct_complex_type call and cp_build_qualified_type
1484 for ARRAY_TYPEs changes the element type. */
1485 return outer;
1487 else if (TREE_CODE (type) == FUNCTION_TYPE)
1489 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1490 outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1491 outer = apply_memfn_quals (outer, type_memfn_quals (type));
1493 else if (TREE_CODE (type) == METHOD_TYPE)
1495 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1496 /* The build_method_type_directly() routine prepends 'this' to argument list,
1497 so we must compensate by getting rid of it. */
1498 outer
1499 = build_method_type_directly
1500 (class_of_this_parm (type), inner,
1501 TREE_CHAIN (TYPE_ARG_TYPES (type)));
1503 else if (TREE_CODE (type) == OFFSET_TYPE)
1505 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1506 outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1508 else
1509 return bottom;
1511 if (TYPE_ATTRIBUTES (type))
1512 outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1513 outer = cp_build_qualified_type (outer, cp_type_quals (type));
1514 outer = cxx_copy_lang_qualifiers (outer, type);
1516 return outer;
1519 /* Replaces any constexpr expression that may be into the attributes
1520 arguments with their reduced value. */
1522 void
1523 cp_check_const_attributes (tree attributes)
1525 if (attributes == error_mark_node)
1526 return;
1528 tree attr;
1529 for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1531 tree arg;
1532 /* As we implement alignas using gnu::aligned attribute and
1533 alignas argument is a constant expression, force manifestly
1534 constant evaluation of aligned attribute argument. */
1535 bool manifestly_const_eval
1536 = is_attribute_p ("aligned", get_attribute_name (attr));
1537 for (arg = TREE_VALUE (attr); arg && TREE_CODE (arg) == TREE_LIST;
1538 arg = TREE_CHAIN (arg))
1540 tree expr = TREE_VALUE (arg);
1541 if (EXPR_P (expr))
1542 TREE_VALUE (arg)
1543 = fold_non_dependent_expr (expr, tf_warning_or_error,
1544 manifestly_const_eval);
1549 /* Return true if TYPE is an OpenMP mappable type.
1550 If NOTES is non-zero, emit a note message for each problem. */
1551 static bool
1552 cp_omp_mappable_type_1 (tree type, bool notes)
1554 bool result = true;
1556 /* Mappable type has to be complete. */
1557 if (type == error_mark_node || !COMPLETE_TYPE_P (type))
1559 if (notes && type != error_mark_node)
1561 tree decl = TYPE_MAIN_DECL (type);
1562 inform ((decl ? DECL_SOURCE_LOCATION (decl) : input_location),
1563 "incomplete type %qT is not mappable", type);
1565 result = false;
1567 /* Arrays have mappable type if the elements have mappable type. */
1568 while (TREE_CODE (type) == ARRAY_TYPE)
1569 type = TREE_TYPE (type);
1570 /* All data members must be non-static. */
1571 if (CLASS_TYPE_P (type))
1573 tree field;
1574 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1575 if (VAR_P (field))
1577 if (notes)
1578 inform (DECL_SOURCE_LOCATION (field),
1579 "static field %qD is not mappable", field);
1580 result = false;
1582 /* All fields must have mappable types. */
1583 else if (TREE_CODE (field) == FIELD_DECL
1584 && !cp_omp_mappable_type_1 (TREE_TYPE (field), notes))
1585 result = false;
1587 return result;
1590 /* Return true if TYPE is an OpenMP mappable type. */
1591 bool
1592 cp_omp_mappable_type (tree type)
1594 return cp_omp_mappable_type_1 (type, false);
1597 /* Return true if TYPE is an OpenMP mappable type.
1598 Emit an error messages if not. */
1599 bool
1600 cp_omp_emit_unmappable_type_notes (tree type)
1602 return cp_omp_mappable_type_1 (type, true);
1605 /* Return the last pushed declaration for the symbol DECL or NULL
1606 when no such declaration exists. */
1608 static tree
1609 find_last_decl (tree decl)
1611 tree last_decl = NULL_TREE;
1613 if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
1615 /* Look up the declaration in its scope. */
1616 tree pushed_scope = NULL_TREE;
1617 if (tree ctype = DECL_CONTEXT (decl))
1618 pushed_scope = push_scope (ctype);
1620 last_decl = lookup_name (name);
1622 if (pushed_scope)
1623 pop_scope (pushed_scope);
1625 /* The declaration may be a member conversion operator
1626 or a bunch of overfloads (handle the latter below). */
1627 if (last_decl && BASELINK_P (last_decl))
1628 last_decl = BASELINK_FUNCTIONS (last_decl);
1631 if (!last_decl)
1632 return NULL_TREE;
1634 if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
1636 /* A set of overloads of the same function. */
1637 for (lkp_iterator iter (last_decl); iter; ++iter)
1639 if (TREE_CODE (*iter) == OVERLOAD)
1640 continue;
1642 tree d = *iter;
1644 /* We can't compare versions in the middle of processing the
1645 attribute that has the version. */
1646 if (TREE_CODE (d) == FUNCTION_DECL
1647 && DECL_FUNCTION_VERSIONED (d))
1648 return NULL_TREE;
1650 if (decls_match (decl, d, /*record_decls=*/false))
1651 return d;
1653 return NULL_TREE;
1656 return NULL_TREE;
1659 /* Like decl_attributes, but handle C++ complexity. */
1661 void
1662 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1664 if (*decl == NULL_TREE || *decl == void_type_node
1665 || *decl == error_mark_node || attributes == error_mark_node)
1666 return;
1668 /* Add implicit "omp declare target" attribute if requested. */
1669 if (vec_safe_length (scope_chain->omp_declare_target_attribute)
1670 && ((VAR_P (*decl)
1671 && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1672 || TREE_CODE (*decl) == FUNCTION_DECL))
1674 if (VAR_P (*decl)
1675 && DECL_CLASS_SCOPE_P (*decl))
1676 error ("%q+D static data member inside of declare target directive",
1677 *decl);
1678 else if (VAR_P (*decl)
1679 && (processing_template_decl
1680 || !cp_omp_mappable_type (TREE_TYPE (*decl))))
1681 attributes = tree_cons (get_identifier ("omp declare target implicit"),
1682 NULL_TREE, attributes);
1683 else
1685 attributes = tree_cons (get_identifier ("omp declare target"),
1686 NULL_TREE, attributes);
1687 attributes = tree_cons (get_identifier ("omp declare target block"),
1688 NULL_TREE, attributes);
1692 tree late_attrs = NULL_TREE;
1693 if (processing_template_decl)
1695 if (check_for_bare_parameter_packs (attributes))
1696 return;
1697 late_attrs = splice_template_attributes (&attributes, *decl);
1700 cp_check_const_attributes (attributes);
1702 if (flag_openmp || flag_openmp_simd)
1704 bool diagnosed = false;
1705 for (tree *pa = &attributes; *pa; )
1707 if (get_attribute_namespace (*pa) == omp_identifier)
1709 tree name = get_attribute_name (*pa);
1710 if (is_attribute_p ("directive", name)
1711 || is_attribute_p ("sequence", name))
1713 if (!diagnosed)
1715 error ("%<omp::%E%> not allowed to be specified in this "
1716 "context", name);
1717 diagnosed = true;
1719 *pa = TREE_CHAIN (*pa);
1720 continue;
1723 pa = &TREE_CHAIN (*pa);
1727 if (TREE_CODE (*decl) == TEMPLATE_DECL)
1728 decl = &DECL_TEMPLATE_RESULT (*decl);
1730 if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1732 attributes
1733 = decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1734 decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1735 attributes, flags);
1737 else
1739 tree last_decl = find_last_decl (*decl);
1740 decl_attributes (decl, attributes, flags, last_decl);
1743 if (late_attrs)
1744 save_template_attributes (late_attrs, decl, flags);
1746 /* Propagate deprecation out to the template. */
1747 if (TREE_DEPRECATED (*decl))
1748 if (tree ti = get_template_info (*decl))
1750 tree tmpl = TI_TEMPLATE (ti);
1751 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1752 : DECL_TEMPLATE_RESULT (tmpl));
1753 if (*decl == pattern)
1754 TREE_DEPRECATED (tmpl) = true;
1757 /* Likewise, propagate unavailability out to the template. */
1758 if (TREE_UNAVAILABLE (*decl))
1759 if (tree ti = get_template_info (*decl))
1761 tree tmpl = TI_TEMPLATE (ti);
1762 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1763 : DECL_TEMPLATE_RESULT (tmpl));
1764 if (*decl == pattern)
1765 TREE_UNAVAILABLE (tmpl) = true;
1769 /* Walks through the namespace- or function-scope anonymous union
1770 OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1771 Returns one of the fields for use in the mangled name. */
1773 static tree
1774 build_anon_union_vars (tree type, tree object)
1776 tree main_decl = NULL_TREE;
1777 tree field;
1779 /* Rather than write the code to handle the non-union case,
1780 just give an error. */
1781 if (TREE_CODE (type) != UNION_TYPE)
1783 error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
1784 "anonymous struct not inside named type");
1785 return error_mark_node;
1788 for (field = TYPE_FIELDS (type);
1789 field != NULL_TREE;
1790 field = DECL_CHAIN (field))
1792 tree decl;
1793 tree ref;
1795 if (DECL_ARTIFICIAL (field))
1796 continue;
1797 if (TREE_CODE (field) != FIELD_DECL)
1799 permerror (DECL_SOURCE_LOCATION (field),
1800 "%q#D invalid; an anonymous union can only "
1801 "have non-static data members", field);
1802 continue;
1805 if (TREE_PRIVATE (field))
1806 permerror (DECL_SOURCE_LOCATION (field),
1807 "private member %q#D in anonymous union", field);
1808 else if (TREE_PROTECTED (field))
1809 permerror (DECL_SOURCE_LOCATION (field),
1810 "protected member %q#D in anonymous union", field);
1812 if (processing_template_decl)
1813 ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1814 DECL_NAME (field), NULL_TREE);
1815 else
1816 ref = build_class_member_access_expr (object, field, NULL_TREE,
1817 false, tf_warning_or_error);
1819 if (DECL_NAME (field))
1821 tree base;
1823 decl = build_decl (input_location,
1824 VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1825 DECL_ANON_UNION_VAR_P (decl) = 1;
1826 DECL_ARTIFICIAL (decl) = 1;
1828 base = get_base_address (object);
1829 TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1830 TREE_STATIC (decl) = TREE_STATIC (base);
1831 DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1833 SET_DECL_VALUE_EXPR (decl, ref);
1834 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1836 decl = pushdecl (decl);
1838 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1839 decl = build_anon_union_vars (TREE_TYPE (field), ref);
1840 else
1841 decl = 0;
1843 if (main_decl == NULL_TREE)
1844 main_decl = decl;
1847 return main_decl;
1850 /* Finish off the processing of a UNION_TYPE structure. If the union is an
1851 anonymous union, then all members must be laid out together. PUBLIC_P
1852 is nonzero if this union is not declared static. */
1854 void
1855 finish_anon_union (tree anon_union_decl)
1857 tree type;
1858 tree main_decl;
1859 bool public_p;
1861 if (anon_union_decl == error_mark_node)
1862 return;
1864 type = TREE_TYPE (anon_union_decl);
1865 public_p = TREE_PUBLIC (anon_union_decl);
1867 /* The VAR_DECL's context is the same as the TYPE's context. */
1868 DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1870 if (TYPE_FIELDS (type) == NULL_TREE)
1871 return;
1873 if (public_p)
1875 error ("namespace-scope anonymous aggregates must be static");
1876 return;
1879 main_decl = build_anon_union_vars (type, anon_union_decl);
1880 if (main_decl == error_mark_node)
1881 return;
1882 if (main_decl == NULL_TREE)
1884 pedwarn (input_location, 0, "anonymous union with no members");
1885 return;
1888 if (!processing_template_decl)
1890 /* Use main_decl to set the mangled name. */
1891 DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1892 maybe_commonize_var (anon_union_decl);
1893 if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1895 if (DECL_DISCRIMINATOR_P (anon_union_decl))
1896 determine_local_discriminator (anon_union_decl);
1897 mangle_decl (anon_union_decl);
1899 DECL_NAME (anon_union_decl) = NULL_TREE;
1902 pushdecl (anon_union_decl);
1903 cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1906 /* Auxiliary functions to make type signatures for
1907 `operator new' and `operator delete' correspond to
1908 what compiler will be expecting. */
1910 tree
1911 coerce_new_type (tree type, location_t loc)
1913 int e = 0;
1914 tree args = TYPE_ARG_TYPES (type);
1916 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1918 if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1920 e = 1;
1921 error_at (loc, "%<operator new%> must return type %qT",
1922 ptr_type_node);
1925 if (args && args != void_list_node)
1927 if (TREE_PURPOSE (args))
1929 /* [basic.stc.dynamic.allocation]
1931 The first parameter shall not have an associated default
1932 argument. */
1933 error_at (loc, "the first parameter of %<operator new%> cannot "
1934 "have a default argument");
1935 /* Throw away the default argument. */
1936 TREE_PURPOSE (args) = NULL_TREE;
1939 if (!same_type_p (TREE_VALUE (args), size_type_node))
1941 e = 2;
1942 args = TREE_CHAIN (args);
1945 else
1946 e = 2;
1948 if (e == 2)
1949 permerror (loc, "%<operator new%> takes type %<size_t%> (%qT) "
1950 "as first parameter", size_type_node);
1952 switch (e)
1954 case 2:
1955 args = tree_cons (NULL_TREE, size_type_node, args);
1956 /* Fall through. */
1957 case 1:
1958 type = (cxx_copy_lang_qualifiers
1959 (build_function_type (ptr_type_node, args),
1960 type));
1961 /* Fall through. */
1962 default:;
1964 return type;
1967 void
1968 coerce_delete_type (tree decl, location_t loc)
1970 int e = 0;
1971 tree type = TREE_TYPE (decl);
1972 tree args = TYPE_ARG_TYPES (type);
1974 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1976 if (!same_type_p (TREE_TYPE (type), void_type_node))
1978 e = 1;
1979 error_at (loc, "%<operator delete%> must return type %qT",
1980 void_type_node);
1983 tree ptrtype = ptr_type_node;
1984 if (destroying_delete_p (decl))
1986 if (DECL_CLASS_SCOPE_P (decl))
1987 /* If the function is a destroying operator delete declared in class
1988 type C, the type of its first parameter shall be C*. */
1989 ptrtype = build_pointer_type (DECL_CONTEXT (decl));
1990 else
1991 /* A destroying operator delete shall be a class member function named
1992 operator delete. */
1993 error_at (loc,
1994 "destroying %<operator delete%> must be a member function");
1995 const ovl_op_info_t *op = IDENTIFIER_OVL_OP_INFO (DECL_NAME (decl));
1996 if (op->flags & OVL_OP_FLAG_VEC)
1997 error_at (loc, "%<operator delete[]%> cannot be a destroying delete");
1998 if (!usual_deallocation_fn_p (decl))
1999 error_at (loc, "destroying %<operator delete%> must be a usual "
2000 "deallocation function");
2003 if (!args || args == void_list_node
2004 || !same_type_p (TREE_VALUE (args), ptrtype))
2006 e = 2;
2007 if (args && args != void_list_node)
2008 args = TREE_CHAIN (args);
2009 error_at (loc, "%<operator delete%> takes type %qT as first parameter",
2010 ptrtype);
2012 switch (e)
2014 case 2:
2015 args = tree_cons (NULL_TREE, ptrtype, args);
2016 /* Fall through. */
2017 case 1:
2018 type = (cxx_copy_lang_qualifiers
2019 (build_function_type (void_type_node, args),
2020 type));
2021 /* Fall through. */
2022 default:;
2025 TREE_TYPE (decl) = type;
2028 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
2029 and mark them as needed. */
2031 static void
2032 mark_vtable_entries (tree decl, vec<tree> &consteval_vtables)
2034 /* It's OK for the vtable to refer to deprecated virtual functions. */
2035 warning_sentinel w(warn_deprecated_decl);
2037 bool consteval_seen = false;
2039 for (auto &e: CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
2041 tree fnaddr = e.value;
2043 STRIP_NOPS (fnaddr);
2045 if (TREE_CODE (fnaddr) != ADDR_EXPR
2046 && TREE_CODE (fnaddr) != FDESC_EXPR)
2047 /* This entry is an offset: a virtual base class offset, a
2048 virtual call offset, an RTTI offset, etc. */
2049 continue;
2051 tree fn = TREE_OPERAND (fnaddr, 0);
2052 if (TREE_CODE (fn) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (fn))
2054 if (!consteval_seen)
2056 consteval_seen = true;
2057 consteval_vtables.safe_push (decl);
2059 continue;
2061 TREE_ADDRESSABLE (fn) = 1;
2062 /* When we don't have vcall offsets, we output thunks whenever
2063 we output the vtables that contain them. With vcall offsets,
2064 we know all the thunks we'll need when we emit a virtual
2065 function, so we emit the thunks there instead. */
2066 if (DECL_THUNK_P (fn))
2067 use_thunk (fn, /*emit_p=*/0);
2068 /* Set the location, as marking the function could cause
2069 instantiation. We do not need to preserve the incoming
2070 location, as we're called from c_parse_final_cleanups, which
2071 takes care of that. */
2072 input_location = DECL_SOURCE_LOCATION (fn);
2073 mark_used (fn);
2077 /* Replace any consteval functions in vtables with null pointers. */
2079 static void
2080 clear_consteval_vfns (vec<tree> &consteval_vtables)
2082 for (tree vtable : consteval_vtables)
2083 for (constructor_elt &elt : CONSTRUCTOR_ELTS (DECL_INITIAL (vtable)))
2085 tree fn = cp_get_fndecl_from_callee (elt.value, /*fold*/false);
2086 if (fn && DECL_IMMEDIATE_FUNCTION_P (fn))
2087 elt.value = build_zero_cst (vtable_entry_type);
2091 /* Adjust the TLS model on variable DECL if need be, typically after
2092 the linkage of DECL has been modified. */
2094 static void
2095 adjust_var_decl_tls_model (tree decl)
2097 if (CP_DECL_THREAD_LOCAL_P (decl)
2098 && !lookup_attribute ("tls_model", DECL_ATTRIBUTES (decl)))
2099 set_decl_tls_model (decl, decl_default_tls_model (decl));
2102 /* Set DECL up to have the closest approximation of "initialized common"
2103 linkage available. */
2105 void
2106 comdat_linkage (tree decl)
2108 if (flag_weak)
2109 make_decl_one_only (decl, cxx_comdat_group (decl));
2110 else if (TREE_CODE (decl) == FUNCTION_DECL
2111 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2112 /* We can just emit function and compiler-generated variables
2113 statically; having multiple copies is (for the most part) only
2114 a waste of space.
2116 There are two correctness issues, however: the address of a
2117 template instantiation with external linkage should be the
2118 same, independent of what translation unit asks for the
2119 address, and this will not hold when we emit multiple copies of
2120 the function. However, there's little else we can do.
2122 Also, by default, the typeinfo implementation assumes that
2123 there will be only one copy of the string used as the name for
2124 each type. Therefore, if weak symbols are unavailable, the
2125 run-time library should perform a more conservative check; it
2126 should perform a string comparison, rather than an address
2127 comparison. */
2128 TREE_PUBLIC (decl) = 0;
2129 else
2131 /* Static data member template instantiations, however, cannot
2132 have multiple copies. */
2133 if (DECL_INITIAL (decl) == 0
2134 || DECL_INITIAL (decl) == error_mark_node)
2135 DECL_COMMON (decl) = 1;
2136 else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
2138 DECL_COMMON (decl) = 1;
2139 DECL_INITIAL (decl) = error_mark_node;
2141 else if (!DECL_EXPLICIT_INSTANTIATION (decl))
2143 /* We can't do anything useful; leave vars for explicit
2144 instantiation. */
2145 DECL_EXTERNAL (decl) = 1;
2146 DECL_NOT_REALLY_EXTERN (decl) = 0;
2150 if (TREE_PUBLIC (decl))
2151 DECL_COMDAT (decl) = 1;
2153 if (VAR_P (decl))
2154 adjust_var_decl_tls_model (decl);
2157 /* For win32 we also want to put explicit instantiations in
2158 linkonce sections, so that they will be merged with implicit
2159 instantiations; otherwise we get duplicate symbol errors.
2160 For Darwin we do not want explicit instantiations to be
2161 linkonce. */
2163 void
2164 maybe_make_one_only (tree decl)
2166 /* We used to say that this was not necessary on targets that support weak
2167 symbols, because the implicit instantiations will defer to the explicit
2168 one. However, that's not actually the case in SVR4; a strong definition
2169 after a weak one is an error. Also, not making explicit
2170 instantiations one_only means that we can end up with two copies of
2171 some template instantiations. */
2172 if (! flag_weak)
2173 return;
2175 /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
2176 we can get away with not emitting them if they aren't used. We need
2177 to for variables so that cp_finish_decl will update their linkage,
2178 because their DECL_INITIAL may not have been set properly yet. */
2180 if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
2181 || (! DECL_EXPLICIT_INSTANTIATION (decl)
2182 && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
2184 make_decl_one_only (decl, cxx_comdat_group (decl));
2186 if (VAR_P (decl))
2188 varpool_node *node = varpool_node::get_create (decl);
2189 DECL_COMDAT (decl) = 1;
2190 /* Mark it needed so we don't forget to emit it. */
2191 node->forced_by_abi = true;
2192 TREE_USED (decl) = 1;
2194 adjust_var_decl_tls_model (decl);
2199 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
2200 This predicate will give the right answer during parsing of the
2201 function, which other tests may not. */
2203 bool
2204 vague_linkage_p (tree decl)
2206 if (!TREE_PUBLIC (decl))
2208 /* maybe_thunk_body clears TREE_PUBLIC and DECL_ABSTRACT_P on the
2209 maybe-in-charge 'tor variants; in that case we need to check one of
2210 the "clones" for the real linkage. But only in that case; before
2211 maybe_clone_body we haven't yet copied the linkage to the clones. */
2212 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl)
2213 && !DECL_ABSTRACT_P (decl)
2214 && DECL_CHAIN (decl)
2215 && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
2216 return vague_linkage_p (DECL_CHAIN (decl));
2218 gcc_checking_assert (!DECL_COMDAT (decl));
2219 return false;
2221 /* Unfortunately, import_export_decl has not always been called
2222 before the function is processed, so we cannot simply check
2223 DECL_COMDAT. */
2224 if (DECL_COMDAT (decl)
2225 || (TREE_CODE (decl) == FUNCTION_DECL
2226 && DECL_DECLARED_INLINE_P (decl))
2227 || (DECL_LANG_SPECIFIC (decl)
2228 && DECL_TEMPLATE_INSTANTIATION (decl))
2229 || (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
2230 return true;
2231 else if (DECL_FUNCTION_SCOPE_P (decl))
2232 /* A local static in an inline effectively has vague linkage. */
2233 return (TREE_STATIC (decl)
2234 && vague_linkage_p (DECL_CONTEXT (decl)));
2235 else
2236 return false;
2239 /* Determine whether or not we want to specifically import or export CTYPE,
2240 using various heuristics. */
2242 static void
2243 import_export_class (tree ctype)
2245 /* -1 for imported, 1 for exported. */
2246 int import_export = 0;
2248 /* It only makes sense to call this function at EOF. The reason is
2249 that this function looks at whether or not the first non-inline
2250 non-abstract virtual member function has been defined in this
2251 translation unit. But, we can't possibly know that until we've
2252 seen the entire translation unit. */
2253 gcc_assert (at_eof);
2255 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2256 return;
2258 /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
2259 we will have CLASSTYPE_INTERFACE_ONLY set but not
2260 CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this
2261 heuristic because someone will supply a #pragma implementation
2262 elsewhere, and deducing it here would produce a conflict. */
2263 if (CLASSTYPE_INTERFACE_ONLY (ctype))
2264 return;
2266 if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2267 import_export = -1;
2268 else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2269 import_export = 1;
2270 else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2271 && !flag_implicit_templates)
2272 /* For a template class, without -fimplicit-templates, check the
2273 repository. If the virtual table is assigned to this
2274 translation unit, then export the class; otherwise, import
2275 it. */
2276 import_export = -1;
2277 else if (TYPE_POLYMORPHIC_P (ctype))
2279 /* The ABI specifies that the virtual table and associated
2280 information are emitted with the key method, if any. */
2281 tree method = CLASSTYPE_KEY_METHOD (ctype);
2282 /* If weak symbol support is not available, then we must be
2283 careful not to emit the vtable when the key function is
2284 inline. An inline function can be defined in multiple
2285 translation units. If we were to emit the vtable in each
2286 translation unit containing a definition, we would get
2287 multiple definition errors at link-time. */
2288 if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
2289 import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2292 /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
2293 a definition anywhere else. */
2294 if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
2295 import_export = 0;
2297 /* Allow back ends the chance to overrule the decision. */
2298 if (targetm.cxx.import_export_class)
2299 import_export = targetm.cxx.import_export_class (ctype, import_export);
2301 if (import_export)
2303 SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2304 CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2308 /* Return true if VAR has already been provided to the back end; in that
2309 case VAR should not be modified further by the front end. */
2310 static bool
2311 var_finalized_p (tree var)
2313 return varpool_node::get_create (var)->definition;
2316 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
2317 must be emitted in this translation unit. Mark it as such. */
2319 void
2320 mark_needed (tree decl)
2322 TREE_USED (decl) = 1;
2323 if (TREE_CODE (decl) == FUNCTION_DECL)
2325 /* Extern inline functions don't become needed when referenced.
2326 If we know a method will be emitted in other TU and no new
2327 functions can be marked reachable, just use the external
2328 definition. */
2329 struct cgraph_node *node = cgraph_node::get_create (decl);
2330 node->forced_by_abi = true;
2332 /* #pragma interface can call mark_needed for
2333 maybe-in-charge 'tors; mark the clones as well. */
2334 tree clone;
2335 FOR_EACH_CLONE (clone, decl)
2336 mark_needed (clone);
2338 else if (VAR_P (decl))
2340 varpool_node *node = varpool_node::get_create (decl);
2341 /* C++ frontend use mark_decl_references to force COMDAT variables
2342 to be output that might appear dead otherwise. */
2343 node->forced_by_abi = true;
2347 /* DECL is either a FUNCTION_DECL or a VAR_DECL. This function
2348 returns true if a definition of this entity should be provided in
2349 this object file. Callers use this function to determine whether
2350 or not to let the back end know that a definition of DECL is
2351 available in this translation unit. */
2353 bool
2354 decl_needed_p (tree decl)
2356 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2357 /* This function should only be called at the end of the translation
2358 unit. We cannot be sure of whether or not something will be
2359 COMDAT until that point. */
2360 gcc_assert (at_eof);
2362 /* All entities with external linkage that are not COMDAT/EXTERN should be
2363 emitted; they may be referred to from other object files. */
2364 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2365 return true;
2367 /* Functions marked "dllexport" must be emitted so that they are
2368 visible to other DLLs. */
2369 if (flag_keep_inline_dllexport
2370 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2371 return true;
2373 /* When not optimizing, do not bother to produce definitions for extern
2374 symbols. */
2375 if (DECL_REALLY_EXTERN (decl)
2376 && ((TREE_CODE (decl) != FUNCTION_DECL
2377 && !optimize)
2378 || (TREE_CODE (decl) == FUNCTION_DECL
2379 && !opt_for_fn (decl, optimize)))
2380 && !lookup_attribute ("always_inline", decl))
2381 return false;
2383 /* If this entity was used, let the back end see it; it will decide
2384 whether or not to emit it into the object file. */
2385 if (TREE_USED (decl))
2386 return true;
2388 /* Virtual functions might be needed for devirtualization. */
2389 if (flag_devirtualize
2390 && TREE_CODE (decl) == FUNCTION_DECL
2391 && DECL_VIRTUAL_P (decl))
2392 return true;
2394 /* Otherwise, DECL does not need to be emitted -- yet. A subsequent
2395 reference to DECL might cause it to be emitted later. */
2396 return false;
2399 /* If necessary, write out the vtables for the dynamic class CTYPE.
2400 Returns true if any vtables were emitted. */
2402 static bool
2403 maybe_emit_vtables (tree ctype, vec<tree> &consteval_vtables)
2405 tree vtbl;
2406 tree primary_vtbl;
2407 int needed = 0;
2408 varpool_node *current = NULL, *last = NULL;
2410 /* If the vtables for this class have already been emitted there is
2411 nothing more to do. */
2412 primary_vtbl = CLASSTYPE_VTABLES (ctype);
2413 if (var_finalized_p (primary_vtbl))
2414 return false;
2415 /* Ignore dummy vtables made by get_vtable_decl. */
2416 if (TREE_TYPE (primary_vtbl) == void_type_node)
2417 return false;
2419 /* On some targets, we cannot determine the key method until the end
2420 of the translation unit -- which is when this function is
2421 called. */
2422 if (!targetm.cxx.key_method_may_be_inline ())
2423 determine_key_method (ctype);
2425 /* See if any of the vtables are needed. */
2426 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2428 import_export_decl (vtbl);
2429 if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2430 needed = 1;
2432 if (!needed)
2434 /* If the references to this class' vtables are optimized away,
2435 still emit the appropriate debugging information. See
2436 dfs_debug_mark. */
2437 if (DECL_COMDAT (primary_vtbl)
2438 && CLASSTYPE_DEBUG_REQUESTED (ctype))
2439 note_debug_info_needed (ctype);
2440 return false;
2443 /* The ABI requires that we emit all of the vtables if we emit any
2444 of them. */
2445 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2447 /* Mark entities references from the virtual table as used. */
2448 mark_vtable_entries (vtbl, consteval_vtables);
2450 if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2452 vec<tree, va_gc> *cleanups = NULL;
2453 tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2454 LOOKUP_NORMAL);
2456 /* It had better be all done at compile-time. */
2457 gcc_assert (!expr && !cleanups);
2460 /* Write it out. */
2461 DECL_EXTERNAL (vtbl) = 0;
2462 rest_of_decl_compilation (vtbl, 1, 1);
2464 /* Because we're only doing syntax-checking, we'll never end up
2465 actually marking the variable as written. */
2466 if (flag_syntax_only)
2467 TREE_ASM_WRITTEN (vtbl) = 1;
2468 else if (DECL_ONE_ONLY (vtbl))
2470 current = varpool_node::get_create (vtbl);
2471 if (last)
2472 current->add_to_same_comdat_group (last);
2473 last = current;
2477 /* For abstract classes, the destructor has been removed from the
2478 vtable (in class.cc's build_vtbl_initializer). For a compiler-
2479 generated destructor, it hence might not have been generated in
2480 this translation unit - and with '#pragma interface' it might
2481 never get generated. */
2482 if (CLASSTYPE_PURE_VIRTUALS (ctype)
2483 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype)
2484 && !CLASSTYPE_LAZY_DESTRUCTOR (ctype)
2485 && DECL_DEFAULTED_IN_CLASS_P (CLASSTYPE_DESTRUCTOR (ctype)))
2486 note_vague_linkage_fn (CLASSTYPE_DESTRUCTOR (ctype));
2488 /* Since we're writing out the vtable here, also write the debug
2489 info. */
2490 note_debug_info_needed (ctype);
2492 return true;
2495 /* A special return value from type_visibility meaning internal
2496 linkage. */
2498 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2500 static int expr_visibility (tree);
2501 static int type_visibility (tree);
2503 /* walk_tree helper function for type_visibility. */
2505 static tree
2506 min_vis_r (tree *tp, int *walk_subtrees, void *data)
2508 int *vis_p = (int *)data;
2509 int this_vis = VISIBILITY_DEFAULT;
2510 if (! TYPE_P (*tp))
2511 *walk_subtrees = 0;
2512 else if (OVERLOAD_TYPE_P (*tp)
2513 && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2515 this_vis = VISIBILITY_ANON;
2516 *walk_subtrees = 0;
2518 else if (CLASS_TYPE_P (*tp))
2520 this_vis = CLASSTYPE_VISIBILITY (*tp);
2521 *walk_subtrees = 0;
2523 else if (TREE_CODE (*tp) == ARRAY_TYPE
2524 && uses_template_parms (TYPE_DOMAIN (*tp)))
2525 this_vis = expr_visibility (TYPE_MAX_VALUE (TYPE_DOMAIN (*tp)));
2527 if (this_vis > *vis_p)
2528 *vis_p = this_vis;
2530 /* Tell cp_walk_subtrees to look through typedefs. */
2531 if (*walk_subtrees == 1)
2532 *walk_subtrees = 2;
2534 return NULL;
2537 /* walk_tree helper function for expr_visibility. */
2539 static tree
2540 min_vis_expr_r (tree *tp, int */*walk_subtrees*/, void *data)
2542 int *vis_p = (int *)data;
2543 int tpvis = VISIBILITY_DEFAULT;
2545 switch (TREE_CODE (*tp))
2547 case CAST_EXPR:
2548 case IMPLICIT_CONV_EXPR:
2549 case STATIC_CAST_EXPR:
2550 case REINTERPRET_CAST_EXPR:
2551 case CONST_CAST_EXPR:
2552 case DYNAMIC_CAST_EXPR:
2553 case NEW_EXPR:
2554 case CONSTRUCTOR:
2555 case LAMBDA_EXPR:
2556 tpvis = type_visibility (TREE_TYPE (*tp));
2557 break;
2559 case VAR_DECL:
2560 case FUNCTION_DECL:
2561 if (! TREE_PUBLIC (*tp))
2562 tpvis = VISIBILITY_ANON;
2563 else
2564 tpvis = DECL_VISIBILITY (*tp);
2565 break;
2567 default:
2568 break;
2571 if (tpvis > *vis_p)
2572 *vis_p = tpvis;
2574 return NULL_TREE;
2577 /* Returns the visibility of TYPE, which is the minimum visibility of its
2578 component types. */
2580 static int
2581 type_visibility (tree type)
2583 int vis = VISIBILITY_DEFAULT;
2584 cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2585 return vis;
2588 /* Returns the visibility of an expression EXPR that appears in the signature
2589 of a function template, which is the minimum visibility of names that appear
2590 in its mangling. */
2592 static int
2593 expr_visibility (tree expr)
2595 int vis = VISIBILITY_DEFAULT;
2596 cp_walk_tree_without_duplicates (&expr, min_vis_expr_r, &vis);
2597 return vis;
2600 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
2601 specified (or if VISIBILITY is static). If TMPL is true, this
2602 constraint is for a template argument, and takes precedence
2603 over explicitly-specified visibility on the template. */
2605 static void
2606 constrain_visibility (tree decl, int visibility, bool tmpl)
2608 if (visibility == VISIBILITY_ANON)
2610 /* extern "C" declarations aren't affected by the anonymous
2611 namespace. */
2612 if (!DECL_EXTERN_C_P (decl))
2614 TREE_PUBLIC (decl) = 0;
2615 DECL_WEAK (decl) = 0;
2616 DECL_COMMON (decl) = 0;
2617 DECL_COMDAT (decl) = false;
2618 if (VAR_OR_FUNCTION_DECL_P (decl))
2620 struct symtab_node *snode = symtab_node::get (decl);
2622 if (snode)
2623 snode->set_comdat_group (NULL);
2625 DECL_INTERFACE_KNOWN (decl) = 1;
2626 if (DECL_LANG_SPECIFIC (decl))
2627 DECL_NOT_REALLY_EXTERN (decl) = 1;
2630 else if (visibility > DECL_VISIBILITY (decl)
2631 && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2633 DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2634 /* This visibility was not specified. */
2635 DECL_VISIBILITY_SPECIFIED (decl) = false;
2639 /* Constrain the visibility of DECL based on the visibility of its template
2640 arguments. */
2642 static void
2643 constrain_visibility_for_template (tree decl, tree targs)
2645 /* If this is a template instantiation, check the innermost
2646 template args for visibility constraints. The outer template
2647 args are covered by the class check. */
2648 tree args = INNERMOST_TEMPLATE_ARGS (targs);
2649 int i;
2650 for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2652 int vis = 0;
2654 tree arg = TREE_VEC_ELT (args, i-1);
2655 if (TYPE_P (arg))
2656 vis = type_visibility (arg);
2657 else
2658 vis = expr_visibility (arg);
2659 if (vis)
2660 constrain_visibility (decl, vis, true);
2664 /* Like c_determine_visibility, but with additional C++-specific
2665 behavior.
2667 Function-scope entities can rely on the function's visibility because
2668 it is set in start_preparsed_function.
2670 Class-scope entities cannot rely on the class's visibility until the end
2671 of the enclosing class definition.
2673 Note that because namespaces have multiple independent definitions,
2674 namespace visibility is handled elsewhere using the #pragma visibility
2675 machinery rather than by decorating the namespace declaration.
2677 The goal is for constraints from the type to give a diagnostic, and
2678 other constraints to be applied silently. */
2680 void
2681 determine_visibility (tree decl)
2683 /* Remember that all decls get VISIBILITY_DEFAULT when built. */
2685 /* Only relevant for names with external linkage. */
2686 if (!TREE_PUBLIC (decl))
2687 return;
2689 /* Cloned constructors and destructors get the same visibility as
2690 the underlying function. That should be set up in
2691 maybe_clone_body. */
2692 gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2694 bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2695 enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
2697 /* The decl may be a template instantiation, which could influence
2698 visibilty. */
2699 tree template_decl = NULL_TREE;
2700 if (TREE_CODE (decl) == TYPE_DECL)
2702 if (CLASS_TYPE_P (TREE_TYPE (decl)))
2704 if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
2705 template_decl = decl;
2707 else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2708 template_decl = decl;
2710 else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
2711 template_decl = decl;
2713 if (TREE_CODE (decl) == TYPE_DECL
2714 && LAMBDA_TYPE_P (TREE_TYPE (decl))
2715 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (decl)) != error_mark_node)
2716 if (tree extra = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl)))
2718 /* The lambda's visibility is limited by that of its extra
2719 scope. */
2720 int vis = 0;
2721 if (TYPE_P (extra))
2722 vis = type_visibility (extra);
2723 else
2724 vis = expr_visibility (extra);
2725 constrain_visibility (decl, vis, false);
2728 /* If DECL is a member of a class, visibility specifiers on the
2729 class can influence the visibility of the DECL. */
2730 tree class_type = NULL_TREE;
2731 if (DECL_CLASS_SCOPE_P (decl))
2732 class_type = DECL_CONTEXT (decl);
2733 else
2735 /* Not a class member. */
2737 /* Virtual tables have DECL_CONTEXT set to their associated class,
2738 so they are automatically handled above. */
2739 gcc_assert (!VAR_P (decl)
2740 || !DECL_VTABLE_OR_VTT_P (decl));
2742 if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2744 /* Local statics and classes get the visibility of their
2745 containing function by default, except that
2746 -fvisibility-inlines-hidden doesn't affect them. */
2747 tree fn = DECL_CONTEXT (decl);
2748 if (DECL_VISIBILITY_SPECIFIED (fn))
2750 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2751 DECL_VISIBILITY_SPECIFIED (decl) =
2752 DECL_VISIBILITY_SPECIFIED (fn);
2754 else
2756 if (DECL_CLASS_SCOPE_P (fn))
2757 determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2758 else if (determine_hidden_inline (fn))
2760 DECL_VISIBILITY (decl) = default_visibility;
2761 DECL_VISIBILITY_SPECIFIED (decl) =
2762 visibility_options.inpragma;
2764 else
2766 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2767 DECL_VISIBILITY_SPECIFIED (decl) =
2768 DECL_VISIBILITY_SPECIFIED (fn);
2772 /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2773 but have no TEMPLATE_INFO, so don't try to check it. */
2774 template_decl = NULL_TREE;
2776 else if (VAR_P (decl) && DECL_TINFO_P (decl)
2777 && flag_visibility_ms_compat)
2779 /* Under -fvisibility-ms-compat, types are visible by default,
2780 even though their contents aren't. */
2781 tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2782 int underlying_vis = type_visibility (underlying_type);
2783 if (underlying_vis == VISIBILITY_ANON
2784 || (CLASS_TYPE_P (underlying_type)
2785 && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2786 constrain_visibility (decl, underlying_vis, false);
2787 else
2788 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2790 else if (VAR_P (decl) && DECL_TINFO_P (decl))
2792 /* tinfo visibility is based on the type it's for. */
2793 constrain_visibility
2794 (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2796 /* Give the target a chance to override the visibility associated
2797 with DECL. */
2798 if (TREE_PUBLIC (decl)
2799 && !DECL_REALLY_EXTERN (decl)
2800 && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2801 && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2802 targetm.cxx.determine_class_data_visibility (decl);
2804 else if (template_decl)
2805 /* Template instantiations and specializations get visibility based
2806 on their template unless they override it with an attribute. */;
2807 else if (! DECL_VISIBILITY_SPECIFIED (decl))
2809 if (determine_hidden_inline (decl))
2810 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2811 else
2813 /* Set default visibility to whatever the user supplied with
2814 #pragma GCC visibility or a namespace visibility attribute. */
2815 DECL_VISIBILITY (decl) = default_visibility;
2816 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2821 if (template_decl)
2823 /* If the specialization doesn't specify visibility, use the
2824 visibility from the template. */
2825 tree tinfo = get_template_info (template_decl);
2826 tree args = TI_ARGS (tinfo);
2827 tree attribs = (TREE_CODE (decl) == TYPE_DECL
2828 ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2829 : DECL_ATTRIBUTES (decl));
2830 tree attr = lookup_attribute ("visibility", attribs);
2832 if (args != error_mark_node)
2834 tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2836 if (!DECL_VISIBILITY_SPECIFIED (decl))
2838 if (!attr
2839 && determine_hidden_inline (decl))
2840 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2841 else
2843 DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2844 DECL_VISIBILITY_SPECIFIED (decl)
2845 = DECL_VISIBILITY_SPECIFIED (pattern);
2849 if (args
2850 /* Template argument visibility outweighs #pragma or namespace
2851 visibility, but not an explicit attribute. */
2852 && !attr)
2854 int depth = TMPL_ARGS_DEPTH (args);
2855 if (DECL_VISIBILITY_SPECIFIED (decl))
2857 /* A class template member with explicit visibility
2858 overrides the class visibility, so we need to apply
2859 all the levels of template args directly. */
2860 int i;
2861 for (i = 1; i <= depth; ++i)
2863 tree lev = TMPL_ARGS_LEVEL (args, i);
2864 constrain_visibility_for_template (decl, lev);
2867 else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2868 /* Limit visibility based on its template arguments. */
2869 constrain_visibility_for_template (decl, args);
2874 if (class_type)
2875 determine_visibility_from_class (decl, class_type);
2877 if (decl_anon_ns_mem_p (decl))
2878 /* Names in an anonymous namespace get internal linkage. */
2879 constrain_visibility (decl, VISIBILITY_ANON, false);
2880 else if (TREE_CODE (decl) != TYPE_DECL)
2882 /* Propagate anonymity from type to decl. */
2883 int tvis = type_visibility (TREE_TYPE (decl));
2884 if (tvis == VISIBILITY_ANON
2885 || ! DECL_VISIBILITY_SPECIFIED (decl))
2886 constrain_visibility (decl, tvis, false);
2888 else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2889 /* DR 757: A type without linkage shall not be used as the type of a
2890 variable or function with linkage, unless
2891 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2892 o the variable or function is not used (3.2 [basic.def.odr]) or is
2893 defined in the same translation unit.
2895 Since non-extern "C" decls need to be defined in the same
2896 translation unit, we can make the type internal. */
2897 constrain_visibility (decl, VISIBILITY_ANON, false);
2899 /* If visibility changed and DECL already has DECL_RTL, ensure
2900 symbol flags are updated. */
2901 if ((DECL_VISIBILITY (decl) != orig_visibility
2902 || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2903 && ((VAR_P (decl) && TREE_STATIC (decl))
2904 || TREE_CODE (decl) == FUNCTION_DECL)
2905 && DECL_RTL_SET_P (decl))
2906 make_decl_rtl (decl);
2909 /* By default, static data members and function members receive
2910 the visibility of their containing class. */
2912 static void
2913 determine_visibility_from_class (tree decl, tree class_type)
2915 if (DECL_VISIBILITY_SPECIFIED (decl))
2916 return;
2918 if (determine_hidden_inline (decl))
2919 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2920 else
2922 /* Default to the class visibility. */
2923 DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2924 DECL_VISIBILITY_SPECIFIED (decl)
2925 = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2928 /* Give the target a chance to override the visibility associated
2929 with DECL. */
2930 if (VAR_P (decl)
2931 && TREE_PUBLIC (decl)
2932 && (DECL_TINFO_P (decl) || DECL_VTABLE_OR_VTT_P (decl))
2933 && !DECL_REALLY_EXTERN (decl)
2934 && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2935 targetm.cxx.determine_class_data_visibility (decl);
2938 /* Returns true iff DECL is an inline that should get hidden visibility
2939 because of -fvisibility-inlines-hidden. */
2941 static bool
2942 determine_hidden_inline (tree decl)
2944 return (visibility_options.inlines_hidden
2945 /* Don't do this for inline templates; specializations might not be
2946 inline, and we don't want them to inherit the hidden
2947 visibility. We'll set it here for all inline instantiations. */
2948 && !processing_template_decl
2949 && TREE_CODE (decl) == FUNCTION_DECL
2950 && DECL_DECLARED_INLINE_P (decl)
2951 && (! DECL_LANG_SPECIFIC (decl)
2952 || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2955 /* Constrain the visibility of a class TYPE based on the visibility of its
2956 field types. Warn if any fields require lesser visibility. */
2958 void
2959 constrain_class_visibility (tree type)
2961 tree binfo;
2962 tree t;
2963 int i;
2965 int vis = type_visibility (type);
2967 if (vis == VISIBILITY_ANON
2968 || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2969 return;
2971 /* Don't warn about visibility if the class has explicit visibility. */
2972 if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2973 vis = VISIBILITY_INTERNAL;
2975 for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2976 if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
2977 && !DECL_ARTIFICIAL (t))
2979 tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2980 int subvis = type_visibility (ftype);
2982 if (subvis == VISIBILITY_ANON)
2984 if (!in_main_input_context())
2986 tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
2987 if (nlt)
2989 if (same_type_p (TREE_TYPE (t), nlt))
2990 warning (OPT_Wsubobject_linkage, "\
2991 %qT has a field %qD whose type has no linkage",
2992 type, t);
2993 else
2994 warning (OPT_Wsubobject_linkage, "\
2995 %qT has a field %qD whose type depends on the type %qT which has no linkage",
2996 type, t, nlt);
2998 else
2999 warning (OPT_Wsubobject_linkage, "\
3000 %qT has a field %qD whose type uses the anonymous namespace",
3001 type, t);
3004 else if (MAYBE_CLASS_TYPE_P (ftype)
3005 && vis < VISIBILITY_HIDDEN
3006 && subvis >= VISIBILITY_HIDDEN)
3007 warning (OPT_Wattributes, "\
3008 %qT declared with greater visibility than the type of its field %qD",
3009 type, t);
3012 binfo = TYPE_BINFO (type);
3013 for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
3015 int subvis = type_visibility (TREE_TYPE (t));
3017 if (subvis == VISIBILITY_ANON)
3019 if (!in_main_input_context())
3021 tree nlt = no_linkage_check (TREE_TYPE (t), /*relaxed_p=*/false);
3022 if (nlt)
3024 if (same_type_p (TREE_TYPE (t), nlt))
3025 warning (OPT_Wsubobject_linkage, "\
3026 %qT has a base %qT whose type has no linkage",
3027 type, TREE_TYPE (t));
3028 else
3029 warning (OPT_Wsubobject_linkage, "\
3030 %qT has a base %qT whose type depends on the type %qT which has no linkage",
3031 type, TREE_TYPE (t), nlt);
3033 else
3034 warning (OPT_Wsubobject_linkage, "\
3035 %qT has a base %qT whose type uses the anonymous namespace",
3036 type, TREE_TYPE (t));
3039 else if (vis < VISIBILITY_HIDDEN
3040 && subvis >= VISIBILITY_HIDDEN)
3041 warning (OPT_Wattributes, "\
3042 %qT declared with greater visibility than its base %qT",
3043 type, TREE_TYPE (t));
3047 /* Functions for adjusting the visibility of a tagged type and its nested
3048 types and declarations when it gets a name for linkage purposes from a
3049 typedef. */
3050 // FIXME: It is now a DR for such a class type to contain anything
3051 // other than C. So at minium most of this can probably be deleted.
3053 /* First reset the visibility of all the types. */
3055 static void
3056 reset_type_linkage_1 (tree type)
3058 set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
3059 if (CLASS_TYPE_P (type))
3060 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
3061 if (DECL_IMPLICIT_TYPEDEF_P (member))
3062 reset_type_linkage_1 (TREE_TYPE (member));
3065 /* Then reset the visibility of any static data members or member
3066 functions that use those types. */
3068 static void
3069 reset_decl_linkage (tree decl)
3071 if (TREE_PUBLIC (decl))
3072 return;
3073 if (DECL_CLONED_FUNCTION_P (decl))
3074 return;
3075 TREE_PUBLIC (decl) = true;
3076 DECL_INTERFACE_KNOWN (decl) = false;
3077 determine_visibility (decl);
3078 tentative_decl_linkage (decl);
3081 void
3082 reset_type_linkage (tree type)
3084 reset_type_linkage_1 (type);
3085 if (CLASS_TYPE_P (type))
3087 if (tree vt = CLASSTYPE_VTABLES (type))
3089 tree name = mangle_vtbl_for_type (type);
3090 DECL_NAME (vt) = name;
3091 SET_DECL_ASSEMBLER_NAME (vt, name);
3092 reset_decl_linkage (vt);
3094 if (!ANON_AGGR_TYPE_P (type))
3095 if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
3097 tree name = mangle_typeinfo_for_type (type);
3098 DECL_NAME (ti) = name;
3099 SET_DECL_ASSEMBLER_NAME (ti, name);
3100 TREE_TYPE (name) = type;
3101 reset_decl_linkage (ti);
3103 for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
3105 tree mem = STRIP_TEMPLATE (m);
3106 if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
3107 reset_decl_linkage (mem);
3108 else if (DECL_IMPLICIT_TYPEDEF_P (mem))
3109 reset_type_linkage (TREE_TYPE (mem));
3114 /* Set up our initial idea of what the linkage of DECL should be. */
3116 void
3117 tentative_decl_linkage (tree decl)
3119 if (DECL_INTERFACE_KNOWN (decl))
3120 /* We've already made a decision as to how this function will
3121 be handled. */;
3122 else if (vague_linkage_p (decl))
3124 if (TREE_CODE (decl) == FUNCTION_DECL
3125 && decl_defined_p (decl))
3127 DECL_EXTERNAL (decl) = 1;
3128 DECL_NOT_REALLY_EXTERN (decl) = 1;
3129 note_vague_linkage_fn (decl);
3130 /* A non-template inline function with external linkage will
3131 always be COMDAT. As we must eventually determine the
3132 linkage of all functions, and as that causes writes to
3133 the data mapped in from the PCH file, it's advantageous
3134 to mark the functions at this point. */
3135 if (DECL_DECLARED_INLINE_P (decl)
3136 && (!DECL_IMPLICIT_INSTANTIATION (decl)
3137 || DECL_DEFAULTED_FN (decl)))
3139 /* This function must have external linkage, as
3140 otherwise DECL_INTERFACE_KNOWN would have been
3141 set. */
3142 gcc_assert (TREE_PUBLIC (decl));
3143 comdat_linkage (decl);
3144 DECL_INTERFACE_KNOWN (decl) = 1;
3147 else if (VAR_P (decl))
3148 maybe_commonize_var (decl);
3152 /* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage
3153 for DECL has not already been determined, do so now by setting
3154 DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this
3155 function is called entities with vague linkage whose definitions
3156 are available must have TREE_PUBLIC set.
3158 If this function decides to place DECL in COMDAT, it will set
3159 appropriate flags -- but will not clear DECL_EXTERNAL. It is up to
3160 the caller to decide whether or not to clear DECL_EXTERNAL. Some
3161 callers defer that decision until it is clear that DECL is actually
3162 required. */
3164 void
3165 import_export_decl (tree decl)
3167 bool comdat_p;
3168 bool import_p;
3169 tree class_type = NULL_TREE;
3171 if (DECL_INTERFACE_KNOWN (decl))
3172 return;
3174 /* We cannot determine what linkage to give to an entity with vague
3175 linkage until the end of the file. For example, a virtual table
3176 for a class will be defined if and only if the key method is
3177 defined in this translation unit. */
3178 gcc_assert (at_eof);
3179 /* Object file linkage for explicit instantiations is handled in
3180 mark_decl_instantiated. For static variables in functions with
3181 vague linkage, maybe_commonize_var is used.
3183 Therefore, the only declarations that should be provided to this
3184 function are those with external linkage that are:
3186 * implicit instantiations of function templates
3188 * inline function
3190 * implicit instantiations of static data members of class
3191 templates
3193 * virtual tables
3195 * typeinfo objects
3197 Furthermore, all entities that reach this point must have a
3198 definition available in this translation unit.
3200 The following assertions check these conditions. */
3201 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
3202 /* Any code that creates entities with TREE_PUBLIC cleared should
3203 also set DECL_INTERFACE_KNOWN. */
3204 gcc_assert (TREE_PUBLIC (decl));
3205 if (TREE_CODE (decl) == FUNCTION_DECL)
3206 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3207 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
3208 || DECL_DECLARED_INLINE_P (decl));
3209 else
3210 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3211 || DECL_VTABLE_OR_VTT_P (decl)
3212 || DECL_TINFO_P (decl));
3213 /* Check that a definition of DECL is available in this translation
3214 unit. */
3215 gcc_assert (!DECL_REALLY_EXTERN (decl));
3217 /* Assume that DECL will not have COMDAT linkage. */
3218 comdat_p = false;
3219 /* Assume that DECL will not be imported into this translation
3220 unit. */
3221 import_p = false;
3223 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
3225 class_type = DECL_CONTEXT (decl);
3226 import_export_class (class_type);
3227 if (CLASSTYPE_INTERFACE_KNOWN (class_type)
3228 && CLASSTYPE_INTERFACE_ONLY (class_type))
3229 import_p = true;
3230 else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
3231 && !CLASSTYPE_USE_TEMPLATE (class_type)
3232 && CLASSTYPE_KEY_METHOD (class_type)
3233 && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
3234 /* The ABI requires that all virtual tables be emitted with
3235 COMDAT linkage. However, on systems where COMDAT symbols
3236 don't show up in the table of contents for a static
3237 archive, or on systems without weak symbols (where we
3238 approximate COMDAT linkage by using internal linkage), the
3239 linker will report errors about undefined symbols because
3240 it will not see the virtual table definition. Therefore,
3241 in the case that we know that the virtual table will be
3242 emitted in only one translation unit, we make the virtual
3243 table an ordinary definition with external linkage. */
3244 DECL_EXTERNAL (decl) = 0;
3245 else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
3247 /* CLASS_TYPE is being exported from this translation unit,
3248 so DECL should be defined here. */
3249 if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
3250 /* If a class is declared in a header with the "extern
3251 template" extension, then it will not be instantiated,
3252 even in translation units that would normally require
3253 it. Often such classes are explicitly instantiated in
3254 one translation unit. Therefore, the explicit
3255 instantiation must be made visible to other translation
3256 units. */
3257 DECL_EXTERNAL (decl) = 0;
3258 else
3260 /* The generic C++ ABI says that class data is always
3261 COMDAT, even if there is a key function. Some
3262 variants (e.g., the ARM EABI) says that class data
3263 only has COMDAT linkage if the class data might be
3264 emitted in more than one translation unit. When the
3265 key method can be inline and is inline, we still have
3266 to arrange for comdat even though
3267 class_data_always_comdat is false. */
3268 if (!CLASSTYPE_KEY_METHOD (class_type)
3269 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
3270 || targetm.cxx.class_data_always_comdat ())
3272 /* The ABI requires COMDAT linkage. Normally, we
3273 only emit COMDAT things when they are needed;
3274 make sure that we realize that this entity is
3275 indeed needed. */
3276 comdat_p = true;
3277 mark_needed (decl);
3281 else if (!flag_implicit_templates
3282 && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
3283 import_p = true;
3284 else
3285 comdat_p = true;
3287 else if (VAR_P (decl) && DECL_TINFO_P (decl))
3289 tree type = TREE_TYPE (DECL_NAME (decl));
3290 if (CLASS_TYPE_P (type))
3292 class_type = type;
3293 import_export_class (type);
3294 if (CLASSTYPE_INTERFACE_KNOWN (type)
3295 && TYPE_POLYMORPHIC_P (type)
3296 && CLASSTYPE_INTERFACE_ONLY (type)
3297 /* If -fno-rtti was specified, then we cannot be sure
3298 that RTTI information will be emitted with the
3299 virtual table of the class, so we must emit it
3300 wherever it is used. */
3301 && flag_rtti)
3302 import_p = true;
3303 else
3305 if (CLASSTYPE_INTERFACE_KNOWN (type)
3306 && !CLASSTYPE_INTERFACE_ONLY (type))
3308 comdat_p = (targetm.cxx.class_data_always_comdat ()
3309 || (CLASSTYPE_KEY_METHOD (type)
3310 && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
3311 mark_needed (decl);
3312 if (!flag_weak)
3314 comdat_p = false;
3315 DECL_EXTERNAL (decl) = 0;
3318 else
3319 comdat_p = true;
3322 else
3323 comdat_p = true;
3325 else if (DECL_TEMPLOID_INSTANTIATION (decl))
3327 /* DECL is an implicit instantiation of a function or static
3328 data member. */
3329 if (flag_implicit_templates
3330 || (flag_implicit_inline_templates
3331 && TREE_CODE (decl) == FUNCTION_DECL
3332 && DECL_DECLARED_INLINE_P (decl)))
3333 comdat_p = true;
3334 else
3335 /* If we are not implicitly generating templates, then mark
3336 this entity as undefined in this translation unit. */
3337 import_p = true;
3339 else if (DECL_FUNCTION_MEMBER_P (decl))
3341 if (!DECL_DECLARED_INLINE_P (decl))
3343 tree ctype = DECL_CONTEXT (decl);
3344 import_export_class (ctype);
3345 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
3347 DECL_NOT_REALLY_EXTERN (decl)
3348 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
3349 || (DECL_DECLARED_INLINE_P (decl)
3350 && ! flag_implement_inlines
3351 && !DECL_VINDEX (decl)));
3353 if (!DECL_NOT_REALLY_EXTERN (decl))
3354 DECL_EXTERNAL (decl) = 1;
3356 /* Always make artificials weak. */
3357 if (DECL_ARTIFICIAL (decl) && flag_weak)
3358 comdat_p = true;
3359 else
3360 maybe_make_one_only (decl);
3363 else
3364 comdat_p = true;
3366 else
3367 comdat_p = true;
3369 if (import_p)
3371 /* If we are importing DECL into this translation unit, mark is
3372 an undefined here. */
3373 DECL_EXTERNAL (decl) = 1;
3374 DECL_NOT_REALLY_EXTERN (decl) = 0;
3376 else if (comdat_p)
3378 /* If we decided to put DECL in COMDAT, mark it accordingly at
3379 this point. */
3380 comdat_linkage (decl);
3383 DECL_INTERFACE_KNOWN (decl) = 1;
3386 /* Return an expression that performs the destruction of DECL, which
3387 must be a VAR_DECL whose type has a non-trivial destructor, or is
3388 an array whose (innermost) elements have a non-trivial destructor. */
3390 tree
3391 build_cleanup (tree decl)
3393 tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
3394 gcc_assert (clean != NULL_TREE);
3395 return clean;
3398 /* GUARD is a helper variable for DECL; make them have the same linkage and
3399 visibility. */
3401 void
3402 copy_linkage (tree guard, tree decl)
3404 TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3405 TREE_STATIC (guard) = TREE_STATIC (decl);
3406 DECL_COMMON (guard) = DECL_COMMON (decl);
3407 DECL_COMDAT (guard) = DECL_COMDAT (decl);
3408 if (TREE_STATIC (guard))
3410 CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
3411 set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3412 if (DECL_ONE_ONLY (decl))
3413 make_decl_one_only (guard, cxx_comdat_group (guard));
3414 if (TREE_PUBLIC (decl))
3415 DECL_WEAK (guard) = DECL_WEAK (decl);
3416 /* Also check vague_linkage_p, as DECL_WEAK and DECL_ONE_ONLY might not
3417 be set until import_export_decl at EOF. */
3418 if (vague_linkage_p (decl))
3419 comdat_linkage (guard);
3420 DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3421 DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3425 /* Returns the initialization guard variable for the variable DECL,
3426 which has static storage duration. */
3428 tree
3429 get_guard (tree decl)
3431 tree sname = mangle_guard_variable (decl);
3432 tree guard = get_global_binding (sname);
3433 if (! guard)
3435 tree guard_type;
3437 /* We use a type that is big enough to contain a mutex as well
3438 as an integer counter. */
3439 guard_type = targetm.cxx.guard_type ();
3440 guard = build_decl (DECL_SOURCE_LOCATION (decl),
3441 VAR_DECL, sname, guard_type);
3443 /* The guard should have the same linkage as what it guards. */
3444 copy_linkage (guard, decl);
3446 DECL_ARTIFICIAL (guard) = 1;
3447 DECL_IGNORED_P (guard) = 1;
3448 TREE_USED (guard) = 1;
3449 pushdecl_top_level_and_finish (guard, NULL_TREE);
3451 return guard;
3454 /* Returns true if accessing the GUARD atomic is expensive,
3455 i.e. involves a call to __sync_synchronize or similar.
3456 In this case let __cxa_guard_acquire handle the atomics. */
3458 static bool
3459 is_atomic_expensive_p (machine_mode mode)
3461 if (!flag_inline_atomics)
3462 return true;
3464 if (!can_compare_and_swap_p (mode, false) || !can_atomic_load_p (mode))
3465 return true;
3467 return false;
3470 /* Return an atomic load of src with the appropriate memory model. */
3472 static tree
3473 build_atomic_load_type (tree src, HOST_WIDE_INT model, tree type)
3475 tree ptr_type = build_pointer_type (type);
3476 tree mem_model = build_int_cst (integer_type_node, model);
3477 tree t, addr, val;
3478 unsigned int size;
3479 int fncode;
3481 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
3483 fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
3484 t = builtin_decl_implicit ((enum built_in_function) fncode);
3486 addr = build1 (ADDR_EXPR, ptr_type, src);
3487 val = build_call_expr (t, 2, addr, mem_model);
3488 return val;
3491 /* Return those bits of the GUARD variable that should be set when the
3492 guarded entity is actually initialized. */
3494 static tree
3495 get_guard_bits (tree guard)
3497 if (!targetm.cxx.guard_mask_bit ())
3499 /* We only set the first byte of the guard, in order to leave room
3500 for a mutex in the high-order bits. */
3501 guard = build1 (ADDR_EXPR,
3502 build_pointer_type (TREE_TYPE (guard)),
3503 guard);
3504 guard = build1 (NOP_EXPR,
3505 build_pointer_type (char_type_node),
3506 guard);
3507 guard = build1 (INDIRECT_REF, char_type_node, guard);
3510 return guard;
3513 /* Return an expression which determines whether or not the GUARD
3514 variable has already been initialized. */
3516 tree
3517 get_guard_cond (tree guard, bool thread_safe)
3519 tree guard_value;
3521 if (!thread_safe)
3522 guard = get_guard_bits (guard);
3523 else
3525 tree type = targetm.cxx.guard_mask_bit ()
3526 ? TREE_TYPE (guard) : char_type_node;
3528 if (is_atomic_expensive_p (TYPE_MODE (type)))
3529 guard = integer_zero_node;
3530 else
3531 guard = build_atomic_load_type (guard, MEMMODEL_ACQUIRE, type);
3534 /* Mask off all but the low bit. */
3535 if (targetm.cxx.guard_mask_bit ())
3537 guard_value = integer_one_node;
3538 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3539 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3540 guard = cp_build_binary_op (input_location,
3541 BIT_AND_EXPR, guard, guard_value,
3542 tf_warning_or_error);
3545 guard_value = integer_zero_node;
3546 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3547 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3548 return cp_build_binary_op (input_location,
3549 EQ_EXPR, guard, guard_value,
3550 tf_warning_or_error);
3553 /* Return an expression which sets the GUARD variable, indicating that
3554 the variable being guarded has been initialized. */
3556 tree
3557 set_guard (tree guard)
3559 tree guard_init;
3561 /* Set the GUARD to one. */
3562 guard = get_guard_bits (guard);
3563 guard_init = integer_one_node;
3564 if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3565 guard_init = fold_convert (TREE_TYPE (guard), guard_init);
3566 return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
3567 tf_warning_or_error);
3570 /* Returns true iff we can tell that VAR does not have a dynamic
3571 initializer. */
3573 static bool
3574 var_defined_without_dynamic_init (tree var)
3576 /* constinit vars are guaranteed to not have dynamic initializer,
3577 but still registering the destructor counts as dynamic initialization. */
3578 if (DECL_DECLARED_CONSTINIT_P (var)
3579 && COMPLETE_TYPE_P (TREE_TYPE (var))
3580 && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3581 return true;
3582 /* If it's defined in another TU, we can't tell. */
3583 if (DECL_EXTERNAL (var))
3584 return false;
3585 /* If it has a non-trivial destructor, registering the destructor
3586 counts as dynamic initialization. */
3587 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3588 return false;
3589 /* If it's in this TU, its initializer has been processed, unless
3590 it's a case of self-initialization, then DECL_INITIALIZED_P is
3591 false while the initializer is handled by finish_id_expression. */
3592 if (!DECL_INITIALIZED_P (var))
3593 return false;
3594 /* If it has no initializer or a constant one, it's not dynamic. */
3595 return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3596 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3599 /* Returns true iff VAR is a variable that needs uses to be
3600 wrapped for possible dynamic initialization. */
3602 static bool
3603 var_needs_tls_wrapper (tree var)
3605 return (!error_operand_p (var)
3606 && CP_DECL_THREAD_LOCAL_P (var)
3607 && !DECL_GNU_TLS_P (var)
3608 && !DECL_FUNCTION_SCOPE_P (var)
3609 && !var_defined_without_dynamic_init (var));
3612 /* Get the FUNCTION_DECL for the shared TLS init function for this
3613 translation unit. */
3615 static tree
3616 get_local_tls_init_fn (location_t loc)
3618 tree sname = get_identifier ("__tls_init");
3619 tree fn = get_global_binding (sname);
3620 if (!fn)
3622 fn = build_lang_decl_loc (loc, FUNCTION_DECL, sname,
3623 build_function_type (void_type_node,
3624 void_list_node));
3625 SET_DECL_LANGUAGE (fn, lang_c);
3626 TREE_PUBLIC (fn) = false;
3627 DECL_ARTIFICIAL (fn) = true;
3628 mark_used (fn);
3629 set_global_binding (fn);
3631 return fn;
3634 /* Get a FUNCTION_DECL for the init function for the thread_local
3635 variable VAR. The init function will be an alias to the function
3636 that initializes all the non-local TLS variables in the translation
3637 unit. The init function is only used by the wrapper function. */
3639 static tree
3640 get_tls_init_fn (tree var)
3642 /* Only C++11 TLS vars need this init fn. */
3643 if (!var_needs_tls_wrapper (var))
3644 return NULL_TREE;
3646 /* If -fno-extern-tls-init, assume that we don't need to call
3647 a tls init function for a variable defined in another TU. */
3648 if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3649 return NULL_TREE;
3651 /* If the variable is internal, or if we can't generate aliases,
3652 call the local init function directly. */
3653 if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
3654 return get_local_tls_init_fn (DECL_SOURCE_LOCATION (var));
3656 tree sname = mangle_tls_init_fn (var);
3657 tree fn = get_global_binding (sname);
3658 if (!fn)
3660 fn = build_lang_decl (FUNCTION_DECL, sname,
3661 build_function_type (void_type_node,
3662 void_list_node));
3663 SET_DECL_LANGUAGE (fn, lang_c);
3664 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3665 DECL_ARTIFICIAL (fn) = true;
3666 DECL_COMDAT (fn) = DECL_COMDAT (var);
3667 DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3668 if (DECL_ONE_ONLY (var))
3669 make_decl_one_only (fn, cxx_comdat_group (fn));
3670 if (TREE_PUBLIC (var))
3672 tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3673 /* If the variable is defined somewhere else and might have static
3674 initialization, make the init function a weak reference. */
3675 if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3676 || TYPE_HAS_CONSTEXPR_CTOR (obtype)
3677 || TYPE_HAS_TRIVIAL_DFLT (obtype))
3678 && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3679 && DECL_EXTERNAL (var))
3680 declare_weak (fn);
3681 else
3682 DECL_WEAK (fn) = DECL_WEAK (var);
3684 DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3685 DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3686 DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3687 DECL_IGNORED_P (fn) = 1;
3688 mark_used (fn);
3690 DECL_BEFRIENDING_CLASSES (fn) = var;
3692 set_global_binding (fn);
3694 return fn;
3697 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3698 variable VAR. The wrapper function calls the init function (if any) for
3699 VAR and then returns a reference to VAR. The wrapper function is used
3700 in place of VAR everywhere VAR is mentioned. */
3702 static tree
3703 get_tls_wrapper_fn (tree var)
3705 /* Only C++11 TLS vars need this wrapper fn. */
3706 if (!var_needs_tls_wrapper (var))
3707 return NULL_TREE;
3709 tree sname = mangle_tls_wrapper_fn (var);
3710 tree fn = get_global_binding (sname);
3711 if (!fn)
3713 /* A named rvalue reference is an lvalue, so the wrapper should
3714 always return an lvalue reference. */
3715 tree type = non_reference (TREE_TYPE (var));
3716 type = build_reference_type (type);
3717 tree fntype = build_function_type (type, void_list_node);
3719 fn = build_lang_decl_loc (DECL_SOURCE_LOCATION (var),
3720 FUNCTION_DECL, sname, fntype);
3721 SET_DECL_LANGUAGE (fn, lang_c);
3722 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3723 DECL_ARTIFICIAL (fn) = true;
3724 DECL_IGNORED_P (fn) = 1;
3725 /* The wrapper is inline and emitted everywhere var is used. */
3726 DECL_DECLARED_INLINE_P (fn) = true;
3727 if (TREE_PUBLIC (var))
3729 comdat_linkage (fn);
3730 #ifdef HAVE_GAS_HIDDEN
3731 /* Make the wrapper bind locally; there's no reason to share
3732 the wrapper between multiple shared objects. */
3733 DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3734 DECL_VISIBILITY_SPECIFIED (fn) = true;
3735 #endif
3737 if (!TREE_PUBLIC (fn))
3738 DECL_INTERFACE_KNOWN (fn) = true;
3739 mark_used (fn);
3740 note_vague_linkage_fn (fn);
3742 #if 0
3743 /* We want CSE to commonize calls to the wrapper, but marking it as
3744 pure is unsafe since it has side-effects. I guess we need a new
3745 ECF flag even weaker than ECF_PURE. FIXME! */
3746 DECL_PURE_P (fn) = true;
3747 #endif
3749 DECL_BEFRIENDING_CLASSES (fn) = var;
3751 set_global_binding (fn);
3753 return fn;
3756 /* If EXPR is a thread_local variable that should be wrapped by init
3757 wrapper function, return a call to that function, otherwise return
3758 NULL. */
3760 tree
3761 maybe_get_tls_wrapper_call (tree expr)
3763 if (VAR_P (expr)
3764 && !processing_template_decl
3765 && !cp_unevaluated_operand
3766 && CP_DECL_THREAD_LOCAL_P (expr))
3767 if (tree wrap = get_tls_wrapper_fn (expr))
3768 return build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
3769 return NULL;
3772 /* At EOF, generate the definition for the TLS wrapper function FN:
3774 T& var_wrapper() {
3775 if (init_fn) init_fn();
3776 return var;
3777 } */
3779 static void
3780 generate_tls_wrapper (tree fn)
3782 tree var = DECL_BEFRIENDING_CLASSES (fn);
3784 start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3785 tree body = begin_function_body ();
3786 /* Only call the init fn if there might be one. */
3787 if (tree init_fn = get_tls_init_fn (var))
3789 tree if_stmt = NULL_TREE;
3790 /* If init_fn is a weakref, make sure it exists before calling. */
3791 if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3793 if_stmt = begin_if_stmt ();
3794 tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3795 tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3796 NE_EXPR, addr, nullptr_node,
3797 tf_warning_or_error);
3798 finish_if_stmt_cond (cond, if_stmt);
3800 finish_expr_stmt (build_cxx_call
3801 (init_fn, 0, NULL, tf_warning_or_error));
3802 if (if_stmt)
3804 finish_then_clause (if_stmt);
3805 finish_if_stmt (if_stmt);
3808 else
3809 /* If there's no initialization, the wrapper is a constant function. */
3810 TREE_READONLY (fn) = true;
3811 finish_return_stmt (convert_from_reference (var));
3812 finish_function_body (body);
3813 expand_or_defer_fn (finish_function (/*inline_p=*/false));
3816 /* Start the process of running a particular set of global constructors
3817 or destructors. Subroutine of do_[cd]tors. Also called from
3818 vtv_start_verification_constructor_init_function. */
3820 static tree
3821 start_objects (int method_type, int initp)
3823 /* Make ctor or dtor function. METHOD_TYPE may be 'I' or 'D'. */
3824 int module_init = 0;
3826 if (initp == DEFAULT_INIT_PRIORITY && method_type == 'I')
3827 module_init = module_initializer_kind ();
3829 tree name = NULL_TREE;
3830 if (module_init > 0)
3831 name = mangle_module_global_init (0);
3832 else
3834 char type[14];
3836 unsigned len = sprintf (type, "sub_%c", method_type);
3837 if (initp != DEFAULT_INIT_PRIORITY)
3839 char joiner = '_';
3840 #ifdef JOINER
3841 joiner = JOINER;
3842 #endif
3843 type[len++] = joiner;
3844 sprintf (type + len, "%.5u", initp);
3846 name = get_file_function_name (type);
3849 tree fntype = build_function_type (void_type_node, void_list_node);
3850 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
3851 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
3852 if (module_init > 0)
3854 SET_DECL_ASSEMBLER_NAME (fndecl, name);
3855 TREE_PUBLIC (fndecl) = true;
3856 determine_visibility (fndecl);
3858 else
3859 TREE_PUBLIC (fndecl) = 0;
3860 start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3862 /* Mark as artificial because it's not explicitly in the user's
3863 source code. */
3864 DECL_ARTIFICIAL (current_function_decl) = 1;
3866 /* Mark this declaration as used to avoid spurious warnings. */
3867 TREE_USED (current_function_decl) = 1;
3869 /* Mark this function as a global constructor or destructor. */
3870 if (method_type == 'I')
3871 DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3872 else
3873 DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3875 tree body = begin_compound_stmt (BCS_FN_BODY);
3877 if (module_init > 0)
3879 // 'static bool __in_chrg = false;
3880 // if (__inchrg) return;
3881 // __inchrg = true
3882 tree var = build_lang_decl (VAR_DECL, in_charge_identifier,
3883 boolean_type_node);
3884 DECL_CONTEXT (var) = fndecl;
3885 DECL_ARTIFICIAL (var) = true;
3886 TREE_STATIC (var) = true;
3887 pushdecl (var);
3888 cp_finish_decl (var, NULL_TREE, false, NULL_TREE, 0);
3890 tree if_stmt = begin_if_stmt ();
3891 finish_if_stmt_cond (var, if_stmt);
3892 finish_return_stmt (NULL_TREE);
3893 finish_then_clause (if_stmt);
3894 finish_if_stmt (if_stmt);
3896 tree assign = build2 (MODIFY_EXPR, boolean_type_node,
3897 var, boolean_true_node);
3898 TREE_SIDE_EFFECTS (assign) = true;
3899 finish_expr_stmt (assign);
3902 if (module_init)
3903 module_add_import_initializers ();
3905 return body;
3908 /* Finish the process of running a particular set of global constructors
3909 or destructors. Subroutine of do_[cd]tors. */
3911 static void
3912 finish_objects (int method_type, int initp, tree body)
3914 /* Finish up. */
3915 finish_compound_stmt (body);
3916 tree fn = finish_function (/*inline_p=*/false);
3918 if (method_type == 'I')
3920 DECL_STATIC_CONSTRUCTOR (fn) = 1;
3921 decl_init_priority_insert (fn, initp);
3923 else
3925 DECL_STATIC_DESTRUCTOR (fn) = 1;
3926 decl_fini_priority_insert (fn, initp);
3929 expand_or_defer_fn (fn);
3932 /* The names of the parameters to the function created to handle
3933 initializations and destructions for objects with static storage
3934 duration. */
3935 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
3936 #define PRIORITY_IDENTIFIER "__priority"
3938 /* The name of the function we create to handle initializations and
3939 destructions for objects with static storage duration. */
3940 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3942 /* The declaration for the __INITIALIZE_P argument. */
3943 static GTY(()) tree initialize_p_decl;
3945 /* The declaration for the __PRIORITY argument. */
3946 static GTY(()) tree priority_decl;
3948 /* The declaration for the static storage duration function. */
3949 static GTY(()) tree ssdf_decl;
3951 /* All the static storage duration functions created in this
3952 translation unit. */
3953 static GTY(()) vec<tree, va_gc> *ssdf_decls;
3955 /* A map from priority levels to information about that priority
3956 level. There may be many such levels, so efficient lookup is
3957 important. */
3958 static splay_tree priority_info_map;
3960 /* Begins the generation of the function that will handle all
3961 initialization and destruction of objects with static storage
3962 duration. The function generated takes two parameters of type
3963 `int': __INITIALIZE_P and __PRIORITY. If __INITIALIZE_P is
3964 nonzero, it performs initializations. Otherwise, it performs
3965 destructions. It only performs those initializations or
3966 destructions with the indicated __PRIORITY. The generated function
3967 returns no value.
3969 It is assumed that this function will only be called once per
3970 translation unit. */
3972 static tree
3973 start_static_storage_duration_function (unsigned count)
3975 tree type;
3976 tree body;
3977 char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3979 /* Create the identifier for this function. It will be of the form
3980 SSDF_IDENTIFIER_<number>. */
3981 sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3983 type = build_function_type_list (void_type_node,
3984 integer_type_node, integer_type_node,
3985 NULL_TREE);
3987 /* Create the FUNCTION_DECL itself. */
3988 ssdf_decl = build_lang_decl (FUNCTION_DECL,
3989 get_identifier (id),
3990 type);
3991 TREE_PUBLIC (ssdf_decl) = 0;
3992 DECL_ARTIFICIAL (ssdf_decl) = 1;
3994 /* Put this function in the list of functions to be called from the
3995 static constructors and destructors. */
3996 if (!ssdf_decls)
3998 vec_alloc (ssdf_decls, 32);
4000 /* Take this opportunity to initialize the map from priority
4001 numbers to information about that priority level. */
4002 priority_info_map = splay_tree_new (splay_tree_compare_ints,
4003 /*delete_key_fn=*/0,
4004 /*delete_value_fn=*/
4005 splay_tree_delete_pointers);
4007 /* We always need to generate functions for the
4008 DEFAULT_INIT_PRIORITY so enter it now. That way when we walk
4009 priorities later, we'll be sure to find the
4010 DEFAULT_INIT_PRIORITY. */
4011 get_priority_info (DEFAULT_INIT_PRIORITY);
4014 vec_safe_push (ssdf_decls, ssdf_decl);
4016 /* Create the argument list. */
4017 initialize_p_decl = cp_build_parm_decl
4018 (ssdf_decl, get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
4019 TREE_USED (initialize_p_decl) = 1;
4020 priority_decl = cp_build_parm_decl
4021 (ssdf_decl, get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
4022 TREE_USED (priority_decl) = 1;
4024 DECL_CHAIN (initialize_p_decl) = priority_decl;
4025 DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
4027 /* Put the function in the global scope. */
4028 pushdecl (ssdf_decl);
4030 /* Start the function itself. This is equivalent to declaring the
4031 function as:
4033 static void __ssdf (int __initialize_p, init __priority_p);
4035 It is static because we only need to call this function from the
4036 various constructor and destructor functions for this module. */
4037 start_preparsed_function (ssdf_decl,
4038 /*attrs=*/NULL_TREE,
4039 SF_PRE_PARSED);
4041 /* Set up the scope of the outermost block in the function. */
4042 body = begin_compound_stmt (BCS_FN_BODY);
4044 return body;
4047 /* Finish the generation of the function which performs initialization
4048 and destruction of objects with static storage duration. After
4049 this point, no more such objects can be created. */
4051 static void
4052 finish_static_storage_duration_function (tree body)
4054 /* Close out the function. */
4055 finish_compound_stmt (body);
4056 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4059 /* Return the information about the indicated PRIORITY level. If no
4060 code to handle this level has yet been generated, generate the
4061 appropriate prologue. */
4063 static priority_info
4064 get_priority_info (int priority)
4066 priority_info pi;
4067 splay_tree_node n;
4069 n = splay_tree_lookup (priority_info_map,
4070 (splay_tree_key) priority);
4071 if (!n)
4073 /* Create a new priority information structure, and insert it
4074 into the map. */
4075 pi = XNEW (struct priority_info_s);
4076 pi->initializations_p = 0;
4077 pi->destructions_p = 0;
4078 splay_tree_insert (priority_info_map,
4079 (splay_tree_key) priority,
4080 (splay_tree_value) pi);
4082 else
4083 pi = (priority_info) n->value;
4085 return pi;
4088 /* The effective initialization priority of a DECL. */
4090 #define DECL_EFFECTIVE_INIT_PRIORITY(decl) \
4091 ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
4092 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
4094 /* Whether a DECL needs a guard to protect it against multiple
4095 initialization. */
4097 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \
4098 || DECL_ONE_ONLY (decl) \
4099 || DECL_WEAK (decl)))
4101 /* Called from one_static_initialization_or_destruction(),
4102 via walk_tree.
4103 Walks the initializer list of a global variable and looks for
4104 temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
4105 and that have their DECL_CONTEXT() == NULL.
4106 For each such temporary variable, set their DECL_CONTEXT() to
4107 the current function. This is necessary because otherwise
4108 some optimizers (enabled by -O2 -fprofile-arcs) might crash
4109 when trying to refer to a temporary variable that does not have
4110 it's DECL_CONTECT() properly set. */
4111 static tree
4112 fix_temporary_vars_context_r (tree *node,
4113 int * /*unused*/,
4114 void * /*unused1*/)
4116 gcc_assert (current_function_decl);
4118 if (TREE_CODE (*node) == BIND_EXPR)
4120 tree var;
4122 for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
4123 if (VAR_P (var)
4124 && !DECL_NAME (var)
4125 && DECL_ARTIFICIAL (var)
4126 && !DECL_CONTEXT (var))
4127 DECL_CONTEXT (var) = current_function_decl;
4130 return NULL_TREE;
4133 /* Set up to handle the initialization or destruction of DECL. If
4134 INITP is nonzero, we are initializing the variable. Otherwise, we
4135 are destroying it. */
4137 static void
4138 one_static_initialization_or_destruction (tree decl, tree init, bool initp)
4140 tree guard_if_stmt = NULL_TREE;
4141 tree guard;
4143 /* If we are supposed to destruct and there's a trivial destructor,
4144 nothing has to be done. */
4145 if (!initp
4146 && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
4147 return;
4149 /* Trick the compiler into thinking we are at the file and line
4150 where DECL was declared so that error-messages make sense, and so
4151 that the debugger will show somewhat sensible file and line
4152 information. */
4153 input_location = DECL_SOURCE_LOCATION (decl);
4155 /* Make sure temporary variables in the initialiser all have
4156 their DECL_CONTEXT() set to a value different from NULL_TREE.
4157 This can happen when global variables initializers are built.
4158 In that case, the DECL_CONTEXT() of the global variables _AND_ of all
4159 the temporary variables that might have been generated in the
4160 accompanying initializers is NULL_TREE, meaning the variables have been
4161 declared in the global namespace.
4162 What we want to do here is to fix that and make sure the DECL_CONTEXT()
4163 of the temporaries are set to the current function decl. */
4164 cp_walk_tree_without_duplicates (&init,
4165 fix_temporary_vars_context_r,
4166 NULL);
4168 /* Because of:
4170 [class.access.spec]
4172 Access control for implicit calls to the constructors,
4173 the conversion functions, or the destructor called to
4174 create and destroy a static data member is performed as
4175 if these calls appeared in the scope of the member's
4176 class.
4178 we pretend we are in a static member function of the class of
4179 which the DECL is a member. */
4180 if (member_p (decl))
4182 DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
4183 DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
4186 /* Assume we don't need a guard. */
4187 guard = NULL_TREE;
4188 /* We need a guard if this is an object with external linkage that
4189 might be initialized in more than one place. (For example, a
4190 static data member of a template, when the data member requires
4191 construction.) */
4192 if (NEEDS_GUARD_P (decl))
4194 tree guard_cond;
4196 guard = get_guard (decl);
4198 /* When using __cxa_atexit, we just check the GUARD as we would
4199 for a local static. */
4200 if (flag_use_cxa_atexit)
4202 /* When using __cxa_atexit, we never try to destroy
4203 anything from a static destructor. */
4204 gcc_assert (initp);
4205 guard_cond = get_guard_cond (guard, false);
4207 /* If we don't have __cxa_atexit, then we will be running
4208 destructors from .fini sections, or their equivalents. So,
4209 we need to know how many times we've tried to initialize this
4210 object. We do initializations only if the GUARD is zero,
4211 i.e., if we are the first to initialize the variable. We do
4212 destructions only if the GUARD is one, i.e., if we are the
4213 last to destroy the variable. */
4214 else if (initp)
4215 guard_cond
4216 = cp_build_binary_op (input_location,
4217 EQ_EXPR,
4218 cp_build_unary_op (PREINCREMENT_EXPR,
4219 guard,
4220 /*noconvert=*/true,
4221 tf_warning_or_error),
4222 integer_one_node,
4223 tf_warning_or_error);
4224 else
4225 guard_cond
4226 = cp_build_binary_op (input_location,
4227 EQ_EXPR,
4228 cp_build_unary_op (PREDECREMENT_EXPR,
4229 guard,
4230 /*noconvert=*/true,
4231 tf_warning_or_error),
4232 integer_zero_node,
4233 tf_warning_or_error);
4235 guard_if_stmt = begin_if_stmt ();
4236 finish_if_stmt_cond (guard_cond, guard_if_stmt);
4240 /* If we're using __cxa_atexit, we have not already set the GUARD,
4241 so we must do so now. */
4242 if (guard && initp && flag_use_cxa_atexit)
4243 finish_expr_stmt (set_guard (guard));
4245 /* Perform the initialization or destruction. */
4246 if (initp)
4248 if (init)
4250 finish_expr_stmt (init);
4251 if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
4253 varpool_node *vnode = varpool_node::get (decl);
4254 if (vnode)
4255 vnode->dynamically_initialized = 1;
4259 /* If we're using __cxa_atexit, register a function that calls the
4260 destructor for the object. */
4261 if (flag_use_cxa_atexit)
4262 finish_expr_stmt (register_dtor_fn (decl));
4264 else
4265 finish_expr_stmt (build_cleanup (decl));
4267 /* Finish the guard if-stmt, if necessary. */
4268 if (guard)
4270 finish_then_clause (guard_if_stmt);
4271 finish_if_stmt (guard_if_stmt);
4274 /* Now that we're done with DECL we don't need to pretend to be a
4275 member of its class any longer. */
4276 DECL_CONTEXT (current_function_decl) = NULL_TREE;
4277 DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
4280 /* Generate code to do the initialization or destruction of the decls in VARS,
4281 a TREE_LIST of VAR_DECL with static storage duration.
4282 Whether initialization or destruction is performed is specified by INITP. */
4284 static void
4285 do_static_initialization_or_destruction (tree vars, bool initp)
4287 tree node, init_if_stmt, cond;
4289 /* Build the outer if-stmt to check for initialization or destruction. */
4290 init_if_stmt = begin_if_stmt ();
4291 cond = initp ? integer_one_node : integer_zero_node;
4292 cond = cp_build_binary_op (input_location,
4293 EQ_EXPR,
4294 initialize_p_decl,
4295 cond,
4296 tf_warning_or_error);
4297 finish_if_stmt_cond (cond, init_if_stmt);
4299 /* To make sure dynamic construction doesn't access globals from other
4300 compilation units where they might not be yet constructed, for
4301 -fsanitize=address insert __asan_before_dynamic_init call that
4302 prevents access to either all global variables that need construction
4303 in other compilation units, or at least those that haven't been
4304 initialized yet. Variables that need dynamic construction in
4305 the current compilation unit are kept accessible. */
4306 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4307 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
4309 node = vars;
4310 do {
4311 tree decl = TREE_VALUE (node);
4312 tree priority_if_stmt;
4313 int priority;
4314 priority_info pi;
4316 /* If we don't need a destructor, there's nothing to do. Avoid
4317 creating a possibly empty if-stmt. */
4318 if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
4320 node = TREE_CHAIN (node);
4321 continue;
4324 /* Remember that we had an initialization or finalization at this
4325 priority. */
4326 priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
4327 pi = get_priority_info (priority);
4328 if (initp)
4329 pi->initializations_p = 1;
4330 else
4331 pi->destructions_p = 1;
4333 /* Conditionalize this initialization on being in the right priority
4334 and being initializing/finalizing appropriately. */
4335 priority_if_stmt = begin_if_stmt ();
4336 cond = cp_build_binary_op (input_location,
4337 EQ_EXPR,
4338 priority_decl,
4339 build_int_cst (NULL_TREE, priority),
4340 tf_warning_or_error);
4341 finish_if_stmt_cond (cond, priority_if_stmt);
4343 /* Process initializers with same priority. */
4344 for (; node
4345 && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
4346 node = TREE_CHAIN (node))
4347 /* Do one initialization or destruction. */
4348 one_static_initialization_or_destruction (TREE_VALUE (node),
4349 TREE_PURPOSE (node), initp);
4351 /* Finish up the priority if-stmt body. */
4352 finish_then_clause (priority_if_stmt);
4353 finish_if_stmt (priority_if_stmt);
4355 } while (node);
4357 /* Revert what __asan_before_dynamic_init did by calling
4358 __asan_after_dynamic_init. */
4359 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4360 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
4362 /* Finish up the init/destruct if-stmt body. */
4363 finish_then_clause (init_if_stmt);
4364 finish_if_stmt (init_if_stmt);
4367 /* VARS is a list of variables with static storage duration which may
4368 need initialization and/or finalization. Remove those variables
4369 that don't really need to be initialized or finalized, and return
4370 the resulting list. The order in which the variables appear in
4371 VARS is in reverse order of the order in which they should actually
4372 be initialized. The list we return is in the unreversed order;
4373 i.e., the first variable should be initialized first. */
4375 static tree
4376 prune_vars_needing_no_initialization (tree *vars)
4378 tree *var = vars;
4379 tree result = NULL_TREE;
4381 while (*var)
4383 tree t = *var;
4384 tree decl = TREE_VALUE (t);
4385 tree init = TREE_PURPOSE (t);
4387 /* Deal gracefully with error. */
4388 if (error_operand_p (decl))
4390 var = &TREE_CHAIN (t);
4391 continue;
4394 /* The only things that can be initialized are variables. */
4395 gcc_assert (VAR_P (decl));
4397 /* If this object is not defined, we don't need to do anything
4398 here. */
4399 if (DECL_EXTERNAL (decl))
4401 var = &TREE_CHAIN (t);
4402 continue;
4405 /* Also, if the initializer already contains errors, we can bail
4406 out now. */
4407 if (init && TREE_CODE (init) == TREE_LIST
4408 && value_member (error_mark_node, init))
4410 var = &TREE_CHAIN (t);
4411 continue;
4414 /* This variable is going to need initialization and/or
4415 finalization, so we add it to the list. */
4416 *var = TREE_CHAIN (t);
4417 TREE_CHAIN (t) = result;
4418 result = t;
4421 return result;
4424 /* Make sure we have told the back end about all the variables in
4425 VARS. */
4427 static void
4428 write_out_vars (tree vars)
4430 tree v;
4432 for (v = vars; v; v = TREE_CHAIN (v))
4434 tree var = TREE_VALUE (v);
4435 if (!var_finalized_p (var))
4437 import_export_decl (var);
4438 rest_of_decl_compilation (var, 1, 1);
4443 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
4444 (otherwise) that will initialize all global objects with static
4445 storage duration having the indicated PRIORITY. */
4447 static void
4448 generate_ctor_or_dtor_function (bool constructor_p, int priority,
4449 location_t *locus)
4451 input_location = *locus;
4453 /* We use `I' to indicate initialization and `D' to indicate
4454 destruction. */
4455 char function_key = constructor_p ? 'I' : 'D';
4457 /* We emit the function lazily, to avoid generating empty
4458 global constructors and destructors. */
4459 tree body = NULL_TREE;
4461 if (constructor_p && priority == DEFAULT_INIT_PRIORITY)
4463 bool objc = c_dialect_objc () && objc_static_init_needed_p ();
4465 /* We may have module initialization to emit and/or insert
4466 before other intializations. */
4467 if (module_initializer_kind () || objc)
4468 body = start_objects (function_key, priority);
4470 /* For Objective-C++, we may need to initialize metadata found
4471 in this module. This must be done _before_ any other static
4472 initializations. */
4473 if (objc)
4474 objc_generate_static_init_call (NULL_TREE);
4477 /* Call the static storage duration function with appropriate
4478 arguments. */
4479 tree fndecl;
4480 size_t i;
4481 FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl)
4483 /* Calls to pure or const functions will expand to nothing. */
4484 if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
4486 if (! body)
4487 body = start_objects (function_key, priority);
4489 tree call = cp_build_function_call_nary (fndecl, tf_warning_or_error,
4490 build_int_cst (NULL_TREE,
4491 constructor_p),
4492 build_int_cst (NULL_TREE,
4493 priority),
4494 NULL_TREE);
4495 finish_expr_stmt (call);
4499 /* Close out the function. */
4500 if (body)
4501 finish_objects (function_key, priority, body);
4504 /* Generate constructor and destructor functions for the priority
4505 indicated by N. */
4507 static int
4508 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
4510 location_t *locus = (location_t *) data;
4511 int priority = (int) n->key;
4512 priority_info pi = (priority_info) n->value;
4514 /* Generate the functions themselves, but only if they are really
4515 needed. */
4516 if (pi->initializations_p)
4517 generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
4518 if (pi->destructions_p)
4519 generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
4521 /* Keep iterating. */
4522 return 0;
4525 /* Return C++ property of T, based on given operation OP. */
4527 static int
4528 cpp_check (tree t, cpp_operation op)
4530 switch (op)
4532 case HAS_DEPENDENT_TEMPLATE_ARGS:
4534 tree ti = CLASSTYPE_TEMPLATE_INFO (t);
4535 if (!ti)
4536 return 0;
4537 ++processing_template_decl;
4538 const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
4539 --processing_template_decl;
4540 return dep;
4542 case IS_ABSTRACT:
4543 return DECL_PURE_VIRTUAL_P (t);
4544 case IS_ASSIGNMENT_OPERATOR:
4545 return DECL_ASSIGNMENT_OPERATOR_P (t);
4546 case IS_CONSTRUCTOR:
4547 return DECL_CONSTRUCTOR_P (t);
4548 case IS_DESTRUCTOR:
4549 return DECL_DESTRUCTOR_P (t);
4550 case IS_COPY_CONSTRUCTOR:
4551 return DECL_COPY_CONSTRUCTOR_P (t);
4552 case IS_MOVE_CONSTRUCTOR:
4553 return DECL_MOVE_CONSTRUCTOR_P (t);
4554 case IS_TEMPLATE:
4555 return TREE_CODE (t) == TEMPLATE_DECL;
4556 case IS_TRIVIAL:
4557 return trivial_type_p (t);
4558 default:
4559 return 0;
4563 /* Collect source file references recursively, starting from NAMESPC. */
4565 static void
4566 collect_source_refs (tree namespc)
4568 /* Iterate over names in this name space. */
4569 for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4570 if (DECL_IS_UNDECLARED_BUILTIN (t))
4572 else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
4573 collect_source_refs (t);
4574 else
4575 collect_source_ref (DECL_SOURCE_FILE (t));
4578 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4579 starting from NAMESPC. */
4581 static void
4582 collect_ada_namespace (tree namespc, const char *source_file)
4584 tree decl = NAMESPACE_LEVEL (namespc)->names;
4586 /* Collect decls from this namespace. This will skip
4587 NAMESPACE_DECLs (both aliases and regular, it cannot tell). */
4588 collect_ada_nodes (decl, source_file);
4590 /* Now scan for namespace children, and dump them. */
4591 for (; decl; decl = TREE_CHAIN (decl))
4592 if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
4593 collect_ada_namespace (decl, source_file);
4596 /* Returns true iff there is a definition available for variable or
4597 function DECL. */
4599 bool
4600 decl_defined_p (tree decl)
4602 if (TREE_CODE (decl) == FUNCTION_DECL)
4603 return (DECL_INITIAL (decl) != NULL_TREE
4604 /* A pending instantiation of a friend temploid is defined. */
4605 || (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
4606 && DECL_INITIAL (DECL_TEMPLATE_RESULT
4607 (DECL_TI_TEMPLATE (decl)))));
4608 else
4610 gcc_assert (VAR_P (decl));
4611 return !DECL_EXTERNAL (decl);
4615 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4617 [expr.const]
4619 An integral constant-expression can only involve ... const
4620 variables of integral or enumeration types initialized with
4621 constant expressions ...
4623 C++0x also allows constexpr variables and temporaries initialized
4624 with constant expressions. We handle the former here, but the latter
4625 are just folded away in cxx_eval_constant_expression.
4627 The standard does not require that the expression be non-volatile.
4628 G++ implements the proposed correction in DR 457. */
4630 bool
4631 decl_constant_var_p (tree decl)
4633 if (!decl_maybe_constant_var_p (decl))
4634 return false;
4636 /* We don't know if a template static data member is initialized with
4637 a constant expression until we instantiate its initializer. Even
4638 in the case of a constexpr variable, we can't treat it as a
4639 constant until its initializer is complete in case it's used in
4640 its own initializer. */
4641 maybe_instantiate_decl (decl);
4642 return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4645 /* Returns true if DECL could be a symbolic constant variable, depending on
4646 its initializer. */
4648 bool
4649 decl_maybe_constant_var_p (tree decl)
4651 tree type = TREE_TYPE (decl);
4652 if (!VAR_P (decl))
4653 return false;
4654 if (DECL_DECLARED_CONSTEXPR_P (decl) && !TREE_THIS_VOLATILE (decl))
4655 return true;
4656 if (DECL_HAS_VALUE_EXPR_P (decl))
4657 /* A proxy isn't constant. */
4658 return false;
4659 if (TYPE_REF_P (type))
4660 /* References can be constant. */;
4661 else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
4662 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4663 /* And const integers. */;
4664 else
4665 return false;
4667 if (DECL_INITIAL (decl)
4668 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
4669 /* We know the initializer, and it isn't constant. */
4670 return false;
4671 else
4672 return true;
4675 /* Complain that DECL uses a type with no linkage. In C++98 mode this is
4676 called from grokfndecl and grokvardecl; in all modes it is called from
4677 cp_write_global_declarations. */
4679 void
4680 no_linkage_error (tree decl)
4682 if (cxx_dialect >= cxx11
4683 && (decl_defined_p (decl)
4684 /* Treat templates which limit_bad_template_recursion decided
4685 not to instantiate as if they were defined. */
4686 || (errorcount + sorrycount > 0
4687 && DECL_LANG_SPECIFIC (decl)
4688 && DECL_TEMPLATE_INFO (decl)
4689 && warning_suppressed_p (decl /* What warning? */))))
4690 /* In C++11 it's ok if the decl is defined. */
4691 return;
4693 if (DECL_LANG_SPECIFIC (decl) && DECL_MODULE_IMPORT_P (decl))
4694 /* An imported decl is ok. */
4695 return;
4697 tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4698 if (t == NULL_TREE)
4699 /* The type that got us on no_linkage_decls must have gotten a name for
4700 linkage purposes. */;
4701 else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4702 // FIXME: This is now invalid, as a DR to c++98
4703 /* The type might end up having a typedef name for linkage purposes. */
4704 vec_safe_push (no_linkage_decls, decl);
4705 else if (TYPE_UNNAMED_P (t))
4707 bool d = false;
4708 auto_diagnostic_group grp;
4709 if (cxx_dialect >= cxx11)
4710 d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4711 "unnamed type, is used but never defined", decl);
4712 else if (DECL_EXTERN_C_P (decl))
4713 /* Allow this; it's pretty common in C. */;
4714 else if (VAR_P (decl))
4715 /* DRs 132, 319 and 389 seem to indicate types with
4716 no linkage can only be used to declare extern "C"
4717 entities. Since it's not always an error in the
4718 ISO C++ 90 Standard, we only issue a warning. */
4719 d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
4720 "with no linkage used to declare variable %q#D with "
4721 "linkage", decl);
4722 else
4723 d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
4724 "linkage used to declare function %q#D with linkage",
4725 decl);
4726 if (d && is_typedef_decl (TYPE_NAME (t)))
4727 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4728 "to the unqualified type, so it is not used for linkage",
4729 TYPE_NAME (t));
4731 else if (cxx_dialect >= cxx11)
4733 if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
4734 permerror (DECL_SOURCE_LOCATION (decl),
4735 "%q#D, declared using local type "
4736 "%qT, is used but never defined", decl, t);
4738 else if (VAR_P (decl))
4739 warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4740 "used to declare variable %q#D with linkage", t, decl);
4741 else
4742 permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4743 "to declare function %q#D with linkage", t, decl);
4746 /* Collect declarations from all namespaces relevant to SOURCE_FILE. */
4748 static void
4749 collect_all_refs (const char *source_file)
4751 collect_ada_namespace (global_namespace, source_file);
4754 /* Clear DECL_EXTERNAL for NODE. */
4756 static bool
4757 clear_decl_external (struct cgraph_node *node, void * /*data*/)
4759 DECL_EXTERNAL (node->decl) = 0;
4760 return false;
4763 /* Build up the function to run dynamic initializers for thread_local
4764 variables in this translation unit and alias the init functions for the
4765 individual variables to it. */
4767 static void
4768 handle_tls_init (void)
4770 tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4771 if (vars == NULL_TREE)
4772 return;
4774 location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4776 write_out_vars (vars);
4778 tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4779 boolean_type_node);
4780 TREE_PUBLIC (guard) = false;
4781 TREE_STATIC (guard) = true;
4782 DECL_ARTIFICIAL (guard) = true;
4783 DECL_IGNORED_P (guard) = true;
4784 TREE_USED (guard) = true;
4785 CP_DECL_THREAD_LOCAL_P (guard) = true;
4786 set_decl_tls_model (guard, decl_default_tls_model (guard));
4787 pushdecl_top_level_and_finish (guard, NULL_TREE);
4789 tree fn = get_local_tls_init_fn (loc);
4790 start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4791 tree body = begin_function_body ();
4792 tree if_stmt = begin_if_stmt ();
4793 tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4794 tf_warning_or_error);
4795 finish_if_stmt_cond (cond, if_stmt);
4796 finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
4797 boolean_true_node,
4798 tf_warning_or_error));
4799 for (; vars; vars = TREE_CHAIN (vars))
4801 tree var = TREE_VALUE (vars);
4802 tree init = TREE_PURPOSE (vars);
4803 one_static_initialization_or_destruction (var, init, true);
4805 /* Output init aliases even with -fno-extern-tls-init. */
4806 if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
4808 tree single_init_fn = get_tls_init_fn (var);
4809 if (single_init_fn == NULL_TREE)
4810 continue;
4811 cgraph_node *alias
4812 = cgraph_node::get_create (fn)->create_same_body_alias
4813 (single_init_fn, fn);
4814 gcc_assert (alias != NULL);
4818 finish_then_clause (if_stmt);
4819 finish_if_stmt (if_stmt);
4820 finish_function_body (body);
4821 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4824 /* We're at the end of compilation, so generate any mangling aliases that
4825 we've been saving up, if DECL is going to be output and ID2 isn't
4826 already taken by another declaration. */
4828 static void
4829 generate_mangling_alias (tree decl, tree id2)
4831 struct cgraph_node *n = NULL;
4833 if (TREE_CODE (decl) == FUNCTION_DECL)
4835 n = cgraph_node::get (decl);
4836 if (!n)
4837 /* Don't create an alias to an unreferenced function. */
4838 return;
4841 tree *slot
4842 = mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
4843 INSERT);
4845 /* If there's a declaration already using this mangled name,
4846 don't create a compatibility alias that conflicts. */
4847 if (*slot)
4848 return;
4850 tree alias = make_alias_for (decl, id2);
4851 *slot = alias;
4853 DECL_IGNORED_P (alias) = 1;
4854 TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4855 DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4856 if (vague_linkage_p (decl))
4857 DECL_WEAK (alias) = 1;
4859 if (n)
4860 n->create_same_body_alias (alias, decl);
4861 else
4862 varpool_node::create_extra_name_alias (alias, decl);
4865 /* Note that we might want to emit an alias with the symbol ID2 for DECL at
4866 the end of translation, for compatibility across bugs in the mangling
4867 implementation. */
4869 void
4870 note_mangling_alias (tree decl, tree id2)
4872 if (TARGET_SUPPORTS_ALIASES)
4874 if (!defer_mangling_aliases)
4875 generate_mangling_alias (decl, id2);
4876 else
4878 vec_safe_push (mangling_aliases, decl);
4879 vec_safe_push (mangling_aliases, id2);
4884 /* Emit all mangling aliases that were deferred up to this point. */
4886 void
4887 generate_mangling_aliases ()
4889 while (!vec_safe_is_empty (mangling_aliases))
4891 tree id2 = mangling_aliases->pop();
4892 tree decl = mangling_aliases->pop();
4893 generate_mangling_alias (decl, id2);
4895 defer_mangling_aliases = false;
4898 /* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
4899 set. NEED_WARNING is true if we must warn about collisions. We do
4900 this to spot changes in mangling that may require compatibility
4901 aliases. */
4903 void
4904 record_mangling (tree decl, bool need_warning)
4906 if (!mangled_decls)
4907 mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
4909 gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
4910 tree id = DECL_ASSEMBLER_NAME_RAW (decl);
4911 tree *slot
4912 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4913 INSERT);
4915 /* If this is already an alias, remove the alias, because the real
4916 decl takes precedence. */
4917 if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
4918 if (symtab_node *n = symtab_node::get (*slot))
4919 if (n->cpp_implicit_alias)
4921 n->remove ();
4922 *slot = NULL_TREE;
4925 if (!*slot)
4926 *slot = decl;
4927 else if (need_warning)
4929 error_at (DECL_SOURCE_LOCATION (decl),
4930 "mangling of %q#D as %qE conflicts with a previous mangle",
4931 decl, id);
4932 inform (DECL_SOURCE_LOCATION (*slot),
4933 "previous mangling %q#D", *slot);
4934 inform (DECL_SOURCE_LOCATION (decl),
4935 "a later %<-fabi-version=%> (or =0)"
4936 " avoids this error with a change in mangling");
4937 *slot = decl;
4941 /* The mangled name of DECL is being forcibly changed to NAME. Remove
4942 any existing knowledge of DECL's mangled name meaning DECL. */
4944 void
4945 overwrite_mangling (tree decl, tree name)
4947 if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
4948 if ((TREE_CODE (decl) == VAR_DECL
4949 || TREE_CODE (decl) == FUNCTION_DECL)
4950 && mangled_decls)
4951 if (tree *slot
4952 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4953 NO_INSERT))
4954 if (*slot == decl)
4956 mangled_decls->clear_slot (slot);
4958 /* If this is an alias, remove it from the symbol table. */
4959 if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
4960 if (symtab_node *n = symtab_node::get (decl))
4961 if (n->cpp_implicit_alias)
4962 n->remove ();
4965 DECL_ASSEMBLER_NAME_RAW (decl) = name;
4968 /* The entire file is now complete. If requested, dump everything
4969 to a file. */
4971 static void
4972 dump_tu (void)
4974 dump_flags_t flags;
4975 if (FILE *stream = dump_begin (raw_dump_id, &flags))
4977 dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4978 dump_end (raw_dump_id, stream);
4982 static location_t locus_at_end_of_parsing;
4984 /* Check the deallocation functions for CODE to see if we want to warn that
4985 only one was defined. */
4987 static void
4988 maybe_warn_sized_delete (enum tree_code code)
4990 tree sized = NULL_TREE;
4991 tree unsized = NULL_TREE;
4993 for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
4994 iter; ++iter)
4996 tree fn = *iter;
4997 /* We're only interested in usual deallocation functions. */
4998 if (!usual_deallocation_fn_p (fn))
4999 continue;
5000 if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
5001 unsized = fn;
5002 else
5003 sized = fn;
5005 if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
5006 warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
5007 "the program should also define %qD", sized);
5008 else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
5009 warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
5010 "the program should also define %qD", unsized);
5013 /* Check the global deallocation functions to see if we want to warn about
5014 defining unsized without sized (or vice versa). */
5016 static void
5017 maybe_warn_sized_delete ()
5019 if (!flag_sized_deallocation || !warn_sized_deallocation)
5020 return;
5021 maybe_warn_sized_delete (DELETE_EXPR);
5022 maybe_warn_sized_delete (VEC_DELETE_EXPR);
5025 /* Earlier we left PTRMEM_CST in variable initializers alone so that we could
5026 look them up when evaluating non-type template parameters. Now we need to
5027 lower them to something the back end can understand. */
5029 static void
5030 lower_var_init ()
5032 varpool_node *node;
5033 FOR_EACH_VARIABLE (node)
5035 tree d = node->decl;
5036 if (tree init = DECL_INITIAL (d))
5037 DECL_INITIAL (d) = cplus_expand_constant (init);
5041 /* This routine is called at the end of compilation.
5042 Its job is to create all the code needed to initialize and
5043 destroy the global aggregates. We do the destruction
5044 first, since that way we only need to reverse the decls once. */
5046 void
5047 c_parse_final_cleanups (void)
5049 size_t i;
5050 tree decl;
5052 locus_at_end_of_parsing = input_location;
5053 at_eof = 1;
5055 /* Bad parse errors. Just forget about it. */
5056 if (! global_bindings_p () || current_class_type
5057 || !vec_safe_is_empty (decl_namespace_list))
5058 return;
5060 /* This is the point to write out a PCH if we're doing that.
5061 In that case we do not want to do anything else. */
5062 if (pch_file)
5064 /* Mangle all symbols at PCH creation time. */
5065 symtab_node *node;
5066 FOR_EACH_SYMBOL (node)
5067 if (! is_a <varpool_node *> (node)
5068 || ! DECL_HARD_REGISTER (node->decl))
5069 DECL_ASSEMBLER_NAME (node->decl);
5070 c_common_write_pch ();
5071 dump_tu ();
5072 /* Ensure even the callers don't try to finalize the CU. */
5073 flag_syntax_only = 1;
5074 return;
5077 timevar_stop (TV_PHASE_PARSING);
5078 timevar_start (TV_PHASE_DEFERRED);
5080 symtab->process_same_body_aliases ();
5082 /* Handle -fdump-ada-spec[-slim] */
5083 if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
5085 collect_source_ref (main_input_filename);
5086 if (!flag_dump_ada_spec_slim)
5087 collect_source_refs (global_namespace);
5089 dump_ada_specs (collect_all_refs, cpp_check);
5092 /* FIXME - huh? was input_line -= 1;*/
5094 /* We now have to write out all the stuff we put off writing out.
5095 These include:
5097 o Template specializations that we have not yet instantiated,
5098 but which are needed.
5099 o Initialization and destruction for non-local objects with
5100 static storage duration. (Local objects with static storage
5101 duration are initialized when their scope is first entered,
5102 and are cleaned up via atexit.)
5103 o Virtual function tables.
5105 All of these may cause others to be needed. For example,
5106 instantiating one function may cause another to be needed, and
5107 generating the initializer for an object may cause templates to be
5108 instantiated, etc., etc. */
5110 emit_support_tinfos ();
5112 /* Track vtables we want to emit that refer to consteval functions. */
5113 auto_vec<tree> consteval_vtables;
5115 int retries = 0;
5116 unsigned ssdf_count = 0;
5117 for (bool reconsider = true; reconsider; retries++)
5119 reconsider = false;
5121 /* If there are templates that we've put off instantiating, do
5122 them now. */
5123 instantiate_pending_templates (retries);
5124 ggc_collect ();
5126 if (header_module_p ())
5127 /* A header modules initializations are handled in its
5128 importer. */
5129 continue;
5131 /* Write out virtual tables as required. Writing out the
5132 virtual table for a template class may cause the
5133 instantiation of members of that class. If we write out
5134 vtables then we remove the class from our list so we don't
5135 have to look at it again. */
5136 tree t;
5137 for (i = keyed_classes->length ();
5138 keyed_classes->iterate (--i, &t);)
5139 if (maybe_emit_vtables (t, consteval_vtables))
5141 reconsider = true;
5142 keyed_classes->unordered_remove (i);
5144 /* The input_location may have been changed during marking of
5145 vtable entries. */
5146 input_location = locus_at_end_of_parsing;
5148 /* Write out needed type info variables. We have to be careful
5149 looping through unemitted decls, because emit_tinfo_decl may
5150 cause other variables to be needed. New elements will be
5151 appended, and we remove from the vector those that actually
5152 get emitted. */
5153 for (i = unemitted_tinfo_decls->length ();
5154 unemitted_tinfo_decls->iterate (--i, &t);)
5155 if (emit_tinfo_decl (t))
5157 reconsider = true;
5158 unemitted_tinfo_decls->unordered_remove (i);
5161 /* The list of objects with static storage duration is built up
5162 in reverse order. We clear STATIC_AGGREGATES so that any new
5163 aggregates added during the initialization of these will be
5164 initialized in the correct order when we next come around the
5165 loop. */
5166 if (tree vars = prune_vars_needing_no_initialization (&static_aggregates))
5168 if (flag_openmp)
5169 /* Add initializer information from VARS into
5170 DYNAMIC_INITIALIZERS. */
5171 for (t = vars; t; t = TREE_CHAIN (t))
5172 hash_map_safe_put<hm_ggc> (dynamic_initializers,
5173 TREE_VALUE (t), TREE_PURPOSE (t));
5175 /* We need to start a new initialization function each time
5176 through the loop. That's because we need to know which
5177 vtables have been referenced, and TREE_SYMBOL_REFERENCED
5178 isn't computed until a function is finished, and written
5179 out. That's a deficiency in the back end. When this is
5180 fixed, these initialization functions could all become
5181 inline, with resulting performance improvements. */
5182 tree ssdf_body;
5184 /* Make sure the back end knows about all the variables. */
5185 write_out_vars (vars);
5187 /* Set the line and file, so that it is obviously not from
5188 the source file. */
5189 input_location = locus_at_end_of_parsing;
5190 ssdf_body = start_static_storage_duration_function (ssdf_count);
5192 /* First generate code to do all the initializations. */
5193 if (vars)
5194 do_static_initialization_or_destruction (vars, /*initp=*/true);
5196 /* Then, generate code to do all the destructions. Do these
5197 in reverse order so that the most recently constructed
5198 variable is the first destroyed. If we're using
5199 __cxa_atexit, then we don't need to do this; functions
5200 were registered at initialization time to destroy the
5201 local statics. */
5202 if (!flag_use_cxa_atexit && vars)
5204 vars = nreverse (vars);
5205 do_static_initialization_or_destruction (vars, /*initp=*/false);
5207 else
5208 vars = NULL_TREE;
5210 /* Finish up the static storage duration function for this
5211 round. */
5212 input_location = locus_at_end_of_parsing;
5213 finish_static_storage_duration_function (ssdf_body);
5215 /* All those initializations and finalizations might cause
5216 us to need more inline functions, more template
5217 instantiations, etc. */
5218 reconsider = true;
5219 ssdf_count++;
5222 /* Now do the same for thread_local variables. */
5223 handle_tls_init ();
5225 /* Go through the set of inline functions whose bodies have not
5226 been emitted yet. If out-of-line copies of these functions
5227 are required, emit them. */
5228 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5230 /* Does it need synthesizing? */
5231 if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
5232 && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
5234 /* Even though we're already at the top-level, we push
5235 there again. That way, when we pop back a few lines
5236 hence, all of our state is restored. Otherwise,
5237 finish_function doesn't clean things up, and we end
5238 up with CURRENT_FUNCTION_DECL set. */
5239 push_to_top_level ();
5240 /* The decl's location will mark where it was first
5241 needed. Save that so synthesize method can indicate
5242 where it was needed from, in case of error */
5243 input_location = DECL_SOURCE_LOCATION (decl);
5244 synthesize_method (decl);
5245 pop_from_top_level ();
5246 reconsider = true;
5249 if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
5250 generate_tls_wrapper (decl);
5252 if (!DECL_SAVED_TREE (decl))
5253 continue;
5255 cgraph_node *node = cgraph_node::get_create (decl);
5257 /* We lie to the back end, pretending that some functions
5258 are not defined when they really are. This keeps these
5259 functions from being put out unnecessarily. But, we must
5260 stop lying when the functions are referenced, or if they
5261 are not comdat since they need to be put out now. If
5262 DECL_INTERFACE_KNOWN, then we have already set
5263 DECL_EXTERNAL appropriately, so there's no need to check
5264 again, and we do not want to clear DECL_EXTERNAL if a
5265 previous call to import_export_decl set it.
5267 This is done in a separate for cycle, because if some
5268 deferred function is contained in another deferred
5269 function later in deferred_fns varray,
5270 rest_of_compilation would skip this function and we
5271 really cannot expand the same function twice. */
5272 import_export_decl (decl);
5273 if (DECL_NOT_REALLY_EXTERN (decl)
5274 && DECL_INITIAL (decl)
5275 && decl_needed_p (decl))
5277 if (node->cpp_implicit_alias)
5278 node = node->get_alias_target ();
5280 node->call_for_symbol_thunks_and_aliases (clear_decl_external,
5281 NULL, true);
5282 /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
5283 group, we need to mark all symbols in the same comdat group
5284 that way. */
5285 if (node->same_comdat_group)
5286 for (cgraph_node *next
5287 = dyn_cast<cgraph_node *> (node->same_comdat_group);
5288 next != node;
5289 next = dyn_cast<cgraph_node *> (next->same_comdat_group))
5290 next->call_for_symbol_thunks_and_aliases (clear_decl_external,
5291 NULL, true);
5294 /* If we're going to need to write this function out, and
5295 there's already a body for it, create RTL for it now.
5296 (There might be no body if this is a method we haven't
5297 gotten around to synthesizing yet.) */
5298 if (!DECL_EXTERNAL (decl)
5299 && decl_needed_p (decl)
5300 && !TREE_ASM_WRITTEN (decl)
5301 && !DECL_IMMEDIATE_FUNCTION_P (decl)
5302 && !node->definition)
5304 /* We will output the function; no longer consider it in this
5305 loop. */
5306 DECL_DEFER_OUTPUT (decl) = 0;
5307 /* Generate RTL for this function now that we know we
5308 need it. */
5309 expand_or_defer_fn (decl);
5310 reconsider = true;
5314 if (wrapup_namespace_globals ())
5315 reconsider = true;
5317 /* Static data members are just like namespace-scope globals. */
5318 FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
5320 if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
5321 /* Don't write it out if we haven't seen a definition. */
5322 || DECL_IN_AGGR_P (decl))
5323 continue;
5324 import_export_decl (decl);
5325 /* If this static data member is needed, provide it to the
5326 back end. */
5327 if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
5328 DECL_EXTERNAL (decl) = 0;
5331 if (vec_safe_length (pending_statics) != 0
5332 && wrapup_global_declarations (pending_statics->address (),
5333 pending_statics->length ()))
5334 reconsider = true;
5337 finish_module_processing (parse_in);
5339 lower_var_init ();
5341 generate_mangling_aliases ();
5343 /* All used inline functions must have a definition at this point. */
5344 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5346 if (/* Check online inline functions that were actually used. */
5347 DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
5348 /* If the definition actually was available here, then the
5349 fact that the function was not defined merely represents
5350 that for some reason (use of a template repository,
5351 #pragma interface, etc.) we decided not to emit the
5352 definition here. */
5353 && !DECL_INITIAL (decl)
5354 /* A defaulted fn in a header module can be synthesized on
5355 demand later. (In non-header modules we should have
5356 synthesized it above.) */
5357 && !(DECL_DEFAULTED_FN (decl) && header_module_p ())
5358 /* Don't complain if the template was defined. */
5359 && !(DECL_TEMPLATE_INSTANTIATION (decl)
5360 && DECL_INITIAL (DECL_TEMPLATE_RESULT
5361 (template_for_substitution (decl))))
5362 && warning_at (DECL_SOURCE_LOCATION (decl), 0,
5363 "inline function %qD used but never defined", decl))
5364 /* Avoid a duplicate warning from check_global_declaration. */
5365 suppress_warning (decl, OPT_Wunused);
5368 /* So must decls that use a type with no linkage. */
5369 FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
5370 no_linkage_error (decl);
5372 maybe_warn_sized_delete ();
5374 /* Then, do the Objective-C stuff. This is where all the
5375 Objective-C module stuff gets generated (symtab,
5376 class/protocol/selector lists etc). This must be done after C++
5377 templates, destructors etc. so that selectors used in C++
5378 templates are properly allocated. */
5379 if (c_dialect_objc ())
5380 objc_write_global_declarations ();
5382 /* We give C linkage to static constructors and destructors. */
5383 push_lang_context (lang_name_c);
5385 /* Generate initialization and destruction functions for all
5386 priorities for which they are required. */
5387 if (priority_info_map)
5388 splay_tree_foreach (priority_info_map,
5389 generate_ctor_and_dtor_functions_for_priority,
5390 /*data=*/&locus_at_end_of_parsing);
5391 else if ((c_dialect_objc () && objc_static_init_needed_p ())
5392 || module_initializer_kind ())
5393 generate_ctor_or_dtor_function (/*constructor_p=*/true,
5394 DEFAULT_INIT_PRIORITY,
5395 &locus_at_end_of_parsing);
5397 /* We're done with the splay-tree now. */
5398 if (priority_info_map)
5399 splay_tree_delete (priority_info_map);
5401 fini_modules ();
5403 /* Generate any missing aliases. */
5404 maybe_apply_pending_pragma_weaks ();
5406 /* We're done with static constructors, so we can go back to "C++"
5407 linkage now. */
5408 pop_lang_context ();
5410 if (flag_vtable_verify)
5412 vtv_recover_class_info ();
5413 vtv_compute_class_hierarchy_transitive_closure ();
5414 vtv_build_vtable_verify_fndecl ();
5417 perform_deferred_noexcept_checks ();
5419 fini_constexpr ();
5420 cp_tree_c_finish_parsing ();
5421 clear_consteval_vfns (consteval_vtables);
5423 /* The entire file is now complete. If requested, dump everything
5424 to a file. */
5425 dump_tu ();
5427 if (flag_detailed_statistics)
5429 dump_tree_statistics ();
5430 dump_time_statistics ();
5433 timevar_stop (TV_PHASE_DEFERRED);
5434 timevar_start (TV_PHASE_PARSING);
5436 /* Indicate that we're done with front end processing. */
5437 at_eof = 2;
5440 /* Perform any post compilation-proper cleanups for the C++ front-end.
5441 This should really go away. No front-end should need to do
5442 anything past the compilation process. */
5444 void
5445 cxx_post_compilation_parsing_cleanups (void)
5447 timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
5449 if (flag_vtable_verify)
5451 /* Generate the special constructor initialization function that
5452 calls __VLTRegisterPairs, and give it a very high
5453 initialization priority. This must be done after
5454 finalize_compilation_unit so that we have accurate
5455 information about which vtable will actually be emitted. */
5456 vtv_generate_init_routine ();
5459 input_location = locus_at_end_of_parsing;
5461 if (flag_checking)
5462 validate_conversion_obstack ();
5464 timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
5467 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
5468 function to call in parse-tree form; it has not yet been
5469 semantically analyzed. ARGS are the arguments to the function.
5470 They have already been semantically analyzed. This may change
5471 ARGS. */
5473 tree
5474 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
5475 tsubst_flags_t complain)
5477 tree orig_fn;
5478 vec<tree, va_gc> *orig_args = NULL;
5479 tree expr;
5480 tree object;
5482 orig_fn = fn;
5483 object = TREE_OPERAND (fn, 0);
5485 if (processing_template_decl)
5487 gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
5488 || TREE_CODE (fn) == MEMBER_REF);
5489 if (type_dependent_expression_p (fn)
5490 || any_type_dependent_arguments_p (*args))
5491 return build_min_nt_call_vec (fn, *args);
5493 orig_args = make_tree_vector_copy (*args);
5495 /* Transform the arguments and add the implicit "this"
5496 parameter. That must be done before the FN is transformed
5497 because we depend on the form of FN. */
5498 make_args_non_dependent (*args);
5499 object = build_non_dependent_expr (object);
5500 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5502 if (TREE_CODE (fn) == DOTSTAR_EXPR)
5503 object = cp_build_addr_expr (object, complain);
5504 vec_safe_insert (*args, 0, object);
5506 /* Now that the arguments are done, transform FN. */
5507 fn = build_non_dependent_expr (fn);
5510 /* A qualified name corresponding to a bound pointer-to-member is
5511 represented as an OFFSET_REF:
5513 struct B { void g(); };
5514 void (B::*p)();
5515 void B::g() { (this->*p)(); } */
5516 if (TREE_CODE (fn) == OFFSET_REF)
5518 tree object_addr = cp_build_addr_expr (object, complain);
5519 fn = TREE_OPERAND (fn, 1);
5520 fn = get_member_function_from_ptrfunc (&object_addr, fn,
5521 complain);
5522 vec_safe_insert (*args, 0, object_addr);
5525 if (CLASS_TYPE_P (TREE_TYPE (fn)))
5526 expr = build_op_call (fn, args, complain);
5527 else
5528 expr = cp_build_function_call_vec (fn, args, complain);
5529 if (processing_template_decl && expr != error_mark_node)
5530 expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
5532 if (orig_args != NULL)
5533 release_tree_vector (orig_args);
5535 return expr;
5539 void
5540 check_default_args (tree x)
5542 tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5543 bool saw_def = false;
5544 bool noted_first_def = false;
5545 int idx_of_first_default_arg = 0;
5546 location_t loc_of_first_default_arg = UNKNOWN_LOCATION;
5547 int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5548 tree fndecl = STRIP_TEMPLATE (x);
5549 auto_diagnostic_group d;
5550 for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5552 if (TREE_PURPOSE (arg))
5554 if (!saw_def)
5556 saw_def = true;
5557 idx_of_first_default_arg = i;
5558 location_t loc = get_fndecl_argument_location (fndecl, i);
5559 if (loc != DECL_SOURCE_LOCATION (x))
5560 loc_of_first_default_arg = loc;
5563 else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
5565 error_at (get_fndecl_argument_location (fndecl, i),
5566 "default argument missing for parameter %P of %q#D", i, x);
5567 if (loc_of_first_default_arg != UNKNOWN_LOCATION
5568 && !noted_first_def)
5570 inform (loc_of_first_default_arg,
5571 "...following parameter %P which has a default argument",
5572 idx_of_first_default_arg);
5573 noted_first_def = true;
5575 TREE_PURPOSE (arg) = error_mark_node;
5580 /* Return true if function DECL can be inlined. This is used to force
5581 instantiation of methods that might be interesting for inlining. */
5582 bool
5583 possibly_inlined_p (tree decl)
5585 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5586 if (DECL_UNINLINABLE (decl))
5587 return false;
5588 if (!optimize)
5589 return DECL_DECLARED_INLINE_P (decl);
5590 /* When optimizing, we might inline everything when flatten
5591 attribute or heuristics inlining for size or autoinlining
5592 is used. */
5593 return true;
5596 /* Normally, we can wait until instantiation-time to synthesize DECL.
5597 However, if DECL is a static data member initialized with a constant
5598 or a constexpr function, we need it right now because a reference to
5599 such a data member or a call to such function is not value-dependent.
5600 For a function that uses auto in the return type, we need to instantiate
5601 it to find out its type. For OpenMP user defined reductions, we need
5602 them instantiated for reduction clauses which inline them by hand
5603 directly. */
5605 void
5606 maybe_instantiate_decl (tree decl)
5608 if (DECL_LANG_SPECIFIC (decl)
5609 && DECL_TEMPLATE_INFO (decl)
5610 && (decl_maybe_constant_var_p (decl)
5611 || (TREE_CODE (decl) == FUNCTION_DECL
5612 && DECL_OMP_DECLARE_REDUCTION_P (decl))
5613 || undeduced_auto_decl (decl))
5614 && !DECL_DECLARED_CONCEPT_P (decl)
5615 && !uses_template_parms (DECL_TI_ARGS (decl)))
5617 /* Instantiating a function will result in garbage collection. We
5618 must treat this situation as if we were within the body of a
5619 function so as to avoid collecting live data only referenced from
5620 the stack (such as overload resolution candidates). */
5621 ++function_depth;
5622 instantiate_decl (decl, /*defer_ok=*/false,
5623 /*expl_inst_class_mem_p=*/false);
5624 --function_depth;
5628 /* Error if the DECL is unavailable (unless this is currently suppressed).
5629 Maybe warn if DECL is deprecated, subject to COMPLAIN. Returns true if
5630 an error or warning was emitted. */
5632 bool
5633 cp_handle_deprecated_or_unavailable (tree decl, tsubst_flags_t complain)
5635 if (!decl)
5636 return false;
5638 if ((complain & tf_error)
5639 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
5641 if (TREE_UNAVAILABLE (decl))
5643 error_unavailable_use (decl, NULL_TREE);
5644 return true;
5646 else
5648 /* Perhaps this is an unavailable typedef. */
5649 if (TYPE_P (decl)
5650 && TYPE_NAME (decl)
5651 && TREE_UNAVAILABLE (TYPE_NAME (decl)))
5653 decl = TYPE_NAME (decl);
5654 /* Don't error within members of a unavailable type. */
5655 if (TYPE_P (decl)
5656 && currently_open_class (decl))
5657 return false;
5659 error_unavailable_use (decl, NULL_TREE);
5660 return true;
5663 /* Carry on to consider deprecatedness. */
5666 if (!(complain & tf_warning)
5667 || deprecated_state == DEPRECATED_SUPPRESS
5668 || deprecated_state == UNAVAILABLE_DEPRECATED_SUPPRESS)
5669 return false;
5671 if (!TREE_DEPRECATED (decl))
5673 /* Perhaps this is a deprecated typedef. */
5674 if (TYPE_P (decl) && TYPE_NAME (decl))
5675 decl = TYPE_NAME (decl);
5677 if (!TREE_DEPRECATED (decl))
5678 return false;
5681 /* Don't warn within members of a deprecated type. */
5682 if (TYPE_P (decl)
5683 && currently_open_class (decl))
5684 return false;
5686 bool warned = false;
5687 if (cxx_dialect >= cxx11
5688 && DECL_P (decl)
5689 && DECL_ARTIFICIAL (decl)
5690 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5691 && copy_fn_p (decl))
5693 /* Don't warn if the flag was disabled around the class definition
5694 (c++/94492). */
5695 if (warning_enabled_at (DECL_SOURCE_LOCATION (decl),
5696 OPT_Wdeprecated_copy))
5698 auto_diagnostic_group d;
5699 tree ctx = DECL_CONTEXT (decl);
5700 tree other = classtype_has_depr_implicit_copy (ctx);
5701 int opt = (DECL_DESTRUCTOR_P (other)
5702 ? OPT_Wdeprecated_copy_dtor
5703 : OPT_Wdeprecated_copy);
5704 warned = warning (opt, "implicitly-declared %qD is deprecated",
5705 decl);
5706 if (warned)
5707 inform (DECL_SOURCE_LOCATION (other),
5708 "because %qT has user-provided %qD",
5709 ctx, other);
5712 else
5713 warned = warn_deprecated_use (decl, NULL_TREE);
5715 return warned;
5718 /* Like above, but takes into account outer scopes. */
5720 void
5721 cp_warn_deprecated_use_scopes (tree scope)
5723 while (scope
5724 && scope != error_mark_node
5725 && scope != global_namespace)
5727 if ((TREE_CODE (scope) == NAMESPACE_DECL || OVERLOAD_TYPE_P (scope))
5728 && cp_handle_deprecated_or_unavailable (scope))
5729 return;
5730 if (TYPE_P (scope))
5731 scope = CP_TYPE_CONTEXT (scope);
5732 else
5733 scope = CP_DECL_CONTEXT (scope);
5737 /* True if DECL or its enclosing scope have unbound template parameters. */
5739 bool
5740 decl_dependent_p (tree decl)
5742 if (DECL_FUNCTION_SCOPE_P (decl)
5743 || TREE_CODE (decl) == CONST_DECL
5744 || TREE_CODE (decl) == USING_DECL
5745 || TREE_CODE (decl) == FIELD_DECL)
5746 decl = CP_DECL_CONTEXT (decl);
5747 if (tree tinfo = get_template_info (decl))
5748 if (any_dependent_template_arguments_p (TI_ARGS (tinfo)))
5749 return true;
5750 if (LAMBDA_FUNCTION_P (decl)
5751 && dependent_type_p (DECL_CONTEXT (decl)))
5752 return true;
5753 return false;
5756 /* [basic.def.odr] A function is named [and therefore odr-used] by an
5757 expression or conversion if it is the selected member of an overload set in
5758 an overload resolution performed as part of forming that expression or
5759 conversion, unless it is a pure virtual function and either the expression
5760 is not an id-expression naming the function with an explicitly qualified
5761 name or the expression forms a pointer to member.
5763 Mostly, we call mark_used in places that actually do something with a
5764 function, like build_over_call. But in a few places we end up with a
5765 non-overloaded FUNCTION_DECL that we aren't going to do any more with, like
5766 convert_to_void. resolve_nondeduced_context is called in those places,
5767 but it's also called in too many other places. */
5769 bool
5770 mark_single_function (tree expr, tsubst_flags_t complain)
5772 expr = maybe_undo_parenthesized_ref (expr);
5773 expr = tree_strip_any_location_wrapper (expr);
5775 if (is_overloaded_fn (expr) == 1
5776 && !mark_used (expr, complain)
5777 && (complain & tf_error))
5778 return false;
5779 return true;
5782 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5783 If DECL is a specialization or implicitly declared class member,
5784 generate the actual definition. Return false if something goes
5785 wrong, true otherwise. */
5787 bool
5788 mark_used (tree decl, tsubst_flags_t complain)
5790 /* If we're just testing conversions or resolving overloads, we
5791 don't want any permanent effects like forcing functions to be
5792 output or instantiating templates. */
5793 if ((complain & tf_conv))
5794 return true;
5796 /* If DECL is a BASELINK for a single function, then treat it just
5797 like the DECL for the function. Otherwise, if the BASELINK is
5798 for an overloaded function, we don't know which function was
5799 actually used until after overload resolution. */
5800 if (BASELINK_P (decl))
5802 tree fns = BASELINK_FUNCTIONS (decl);
5803 if (really_overloaded_fn (fns))
5804 return true;
5805 fns = OVL_FIRST (fns);
5806 if (!mark_used (fns, complain))
5807 return false;
5808 /* We might have deduced its return type. */
5809 TREE_TYPE (decl) = TREE_TYPE (fns);
5810 return true;
5813 if (!DECL_P (decl))
5814 return true;
5816 /* Set TREE_USED for the benefit of -Wunused. */
5817 TREE_USED (decl) = true;
5819 /* And for structured bindings also the underlying decl. */
5820 if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
5821 TREE_USED (DECL_DECOMP_BASE (decl)) = true;
5823 if (TREE_CODE (decl) == TEMPLATE_DECL)
5824 return true;
5826 if (DECL_CLONED_FUNCTION_P (decl))
5827 TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5829 /* Mark enumeration types as used. */
5830 if (TREE_CODE (decl) == CONST_DECL)
5831 used_types_insert (DECL_CONTEXT (decl));
5833 if (TREE_CODE (decl) == FUNCTION_DECL)
5835 if (DECL_MAYBE_DELETED (decl))
5837 ++function_depth;
5838 maybe_synthesize_method (decl);
5839 --function_depth;
5842 if (DECL_DELETED_FN (decl))
5844 if (DECL_ARTIFICIAL (decl)
5845 && DECL_CONV_FN_P (decl)
5846 && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5847 /* We mark a lambda conversion op as deleted if we can't
5848 generate it properly; see maybe_add_lambda_conv_op. */
5849 sorry ("converting lambda that uses %<...%> to function pointer");
5850 else if (complain & tf_error)
5852 error ("use of deleted function %qD", decl);
5853 if (!maybe_explain_implicit_delete (decl))
5854 inform (DECL_SOURCE_LOCATION (decl), "declared here");
5856 return false;
5859 if (!maybe_instantiate_noexcept (decl, complain))
5860 return false;
5863 if (VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl))
5865 if (!DECL_LANG_SPECIFIC (decl))
5866 /* An unresolved dependent local extern. */
5867 return true;
5869 DECL_ODR_USED (decl) = 1;
5870 auto alias = DECL_LOCAL_DECL_ALIAS (decl);
5871 if (!alias || alias == error_mark_node)
5872 return true;
5874 /* Process the underlying decl. */
5875 decl = alias;
5876 TREE_USED (decl) = true;
5879 cp_handle_deprecated_or_unavailable (decl, complain);
5881 /* We can only check DECL_ODR_USED on variables or functions with
5882 DECL_LANG_SPECIFIC set, and these are also the only decls that we
5883 might need special handling for. */
5884 if (!VAR_OR_FUNCTION_DECL_P (decl)
5885 || DECL_LANG_SPECIFIC (decl) == NULL
5886 || DECL_THUNK_P (decl))
5888 if (!decl_dependent_p (decl)
5889 && !require_deduced_type (decl, complain))
5890 return false;
5891 return true;
5894 /* We only want to do this processing once. We don't need to keep trying
5895 to instantiate inline templates, because unit-at-a-time will make sure
5896 we get them compiled before functions that want to inline them. */
5897 if (DECL_ODR_USED (decl))
5898 return true;
5900 if (flag_concepts && TREE_CODE (decl) == FUNCTION_DECL
5901 && !constraints_satisfied_p (decl))
5903 if (complain & tf_error)
5905 auto_diagnostic_group d;
5906 error ("use of function %qD with unsatisfied constraints",
5907 decl);
5908 location_t loc = DECL_SOURCE_LOCATION (decl);
5909 inform (loc, "declared here");
5910 diagnose_constraints (loc, decl, NULL_TREE);
5912 return false;
5915 /* Normally, we can wait until instantiation-time to synthesize DECL.
5916 However, if DECL is a static data member initialized with a constant
5917 or a constexpr function, we need it right now because a reference to
5918 such a data member or a call to such function is not value-dependent.
5919 For a function that uses auto in the return type, we need to instantiate
5920 it to find out its type. For OpenMP user defined reductions, we need
5921 them instantiated for reduction clauses which inline them by hand
5922 directly. */
5923 maybe_instantiate_decl (decl);
5925 if (processing_template_decl || in_template_function ())
5926 return true;
5928 /* Check this too in case we're within instantiate_non_dependent_expr. */
5929 if (DECL_TEMPLATE_INFO (decl)
5930 && uses_template_parms (DECL_TI_ARGS (decl)))
5931 return true;
5933 if (!require_deduced_type (decl, complain))
5934 return false;
5936 if (builtin_pack_fn_p (decl))
5938 error ("use of built-in parameter pack %qD outside of a template",
5939 DECL_NAME (decl));
5940 return false;
5943 /* If we don't need a value, then we don't need to synthesize DECL. */
5944 if (cp_unevaluated_operand || in_discarded_stmt)
5945 return true;
5947 DECL_ODR_USED (decl) = 1;
5948 if (DECL_CLONED_FUNCTION_P (decl))
5949 DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5951 /* DR 757: A type without linkage shall not be used as the type of a
5952 variable or function with linkage, unless
5953 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5954 o the variable or function is not used (3.2 [basic.def.odr]) or is
5955 defined in the same translation unit. */
5956 if (cxx_dialect > cxx98
5957 && decl_linkage (decl) != lk_none
5958 && !DECL_EXTERN_C_P (decl)
5959 && !DECL_ARTIFICIAL (decl)
5960 && !decl_defined_p (decl)
5961 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5962 vec_safe_push (no_linkage_decls, decl);
5964 if (TREE_CODE (decl) == FUNCTION_DECL
5965 && DECL_DECLARED_INLINE_P (decl)
5966 && !DECL_INITIAL (decl)
5967 && !DECL_ARTIFICIAL (decl)
5968 && !DECL_PURE_VIRTUAL_P (decl))
5969 /* Remember it, so we can check it was defined. */
5970 note_vague_linkage_fn (decl);
5972 /* Is it a synthesized method that needs to be synthesized? */
5973 if (TREE_CODE (decl) == FUNCTION_DECL
5974 && DECL_DEFAULTED_FN (decl)
5975 /* A function defaulted outside the class is synthesized either by
5976 cp_finish_decl or instantiate_decl. */
5977 && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5978 && ! DECL_INITIAL (decl))
5980 /* Defer virtual destructors so that thunks get the right
5981 linkage. */
5982 if (DECL_VIRTUAL_P (decl) && !at_eof)
5984 note_vague_linkage_fn (decl);
5985 return true;
5988 /* Remember the current location for a function we will end up
5989 synthesizing. Then we can inform the user where it was
5990 required in the case of error. */
5991 if (decl_remember_implicit_trigger_p (decl))
5992 DECL_SOURCE_LOCATION (decl) = input_location;
5994 /* Synthesizing an implicitly defined member function will result in
5995 garbage collection. We must treat this situation as if we were
5996 within the body of a function so as to avoid collecting live data
5997 on the stack (such as overload resolution candidates).
5999 We could just let c_parse_final_cleanups handle synthesizing
6000 this function by adding it to deferred_fns, but doing
6001 it at the use site produces better error messages. */
6002 ++function_depth;
6003 synthesize_method (decl);
6004 --function_depth;
6005 /* If this is a synthesized method we don't need to
6006 do the instantiation test below. */
6008 else if (VAR_OR_FUNCTION_DECL_P (decl)
6009 && DECL_TEMPLATE_INFO (decl)
6010 && !DECL_DECLARED_CONCEPT_P (decl)
6011 && (!DECL_EXPLICIT_INSTANTIATION (decl)
6012 || always_instantiate_p (decl)))
6013 /* If this is a function or variable that is an instance of some
6014 template, we now know that we will need to actually do the
6015 instantiation. We check that DECL is not an explicit
6016 instantiation because that is not checked in instantiate_decl.
6018 We put off instantiating functions in order to improve compile
6019 times. Maintaining a stack of active functions is expensive,
6020 and the inliner knows to instantiate any functions it might
6021 need. Therefore, we always try to defer instantiation. */
6023 ++function_depth;
6024 instantiate_decl (decl, /*defer_ok=*/true,
6025 /*expl_inst_class_mem_p=*/false);
6026 --function_depth;
6029 return true;
6032 bool
6033 mark_used (tree decl)
6035 return mark_used (decl, tf_warning_or_error);
6038 tree
6039 vtv_start_verification_constructor_init_function (void)
6041 return start_objects ('I', MAX_RESERVED_INIT_PRIORITY - 1);
6044 tree
6045 vtv_finish_verification_constructor_init_function (tree function_body)
6047 tree fn;
6049 finish_compound_stmt (function_body);
6050 fn = finish_function (/*inline_p=*/false);
6051 DECL_STATIC_CONSTRUCTOR (fn) = 1;
6052 decl_init_priority_insert (fn, MAX_RESERVED_INIT_PRIORITY - 1);
6054 return fn;
6057 #include "gt-cp-decl2.h"