c++: remove NON_DEPENDENT_EXPR, part 2
[official-gcc.git] / gcc / cp / decl2.cc
blob0aa1e3559720e4e9e8c7db9e73374566f2593826
1 /* Process declarations and variables for C++ compiler.
2 Copyright (C) 1988-2023 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"
52 #include "omp-general.h"
54 /* Id for dumping the raw trees. */
55 int raw_dump_id;
57 extern cpp_reader *parse_in;
59 static tree start_objects (bool, unsigned, bool);
60 static tree finish_objects (bool, unsigned, tree, bool = true);
61 static tree start_partial_init_fini_fn (bool, unsigned, unsigned);
62 static void finish_partial_init_fini_fn (tree);
63 static void emit_partial_init_fini_fn (bool, unsigned, tree,
64 unsigned, location_t);
65 static void one_static_initialization_or_destruction (bool, tree, tree);
66 static void generate_ctor_or_dtor_function (bool, unsigned, tree, location_t);
67 static tree prune_vars_needing_no_initialization (tree *);
68 static void write_out_vars (tree);
69 static void import_export_class (tree);
70 static tree get_guard_bits (tree);
71 static void determine_visibility_from_class (tree, tree);
72 static bool determine_hidden_inline (tree);
74 /* A list of static class variables. This is needed, because a
75 static class variable can be declared inside the class without
76 an initializer, and then initialized, statically, outside the class. */
77 static GTY(()) vec<tree, va_gc> *pending_statics;
79 /* A list of functions which were declared inline, but which we
80 may need to emit outline anyway. */
81 static GTY(()) vec<tree, va_gc> *deferred_fns;
83 /* A list of decls that use types with no linkage, which we need to make
84 sure are defined. */
85 static GTY(()) vec<tree, va_gc> *no_linkage_decls;
87 /* A vector of alternating decls and identifiers, where the latter
88 is to be an alias for the former if the former is defined. */
89 static GTY(()) vec<tree, va_gc> *mangling_aliases;
91 /* hash traits for declarations. Hashes single decls via
92 DECL_ASSEMBLER_NAME_RAW. */
94 struct mangled_decl_hash : ggc_remove <tree>
96 typedef tree value_type; /* A DECL. */
97 typedef tree compare_type; /* An identifier. */
99 static hashval_t hash (const value_type decl)
101 return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME_RAW (decl));
103 static bool equal (const value_type existing, compare_type candidate)
105 tree name = DECL_ASSEMBLER_NAME_RAW (existing);
106 return candidate == name;
109 static const bool empty_zero_p = true;
110 static inline void mark_empty (value_type &p) {p = NULL_TREE;}
111 static inline bool is_empty (value_type p) {return !p;}
113 static bool is_deleted (value_type e)
115 return e == reinterpret_cast <value_type> (1);
117 static void mark_deleted (value_type &e)
119 e = reinterpret_cast <value_type> (1);
123 /* A hash table of decls keyed by mangled name. Used to figure out if
124 we need compatibility aliases. */
125 static GTY(()) hash_table<mangled_decl_hash> *mangled_decls;
127 // Hash table mapping priority to lists of variables or functions.
128 struct priority_map_traits
130 typedef unsigned key_type;
131 typedef tree value_type;
132 static const bool maybe_mx = true;
133 static hashval_t hash (key_type v)
135 return hashval_t (v);
137 static bool equal_keys (key_type k1, key_type k2)
139 return k1 == k2;
141 template <typename T> static void remove (T &)
144 // Zero is not a priority
145 static const bool empty_zero_p = true;
146 template <typename T> static bool is_empty (const T &entry)
148 return entry.m_key == 0;
150 template <typename T> static void mark_empty (T &entry)
152 entry.m_key = 0;
154 // Entries are not deleteable
155 template <typename T> static bool is_deleted (const T &)
157 return false;
159 template <typename T> static void mark_deleted (T &)
161 gcc_unreachable ();
165 typedef hash_map<unsigned/*Priority*/, tree/*List*/,
166 priority_map_traits> priority_map_t;
168 /* A pair of such hash tables, indexed by initp -- one for fini and
169 one for init. The fini table is only ever used when !cxa_atexit. */
170 static GTY(()) priority_map_t *static_init_fini_fns[2];
172 /* Nonzero if we're done parsing and into end-of-file activities. */
174 int at_eof;
176 /* True if note_mangling_alias should enqueue mangling aliases for
177 later generation, rather than emitting them right away. */
179 bool defer_mangling_aliases = true;
182 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
183 FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
184 that apply to the function). */
186 tree
187 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
188 cp_ref_qualifier rqual)
190 if (fntype == error_mark_node || ctype == error_mark_node)
191 return error_mark_node;
193 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
195 cp_cv_quals type_quals = quals & ~TYPE_QUAL_RESTRICT;
196 ctype = cp_build_qualified_type (ctype, type_quals);
198 tree newtype
199 = build_method_type_directly (ctype, TREE_TYPE (fntype),
200 (TREE_CODE (fntype) == METHOD_TYPE
201 ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
202 : TYPE_ARG_TYPES (fntype)));
203 if (tree attrs = TYPE_ATTRIBUTES (fntype))
204 newtype = cp_build_type_attribute_variant (newtype, attrs);
205 newtype = build_cp_fntype_variant (newtype, rqual,
206 TYPE_RAISES_EXCEPTIONS (fntype),
207 TYPE_HAS_LATE_RETURN_TYPE (fntype));
209 return newtype;
212 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
213 return type changed to NEW_RET. */
215 tree
216 change_return_type (tree new_ret, tree fntype)
218 if (new_ret == error_mark_node)
219 return fntype;
221 if (same_type_p (new_ret, TREE_TYPE (fntype)))
222 return fntype;
224 tree newtype;
225 tree args = TYPE_ARG_TYPES (fntype);
227 if (TREE_CODE (fntype) == FUNCTION_TYPE)
229 newtype = build_function_type (new_ret, args);
230 newtype = apply_memfn_quals (newtype,
231 type_memfn_quals (fntype));
233 else
234 newtype = build_method_type_directly
235 (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
237 if (tree attrs = TYPE_ATTRIBUTES (fntype))
238 newtype = cp_build_type_attribute_variant (newtype, attrs);
239 newtype = cxx_copy_lang_qualifiers (newtype, fntype);
241 return newtype;
244 /* Build a PARM_DECL of FN with NAME and TYPE, and set DECL_ARG_TYPE
245 appropriately. */
247 tree
248 cp_build_parm_decl (tree fn, tree name, tree type)
250 tree parm = build_decl (input_location,
251 PARM_DECL, name, type);
252 DECL_CONTEXT (parm) = fn;
254 /* DECL_ARG_TYPE is only used by the back end and the back end never
255 sees templates. */
256 if (!processing_template_decl)
257 DECL_ARG_TYPE (parm) = type_passed_as (type);
259 return parm;
262 /* Returns a PARM_DECL of FN for a parameter of the indicated TYPE, with the
263 indicated NAME. */
265 tree
266 build_artificial_parm (tree fn, tree name, tree type)
268 tree parm = cp_build_parm_decl (fn, name, type);
269 DECL_ARTIFICIAL (parm) = 1;
270 /* All our artificial parms are implicitly `const'; they cannot be
271 assigned to. */
272 TREE_READONLY (parm) = 1;
273 return parm;
276 /* Constructors for types with virtual baseclasses need an "in-charge" flag
277 saying whether this constructor is responsible for initialization of
278 virtual baseclasses or not. All destructors also need this "in-charge"
279 flag, which additionally determines whether or not the destructor should
280 free the memory for the object.
282 This function adds the "in-charge" flag to member function FN if
283 appropriate. It is called from grokclassfn and tsubst.
284 FN must be either a constructor or destructor.
286 The in-charge flag follows the 'this' parameter, and is followed by the
287 VTT parm (if any), then the user-written parms. */
289 void
290 maybe_retrofit_in_chrg (tree fn)
292 tree basetype, arg_types, parms, parm, fntype;
294 /* If we've already add the in-charge parameter don't do it again. */
295 if (DECL_HAS_IN_CHARGE_PARM_P (fn))
296 return;
298 /* When processing templates we can't know, in general, whether or
299 not we're going to have virtual baseclasses. */
300 if (processing_template_decl)
301 return;
303 /* We don't need an in-charge parameter for constructors that don't
304 have virtual bases. */
305 if (DECL_CONSTRUCTOR_P (fn)
306 && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
307 return;
309 arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
310 basetype = TREE_TYPE (TREE_VALUE (arg_types));
311 arg_types = TREE_CHAIN (arg_types);
313 parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
315 /* If this is a subobject constructor or destructor, our caller will
316 pass us a pointer to our VTT. */
317 if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
319 parm = build_artificial_parm (fn, vtt_parm_identifier, vtt_parm_type);
321 /* First add it to DECL_ARGUMENTS between 'this' and the real args... */
322 DECL_CHAIN (parm) = parms;
323 parms = parm;
325 /* ...and then to TYPE_ARG_TYPES. */
326 arg_types = hash_tree_chain (vtt_parm_type, arg_types);
328 DECL_HAS_VTT_PARM_P (fn) = 1;
331 /* Then add the in-charge parm (before the VTT parm). */
332 parm = build_artificial_parm (fn, in_charge_identifier, integer_type_node);
333 DECL_CHAIN (parm) = parms;
334 parms = parm;
335 arg_types = hash_tree_chain (integer_type_node, arg_types);
337 /* Insert our new parameter(s) into the list. */
338 DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
340 /* And rebuild the function type. */
341 fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
342 arg_types);
343 if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
344 fntype = (cp_build_type_attribute_variant
345 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
346 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (fn));
347 TREE_TYPE (fn) = fntype;
349 /* Now we've got the in-charge parameter. */
350 DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
353 /* Classes overload their constituent function names automatically.
354 When a function name is declared in a record structure,
355 its name is changed to it overloaded name. Since names for
356 constructors and destructors can conflict, we place a leading
357 '$' for destructors.
359 CNAME is the name of the class we are grokking for.
361 FUNCTION is a FUNCTION_DECL. It was created by `grokdeclarator'.
363 FLAGS contains bits saying what's special about today's
364 arguments. DTOR_FLAG == DESTRUCTOR.
366 If FUNCTION is a destructor, then we must add the `auto-delete' field
367 as a second parameter. There is some hair associated with the fact
368 that we must "declare" this variable in the manner consistent with the
369 way the rest of the arguments were declared.
371 QUALS are the qualifiers for the this pointer. */
373 void
374 grokclassfn (tree ctype, tree function, enum overload_flags flags)
376 tree fn_name = DECL_NAME (function);
378 /* Even within an `extern "C"' block, members get C++ linkage. See
379 [dcl.link] for details. */
380 SET_DECL_LANGUAGE (function, lang_cplusplus);
382 if (fn_name == NULL_TREE)
384 error ("name missing for member function");
385 fn_name = get_identifier ("<anonymous>");
386 DECL_NAME (function) = fn_name;
389 DECL_CONTEXT (function) = ctype;
391 if (flags == DTOR_FLAG)
392 DECL_CXX_DESTRUCTOR_P (function) = 1;
394 if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
395 maybe_retrofit_in_chrg (function);
398 /* Create an ARRAY_REF, checking for the user doing things backwards
399 along the way.
400 If INDEX_EXP is non-NULL, then that is the index expression,
401 otherwise INDEX_EXP_LIST is the list of index expressions. */
403 tree
404 grok_array_decl (location_t loc, tree array_expr, tree index_exp,
405 vec<tree, va_gc> **index_exp_list, tsubst_flags_t complain)
407 tree type;
408 tree expr;
409 tree orig_array_expr = array_expr;
410 tree orig_index_exp = index_exp;
411 vec<tree, va_gc> *orig_index_exp_list
412 = index_exp_list ? *index_exp_list : NULL;
413 tree overload = NULL_TREE;
415 if (error_operand_p (array_expr) || error_operand_p (index_exp))
416 return error_mark_node;
418 if (processing_template_decl)
420 if (type_dependent_expression_p (array_expr)
421 || (index_exp ? type_dependent_expression_p (index_exp)
422 : any_type_dependent_arguments_p (*index_exp_list)))
424 if (index_exp == NULL)
425 index_exp = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
426 *index_exp_list);
427 return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
428 NULL_TREE, NULL_TREE);
430 if (!index_exp)
431 orig_index_exp_list = make_tree_vector_copy (*index_exp_list);
434 type = TREE_TYPE (array_expr);
435 gcc_assert (type);
436 type = non_reference (type);
438 /* If they have an `operator[]', use that. */
439 if (MAYBE_CLASS_TYPE_P (type)
440 || (index_exp && MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
441 || (index_exp == NULL_TREE
442 && !(*index_exp_list)->is_empty ()
443 && MAYBE_CLASS_TYPE_P (TREE_TYPE ((*index_exp_list)->last ()))))
445 if (index_exp)
446 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
447 index_exp, NULL_TREE, NULL_TREE,
448 &overload, complain);
449 else if ((*index_exp_list)->is_empty ())
450 expr = build_op_subscript (loc, array_expr, index_exp_list, &overload,
451 complain);
452 else
454 expr = build_op_subscript (loc, array_expr, index_exp_list,
455 &overload, complain & tf_decltype);
456 if (expr == error_mark_node
457 /* Don't do the backward compatibility fallback in a SFINAE
458 context. */
459 && (complain & tf_error))
461 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
462 tf_none);
463 if (idx != error_mark_node)
464 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
465 idx, NULL_TREE, NULL_TREE, &overload,
466 complain & tf_decltype);
467 if (expr == error_mark_node)
469 overload = NULL_TREE;
470 expr = build_op_subscript (loc, array_expr, index_exp_list,
471 &overload, complain);
473 else
475 /* If it would be valid albeit deprecated expression in
476 C++20, just pedwarn on it and treat it as if wrapped
477 in (). */
478 pedwarn (loc, OPT_Wcomma_subscript,
479 "top-level comma expression in array subscript "
480 "changed meaning in C++23");
481 if (processing_template_decl)
483 orig_index_exp
484 = build_x_compound_expr_from_vec (orig_index_exp_list,
485 NULL, complain);
486 if (orig_index_exp == error_mark_node)
487 expr = error_mark_node;
488 release_tree_vector (orig_index_exp_list);
494 else
496 tree p1, p2, i1, i2;
497 bool swapped = false;
499 /* Otherwise, create an ARRAY_REF for a pointer or array type.
500 It is a little-known fact that, if `a' is an array and `i' is
501 an int, you can write `i[a]', which means the same thing as
502 `a[i]'. */
503 if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
504 p1 = array_expr;
505 else
506 p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
508 if (index_exp == NULL_TREE)
510 if (!(complain & tf_error))
511 /* Don't do the backward compatibility fallback in a SFINAE
512 context. */
513 return error_mark_node;
515 if ((*index_exp_list)->is_empty ())
517 error_at (loc, "built-in subscript operator without expression "
518 "list");
519 return error_mark_node;
521 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
522 tf_none);
523 if (idx != error_mark_node)
524 /* If it would be valid albeit deprecated expression in C++20,
525 just pedwarn on it and treat it as if wrapped in (). */
526 pedwarn (loc, OPT_Wcomma_subscript,
527 "top-level comma expression in array subscript "
528 "changed meaning in C++23");
529 else
531 error_at (loc, "built-in subscript operator with more than one "
532 "expression in expression list");
533 return error_mark_node;
535 index_exp = idx;
536 if (processing_template_decl)
538 orig_index_exp
539 = build_x_compound_expr_from_vec (orig_index_exp_list,
540 NULL, complain);
541 release_tree_vector (orig_index_exp_list);
542 if (orig_index_exp == error_mark_node)
543 return error_mark_node;
547 if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
548 p2 = index_exp;
549 else
550 p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
552 i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
553 false);
554 i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
555 false);
557 if ((p1 && i2) && (i1 && p2))
558 error ("ambiguous conversion for array subscript");
560 if (p1 && i2)
561 array_expr = p1, index_exp = i2;
562 else if (i1 && p2)
563 swapped = true, array_expr = p2, index_exp = i1;
564 else
566 if (complain & tf_error)
567 error_at (loc, "invalid types %<%T[%T]%> for array subscript",
568 type, TREE_TYPE (index_exp));
569 return error_mark_node;
572 if (array_expr == error_mark_node || index_exp == error_mark_node)
573 error ("ambiguous conversion for array subscript");
575 if (TYPE_PTR_P (TREE_TYPE (array_expr)))
576 array_expr = mark_rvalue_use (array_expr);
577 else
578 array_expr = mark_lvalue_use_nonread (array_expr);
579 index_exp = mark_rvalue_use (index_exp);
580 if (swapped
581 && flag_strong_eval_order == 2
582 && (TREE_SIDE_EFFECTS (array_expr) || TREE_SIDE_EFFECTS (index_exp)))
583 expr = build_array_ref (input_location, index_exp, array_expr);
584 else
585 expr = build_array_ref (input_location, array_expr, index_exp);
587 if (processing_template_decl && expr != error_mark_node)
589 if (overload != NULL_TREE)
591 if (orig_index_exp == NULL_TREE)
593 expr = build_min_non_dep_op_overload (expr, overload,
594 orig_array_expr,
595 orig_index_exp_list);
596 release_tree_vector (orig_index_exp_list);
597 return expr;
599 return build_min_non_dep_op_overload (ARRAY_REF, expr, overload,
600 orig_array_expr,
601 orig_index_exp);
604 if (orig_index_exp == NULL_TREE)
606 orig_index_exp
607 = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
608 orig_index_exp_list);
609 release_tree_vector (orig_index_exp_list);
612 return build_min_non_dep (ARRAY_REF, expr, orig_array_expr,
613 orig_index_exp, NULL_TREE, NULL_TREE);
615 return expr;
618 /* Given the cast expression EXP, checking out its validity. Either return
619 an error_mark_node if there was an unavoidable error, return a cast to
620 void for trying to delete a pointer w/ the value 0, or return the
621 call to delete. If DOING_VEC is true, we handle things differently
622 for doing an array delete.
623 Implements ARM $5.3.4. This is called from the parser. */
625 tree
626 delete_sanity (location_t loc, tree exp, tree size, bool doing_vec,
627 int use_global_delete, tsubst_flags_t complain)
629 tree t, type;
631 if (exp == error_mark_node)
632 return exp;
634 if (processing_template_decl)
636 t = build_min (DELETE_EXPR, void_type_node, exp, size);
637 DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
638 DELETE_EXPR_USE_VEC (t) = doing_vec;
639 TREE_SIDE_EFFECTS (t) = 1;
640 SET_EXPR_LOCATION (t, loc);
641 return t;
644 location_t exp_loc = cp_expr_loc_or_loc (exp, loc);
646 /* An array can't have been allocated by new, so complain. */
647 if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
648 && (complain & tf_warning))
649 warning_at (exp_loc, 0, "deleting array %q#E", exp);
651 t = build_expr_type_conversion (WANT_POINTER, exp, true);
653 if (t == NULL_TREE || t == error_mark_node)
655 if (complain & tf_error)
656 error_at (exp_loc,
657 "type %q#T argument given to %<delete%>, expected pointer",
658 TREE_TYPE (exp));
659 return error_mark_node;
662 type = TREE_TYPE (t);
664 /* As of Valley Forge, you can delete a pointer to const. */
666 /* You can't delete functions. */
667 if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
669 if (complain & tf_error)
670 error_at (exp_loc,
671 "cannot delete a function. Only pointer-to-objects are "
672 "valid arguments to %<delete%>");
673 return error_mark_node;
676 /* Deleting ptr to void is undefined behavior [expr.delete/3]. */
677 if (VOID_TYPE_P (TREE_TYPE (type)))
679 if (complain & tf_warning)
680 warning_at (exp_loc, OPT_Wdelete_incomplete,
681 "deleting %qT is undefined", type);
682 doing_vec = 0;
685 /* Deleting a pointer with the value zero is valid and has no effect. */
686 if (integer_zerop (t))
687 return build1_loc (loc, NOP_EXPR, void_type_node, t);
689 if (doing_vec)
690 return build_vec_delete (loc, t, /*maxindex=*/NULL_TREE,
691 sfk_deleting_destructor,
692 use_global_delete, complain);
693 else
694 return build_delete (loc, type, t, sfk_deleting_destructor,
695 LOOKUP_NORMAL, use_global_delete,
696 complain);
699 /* Report an error if the indicated template declaration is not the
700 sort of thing that should be a member template. */
702 void
703 check_member_template (tree tmpl)
705 tree decl;
707 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
708 decl = DECL_TEMPLATE_RESULT (tmpl);
710 if (TREE_CODE (decl) == FUNCTION_DECL
711 || DECL_ALIAS_TEMPLATE_P (tmpl)
712 || (TREE_CODE (decl) == TYPE_DECL
713 && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
715 /* The parser rejects template declarations in local classes
716 (with the exception of generic lambdas). */
717 gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
718 /* The parser rejects any use of virtual in a function template. */
719 gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
720 && DECL_VIRTUAL_P (decl)));
722 /* The debug-information generating code doesn't know what to do
723 with member templates. */
724 DECL_IGNORED_P (tmpl) = 1;
726 else if (variable_template_p (tmpl))
727 /* OK */;
728 else
729 error ("template declaration of %q#D", decl);
732 /* Sanity check: report error if this function FUNCTION is not
733 really a member of the class (CTYPE) it is supposed to belong to.
734 TEMPLATE_PARMS is used to specify the template parameters of a member
735 template passed as FUNCTION_DECL. If the member template is passed as a
736 TEMPLATE_DECL, it can be NULL since the parameters can be extracted
737 from the declaration. If the function is not a function template, it
738 must be NULL.
739 It returns the original declaration for the function, NULL_TREE if
740 no declaration was found, error_mark_node if an error was emitted. */
742 tree
743 check_classfn (tree ctype, tree function, tree template_parms)
745 if (DECL_USE_TEMPLATE (function)
746 && !(TREE_CODE (function) == TEMPLATE_DECL
747 && DECL_TEMPLATE_SPECIALIZATION (function))
748 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
749 /* Since this is a specialization of a member template,
750 we're not going to find the declaration in the class.
751 For example, in:
753 struct S { template <typename T> void f(T); };
754 template <> void S::f(int);
756 we're not going to find `S::f(int)', but there's no
757 reason we should, either. We let our callers know we didn't
758 find the method, but we don't complain. */
759 return NULL_TREE;
761 /* Basic sanity check: for a template function, the template parameters
762 either were not passed, or they are the same of DECL_TEMPLATE_PARMS. */
763 if (TREE_CODE (function) == TEMPLATE_DECL)
765 if (template_parms
766 && !comp_template_parms (template_parms,
767 DECL_TEMPLATE_PARMS (function)))
769 error ("template parameter lists provided don%'t match the "
770 "template parameters of %qD", function);
771 return error_mark_node;
773 template_parms = DECL_TEMPLATE_PARMS (function);
776 /* OK, is this a definition of a member template? */
777 bool is_template = (template_parms != NULL_TREE);
779 /* [temp.mem]
781 A destructor shall not be a member template. */
782 if (DECL_DESTRUCTOR_P (function) && is_template)
784 error ("destructor %qD declared as member template", function);
785 return error_mark_node;
788 /* We must enter the scope here, because conversion operators are
789 named by target type, and type equivalence relies on typenames
790 resolving within the scope of CTYPE. */
791 tree pushed_scope = push_scope (ctype);
792 tree matched = NULL_TREE;
793 tree fns = get_class_binding (ctype, DECL_NAME (function));
794 bool saw_template = false;
796 for (ovl_iterator iter (fns); !matched && iter; ++iter)
798 tree fndecl = *iter;
800 if (TREE_CODE (fndecl) == TEMPLATE_DECL)
801 saw_template = true;
803 /* A member template definition only matches a member template
804 declaration. */
805 if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
806 continue;
808 if (!DECL_DECLARES_FUNCTION_P (fndecl))
809 continue;
811 tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
812 tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
814 /* We cannot simply call decls_match because this doesn't work
815 for static member functions that are pretending to be
816 methods, and because the name may have been changed by
817 asm("new_name"). */
819 /* Get rid of the this parameter on functions that become
820 static. */
821 if (DECL_STATIC_FUNCTION_P (fndecl)
822 && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
823 p1 = TREE_CHAIN (p1);
825 /* ref-qualifier or absence of same must match. */
826 if (type_memfn_rqual (TREE_TYPE (function))
827 != type_memfn_rqual (TREE_TYPE (fndecl)))
828 continue;
830 // Include constraints in the match.
831 tree c1 = get_constraints (function);
832 tree c2 = get_constraints (fndecl);
834 /* While finding a match, same types and params are not enough
835 if the function is versioned. Also check version ("target")
836 attributes. */
837 if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
838 TREE_TYPE (TREE_TYPE (fndecl)))
839 && compparms (p1, p2)
840 && !targetm.target_option.function_versions (function, fndecl)
841 && (!is_template
842 || comp_template_parms (template_parms,
843 DECL_TEMPLATE_PARMS (fndecl)))
844 && equivalent_constraints (c1, c2)
845 && (DECL_TEMPLATE_SPECIALIZATION (function)
846 == DECL_TEMPLATE_SPECIALIZATION (fndecl))
847 && (!DECL_TEMPLATE_SPECIALIZATION (function)
848 || (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl))))
849 matched = fndecl;
852 if (!matched && !is_template && saw_template
853 && !processing_template_decl && DECL_UNIQUE_FRIEND_P (function))
855 /* "[if no non-template match is found,] each remaining function template
856 is replaced with the specialization chosen by deduction from the
857 friend declaration or discarded if deduction fails."
859 So tell check_explicit_specialization to look for a match. */
860 SET_DECL_IMPLICIT_INSTANTIATION (function);
861 DECL_TEMPLATE_INFO (function) = build_template_info (fns, NULL_TREE);
862 matched = function;
865 if (!matched)
867 if (!COMPLETE_TYPE_P (ctype))
868 cxx_incomplete_type_error (DECL_SOURCE_LOCATION (function),
869 function, ctype);
870 else
872 if (DECL_CONV_FN_P (function))
873 fns = get_class_binding (ctype, conv_op_identifier);
875 error_at (DECL_SOURCE_LOCATION (function),
876 "no declaration matches %q#D", function);
877 if (fns)
878 print_candidates (fns);
879 else if (DECL_CONV_FN_P (function))
880 inform (DECL_SOURCE_LOCATION (function),
881 "no conversion operators declared");
882 else
883 inform (DECL_SOURCE_LOCATION (function),
884 "no functions named %qD", function);
885 inform (DECL_SOURCE_LOCATION (TYPE_NAME (ctype)),
886 "%#qT defined here", ctype);
888 matched = error_mark_node;
891 if (pushed_scope)
892 pop_scope (pushed_scope);
894 return matched;
897 /* DECL is a function with vague linkage. Remember it so that at the
898 end of the translation unit we can decide whether or not to emit
899 it. */
901 void
902 note_vague_linkage_fn (tree decl)
904 if (processing_template_decl)
905 return;
907 DECL_DEFER_OUTPUT (decl) = 1;
908 vec_safe_push (deferred_fns, decl);
911 /* As above, but for variable template instantiations. */
913 void
914 note_variable_template_instantiation (tree decl)
916 vec_safe_push (pending_statics, decl);
919 /* We have just processed the DECL, which is a static data member.
920 The other parameters are as for cp_finish_decl. */
922 void
923 finish_static_data_member_decl (tree decl,
924 tree init, bool init_const_expr_p,
925 tree asmspec_tree,
926 int flags)
928 if (DECL_TEMPLATE_INSTANTIATED (decl))
929 /* We already needed to instantiate this, so the processing in this
930 function is unnecessary/wrong. */
931 return;
933 DECL_CONTEXT (decl) = current_class_type;
935 /* We cannot call pushdecl here, because that would fill in the
936 TREE_CHAIN of our decl. Instead, we modify cp_finish_decl to do
937 the right thing, namely, to put this decl out straight away. */
939 if (! processing_template_decl)
940 vec_safe_push (pending_statics, decl);
942 if (LOCAL_CLASS_P (current_class_type)
943 /* We already complained about the template definition. */
944 && !DECL_TEMPLATE_INSTANTIATION (decl))
945 permerror (DECL_SOURCE_LOCATION (decl),
946 "local class %q#T shall not have static data member %q#D",
947 current_class_type, decl);
948 else
949 for (tree t = current_class_type; TYPE_P (t);
950 t = CP_TYPE_CONTEXT (t))
951 if (TYPE_UNNAMED_P (t))
953 auto_diagnostic_group d;
954 if (permerror (DECL_SOURCE_LOCATION (decl),
955 "static data member %qD in unnamed class", decl))
956 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
957 "unnamed class defined here");
958 break;
961 if (DECL_INLINE_VAR_P (decl) && !DECL_TEMPLATE_INSTANTIATION (decl))
962 /* An inline variable is immediately defined, so don't set DECL_IN_AGGR_P.
963 Except that if decl is a template instantiation, it isn't defined until
964 instantiate_decl. */;
965 else
966 DECL_IN_AGGR_P (decl) = 1;
968 if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
969 && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
970 SET_VAR_HAD_UNKNOWN_BOUND (decl);
972 if (init)
974 /* Similarly to start_decl_1, we want to complete the type in order
975 to do the right thing in cp_apply_type_quals_to_decl, possibly
976 clear TYPE_QUAL_CONST (c++/65579). */
977 tree type = TREE_TYPE (decl) = complete_type (TREE_TYPE (decl));
978 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
981 cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
984 /* DECLARATOR and DECLSPECS correspond to a class member. The other
985 parameters are as for cp_finish_decl. Return the DECL for the
986 class member declared. */
988 tree
989 grokfield (const cp_declarator *declarator,
990 cp_decl_specifier_seq *declspecs,
991 tree init, bool init_const_expr_p,
992 tree asmspec_tree,
993 tree attrlist)
995 tree value;
996 const char *asmspec = 0;
997 int flags;
999 if (init
1000 && TREE_CODE (init) == TREE_LIST
1001 && TREE_VALUE (init) == error_mark_node
1002 && TREE_CHAIN (init) == NULL_TREE)
1003 init = NULL_TREE;
1005 int initialized;
1006 if (init == ridpointers[(int)RID_DELETE])
1007 initialized = SD_DELETED;
1008 else if (init == ridpointers[(int)RID_DEFAULT])
1009 initialized = SD_DEFAULTED;
1010 else if (init)
1011 initialized = SD_INITIALIZED;
1012 else
1013 initialized = SD_UNINITIALIZED;
1015 value = grokdeclarator (declarator, declspecs, FIELD, initialized, &attrlist);
1016 if (! value || value == error_mark_node)
1017 /* friend or constructor went bad. */
1018 return error_mark_node;
1019 if (TREE_TYPE (value) == error_mark_node)
1020 return value;
1022 if (TREE_CODE (value) == TYPE_DECL && init)
1024 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value)),
1025 "typedef %qD is initialized (use %qs instead)",
1026 value, "decltype");
1027 init = NULL_TREE;
1030 /* Pass friendly classes back. */
1031 if (value == void_type_node)
1032 return value;
1034 if (DECL_NAME (value)
1035 && TREE_CODE (DECL_NAME (value)) == TEMPLATE_ID_EXPR)
1037 error_at (declarator->id_loc,
1038 "explicit template argument list not allowed");
1039 return error_mark_node;
1042 /* Stash away type declarations. */
1043 if (TREE_CODE (value) == TYPE_DECL)
1045 DECL_NONLOCAL (value) = 1;
1046 DECL_CONTEXT (value) = current_class_type;
1048 if (attrlist)
1050 int attrflags = 0;
1052 /* If this is a typedef that names the class for linkage purposes
1053 (7.1.3p8), apply any attributes directly to the type. */
1054 if (OVERLOAD_TYPE_P (TREE_TYPE (value))
1055 && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
1056 attrflags = ATTR_FLAG_TYPE_IN_PLACE;
1058 cplus_decl_attributes (&value, attrlist, attrflags);
1061 if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
1062 && TREE_TYPE (value) != error_mark_node
1063 && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
1064 set_underlying_type (value);
1066 /* It's important that push_template_decl below follows
1067 set_underlying_type above so that the created template
1068 carries the properly set type of VALUE. */
1069 if (processing_template_decl)
1070 value = push_template_decl (value);
1072 record_locally_defined_typedef (value);
1073 return value;
1076 int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
1078 if (!friendp && DECL_IN_AGGR_P (value))
1080 error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
1081 return void_type_node;
1084 if (asmspec_tree && asmspec_tree != error_mark_node)
1085 asmspec = TREE_STRING_POINTER (asmspec_tree);
1087 if (init)
1089 if (TREE_CODE (value) == FUNCTION_DECL)
1091 if (init == ridpointers[(int)RID_DELETE])
1093 DECL_DELETED_FN (value) = 1;
1094 DECL_DECLARED_INLINE_P (value) = 1;
1096 else if (init == ridpointers[(int)RID_DEFAULT])
1098 if (defaultable_fn_check (value))
1100 DECL_DEFAULTED_FN (value) = 1;
1101 DECL_INITIALIZED_IN_CLASS_P (value) = 1;
1102 DECL_DECLARED_INLINE_P (value) = 1;
1103 /* grokfndecl set this to error_mark_node, but we want to
1104 leave it unset until synthesize_method. */
1105 DECL_INITIAL (value) = NULL_TREE;
1108 else if (TREE_CODE (init) == DEFERRED_PARSE)
1109 error ("invalid initializer for member function %qD", value);
1110 else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
1112 if (integer_zerop (init))
1113 DECL_PURE_VIRTUAL_P (value) = 1;
1114 else if (error_operand_p (init))
1115 ; /* An error has already been reported. */
1116 else
1117 error ("invalid initializer for member function %qD",
1118 value);
1120 else
1122 gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
1123 location_t iloc
1124 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value));
1125 if (friendp)
1126 error_at (iloc, "initializer specified for friend "
1127 "function %qD", value);
1128 else
1129 error_at (iloc, "initializer specified for static "
1130 "member function %qD", value);
1133 else if (TREE_CODE (value) == FIELD_DECL)
1134 /* C++11 NSDMI, keep going. */;
1135 else if (!VAR_P (value))
1136 gcc_unreachable ();
1139 /* Pass friend decls back. */
1140 if ((TREE_CODE (value) == FUNCTION_DECL
1141 || TREE_CODE (value) == TEMPLATE_DECL)
1142 && DECL_CONTEXT (value) != current_class_type)
1144 if (attrlist)
1145 cplus_decl_attributes (&value, attrlist, 0);
1146 return value;
1149 /* Need to set this before push_template_decl. */
1150 if (VAR_P (value))
1151 DECL_CONTEXT (value) = current_class_type;
1153 if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
1155 value = push_template_decl (value);
1156 if (error_operand_p (value))
1157 return error_mark_node;
1160 if (attrlist)
1161 cplus_decl_attributes (&value, attrlist, 0);
1163 if (init && DIRECT_LIST_INIT_P (init))
1164 flags = LOOKUP_NORMAL;
1165 else
1166 flags = LOOKUP_IMPLICIT;
1168 switch (TREE_CODE (value))
1170 case VAR_DECL:
1171 finish_static_data_member_decl (value, init, init_const_expr_p,
1172 asmspec_tree, flags);
1173 return value;
1175 case FIELD_DECL:
1176 if (asmspec)
1177 error ("%<asm%> specifiers are not permitted on non-static data members");
1178 if (DECL_INITIAL (value) == error_mark_node)
1179 init = error_mark_node;
1180 cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1181 NULL_TREE, flags);
1182 DECL_IN_AGGR_P (value) = 1;
1183 return value;
1185 case FUNCTION_DECL:
1186 if (asmspec)
1187 set_user_assembler_name (value, asmspec);
1189 cp_finish_decl (value,
1190 /*init=*/NULL_TREE,
1191 /*init_const_expr_p=*/false,
1192 asmspec_tree, flags);
1194 /* Pass friends back this way. */
1195 if (DECL_UNIQUE_FRIEND_P (value))
1196 return void_type_node;
1198 DECL_IN_AGGR_P (value) = 1;
1199 return value;
1201 default:
1202 gcc_unreachable ();
1204 return NULL_TREE;
1207 /* Like `grokfield', but for bitfields.
1208 WIDTH is the width of the bitfield, a constant expression.
1209 The other parameters are as for grokfield. */
1211 tree
1212 grokbitfield (const cp_declarator *declarator,
1213 cp_decl_specifier_seq *declspecs, tree width, tree init,
1214 tree attrlist)
1216 tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1217 init != NULL_TREE, &attrlist);
1219 if (value == error_mark_node)
1220 return NULL_TREE; /* friends went bad. */
1222 tree type = TREE_TYPE (value);
1223 if (type == error_mark_node)
1224 return value;
1226 /* Pass friendly classes back. */
1227 if (VOID_TYPE_P (value))
1228 return void_type_node;
1230 if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type)
1231 && (INDIRECT_TYPE_P (type) || !dependent_type_p (type)))
1233 error_at (DECL_SOURCE_LOCATION (value),
1234 "bit-field %qD with non-integral type %qT",
1235 value, type);
1236 return error_mark_node;
1239 if (TREE_CODE (value) == TYPE_DECL)
1241 error_at (DECL_SOURCE_LOCATION (value),
1242 "cannot declare %qD to be a bit-field type", value);
1243 return NULL_TREE;
1246 /* Usually, finish_struct_1 catches bitfields with invalid types.
1247 But, in the case of bitfields with function type, we confuse
1248 ourselves into thinking they are member functions, so we must
1249 check here. */
1250 if (TREE_CODE (value) == FUNCTION_DECL)
1252 error_at (DECL_SOURCE_LOCATION (value),
1253 "cannot declare bit-field %qD with function type", value);
1254 return NULL_TREE;
1257 if (TYPE_WARN_IF_NOT_ALIGN (type))
1259 error_at (DECL_SOURCE_LOCATION (value), "cannot declare bit-field "
1260 "%qD with %<warn_if_not_aligned%> type", value);
1261 return NULL_TREE;
1264 if (DECL_IN_AGGR_P (value))
1266 error ("%qD is already defined in the class %qT", value,
1267 DECL_CONTEXT (value));
1268 return void_type_node;
1271 if (TREE_STATIC (value))
1273 error_at (DECL_SOURCE_LOCATION (value),
1274 "static member %qD cannot be a bit-field", value);
1275 return NULL_TREE;
1278 int flags = LOOKUP_IMPLICIT;
1279 if (init && DIRECT_LIST_INIT_P (init))
1280 flags = LOOKUP_NORMAL;
1281 cp_finish_decl (value, init, false, NULL_TREE, flags);
1283 if (width != error_mark_node)
1285 /* The width must be an integer type. */
1286 if (!type_dependent_expression_p (width)
1287 && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1288 error ("width of bit-field %qD has non-integral type %qT", value,
1289 TREE_TYPE (width));
1290 else if (!check_for_bare_parameter_packs (width))
1292 /* Temporarily stash the width in DECL_BIT_FIELD_REPRESENTATIVE.
1293 check_bitfield_decl picks it from there later and sets DECL_SIZE
1294 accordingly. */
1295 DECL_BIT_FIELD_REPRESENTATIVE (value) = width;
1296 SET_DECL_C_BIT_FIELD (value);
1300 DECL_IN_AGGR_P (value) = 1;
1302 if (attrlist)
1303 cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1305 return value;
1309 /* Returns true iff ATTR is an attribute which needs to be applied at
1310 instantiation time rather than template definition time. */
1312 static bool
1313 is_late_template_attribute (tree attr, tree decl)
1315 tree name = get_attribute_name (attr);
1316 tree args = TREE_VALUE (attr);
1317 const struct attribute_spec *spec = lookup_attribute_spec (name);
1318 tree arg;
1320 if (!spec)
1321 /* Unknown attribute. */
1322 return false;
1324 /* Attribute weak handling wants to write out assembly right away. */
1325 if (is_attribute_p ("weak", name))
1326 return true;
1328 /* Attributes used and unused are applied directly to typedefs for the
1329 benefit of maybe_warn_unused_local_typedefs. */
1330 if (TREE_CODE (decl) == TYPE_DECL
1331 && (is_attribute_p ("unused", name)
1332 || is_attribute_p ("used", name)))
1333 return false;
1335 /* Attribute tls_model wants to modify the symtab. */
1336 if (is_attribute_p ("tls_model", name))
1337 return true;
1339 /* #pragma omp declare simd attribute needs to be always deferred. */
1340 if (flag_openmp
1341 && is_attribute_p ("omp declare simd", name))
1342 return true;
1344 if (args == error_mark_node)
1345 return false;
1347 /* An attribute pack is clearly dependent. */
1348 if (args && PACK_EXPANSION_P (args))
1349 return true;
1351 /* If any of the arguments are dependent expressions, we can't evaluate
1352 the attribute until instantiation time. */
1353 for (arg = args; arg; arg = TREE_CHAIN (arg))
1355 tree t = TREE_VALUE (arg);
1357 /* If the first attribute argument is an identifier, only consider
1358 second and following arguments. Attributes like mode, format,
1359 cleanup and several target specific attributes aren't late
1360 just because they have an IDENTIFIER_NODE as first argument. */
1361 if (arg == args && attribute_takes_identifier_p (name)
1362 && identifier_p (t))
1363 continue;
1365 if (value_dependent_expression_p (t))
1366 return true;
1369 if (TREE_CODE (decl) == TYPE_DECL
1370 || TYPE_P (decl)
1371 || spec->type_required)
1373 tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1375 if (!type)
1376 return true;
1378 /* We can't apply any attributes to a completely unknown type until
1379 instantiation time. */
1380 enum tree_code code = TREE_CODE (type);
1381 if (code == TEMPLATE_TYPE_PARM
1382 || code == BOUND_TEMPLATE_TEMPLATE_PARM
1383 || code == TYPENAME_TYPE)
1384 return true;
1385 /* Also defer most attributes on dependent types. This is not
1386 necessary in all cases, but is the better default. */
1387 else if (dependent_type_p (type)
1388 /* But some attributes specifically apply to templates. */
1389 && !is_attribute_p ("abi_tag", name)
1390 && !is_attribute_p ("deprecated", name)
1391 && !is_attribute_p ("unavailable", name)
1392 && !is_attribute_p ("visibility", name))
1393 return true;
1394 else
1395 return false;
1397 else
1398 return false;
1401 /* ATTR_P is a list of attributes. Remove any attributes which need to be
1402 applied at instantiation time and return them. If IS_DEPENDENT is true,
1403 the declaration itself is dependent, so all attributes should be applied
1404 at instantiation time. */
1406 tree
1407 splice_template_attributes (tree *attr_p, tree decl)
1409 tree *p = attr_p;
1410 tree late_attrs = NULL_TREE;
1411 tree *q = &late_attrs;
1413 if (!p || *p == error_mark_node)
1414 return NULL_TREE;
1416 for (; *p; )
1418 if (is_late_template_attribute (*p, decl))
1420 ATTR_IS_DEPENDENT (*p) = 1;
1421 *q = *p;
1422 *p = TREE_CHAIN (*p);
1423 q = &TREE_CHAIN (*q);
1424 *q = NULL_TREE;
1426 else
1427 p = &TREE_CHAIN (*p);
1430 return late_attrs;
1433 /* Attach any LATE_ATTRS to DECL_P, after the non-dependent attributes have
1434 been applied by a previous call to decl_attributes. */
1436 static void
1437 save_template_attributes (tree late_attrs, tree *decl_p, int flags)
1439 tree *q;
1441 if (!late_attrs)
1442 return;
1444 if (DECL_P (*decl_p))
1445 q = &DECL_ATTRIBUTES (*decl_p);
1446 else
1447 q = &TYPE_ATTRIBUTES (*decl_p);
1449 tree old_attrs = *q;
1451 /* Place the late attributes at the beginning of the attribute
1452 list. */
1453 late_attrs = chainon (late_attrs, *q);
1454 if (*q != late_attrs
1455 && !DECL_P (*decl_p)
1456 && !(flags & ATTR_FLAG_TYPE_IN_PLACE))
1458 if (!dependent_type_p (*decl_p))
1459 *decl_p = cp_build_type_attribute_variant (*decl_p, late_attrs);
1460 else
1462 *decl_p = build_variant_type_copy (*decl_p);
1463 TYPE_ATTRIBUTES (*decl_p) = late_attrs;
1466 else
1467 *q = late_attrs;
1469 if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1471 /* We've added new attributes directly to the main variant, so
1472 now we need to update all of the other variants to include
1473 these new attributes. */
1474 tree variant;
1475 for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1476 variant = TYPE_NEXT_VARIANT (variant))
1478 gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1479 TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1484 /* True if ATTRS contains any dependent attributes that affect type
1485 identity. */
1487 bool
1488 any_dependent_type_attributes_p (tree attrs)
1490 for (tree a = attrs; a; a = TREE_CHAIN (a))
1491 if (ATTR_IS_DEPENDENT (a))
1493 const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (a));
1494 if (as && as->affects_type_identity)
1495 return true;
1497 return false;
1500 /* Return true iff ATTRS are acceptable attributes to be applied in-place
1501 to a typedef which gives a previously unnamed class or enum a name for
1502 linkage purposes. */
1504 bool
1505 attributes_naming_typedef_ok (tree attrs)
1507 for (; attrs; attrs = TREE_CHAIN (attrs))
1509 tree name = get_attribute_name (attrs);
1510 if (is_attribute_p ("vector_size", name))
1511 return false;
1513 return true;
1516 /* Like reconstruct_complex_type, but handle also template trees. */
1518 tree
1519 cp_reconstruct_complex_type (tree type, tree bottom)
1521 tree inner, outer;
1523 if (TYPE_PTR_P (type))
1525 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1526 outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1527 TYPE_REF_CAN_ALIAS_ALL (type));
1529 else if (TYPE_REF_P (type))
1531 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1532 outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1533 TYPE_REF_CAN_ALIAS_ALL (type));
1535 else if (TREE_CODE (type) == ARRAY_TYPE)
1537 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1538 outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1539 /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1540 element type qualification will be handled by the recursive
1541 cp_reconstruct_complex_type call and cp_build_qualified_type
1542 for ARRAY_TYPEs changes the element type. */
1543 return outer;
1545 else if (TREE_CODE (type) == FUNCTION_TYPE)
1547 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1548 outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1549 outer = apply_memfn_quals (outer, type_memfn_quals (type));
1551 else if (TREE_CODE (type) == METHOD_TYPE)
1553 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1554 /* The build_method_type_directly() routine prepends 'this' to argument list,
1555 so we must compensate by getting rid of it. */
1556 outer
1557 = build_method_type_directly
1558 (class_of_this_parm (type), inner,
1559 TREE_CHAIN (TYPE_ARG_TYPES (type)));
1561 else if (TREE_CODE (type) == OFFSET_TYPE)
1563 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1564 outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1566 else
1567 return bottom;
1569 if (TYPE_ATTRIBUTES (type))
1570 outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1571 outer = cp_build_qualified_type (outer, cp_type_quals (type));
1572 outer = cxx_copy_lang_qualifiers (outer, type);
1574 return outer;
1577 /* Replaces any constexpr expression that may be into the attributes
1578 arguments with their reduced value. */
1580 void
1581 cp_check_const_attributes (tree attributes)
1583 if (attributes == error_mark_node)
1584 return;
1586 tree attr;
1587 for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1589 if (cxx_contract_attribute_p (attr))
1590 continue;
1592 tree arg;
1593 /* As we implement alignas using gnu::aligned attribute and
1594 alignas argument is a constant expression, force manifestly
1595 constant evaluation of aligned attribute argument. */
1596 bool manifestly_const_eval
1597 = is_attribute_p ("aligned", get_attribute_name (attr));
1598 for (arg = TREE_VALUE (attr); arg && TREE_CODE (arg) == TREE_LIST;
1599 arg = TREE_CHAIN (arg))
1601 tree expr = TREE_VALUE (arg);
1602 if (EXPR_P (expr))
1603 TREE_VALUE (arg)
1604 = fold_non_dependent_expr (expr, tf_warning_or_error,
1605 manifestly_const_eval);
1610 /* Copies hot or cold attributes to a function FN if present on the
1611 encapsulating class, struct, or union TYPE. */
1613 void
1614 maybe_propagate_warmth_attributes (tree fn, tree type)
1616 if (fn == NULL_TREE || type == NULL_TREE
1617 || !(TREE_CODE (type) == RECORD_TYPE
1618 || TREE_CODE (type) == UNION_TYPE))
1619 return;
1621 tree has_cold_attr = lookup_attribute ("cold", TYPE_ATTRIBUTES (type));
1622 tree has_hot_attr = lookup_attribute ("hot", TYPE_ATTRIBUTES (type));
1624 if (has_cold_attr || has_hot_attr)
1626 /* Transparently ignore the new warmth attribute if it
1627 conflicts with a present function attribute. Otherwise
1628 decl_attribute would still honour the present attribute,
1629 but producing an undesired warning in the process. */
1631 if (has_cold_attr)
1633 if (lookup_attribute ("hot", DECL_ATTRIBUTES (fn)) == NULL)
1635 tree cold_cons
1636 = tree_cons (get_identifier ("cold"), NULL, NULL);
1638 decl_attributes (&fn, cold_cons, 0);
1641 else if (has_hot_attr)
1643 if (lookup_attribute ("cold", DECL_ATTRIBUTES (fn)) == NULL)
1645 tree hot_cons
1646 = tree_cons (get_identifier ("hot"), NULL, NULL);
1648 decl_attributes (&fn, hot_cons, 0);
1654 /* Return the last pushed declaration for the symbol DECL or NULL
1655 when no such declaration exists. */
1657 static tree
1658 find_last_decl (tree decl)
1660 tree last_decl = NULL_TREE;
1662 if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
1664 /* Template specializations are matched elsewhere. */
1665 if (DECL_LANG_SPECIFIC (decl)
1666 && DECL_USE_TEMPLATE (decl))
1667 return NULL_TREE;
1669 /* Look up the declaration in its scope. */
1670 tree pushed_scope = NULL_TREE;
1671 if (tree ctype = DECL_CONTEXT (decl))
1672 pushed_scope = push_scope (ctype);
1674 last_decl = lookup_name (name);
1676 if (pushed_scope)
1677 pop_scope (pushed_scope);
1679 /* The declaration may be a member conversion operator
1680 or a bunch of overfloads (handle the latter below). */
1681 if (last_decl && BASELINK_P (last_decl))
1682 last_decl = BASELINK_FUNCTIONS (last_decl);
1685 if (!last_decl)
1686 return NULL_TREE;
1688 if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
1690 /* A set of overloads of the same function. */
1691 for (lkp_iterator iter (last_decl); iter; ++iter)
1693 if (TREE_CODE (*iter) == OVERLOAD)
1694 continue;
1696 tree d = *iter;
1698 /* We can't compare versions in the middle of processing the
1699 attribute that has the version. */
1700 if (TREE_CODE (d) == FUNCTION_DECL
1701 && DECL_FUNCTION_VERSIONED (d))
1702 return NULL_TREE;
1704 if (decls_match (decl, d, /*record_decls=*/false))
1705 return d;
1707 return NULL_TREE;
1710 return NULL_TREE;
1713 /* Like decl_attributes, but handle C++ complexity. */
1715 void
1716 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1718 if (*decl == NULL_TREE || *decl == void_type_node
1719 || *decl == error_mark_node || attributes == error_mark_node)
1720 return;
1722 /* Add implicit "omp declare target" attribute if requested. */
1723 if (vec_safe_length (scope_chain->omp_declare_target_attribute)
1724 && ((VAR_P (*decl)
1725 && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1726 || TREE_CODE (*decl) == FUNCTION_DECL))
1728 if (VAR_P (*decl)
1729 && DECL_CLASS_SCOPE_P (*decl))
1730 error ("%q+D static data member inside of declare target directive",
1731 *decl);
1732 else
1734 if (VAR_P (*decl)
1735 && (processing_template_decl
1736 || !omp_mappable_type (TREE_TYPE (*decl))))
1737 attributes
1738 = tree_cons (get_identifier ("omp declare target implicit"),
1739 NULL_TREE, attributes);
1740 else
1742 attributes = tree_cons (get_identifier ("omp declare target"),
1743 NULL_TREE, attributes);
1744 attributes
1745 = tree_cons (get_identifier ("omp declare target block"),
1746 NULL_TREE, attributes);
1748 if (TREE_CODE (*decl) == FUNCTION_DECL)
1750 cp_omp_declare_target_attr &last
1751 = scope_chain->omp_declare_target_attribute->last ();
1752 int device_type = MAX (last.device_type, 0);
1753 if ((device_type & OMP_CLAUSE_DEVICE_TYPE_HOST) != 0
1754 && !lookup_attribute ("omp declare target host",
1755 attributes))
1756 attributes
1757 = tree_cons (get_identifier ("omp declare target host"),
1758 NULL_TREE, attributes);
1759 if ((device_type & OMP_CLAUSE_DEVICE_TYPE_NOHOST) != 0
1760 && !lookup_attribute ("omp declare target nohost",
1761 attributes))
1762 attributes
1763 = tree_cons (get_identifier ("omp declare target nohost"),
1764 NULL_TREE, attributes);
1769 tree late_attrs = NULL_TREE;
1770 if (processing_template_decl)
1772 if (check_for_bare_parameter_packs (attributes))
1773 return;
1774 late_attrs = splice_template_attributes (&attributes, *decl);
1777 cp_check_const_attributes (attributes);
1779 if (flag_openmp || flag_openmp_simd)
1781 bool diagnosed = false;
1782 for (tree *pa = &attributes; *pa; )
1784 if (get_attribute_namespace (*pa) == omp_identifier)
1786 tree name = get_attribute_name (*pa);
1787 if (is_attribute_p ("directive", name)
1788 || is_attribute_p ("sequence", name)
1789 || is_attribute_p ("decl", name))
1791 const char *p = NULL;
1792 if (TREE_VALUE (*pa) == NULL_TREE)
1793 p = IDENTIFIER_POINTER (name);
1794 for (tree a = TREE_VALUE (*pa); a; a = TREE_CHAIN (a))
1796 tree d = TREE_VALUE (a);
1797 gcc_assert (TREE_CODE (d) == DEFERRED_PARSE);
1798 if (TREE_PUBLIC (d)
1799 && (VAR_P (*decl)
1800 || TREE_CODE (*decl) == FUNCTION_DECL)
1801 && cp_maybe_parse_omp_decl (*decl, d))
1802 continue;
1803 p = TREE_PUBLIC (d) ? "decl" : "directive";
1805 if (p && !diagnosed)
1807 error ("%<omp::%s%> not allowed to be specified in "
1808 "this context", p);
1809 diagnosed = true;
1811 if (p)
1813 *pa = TREE_CHAIN (*pa);
1814 continue;
1818 pa = &TREE_CHAIN (*pa);
1822 if (TREE_CODE (*decl) == TEMPLATE_DECL)
1823 decl = &DECL_TEMPLATE_RESULT (*decl);
1825 if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1827 attributes
1828 = decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1829 decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1830 attributes, flags);
1832 else
1834 tree last_decl = find_last_decl (*decl);
1835 decl_attributes (decl, attributes, flags, last_decl);
1838 if (late_attrs)
1839 save_template_attributes (late_attrs, decl, flags);
1841 /* Propagate deprecation out to the template. */
1842 if (TREE_DEPRECATED (*decl))
1843 if (tree ti = get_template_info (*decl))
1845 tree tmpl = TI_TEMPLATE (ti);
1846 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1847 : DECL_TEMPLATE_RESULT (tmpl));
1848 if (*decl == pattern)
1849 TREE_DEPRECATED (tmpl) = true;
1852 /* Likewise, propagate unavailability out to the template. */
1853 if (TREE_UNAVAILABLE (*decl))
1854 if (tree ti = get_template_info (*decl))
1856 tree tmpl = TI_TEMPLATE (ti);
1857 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1858 : DECL_TEMPLATE_RESULT (tmpl));
1859 if (*decl == pattern)
1860 TREE_UNAVAILABLE (tmpl) = true;
1864 /* Walks through the namespace- or function-scope anonymous union
1865 OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1866 Returns one of the fields for use in the mangled name. */
1868 static tree
1869 build_anon_union_vars (tree type, tree object)
1871 tree main_decl = NULL_TREE;
1872 tree field;
1874 /* Rather than write the code to handle the non-union case,
1875 just give an error. */
1876 if (TREE_CODE (type) != UNION_TYPE)
1878 error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
1879 "anonymous struct not inside named type");
1880 return error_mark_node;
1883 for (field = TYPE_FIELDS (type);
1884 field != NULL_TREE;
1885 field = DECL_CHAIN (field))
1887 tree decl;
1888 tree ref;
1890 if (DECL_ARTIFICIAL (field))
1891 continue;
1892 if (TREE_CODE (field) != FIELD_DECL)
1894 permerror (DECL_SOURCE_LOCATION (field),
1895 "%q#D invalid; an anonymous union can only "
1896 "have non-static data members", field);
1897 continue;
1900 if (TREE_PRIVATE (field))
1901 permerror (DECL_SOURCE_LOCATION (field),
1902 "private member %q#D in anonymous union", field);
1903 else if (TREE_PROTECTED (field))
1904 permerror (DECL_SOURCE_LOCATION (field),
1905 "protected member %q#D in anonymous union", field);
1907 if (processing_template_decl)
1908 ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1909 DECL_NAME (field), NULL_TREE);
1910 else
1911 ref = build_class_member_access_expr (object, field, NULL_TREE,
1912 false, tf_warning_or_error);
1914 if (DECL_NAME (field))
1916 tree base;
1918 decl = build_decl (input_location,
1919 VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1920 DECL_ANON_UNION_VAR_P (decl) = 1;
1921 DECL_ARTIFICIAL (decl) = 1;
1923 base = get_base_address (object);
1924 TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1925 TREE_STATIC (decl) = TREE_STATIC (base);
1926 DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1928 SET_DECL_VALUE_EXPR (decl, ref);
1929 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1931 decl = pushdecl (decl);
1933 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1934 decl = build_anon_union_vars (TREE_TYPE (field), ref);
1935 else
1936 decl = 0;
1938 if (main_decl == NULL_TREE)
1939 main_decl = decl;
1942 return main_decl;
1945 /* Finish off the processing of a UNION_TYPE structure. If the union is an
1946 anonymous union, then all members must be laid out together. PUBLIC_P
1947 is nonzero if this union is not declared static. */
1949 void
1950 finish_anon_union (tree anon_union_decl)
1952 tree type;
1953 tree main_decl;
1954 bool public_p;
1956 if (anon_union_decl == error_mark_node)
1957 return;
1959 type = TREE_TYPE (anon_union_decl);
1960 public_p = TREE_PUBLIC (anon_union_decl);
1962 /* The VAR_DECL's context is the same as the TYPE's context. */
1963 DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1965 if (TYPE_FIELDS (type) == NULL_TREE)
1966 return;
1968 if (public_p)
1970 error ("namespace-scope anonymous aggregates must be static");
1971 return;
1974 main_decl = build_anon_union_vars (type, anon_union_decl);
1975 if (main_decl == error_mark_node)
1976 return;
1977 if (main_decl == NULL_TREE)
1979 pedwarn (input_location, 0, "anonymous union with no members");
1980 return;
1983 if (!processing_template_decl)
1985 /* Use main_decl to set the mangled name. */
1986 DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1987 maybe_commonize_var (anon_union_decl);
1988 if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1990 if (DECL_DISCRIMINATOR_P (anon_union_decl))
1991 determine_local_discriminator (anon_union_decl);
1992 mangle_decl (anon_union_decl);
1994 DECL_NAME (anon_union_decl) = NULL_TREE;
1997 pushdecl (anon_union_decl);
1998 cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
2001 /* Auxiliary functions to make type signatures for
2002 `operator new' and `operator delete' correspond to
2003 what compiler will be expecting. */
2005 tree
2006 coerce_new_type (tree type, location_t loc)
2008 int e = 0;
2009 tree args = TYPE_ARG_TYPES (type);
2011 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
2013 if (!same_type_p (TREE_TYPE (type), ptr_type_node))
2015 e = 1;
2016 error_at (loc, "%<operator new%> must return type %qT",
2017 ptr_type_node);
2020 if (args && args != void_list_node)
2022 if (TREE_PURPOSE (args))
2024 /* [basic.stc.dynamic.allocation]
2026 The first parameter shall not have an associated default
2027 argument. */
2028 error_at (loc, "the first parameter of %<operator new%> cannot "
2029 "have a default argument");
2030 /* Throw away the default argument. */
2031 TREE_PURPOSE (args) = NULL_TREE;
2034 if (!same_type_p (TREE_VALUE (args), size_type_node))
2036 e = 2;
2037 args = TREE_CHAIN (args);
2040 else
2041 e = 2;
2043 if (e == 2)
2044 permerror (loc, "%<operator new%> takes type %<size_t%> (%qT) "
2045 "as first parameter", size_type_node);
2047 switch (e)
2049 case 2:
2050 args = tree_cons (NULL_TREE, size_type_node, args);
2051 /* Fall through. */
2052 case 1:
2053 type = (cxx_copy_lang_qualifiers
2054 (build_function_type (ptr_type_node, args),
2055 type));
2056 /* Fall through. */
2057 default:;
2059 return type;
2062 void
2063 coerce_delete_type (tree decl, location_t loc)
2065 int e = 0;
2066 tree type = TREE_TYPE (decl);
2067 tree args = TYPE_ARG_TYPES (type);
2069 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
2071 if (!same_type_p (TREE_TYPE (type), void_type_node))
2073 e = 1;
2074 error_at (loc, "%<operator delete%> must return type %qT",
2075 void_type_node);
2078 tree ptrtype = ptr_type_node;
2079 if (destroying_delete_p (decl))
2081 if (DECL_CLASS_SCOPE_P (decl))
2082 /* If the function is a destroying operator delete declared in class
2083 type C, the type of its first parameter shall be C*. */
2084 ptrtype = build_pointer_type (DECL_CONTEXT (decl));
2085 else
2086 /* A destroying operator delete shall be a class member function named
2087 operator delete. */
2088 error_at (loc,
2089 "destroying %<operator delete%> must be a member function");
2090 const ovl_op_info_t *op = IDENTIFIER_OVL_OP_INFO (DECL_NAME (decl));
2091 if (op->flags & OVL_OP_FLAG_VEC)
2092 error_at (loc, "%<operator delete[]%> cannot be a destroying delete");
2093 if (!usual_deallocation_fn_p (decl))
2094 error_at (loc, "destroying %<operator delete%> must be a usual "
2095 "deallocation function");
2098 if (!args || args == void_list_node
2099 || !same_type_p (TREE_VALUE (args), ptrtype))
2101 e = 2;
2102 if (args && args != void_list_node)
2103 args = TREE_CHAIN (args);
2104 error_at (loc, "%<operator delete%> takes type %qT as first parameter",
2105 ptrtype);
2107 switch (e)
2109 case 2:
2110 args = tree_cons (NULL_TREE, ptrtype, args);
2111 /* Fall through. */
2112 case 1:
2113 type = (cxx_copy_lang_qualifiers
2114 (build_function_type (void_type_node, args),
2115 type));
2116 /* Fall through. */
2117 default:;
2120 TREE_TYPE (decl) = type;
2123 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
2124 and mark them as needed. */
2126 static void
2127 mark_vtable_entries (tree decl, vec<tree> &consteval_vtables)
2129 /* It's OK for the vtable to refer to deprecated virtual functions. */
2130 warning_sentinel w(warn_deprecated_decl);
2132 bool consteval_seen = false;
2134 for (auto &e: CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
2136 tree fnaddr = e.value;
2138 STRIP_NOPS (fnaddr);
2140 if (TREE_CODE (fnaddr) != ADDR_EXPR
2141 && TREE_CODE (fnaddr) != FDESC_EXPR)
2142 /* This entry is an offset: a virtual base class offset, a
2143 virtual call offset, an RTTI offset, etc. */
2144 continue;
2146 tree fn = TREE_OPERAND (fnaddr, 0);
2147 if (TREE_CODE (fn) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (fn))
2149 if (!consteval_seen)
2151 consteval_seen = true;
2152 consteval_vtables.safe_push (decl);
2154 continue;
2156 TREE_ADDRESSABLE (fn) = 1;
2157 /* When we don't have vcall offsets, we output thunks whenever
2158 we output the vtables that contain them. With vcall offsets,
2159 we know all the thunks we'll need when we emit a virtual
2160 function, so we emit the thunks there instead. */
2161 if (DECL_THUNK_P (fn))
2162 use_thunk (fn, /*emit_p=*/0);
2163 /* Set the location, as marking the function could cause
2164 instantiation. We do not need to preserve the incoming
2165 location, as we're called from c_parse_final_cleanups, which
2166 takes care of that. */
2167 input_location = DECL_SOURCE_LOCATION (fn);
2168 mark_used (fn);
2172 /* Replace any consteval functions in vtables with null pointers. */
2174 static void
2175 clear_consteval_vfns (vec<tree> &consteval_vtables)
2177 for (tree vtable : consteval_vtables)
2178 for (constructor_elt &elt : CONSTRUCTOR_ELTS (DECL_INITIAL (vtable)))
2180 tree fn = cp_get_fndecl_from_callee (elt.value, /*fold*/false);
2181 if (fn && DECL_IMMEDIATE_FUNCTION_P (fn))
2182 elt.value = build_zero_cst (vtable_entry_type);
2186 /* Adjust the TLS model on variable DECL if need be, typically after
2187 the linkage of DECL has been modified. */
2189 static void
2190 adjust_var_decl_tls_model (tree decl)
2192 if (CP_DECL_THREAD_LOCAL_P (decl)
2193 && !lookup_attribute ("tls_model", DECL_ATTRIBUTES (decl)))
2194 set_decl_tls_model (decl, decl_default_tls_model (decl));
2197 /* Set DECL up to have the closest approximation of "initialized common"
2198 linkage available. */
2200 void
2201 comdat_linkage (tree decl)
2203 if (flag_weak)
2205 make_decl_one_only (decl, cxx_comdat_group (decl));
2206 if (HAVE_COMDAT_GROUP && flag_contracts && DECL_CONTRACTS (decl))
2208 symtab_node *n = symtab_node::get (decl);
2209 if (tree pre = DECL_PRE_FN (decl))
2210 cgraph_node::get_create (pre)->add_to_same_comdat_group (n);
2211 if (tree post = DECL_POST_FN (decl))
2212 cgraph_node::get_create (post)->add_to_same_comdat_group (n);
2215 else if (TREE_CODE (decl) == FUNCTION_DECL
2216 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2217 /* We can just emit function and compiler-generated variables
2218 statically; having multiple copies is (for the most part) only
2219 a waste of space.
2221 There are two correctness issues, however: the address of a
2222 template instantiation with external linkage should be the
2223 same, independent of what translation unit asks for the
2224 address, and this will not hold when we emit multiple copies of
2225 the function. However, there's little else we can do.
2227 Also, by default, the typeinfo implementation assumes that
2228 there will be only one copy of the string used as the name for
2229 each type. Therefore, if weak symbols are unavailable, the
2230 run-time library should perform a more conservative check; it
2231 should perform a string comparison, rather than an address
2232 comparison. */
2233 TREE_PUBLIC (decl) = 0;
2234 else
2236 /* Static data member template instantiations, however, cannot
2237 have multiple copies. */
2238 if (DECL_INITIAL (decl) == 0
2239 || DECL_INITIAL (decl) == error_mark_node)
2240 DECL_COMMON (decl) = 1;
2241 else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
2243 DECL_COMMON (decl) = 1;
2244 DECL_INITIAL (decl) = error_mark_node;
2246 else if (!DECL_EXPLICIT_INSTANTIATION (decl))
2248 /* We can't do anything useful; leave vars for explicit
2249 instantiation. */
2250 DECL_EXTERNAL (decl) = 1;
2251 DECL_NOT_REALLY_EXTERN (decl) = 0;
2255 if (TREE_PUBLIC (decl))
2256 DECL_COMDAT (decl) = 1;
2258 if (VAR_P (decl))
2259 adjust_var_decl_tls_model (decl);
2262 /* For win32 we also want to put explicit instantiations in
2263 linkonce sections, so that they will be merged with implicit
2264 instantiations; otherwise we get duplicate symbol errors.
2265 For Darwin we do not want explicit instantiations to be
2266 linkonce. */
2268 void
2269 maybe_make_one_only (tree decl)
2271 /* We used to say that this was not necessary on targets that support weak
2272 symbols, because the implicit instantiations will defer to the explicit
2273 one. However, that's not actually the case in SVR4; a strong definition
2274 after a weak one is an error. Also, not making explicit
2275 instantiations one_only means that we can end up with two copies of
2276 some template instantiations. */
2277 if (! flag_weak)
2278 return;
2280 /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
2281 we can get away with not emitting them if they aren't used. We need
2282 to for variables so that cp_finish_decl will update their linkage,
2283 because their DECL_INITIAL may not have been set properly yet. */
2285 if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
2286 || (! DECL_EXPLICIT_INSTANTIATION (decl)
2287 && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
2289 make_decl_one_only (decl, cxx_comdat_group (decl));
2291 if (VAR_P (decl))
2293 varpool_node *node = varpool_node::get_create (decl);
2294 DECL_COMDAT (decl) = 1;
2295 /* Mark it needed so we don't forget to emit it. */
2296 node->forced_by_abi = true;
2297 TREE_USED (decl) = 1;
2299 adjust_var_decl_tls_model (decl);
2304 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
2305 This predicate will give the right answer during parsing of the
2306 function, which other tests may not. */
2308 bool
2309 vague_linkage_p (tree decl)
2311 if (!TREE_PUBLIC (decl))
2313 /* maybe_thunk_body clears TREE_PUBLIC and DECL_ABSTRACT_P on the
2314 maybe-in-charge 'tor variants; in that case we need to check one of
2315 the "clones" for the real linkage. But only in that case; before
2316 maybe_clone_body we haven't yet copied the linkage to the clones. */
2317 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl)
2318 && !DECL_ABSTRACT_P (decl)
2319 && DECL_CHAIN (decl)
2320 && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
2321 return vague_linkage_p (DECL_CHAIN (decl));
2323 gcc_checking_assert (!DECL_COMDAT (decl));
2324 return false;
2326 /* Unfortunately, import_export_decl has not always been called
2327 before the function is processed, so we cannot simply check
2328 DECL_COMDAT. */
2329 if (DECL_COMDAT (decl)
2330 || (TREE_CODE (decl) == FUNCTION_DECL
2331 && DECL_DECLARED_INLINE_P (decl))
2332 || (DECL_LANG_SPECIFIC (decl)
2333 && DECL_TEMPLATE_INSTANTIATION (decl))
2334 || (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
2335 return true;
2336 else if (DECL_FUNCTION_SCOPE_P (decl))
2337 /* A local static in an inline effectively has vague linkage. */
2338 return (TREE_STATIC (decl)
2339 && vague_linkage_p (DECL_CONTEXT (decl)));
2340 else
2341 return false;
2344 /* Determine whether or not we want to specifically import or export CTYPE,
2345 using various heuristics. */
2347 static void
2348 import_export_class (tree ctype)
2350 /* -1 for imported, 1 for exported. */
2351 int import_export = 0;
2353 /* It only makes sense to call this function at EOF. The reason is
2354 that this function looks at whether or not the first non-inline
2355 non-abstract virtual member function has been defined in this
2356 translation unit. But, we can't possibly know that until we've
2357 seen the entire translation unit. */
2358 gcc_assert (at_eof);
2360 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2361 return;
2363 /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
2364 we will have CLASSTYPE_INTERFACE_ONLY set but not
2365 CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this
2366 heuristic because someone will supply a #pragma implementation
2367 elsewhere, and deducing it here would produce a conflict. */
2368 if (CLASSTYPE_INTERFACE_ONLY (ctype))
2369 return;
2371 if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2372 import_export = -1;
2373 else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2374 import_export = 1;
2375 else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2376 && !flag_implicit_templates)
2377 /* For a template class, without -fimplicit-templates, check the
2378 repository. If the virtual table is assigned to this
2379 translation unit, then export the class; otherwise, import
2380 it. */
2381 import_export = -1;
2382 else if (TYPE_POLYMORPHIC_P (ctype))
2384 /* The ABI specifies that the virtual table and associated
2385 information are emitted with the key method, if any. */
2386 tree method = CLASSTYPE_KEY_METHOD (ctype);
2387 /* If weak symbol support is not available, then we must be
2388 careful not to emit the vtable when the key function is
2389 inline. An inline function can be defined in multiple
2390 translation units. If we were to emit the vtable in each
2391 translation unit containing a definition, we would get
2392 multiple definition errors at link-time. */
2393 if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
2394 import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2397 /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
2398 a definition anywhere else. */
2399 if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
2400 import_export = 0;
2402 /* Allow back ends the chance to overrule the decision. */
2403 if (targetm.cxx.import_export_class)
2404 import_export = targetm.cxx.import_export_class (ctype, import_export);
2406 if (import_export)
2408 SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2409 CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2413 /* Return true if VAR has already been provided to the back end; in that
2414 case VAR should not be modified further by the front end. */
2415 static bool
2416 var_finalized_p (tree var)
2418 return varpool_node::get_create (var)->definition;
2421 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
2422 must be emitted in this translation unit. Mark it as such. */
2424 void
2425 mark_needed (tree decl)
2427 TREE_USED (decl) = 1;
2428 if (TREE_CODE (decl) == FUNCTION_DECL)
2430 /* Extern inline functions don't become needed when referenced.
2431 If we know a method will be emitted in other TU and no new
2432 functions can be marked reachable, just use the external
2433 definition. */
2434 struct cgraph_node *node = cgraph_node::get_create (decl);
2435 node->forced_by_abi = true;
2437 /* #pragma interface can call mark_needed for
2438 maybe-in-charge 'tors; mark the clones as well. */
2439 tree clone;
2440 FOR_EACH_CLONE (clone, decl)
2441 mark_needed (clone);
2443 else if (VAR_P (decl))
2445 varpool_node *node = varpool_node::get_create (decl);
2446 /* C++ frontend use mark_decl_references to force COMDAT variables
2447 to be output that might appear dead otherwise. */
2448 node->forced_by_abi = true;
2452 /* DECL is either a FUNCTION_DECL or a VAR_DECL. This function
2453 returns true if a definition of this entity should be provided in
2454 this object file. Callers use this function to determine whether
2455 or not to let the back end know that a definition of DECL is
2456 available in this translation unit. */
2458 bool
2459 decl_needed_p (tree decl)
2461 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2462 /* This function should only be called at the end of the translation
2463 unit. We cannot be sure of whether or not something will be
2464 COMDAT until that point. */
2465 gcc_assert (at_eof);
2467 /* All entities with external linkage that are not COMDAT/EXTERN should be
2468 emitted; they may be referred to from other object files. */
2469 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2470 return true;
2472 /* Functions marked "dllexport" must be emitted so that they are
2473 visible to other DLLs. */
2474 if (flag_keep_inline_dllexport
2475 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2476 return true;
2478 /* When not optimizing, do not bother to produce definitions for extern
2479 symbols. */
2480 if (DECL_REALLY_EXTERN (decl)
2481 && ((TREE_CODE (decl) != FUNCTION_DECL
2482 && !optimize)
2483 || (TREE_CODE (decl) == FUNCTION_DECL
2484 && !opt_for_fn (decl, optimize)))
2485 && !lookup_attribute ("always_inline", decl))
2486 return false;
2488 /* If this entity was used, let the back end see it; it will decide
2489 whether or not to emit it into the object file. */
2490 if (TREE_USED (decl))
2491 return true;
2493 /* Virtual functions might be needed for devirtualization. */
2494 if (flag_devirtualize
2495 && TREE_CODE (decl) == FUNCTION_DECL
2496 && DECL_VIRTUAL_P (decl))
2497 return true;
2499 /* Otherwise, DECL does not need to be emitted -- yet. A subsequent
2500 reference to DECL might cause it to be emitted later. */
2501 return false;
2504 /* If necessary, write out the vtables for the dynamic class CTYPE.
2505 Returns true if any vtables were emitted. */
2507 static bool
2508 maybe_emit_vtables (tree ctype, vec<tree> &consteval_vtables)
2510 tree vtbl;
2511 tree primary_vtbl;
2512 int needed = 0;
2513 varpool_node *current = NULL, *last = NULL;
2515 /* If the vtables for this class have already been emitted there is
2516 nothing more to do. */
2517 primary_vtbl = CLASSTYPE_VTABLES (ctype);
2518 if (var_finalized_p (primary_vtbl))
2519 return false;
2520 /* Ignore dummy vtables made by get_vtable_decl. */
2521 if (TREE_TYPE (primary_vtbl) == void_type_node)
2522 return false;
2524 /* On some targets, we cannot determine the key method until the end
2525 of the translation unit -- which is when this function is
2526 called. */
2527 if (!targetm.cxx.key_method_may_be_inline ())
2528 determine_key_method (ctype);
2530 /* See if any of the vtables are needed. */
2531 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2533 import_export_decl (vtbl);
2534 if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2535 needed = 1;
2537 if (!needed)
2539 /* If the references to this class' vtables are optimized away,
2540 still emit the appropriate debugging information. See
2541 dfs_debug_mark. */
2542 if (DECL_COMDAT (primary_vtbl)
2543 && CLASSTYPE_DEBUG_REQUESTED (ctype))
2544 note_debug_info_needed (ctype);
2545 return false;
2548 /* The ABI requires that we emit all of the vtables if we emit any
2549 of them. */
2550 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2552 /* Mark entities references from the virtual table as used. */
2553 mark_vtable_entries (vtbl, consteval_vtables);
2555 if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2557 vec<tree, va_gc> *cleanups = NULL;
2558 tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2559 LOOKUP_NORMAL);
2561 /* It had better be all done at compile-time. */
2562 gcc_assert (!expr && !cleanups);
2565 /* Write it out. */
2566 DECL_EXTERNAL (vtbl) = 0;
2567 rest_of_decl_compilation (vtbl, 1, 1);
2569 /* Because we're only doing syntax-checking, we'll never end up
2570 actually marking the variable as written. */
2571 if (flag_syntax_only)
2572 TREE_ASM_WRITTEN (vtbl) = 1;
2573 else if (DECL_ONE_ONLY (vtbl))
2575 current = varpool_node::get_create (vtbl);
2576 if (last)
2577 current->add_to_same_comdat_group (last);
2578 last = current;
2582 /* For abstract classes, the destructor has been removed from the
2583 vtable (in class.cc's build_vtbl_initializer). For a compiler-
2584 generated destructor, it hence might not have been generated in
2585 this translation unit - and with '#pragma interface' it might
2586 never get generated. */
2587 if (CLASSTYPE_PURE_VIRTUALS (ctype)
2588 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype)
2589 && !CLASSTYPE_LAZY_DESTRUCTOR (ctype)
2590 && DECL_DEFAULTED_IN_CLASS_P (CLASSTYPE_DESTRUCTOR (ctype)))
2591 note_vague_linkage_fn (CLASSTYPE_DESTRUCTOR (ctype));
2593 /* Since we're writing out the vtable here, also write the debug
2594 info. */
2595 note_debug_info_needed (ctype);
2597 return true;
2600 /* A special return value from type_visibility meaning internal
2601 linkage. */
2603 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2605 static int expr_visibility (tree);
2606 static int type_visibility (tree);
2608 /* walk_tree helper function for type_visibility. */
2610 static tree
2611 min_vis_r (tree *tp, int *walk_subtrees, void *data)
2613 int *vis_p = (int *)data;
2614 int this_vis = VISIBILITY_DEFAULT;
2615 if (! TYPE_P (*tp))
2616 *walk_subtrees = 0;
2617 else if (OVERLOAD_TYPE_P (*tp)
2618 && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2620 this_vis = VISIBILITY_ANON;
2621 *walk_subtrees = 0;
2623 else if (CLASS_TYPE_P (*tp))
2625 this_vis = CLASSTYPE_VISIBILITY (*tp);
2626 *walk_subtrees = 0;
2628 else if (TREE_CODE (*tp) == ARRAY_TYPE
2629 && uses_template_parms (TYPE_DOMAIN (*tp)))
2630 this_vis = expr_visibility (TYPE_MAX_VALUE (TYPE_DOMAIN (*tp)));
2632 if (this_vis > *vis_p)
2633 *vis_p = this_vis;
2635 /* Tell cp_walk_subtrees to look through typedefs. */
2636 if (*walk_subtrees == 1)
2637 *walk_subtrees = 2;
2639 return NULL;
2642 /* walk_tree helper function for expr_visibility. */
2644 static tree
2645 min_vis_expr_r (tree *tp, int */*walk_subtrees*/, void *data)
2647 int *vis_p = (int *)data;
2648 int tpvis = VISIBILITY_DEFAULT;
2650 switch (TREE_CODE (*tp))
2652 case CAST_EXPR:
2653 case IMPLICIT_CONV_EXPR:
2654 case STATIC_CAST_EXPR:
2655 case REINTERPRET_CAST_EXPR:
2656 case CONST_CAST_EXPR:
2657 case DYNAMIC_CAST_EXPR:
2658 case NEW_EXPR:
2659 case CONSTRUCTOR:
2660 case LAMBDA_EXPR:
2661 tpvis = type_visibility (TREE_TYPE (*tp));
2662 break;
2664 case VAR_DECL:
2665 case FUNCTION_DECL:
2666 if (! TREE_PUBLIC (*tp))
2667 tpvis = VISIBILITY_ANON;
2668 else
2669 tpvis = DECL_VISIBILITY (*tp);
2670 break;
2672 default:
2673 break;
2676 if (tpvis > *vis_p)
2677 *vis_p = tpvis;
2679 return NULL_TREE;
2682 /* Returns the visibility of TYPE, which is the minimum visibility of its
2683 component types. */
2685 static int
2686 type_visibility (tree type)
2688 int vis = VISIBILITY_DEFAULT;
2689 cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2690 return vis;
2693 /* Returns the visibility of an expression EXPR that appears in the signature
2694 of a function template, which is the minimum visibility of names that appear
2695 in its mangling. */
2697 static int
2698 expr_visibility (tree expr)
2700 int vis = VISIBILITY_DEFAULT;
2701 cp_walk_tree_without_duplicates (&expr, min_vis_expr_r, &vis);
2702 return vis;
2705 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
2706 specified (or if VISIBILITY is static). If TMPL is true, this
2707 constraint is for a template argument, and takes precedence
2708 over explicitly-specified visibility on the template. */
2710 static void
2711 constrain_visibility (tree decl, int visibility, bool tmpl)
2713 if (visibility == VISIBILITY_ANON)
2715 /* extern "C" declarations aren't affected by the anonymous
2716 namespace. */
2717 if (!DECL_EXTERN_C_P (decl))
2719 TREE_PUBLIC (decl) = 0;
2720 DECL_WEAK (decl) = 0;
2721 DECL_COMMON (decl) = 0;
2722 DECL_COMDAT (decl) = false;
2723 if (VAR_OR_FUNCTION_DECL_P (decl))
2725 struct symtab_node *snode = symtab_node::get (decl);
2727 if (snode)
2728 snode->set_comdat_group (NULL);
2730 DECL_INTERFACE_KNOWN (decl) = 1;
2731 if (DECL_LANG_SPECIFIC (decl))
2732 DECL_NOT_REALLY_EXTERN (decl) = 1;
2735 else if (visibility > DECL_VISIBILITY (decl)
2736 && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2738 DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2739 /* This visibility was not specified. */
2740 DECL_VISIBILITY_SPECIFIED (decl) = false;
2744 /* Constrain the visibility of DECL based on the visibility of its template
2745 arguments. */
2747 static void
2748 constrain_visibility_for_template (tree decl, tree targs)
2750 /* If this is a template instantiation, check the innermost
2751 template args for visibility constraints. The outer template
2752 args are covered by the class check. */
2753 tree args = INNERMOST_TEMPLATE_ARGS (targs);
2754 int i;
2755 for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2757 int vis = 0;
2759 tree arg = TREE_VEC_ELT (args, i-1);
2760 if (TYPE_P (arg))
2761 vis = type_visibility (arg);
2762 else
2763 vis = expr_visibility (arg);
2764 if (vis)
2765 constrain_visibility (decl, vis, true);
2769 /* Like c_determine_visibility, but with additional C++-specific
2770 behavior.
2772 Function-scope entities can rely on the function's visibility because
2773 it is set in start_preparsed_function.
2775 Class-scope entities cannot rely on the class's visibility until the end
2776 of the enclosing class definition.
2778 Note that because namespaces have multiple independent definitions,
2779 namespace visibility is handled elsewhere using the #pragma visibility
2780 machinery rather than by decorating the namespace declaration.
2782 The goal is for constraints from the type to give a diagnostic, and
2783 other constraints to be applied silently. */
2785 void
2786 determine_visibility (tree decl)
2788 /* Remember that all decls get VISIBILITY_DEFAULT when built. */
2790 /* Only relevant for names with external linkage. */
2791 if (!TREE_PUBLIC (decl))
2792 return;
2794 /* Cloned constructors and destructors get the same visibility as
2795 the underlying function. That should be set up in
2796 maybe_clone_body. */
2797 gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2799 bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2800 enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
2802 /* The decl may be a template instantiation, which could influence
2803 visibilty. */
2804 tree template_decl = NULL_TREE;
2805 if (TREE_CODE (decl) == TYPE_DECL)
2807 if (CLASS_TYPE_P (TREE_TYPE (decl)))
2809 if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
2810 template_decl = decl;
2812 else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2813 template_decl = decl;
2815 else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
2816 template_decl = decl;
2818 if (TREE_CODE (decl) == TYPE_DECL
2819 && LAMBDA_TYPE_P (TREE_TYPE (decl))
2820 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (decl)) != error_mark_node)
2821 if (tree extra = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl)))
2823 /* The lambda's visibility is limited by that of its extra
2824 scope. */
2825 int vis = 0;
2826 if (TYPE_P (extra))
2827 vis = type_visibility (extra);
2828 else
2829 vis = expr_visibility (extra);
2830 constrain_visibility (decl, vis, false);
2833 /* If DECL is a member of a class, visibility specifiers on the
2834 class can influence the visibility of the DECL. */
2835 tree class_type = NULL_TREE;
2836 if (DECL_CLASS_SCOPE_P (decl))
2837 class_type = DECL_CONTEXT (decl);
2838 else
2840 /* Not a class member. */
2842 /* Virtual tables have DECL_CONTEXT set to their associated class,
2843 so they are automatically handled above. */
2844 gcc_assert (!VAR_P (decl)
2845 || !DECL_VTABLE_OR_VTT_P (decl));
2847 if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2849 /* Local statics and classes get the visibility of their
2850 containing function by default, except that
2851 -fvisibility-inlines-hidden doesn't affect them. */
2852 tree fn = DECL_CONTEXT (decl);
2853 if (DECL_VISIBILITY_SPECIFIED (fn))
2855 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2856 DECL_VISIBILITY_SPECIFIED (decl) =
2857 DECL_VISIBILITY_SPECIFIED (fn);
2859 else
2861 if (DECL_CLASS_SCOPE_P (fn))
2862 determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2863 else if (determine_hidden_inline (fn))
2865 DECL_VISIBILITY (decl) = default_visibility;
2866 DECL_VISIBILITY_SPECIFIED (decl) =
2867 visibility_options.inpragma;
2869 else
2871 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2872 DECL_VISIBILITY_SPECIFIED (decl) =
2873 DECL_VISIBILITY_SPECIFIED (fn);
2877 /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2878 but have no TEMPLATE_INFO, so don't try to check it. */
2879 template_decl = NULL_TREE;
2881 else if (VAR_P (decl) && DECL_TINFO_P (decl)
2882 && flag_visibility_ms_compat)
2884 /* Under -fvisibility-ms-compat, types are visible by default,
2885 even though their contents aren't. */
2886 tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2887 int underlying_vis = type_visibility (underlying_type);
2888 if (underlying_vis == VISIBILITY_ANON
2889 || (CLASS_TYPE_P (underlying_type)
2890 && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2891 constrain_visibility (decl, underlying_vis, false);
2892 else
2893 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2895 else if (VAR_P (decl) && DECL_TINFO_P (decl))
2897 /* tinfo visibility is based on the type it's for. */
2898 constrain_visibility
2899 (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2901 /* Give the target a chance to override the visibility associated
2902 with DECL. */
2903 if (TREE_PUBLIC (decl)
2904 && !DECL_REALLY_EXTERN (decl)
2905 && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2906 && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2907 targetm.cxx.determine_class_data_visibility (decl);
2909 else if (template_decl)
2910 /* Template instantiations and specializations get visibility based
2911 on their template unless they override it with an attribute. */;
2912 else if (! DECL_VISIBILITY_SPECIFIED (decl))
2914 if (determine_hidden_inline (decl))
2915 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2916 else
2918 /* Set default visibility to whatever the user supplied with
2919 #pragma GCC visibility or a namespace visibility attribute. */
2920 DECL_VISIBILITY (decl) = default_visibility;
2921 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2926 if (template_decl)
2928 /* If the specialization doesn't specify visibility, use the
2929 visibility from the template. */
2930 tree tinfo = get_template_info (template_decl);
2931 tree args = TI_ARGS (tinfo);
2932 tree attribs = (TREE_CODE (decl) == TYPE_DECL
2933 ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2934 : DECL_ATTRIBUTES (decl));
2935 tree attr = lookup_attribute ("visibility", attribs);
2937 if (args != error_mark_node)
2939 tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2941 if (!DECL_VISIBILITY_SPECIFIED (decl))
2943 if (!attr
2944 && determine_hidden_inline (decl))
2945 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2946 else
2948 DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2949 DECL_VISIBILITY_SPECIFIED (decl)
2950 = DECL_VISIBILITY_SPECIFIED (pattern);
2954 if (args
2955 /* Template argument visibility outweighs #pragma or namespace
2956 visibility, but not an explicit attribute. */
2957 && !attr)
2959 int depth = TMPL_ARGS_DEPTH (args);
2960 if (DECL_VISIBILITY_SPECIFIED (decl))
2962 /* A class template member with explicit visibility
2963 overrides the class visibility, so we need to apply
2964 all the levels of template args directly. */
2965 int i;
2966 for (i = 1; i <= depth; ++i)
2968 tree lev = TMPL_ARGS_LEVEL (args, i);
2969 constrain_visibility_for_template (decl, lev);
2972 else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2973 /* Limit visibility based on its template arguments. */
2974 constrain_visibility_for_template (decl, args);
2979 if (class_type)
2980 determine_visibility_from_class (decl, class_type);
2982 if (decl_internal_context_p (decl))
2983 /* Names in an anonymous namespace get internal linkage. */
2984 constrain_visibility (decl, VISIBILITY_ANON, false);
2985 else if (TREE_CODE (decl) != TYPE_DECL)
2987 /* Propagate anonymity from type to decl. */
2988 int tvis = type_visibility (TREE_TYPE (decl));
2989 if (tvis == VISIBILITY_ANON
2990 || ! DECL_VISIBILITY_SPECIFIED (decl))
2991 constrain_visibility (decl, tvis, false);
2993 else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2994 /* DR 757: A type without linkage shall not be used as the type of a
2995 variable or function with linkage, unless
2996 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2997 o the variable or function is not used (3.2 [basic.def.odr]) or is
2998 defined in the same translation unit.
3000 Since non-extern "C" decls need to be defined in the same
3001 translation unit, we can make the type internal. */
3002 constrain_visibility (decl, VISIBILITY_ANON, false);
3004 /* If visibility changed and DECL already has DECL_RTL, ensure
3005 symbol flags are updated. */
3006 if ((DECL_VISIBILITY (decl) != orig_visibility
3007 || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
3008 && ((VAR_P (decl) && TREE_STATIC (decl))
3009 || TREE_CODE (decl) == FUNCTION_DECL)
3010 && DECL_RTL_SET_P (decl))
3011 make_decl_rtl (decl);
3014 /* By default, static data members and function members receive
3015 the visibility of their containing class. */
3017 static void
3018 determine_visibility_from_class (tree decl, tree class_type)
3020 if (DECL_VISIBILITY_SPECIFIED (decl))
3021 return;
3023 if (determine_hidden_inline (decl))
3024 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
3025 else
3027 /* Default to the class visibility. */
3028 DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
3029 DECL_VISIBILITY_SPECIFIED (decl)
3030 = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
3033 /* Give the target a chance to override the visibility associated
3034 with DECL. */
3035 if (VAR_P (decl)
3036 && TREE_PUBLIC (decl)
3037 && (DECL_TINFO_P (decl) || DECL_VTABLE_OR_VTT_P (decl))
3038 && !DECL_REALLY_EXTERN (decl)
3039 && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
3040 targetm.cxx.determine_class_data_visibility (decl);
3043 /* Returns true iff DECL is an inline that should get hidden visibility
3044 because of -fvisibility-inlines-hidden. */
3046 static bool
3047 determine_hidden_inline (tree decl)
3049 return (visibility_options.inlines_hidden
3050 /* Don't do this for inline templates; specializations might not be
3051 inline, and we don't want them to inherit the hidden
3052 visibility. We'll set it here for all inline instantiations. */
3053 && !processing_template_decl
3054 && TREE_CODE (decl) == FUNCTION_DECL
3055 && DECL_DECLARED_INLINE_P (decl)
3056 && (! DECL_LANG_SPECIFIC (decl)
3057 || ! DECL_EXPLICIT_INSTANTIATION (decl)));
3060 /* Constrain the visibility of a class TYPE based on the visibility of its
3061 field types. Warn if any fields require lesser visibility. */
3063 void
3064 constrain_class_visibility (tree type)
3066 tree binfo;
3067 tree t;
3068 int i;
3070 int vis = type_visibility (type);
3072 if (vis == VISIBILITY_ANON
3073 || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
3074 return;
3076 /* Don't warn about visibility if the class has explicit visibility. */
3077 if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
3078 vis = VISIBILITY_INTERNAL;
3080 for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
3081 if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
3082 && !DECL_ARTIFICIAL (t))
3084 tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
3085 int subvis = type_visibility (ftype);
3087 if (subvis == VISIBILITY_ANON)
3089 if (!in_main_input_context())
3091 tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
3092 if (nlt)
3094 if (same_type_p (TREE_TYPE (t), nlt))
3095 warning (OPT_Wsubobject_linkage, "\
3096 %qT has a field %q#D whose type has no linkage",
3097 type, t);
3098 else
3099 warning (OPT_Wsubobject_linkage, "\
3100 %qT has a field %qD whose type depends on the type %qT which has no linkage",
3101 type, t, nlt);
3103 else if (cxx_dialect > cxx98
3104 && !decl_anon_ns_mem_p (ftype))
3105 warning (OPT_Wsubobject_linkage, "\
3106 %qT has a field %q#D whose type has internal linkage",
3107 type, t);
3108 else // In C++98 this can only happen with unnamed namespaces.
3109 warning (OPT_Wsubobject_linkage, "\
3110 %qT has a field %q#D whose type uses the anonymous namespace",
3111 type, t);
3114 else if (MAYBE_CLASS_TYPE_P (ftype)
3115 && vis < VISIBILITY_HIDDEN
3116 && subvis >= VISIBILITY_HIDDEN)
3117 warning (OPT_Wattributes, "\
3118 %qT declared with greater visibility than the type of its field %qD",
3119 type, t);
3122 binfo = TYPE_BINFO (type);
3123 for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
3125 tree btype = BINFO_TYPE (t);
3126 int subvis = type_visibility (btype);
3128 if (subvis == VISIBILITY_ANON)
3130 if (!in_main_input_context())
3132 tree nlt = no_linkage_check (btype, /*relaxed_p=*/false);
3133 if (nlt)
3135 if (same_type_p (btype, nlt))
3136 warning (OPT_Wsubobject_linkage, "\
3137 %qT has a base %qT which has no linkage",
3138 type, btype);
3139 else
3140 warning (OPT_Wsubobject_linkage, "\
3141 %qT has a base %qT which depends on the type %qT which has no linkage",
3142 type, btype, nlt);
3144 else if (cxx_dialect > cxx98
3145 && !decl_anon_ns_mem_p (btype))
3146 warning (OPT_Wsubobject_linkage, "\
3147 %qT has a base %qT which has internal linkage",
3148 type, btype);
3149 else // In C++98 this can only happen with unnamed namespaces.
3150 warning (OPT_Wsubobject_linkage, "\
3151 %qT has a base %qT which uses the anonymous namespace",
3152 type, btype);
3155 else if (vis < VISIBILITY_HIDDEN
3156 && subvis >= VISIBILITY_HIDDEN)
3157 warning (OPT_Wattributes, "\
3158 %qT declared with greater visibility than its base %qT",
3159 type, TREE_TYPE (t));
3163 /* Functions for adjusting the visibility of a tagged type and its nested
3164 types and declarations when it gets a name for linkage purposes from a
3165 typedef. */
3166 // FIXME: It is now a DR for such a class type to contain anything
3167 // other than C. So at minium most of this can probably be deleted.
3169 /* First reset the visibility of all the types. */
3171 static void
3172 reset_type_linkage_1 (tree type)
3174 set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
3175 if (CLASS_TYPE_P (type))
3176 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
3177 if (DECL_IMPLICIT_TYPEDEF_P (member))
3178 reset_type_linkage_1 (TREE_TYPE (member));
3181 /* Then reset the visibility of any static data members or member
3182 functions that use those types. */
3184 static void
3185 reset_decl_linkage (tree decl)
3187 if (TREE_PUBLIC (decl))
3188 return;
3189 if (DECL_CLONED_FUNCTION_P (decl))
3190 return;
3191 TREE_PUBLIC (decl) = true;
3192 DECL_INTERFACE_KNOWN (decl) = false;
3193 determine_visibility (decl);
3194 tentative_decl_linkage (decl);
3197 void
3198 reset_type_linkage (tree type)
3200 reset_type_linkage_1 (type);
3201 if (CLASS_TYPE_P (type))
3203 if (tree vt = CLASSTYPE_VTABLES (type))
3205 tree name = mangle_vtbl_for_type (type);
3206 DECL_NAME (vt) = name;
3207 SET_DECL_ASSEMBLER_NAME (vt, name);
3208 reset_decl_linkage (vt);
3210 if (!ANON_AGGR_TYPE_P (type))
3211 if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
3213 tree name = mangle_typeinfo_for_type (type);
3214 DECL_NAME (ti) = name;
3215 SET_DECL_ASSEMBLER_NAME (ti, name);
3216 TREE_TYPE (name) = type;
3217 reset_decl_linkage (ti);
3219 for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
3221 tree mem = STRIP_TEMPLATE (m);
3222 if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
3223 reset_decl_linkage (mem);
3224 else if (DECL_IMPLICIT_TYPEDEF_P (mem))
3225 reset_type_linkage (TREE_TYPE (mem));
3230 /* Set up our initial idea of what the linkage of DECL should be. */
3232 void
3233 tentative_decl_linkage (tree decl)
3235 if (DECL_INTERFACE_KNOWN (decl))
3236 /* We've already made a decision as to how this function will
3237 be handled. */;
3238 else if (vague_linkage_p (decl))
3240 if (TREE_CODE (decl) == FUNCTION_DECL
3241 && decl_defined_p (decl))
3243 DECL_EXTERNAL (decl) = 1;
3244 DECL_NOT_REALLY_EXTERN (decl) = 1;
3245 note_vague_linkage_fn (decl);
3246 /* A non-template inline function with external linkage will
3247 always be COMDAT. As we must eventually determine the
3248 linkage of all functions, and as that causes writes to
3249 the data mapped in from the PCH file, it's advantageous
3250 to mark the functions at this point. */
3251 if (DECL_DECLARED_INLINE_P (decl)
3252 && (!DECL_IMPLICIT_INSTANTIATION (decl)
3253 || DECL_DEFAULTED_FN (decl)))
3255 /* This function must have external linkage, as
3256 otherwise DECL_INTERFACE_KNOWN would have been
3257 set. */
3258 gcc_assert (TREE_PUBLIC (decl));
3259 comdat_linkage (decl);
3260 DECL_INTERFACE_KNOWN (decl) = 1;
3263 else if (VAR_P (decl))
3264 maybe_commonize_var (decl);
3268 /* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage
3269 for DECL has not already been determined, do so now by setting
3270 DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this
3271 function is called entities with vague linkage whose definitions
3272 are available must have TREE_PUBLIC set.
3274 If this function decides to place DECL in COMDAT, it will set
3275 appropriate flags -- but will not clear DECL_EXTERNAL. It is up to
3276 the caller to decide whether or not to clear DECL_EXTERNAL. Some
3277 callers defer that decision until it is clear that DECL is actually
3278 required. */
3280 void
3281 import_export_decl (tree decl)
3283 bool comdat_p;
3284 bool import_p;
3285 tree class_type = NULL_TREE;
3287 if (DECL_INTERFACE_KNOWN (decl))
3288 return;
3290 /* We cannot determine what linkage to give to an entity with vague
3291 linkage until the end of the file. For example, a virtual table
3292 for a class will be defined if and only if the key method is
3293 defined in this translation unit. */
3294 gcc_assert (at_eof);
3295 /* Object file linkage for explicit instantiations is handled in
3296 mark_decl_instantiated. For static variables in functions with
3297 vague linkage, maybe_commonize_var is used.
3299 Therefore, the only declarations that should be provided to this
3300 function are those with external linkage that are:
3302 * implicit instantiations of function templates
3304 * inline function
3306 * implicit instantiations of static data members of class
3307 templates
3309 * virtual tables
3311 * typeinfo objects
3313 Furthermore, all entities that reach this point must have a
3314 definition available in this translation unit.
3316 The following assertions check these conditions. */
3317 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
3318 /* Any code that creates entities with TREE_PUBLIC cleared should
3319 also set DECL_INTERFACE_KNOWN. */
3320 gcc_assert (TREE_PUBLIC (decl));
3321 if (TREE_CODE (decl) == FUNCTION_DECL)
3322 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3323 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
3324 || DECL_DECLARED_INLINE_P (decl));
3325 else
3326 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3327 || DECL_VTABLE_OR_VTT_P (decl)
3328 || DECL_TINFO_P (decl));
3329 /* Check that a definition of DECL is available in this translation
3330 unit. */
3331 gcc_assert (!DECL_REALLY_EXTERN (decl));
3333 /* Assume that DECL will not have COMDAT linkage. */
3334 comdat_p = false;
3335 /* Assume that DECL will not be imported into this translation
3336 unit. */
3337 import_p = false;
3339 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
3341 class_type = DECL_CONTEXT (decl);
3342 import_export_class (class_type);
3343 if (CLASSTYPE_INTERFACE_KNOWN (class_type)
3344 && CLASSTYPE_INTERFACE_ONLY (class_type))
3345 import_p = true;
3346 else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
3347 && !CLASSTYPE_USE_TEMPLATE (class_type)
3348 && CLASSTYPE_KEY_METHOD (class_type)
3349 && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
3350 /* The ABI requires that all virtual tables be emitted with
3351 COMDAT linkage. However, on systems where COMDAT symbols
3352 don't show up in the table of contents for a static
3353 archive, or on systems without weak symbols (where we
3354 approximate COMDAT linkage by using internal linkage), the
3355 linker will report errors about undefined symbols because
3356 it will not see the virtual table definition. Therefore,
3357 in the case that we know that the virtual table will be
3358 emitted in only one translation unit, we make the virtual
3359 table an ordinary definition with external linkage. */
3360 DECL_EXTERNAL (decl) = 0;
3361 else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
3363 /* CLASS_TYPE is being exported from this translation unit,
3364 so DECL should be defined here. */
3365 if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
3366 /* If a class is declared in a header with the "extern
3367 template" extension, then it will not be instantiated,
3368 even in translation units that would normally require
3369 it. Often such classes are explicitly instantiated in
3370 one translation unit. Therefore, the explicit
3371 instantiation must be made visible to other translation
3372 units. */
3373 DECL_EXTERNAL (decl) = 0;
3374 else
3376 /* The generic C++ ABI says that class data is always
3377 COMDAT, even if there is a key function. Some
3378 variants (e.g., the ARM EABI) says that class data
3379 only has COMDAT linkage if the class data might be
3380 emitted in more than one translation unit. When the
3381 key method can be inline and is inline, we still have
3382 to arrange for comdat even though
3383 class_data_always_comdat is false. */
3384 if (!CLASSTYPE_KEY_METHOD (class_type)
3385 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
3386 || targetm.cxx.class_data_always_comdat ())
3388 /* The ABI requires COMDAT linkage. Normally, we
3389 only emit COMDAT things when they are needed;
3390 make sure that we realize that this entity is
3391 indeed needed. */
3392 comdat_p = true;
3393 mark_needed (decl);
3397 else if (!flag_implicit_templates
3398 && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
3399 import_p = true;
3400 else
3401 comdat_p = true;
3403 else if (VAR_P (decl) && DECL_TINFO_P (decl))
3405 tree type = TREE_TYPE (DECL_NAME (decl));
3406 if (CLASS_TYPE_P (type))
3408 class_type = type;
3409 import_export_class (type);
3410 if (CLASSTYPE_INTERFACE_KNOWN (type)
3411 && TYPE_POLYMORPHIC_P (type)
3412 && CLASSTYPE_INTERFACE_ONLY (type)
3413 /* If -fno-rtti was specified, then we cannot be sure
3414 that RTTI information will be emitted with the
3415 virtual table of the class, so we must emit it
3416 wherever it is used. */
3417 && flag_rtti)
3418 import_p = true;
3419 else
3421 if (CLASSTYPE_INTERFACE_KNOWN (type)
3422 && !CLASSTYPE_INTERFACE_ONLY (type))
3424 comdat_p = (targetm.cxx.class_data_always_comdat ()
3425 || (CLASSTYPE_KEY_METHOD (type)
3426 && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
3427 mark_needed (decl);
3428 if (!flag_weak)
3430 comdat_p = false;
3431 DECL_EXTERNAL (decl) = 0;
3434 else
3435 comdat_p = true;
3438 else
3439 comdat_p = true;
3441 else if (DECL_TEMPLOID_INSTANTIATION (decl))
3443 /* DECL is an implicit instantiation of a function or static
3444 data member. */
3445 if (flag_implicit_templates
3446 || (flag_implicit_inline_templates
3447 && TREE_CODE (decl) == FUNCTION_DECL
3448 && DECL_DECLARED_INLINE_P (decl)))
3449 comdat_p = true;
3450 else
3451 /* If we are not implicitly generating templates, then mark
3452 this entity as undefined in this translation unit. */
3453 import_p = true;
3455 else if (DECL_FUNCTION_MEMBER_P (decl))
3457 if (!DECL_DECLARED_INLINE_P (decl))
3459 tree ctype = DECL_CONTEXT (decl);
3460 import_export_class (ctype);
3461 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
3463 DECL_NOT_REALLY_EXTERN (decl)
3464 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
3465 || (DECL_DECLARED_INLINE_P (decl)
3466 && ! flag_implement_inlines
3467 && !DECL_VINDEX (decl)));
3469 if (!DECL_NOT_REALLY_EXTERN (decl))
3470 DECL_EXTERNAL (decl) = 1;
3472 /* Always make artificials weak. */
3473 if (DECL_ARTIFICIAL (decl) && flag_weak)
3474 comdat_p = true;
3475 else
3476 maybe_make_one_only (decl);
3479 else
3480 comdat_p = true;
3482 else
3483 comdat_p = true;
3485 if (import_p)
3487 /* If we are importing DECL into this translation unit, mark is
3488 an undefined here. */
3489 DECL_EXTERNAL (decl) = 1;
3490 DECL_NOT_REALLY_EXTERN (decl) = 0;
3492 else if (comdat_p)
3494 /* If we decided to put DECL in COMDAT, mark it accordingly at
3495 this point. */
3496 comdat_linkage (decl);
3499 DECL_INTERFACE_KNOWN (decl) = 1;
3502 /* Return an expression that performs the destruction of DECL, which
3503 must be a VAR_DECL whose type has a non-trivial destructor, or is
3504 an array whose (innermost) elements have a non-trivial destructor. */
3506 tree
3507 build_cleanup (tree decl)
3509 tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
3510 gcc_assert (clean != NULL_TREE);
3511 return clean;
3514 /* GUARD is a helper variable for DECL; make them have the same linkage and
3515 visibility. */
3517 void
3518 copy_linkage (tree guard, tree decl)
3520 TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3521 TREE_STATIC (guard) = TREE_STATIC (decl);
3522 DECL_COMMON (guard) = DECL_COMMON (decl);
3523 DECL_COMDAT (guard) = DECL_COMDAT (decl);
3524 if (TREE_STATIC (guard))
3526 CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
3527 set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3528 if (DECL_ONE_ONLY (decl))
3529 make_decl_one_only (guard, cxx_comdat_group (guard));
3530 if (TREE_PUBLIC (decl))
3531 DECL_WEAK (guard) = DECL_WEAK (decl);
3532 /* Also check vague_linkage_p, as DECL_WEAK and DECL_ONE_ONLY might not
3533 be set until import_export_decl at EOF. */
3534 if (vague_linkage_p (decl))
3535 comdat_linkage (guard);
3536 DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3537 DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3541 /* Returns the initialization guard variable for the variable DECL,
3542 which has static storage duration. */
3544 tree
3545 get_guard (tree decl)
3547 tree sname = mangle_guard_variable (decl);
3548 tree guard = get_global_binding (sname);
3549 if (! guard)
3551 tree guard_type;
3553 /* We use a type that is big enough to contain a mutex as well
3554 as an integer counter. */
3555 guard_type = targetm.cxx.guard_type ();
3556 guard = build_decl (DECL_SOURCE_LOCATION (decl),
3557 VAR_DECL, sname, guard_type);
3559 /* The guard should have the same linkage as what it guards. */
3560 copy_linkage (guard, decl);
3562 DECL_ARTIFICIAL (guard) = 1;
3563 DECL_IGNORED_P (guard) = 1;
3564 TREE_USED (guard) = 1;
3565 pushdecl_top_level_and_finish (guard, NULL_TREE);
3567 return guard;
3570 /* Returns true if accessing the GUARD atomic is expensive,
3571 i.e. involves a call to __sync_synchronize or similar.
3572 In this case let __cxa_guard_acquire handle the atomics. */
3574 static bool
3575 is_atomic_expensive_p (machine_mode mode)
3577 if (!flag_inline_atomics)
3578 return true;
3580 if (!can_compare_and_swap_p (mode, false) || !can_atomic_load_p (mode))
3581 return true;
3583 return false;
3586 /* Return an atomic load of src with the appropriate memory model. */
3588 static tree
3589 build_atomic_load_type (tree src, HOST_WIDE_INT model, tree type)
3591 tree ptr_type = build_pointer_type (type);
3592 tree mem_model = build_int_cst (integer_type_node, model);
3593 tree t, addr, val;
3594 unsigned int size;
3595 int fncode;
3597 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
3599 fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
3600 t = builtin_decl_implicit ((enum built_in_function) fncode);
3602 addr = build1 (ADDR_EXPR, ptr_type, src);
3603 val = build_call_expr (t, 2, addr, mem_model);
3604 return val;
3607 /* Return those bits of the GUARD variable that should be set when the
3608 guarded entity is actually initialized. */
3610 static tree
3611 get_guard_bits (tree guard)
3613 if (!targetm.cxx.guard_mask_bit ())
3615 /* We only set the first byte of the guard, in order to leave room
3616 for a mutex in the high-order bits. */
3617 guard = build1 (ADDR_EXPR,
3618 build_pointer_type (TREE_TYPE (guard)),
3619 guard);
3620 guard = build1 (NOP_EXPR,
3621 build_pointer_type (char_type_node),
3622 guard);
3623 guard = build1 (INDIRECT_REF, char_type_node, guard);
3626 return guard;
3629 /* Return an expression which determines whether or not the GUARD
3630 variable has already been initialized. */
3632 tree
3633 get_guard_cond (tree guard, bool thread_safe)
3635 tree guard_value;
3637 if (!thread_safe)
3638 guard = get_guard_bits (guard);
3639 else
3641 tree type = targetm.cxx.guard_mask_bit ()
3642 ? TREE_TYPE (guard) : char_type_node;
3644 if (is_atomic_expensive_p (TYPE_MODE (type)))
3645 guard = integer_zero_node;
3646 else
3647 guard = build_atomic_load_type (guard, MEMMODEL_ACQUIRE, type);
3650 /* Mask off all but the low bit. */
3651 if (targetm.cxx.guard_mask_bit ())
3653 guard_value = integer_one_node;
3654 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3655 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3656 guard = cp_build_binary_op (input_location,
3657 BIT_AND_EXPR, guard, guard_value,
3658 tf_warning_or_error);
3661 guard_value = integer_zero_node;
3662 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3663 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3664 return cp_build_binary_op (input_location,
3665 EQ_EXPR, guard, guard_value,
3666 tf_warning_or_error);
3669 /* Return an expression which sets the GUARD variable, indicating that
3670 the variable being guarded has been initialized. */
3672 tree
3673 set_guard (tree guard)
3675 tree guard_init;
3677 /* Set the GUARD to one. */
3678 guard = get_guard_bits (guard);
3679 guard_init = integer_one_node;
3680 if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3681 guard_init = fold_convert (TREE_TYPE (guard), guard_init);
3682 return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
3683 tf_warning_or_error);
3686 /* Returns true iff we can tell that VAR does not have a dynamic
3687 initializer. */
3689 static bool
3690 var_defined_without_dynamic_init (tree var)
3692 /* constinit vars are guaranteed to not have dynamic initializer,
3693 but still registering the destructor counts as dynamic initialization. */
3694 if (DECL_DECLARED_CONSTINIT_P (var)
3695 && COMPLETE_TYPE_P (TREE_TYPE (var))
3696 && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3697 return true;
3698 /* If it's defined in another TU, we can't tell. */
3699 if (DECL_EXTERNAL (var))
3700 return false;
3701 /* If it has a non-trivial destructor, registering the destructor
3702 counts as dynamic initialization. */
3703 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3704 return false;
3705 /* If it's in this TU, its initializer has been processed, unless
3706 it's a case of self-initialization, then DECL_INITIALIZED_P is
3707 false while the initializer is handled by finish_id_expression. */
3708 if (!DECL_INITIALIZED_P (var))
3709 return false;
3710 /* If it has no initializer or a constant one, it's not dynamic. */
3711 return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3712 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3715 /* Returns true iff VAR is a variable that needs uses to be
3716 wrapped for possible dynamic initialization. */
3718 bool
3719 var_needs_tls_wrapper (tree var)
3721 return (!error_operand_p (var)
3722 && CP_DECL_THREAD_LOCAL_P (var)
3723 && !DECL_GNU_TLS_P (var)
3724 && !DECL_FUNCTION_SCOPE_P (var)
3725 && !var_defined_without_dynamic_init (var));
3728 /* Get the FUNCTION_DECL for the shared TLS init function for this
3729 translation unit. */
3731 static tree
3732 get_local_tls_init_fn (location_t loc)
3734 tree sname = get_identifier ("__tls_init");
3735 tree fn = get_global_binding (sname);
3736 if (!fn)
3738 fn = build_lang_decl_loc (loc, FUNCTION_DECL, sname,
3739 build_function_type (void_type_node,
3740 void_list_node));
3741 SET_DECL_LANGUAGE (fn, lang_c);
3742 TREE_PUBLIC (fn) = false;
3743 DECL_ARTIFICIAL (fn) = true;
3744 mark_used (fn);
3745 set_global_binding (fn);
3747 return fn;
3750 /* Get a FUNCTION_DECL for the init function for the thread_local
3751 variable VAR. The init function will be an alias to the function
3752 that initializes all the non-local TLS variables in the translation
3753 unit. The init function is only used by the wrapper function. */
3755 static tree
3756 get_tls_init_fn (tree var)
3758 /* Only C++11 TLS vars need this init fn. */
3759 if (!var_needs_tls_wrapper (var))
3760 return NULL_TREE;
3762 /* If -fno-extern-tls-init, assume that we don't need to call
3763 a tls init function for a variable defined in another TU. */
3764 if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3765 return NULL_TREE;
3767 /* If the variable is internal, or if we can't generate aliases,
3768 call the local init function directly. */
3769 if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
3770 return get_local_tls_init_fn (DECL_SOURCE_LOCATION (var));
3772 tree sname = mangle_tls_init_fn (var);
3773 tree fn = get_global_binding (sname);
3774 if (!fn)
3776 fn = build_lang_decl (FUNCTION_DECL, sname,
3777 build_function_type (void_type_node,
3778 void_list_node));
3779 SET_DECL_LANGUAGE (fn, lang_c);
3780 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3781 DECL_ARTIFICIAL (fn) = true;
3782 DECL_COMDAT (fn) = DECL_COMDAT (var);
3783 DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3784 if (DECL_ONE_ONLY (var))
3785 make_decl_one_only (fn, cxx_comdat_group (fn));
3786 if (TREE_PUBLIC (var))
3788 tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3789 /* If the variable is defined somewhere else and might have static
3790 initialization, make the init function a weak reference. */
3791 if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3792 || TYPE_HAS_CONSTEXPR_CTOR (obtype)
3793 || TYPE_HAS_TRIVIAL_DFLT (obtype))
3794 && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3795 && DECL_EXTERNAL (var))
3796 declare_weak (fn);
3797 else
3798 DECL_WEAK (fn) = DECL_WEAK (var);
3800 DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3801 DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3802 DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3803 DECL_IGNORED_P (fn) = 1;
3804 mark_used (fn);
3806 DECL_BEFRIENDING_CLASSES (fn) = var;
3808 set_global_binding (fn);
3810 return fn;
3813 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3814 variable VAR. The wrapper function calls the init function (if any) for
3815 VAR and then returns a reference to VAR. The wrapper function is used
3816 in place of VAR everywhere VAR is mentioned. */
3818 static tree
3819 get_tls_wrapper_fn (tree var)
3821 /* Only C++11 TLS vars need this wrapper fn. */
3822 if (!var_needs_tls_wrapper (var))
3823 return NULL_TREE;
3825 tree sname = mangle_tls_wrapper_fn (var);
3826 tree fn = get_global_binding (sname);
3827 if (!fn)
3829 /* A named rvalue reference is an lvalue, so the wrapper should
3830 always return an lvalue reference. */
3831 tree type = non_reference (TREE_TYPE (var));
3832 type = build_reference_type (type);
3833 tree fntype = build_function_type (type, void_list_node);
3835 fn = build_lang_decl_loc (DECL_SOURCE_LOCATION (var),
3836 FUNCTION_DECL, sname, fntype);
3837 SET_DECL_LANGUAGE (fn, lang_c);
3838 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3839 DECL_ARTIFICIAL (fn) = true;
3840 DECL_IGNORED_P (fn) = 1;
3841 /* The wrapper is inline and emitted everywhere var is used. */
3842 DECL_DECLARED_INLINE_P (fn) = true;
3843 if (TREE_PUBLIC (var))
3845 comdat_linkage (fn);
3846 #ifdef HAVE_GAS_HIDDEN
3847 /* Make the wrapper bind locally; there's no reason to share
3848 the wrapper between multiple shared objects. */
3849 DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3850 DECL_VISIBILITY_SPECIFIED (fn) = true;
3851 #endif
3853 if (!TREE_PUBLIC (fn))
3854 DECL_INTERFACE_KNOWN (fn) = true;
3855 mark_used (fn);
3856 note_vague_linkage_fn (fn);
3858 #if 0
3859 /* We want CSE to commonize calls to the wrapper, but marking it as
3860 pure is unsafe since it has side-effects. I guess we need a new
3861 ECF flag even weaker than ECF_PURE. FIXME! */
3862 DECL_PURE_P (fn) = true;
3863 #endif
3865 DECL_BEFRIENDING_CLASSES (fn) = var;
3867 set_global_binding (fn);
3869 return fn;
3872 /* If EXPR is a thread_local variable that should be wrapped by init
3873 wrapper function, return a call to that function, otherwise return
3874 NULL. */
3876 tree
3877 maybe_get_tls_wrapper_call (tree expr)
3879 if (VAR_P (expr)
3880 && !processing_template_decl
3881 && !cp_unevaluated_operand
3882 && CP_DECL_THREAD_LOCAL_P (expr))
3883 if (tree wrap = get_tls_wrapper_fn (expr))
3884 return build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
3885 return NULL;
3888 /* At EOF, generate the definition for the TLS wrapper function FN:
3890 T& var_wrapper() {
3891 if (init_fn) init_fn();
3892 return var;
3893 } */
3895 static void
3896 generate_tls_wrapper (tree fn)
3898 tree var = DECL_BEFRIENDING_CLASSES (fn);
3900 start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3901 tree body = begin_function_body ();
3902 /* Only call the init fn if there might be one. */
3903 if (tree init_fn = get_tls_init_fn (var))
3905 tree if_stmt = NULL_TREE;
3906 /* If init_fn is a weakref, make sure it exists before calling. */
3907 if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3909 if_stmt = begin_if_stmt ();
3910 tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3911 tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3912 NE_EXPR, addr, nullptr_node,
3913 tf_warning_or_error);
3914 finish_if_stmt_cond (cond, if_stmt);
3916 finish_expr_stmt (build_cxx_call
3917 (init_fn, 0, NULL, tf_warning_or_error));
3918 if (if_stmt)
3920 finish_then_clause (if_stmt);
3921 finish_if_stmt (if_stmt);
3924 else
3925 /* If there's no initialization, the wrapper is a constant function. */
3926 TREE_READONLY (fn) = true;
3927 finish_return_stmt (convert_from_reference (var));
3928 finish_function_body (body);
3929 expand_or_defer_fn (finish_function (/*inline_p=*/false));
3932 /* Start a global constructor or destructor function. */
3934 static tree
3935 start_objects (bool initp, unsigned priority, bool has_body)
3937 bool default_init = initp && priority == DEFAULT_INIT_PRIORITY;
3938 bool is_module_init = default_init && module_global_init_needed ();
3939 tree name = NULL_TREE;
3941 if (is_module_init)
3942 name = mangle_module_global_init (0);
3943 else
3945 char type[14];
3947 /* We use `I' to indicate initialization and `D' to indicate
3948 destruction. */
3949 unsigned len = sprintf (type, "sub_%c", initp ? 'I' : 'D');
3950 if (priority != DEFAULT_INIT_PRIORITY)
3952 char joiner = '_';
3953 #ifdef JOINER
3954 joiner = JOINER;
3955 #endif
3956 type[len++] = joiner;
3957 sprintf (type + len, "%.5u", priority);
3959 name = get_file_function_name (type);
3962 tree fntype = build_function_type (void_type_node, void_list_node);
3963 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
3964 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
3965 if (is_module_init)
3967 SET_DECL_ASSEMBLER_NAME (fndecl, name);
3968 TREE_PUBLIC (fndecl) = true;
3969 determine_visibility (fndecl);
3971 else
3972 TREE_PUBLIC (fndecl) = 0;
3973 start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3975 /* Mark as artificial because it's not explicitly in the user's
3976 source code. */
3977 DECL_ARTIFICIAL (current_function_decl) = 1;
3979 /* Mark this declaration as used to avoid spurious warnings. */
3980 TREE_USED (current_function_decl) = 1;
3982 /* Mark this function as a global constructor or destructor. */
3983 if (initp)
3984 DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3985 else
3986 DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3988 tree body = begin_compound_stmt (BCS_FN_BODY);
3990 if (is_module_init && has_body)
3992 // If the function is going to be empty, don't emit idempotency.
3993 // 'static bool __in_chrg = false;
3994 // if (__inchrg) return;
3995 // __inchrg = true
3996 tree var = build_lang_decl (VAR_DECL, in_charge_identifier,
3997 boolean_type_node);
3998 DECL_CONTEXT (var) = fndecl;
3999 DECL_ARTIFICIAL (var) = true;
4000 TREE_STATIC (var) = true;
4001 pushdecl (var);
4002 cp_finish_decl (var, NULL_TREE, false, NULL_TREE, 0);
4004 tree if_stmt = begin_if_stmt ();
4005 finish_if_stmt_cond (var, if_stmt);
4006 finish_return_stmt (NULL_TREE);
4007 finish_then_clause (if_stmt);
4008 finish_if_stmt (if_stmt);
4010 tree assign = build2 (MODIFY_EXPR, boolean_type_node,
4011 var, boolean_true_node);
4012 TREE_SIDE_EFFECTS (assign) = true;
4013 finish_expr_stmt (assign);
4016 return body;
4019 /* Finish a global constructor or destructor. Add it to the global
4020 ctors or dtors, if STARTP is true. */
4022 static tree
4023 finish_objects (bool initp, unsigned priority, tree body, bool startp)
4025 /* Finish up. */
4026 finish_compound_stmt (body);
4027 tree fn = finish_function (/*inline_p=*/false);
4029 if (!startp)
4030 ; // Neither ctor nor dtor I be.
4031 else if (initp)
4033 DECL_STATIC_CONSTRUCTOR (fn) = 1;
4034 decl_init_priority_insert (fn, priority);
4036 else
4038 DECL_STATIC_DESTRUCTOR (fn) = 1;
4039 decl_fini_priority_insert (fn, priority);
4042 return fn;
4045 /* The name of the function we create to handle initializations and
4046 destructions for objects with static storage duration. */
4047 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
4049 /* Begins the generation of the function that will handle all
4050 initialization or destruction of objects with static storage
4051 duration at PRIORITY.
4053 It is assumed that this function will only be called once. */
4055 static tree
4056 start_partial_init_fini_fn (bool initp, unsigned priority, unsigned count)
4058 char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
4060 /* Create the identifier for this function. It will be of the form
4061 SSDF_IDENTIFIER_<number>. */
4062 sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
4064 tree type = build_function_type (void_type_node, void_list_node);
4066 /* Create the FUNCTION_DECL itself. */
4067 tree fn = build_lang_decl (FUNCTION_DECL, get_identifier (id), type);
4068 TREE_PUBLIC (fn) = 0;
4069 DECL_ARTIFICIAL (fn) = 1;
4071 /* Put this function in the list of functions to be called from the
4072 static constructors and destructors. */
4073 if (!static_init_fini_fns[initp])
4074 static_init_fini_fns[initp] = priority_map_t::create_ggc ();
4075 auto &slot = static_init_fini_fns[initp]->get_or_insert (priority);
4076 slot = tree_cons (fn, NULL_TREE, slot);
4078 /* Put the function in the global scope. */
4079 pushdecl (fn);
4081 /* Start the function itself. This is equivalent to declaring the
4082 function as:
4084 static void __ssdf (int __initialize_p, init __priority_p);
4086 It is static because we only need to call this function from the
4087 various constructor and destructor functions for this module. */
4088 start_preparsed_function (fn, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
4090 /* Set up the scope of the outermost block in the function. */
4091 return begin_compound_stmt (BCS_FN_BODY);
4094 /* Finish the generation of the function which performs initialization
4095 or destruction of objects with static storage duration. */
4097 static void
4098 finish_partial_init_fini_fn (tree body)
4100 /* Close out the function. */
4101 finish_compound_stmt (body);
4102 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4105 /* The effective initialization priority of a DECL. */
4107 #define DECL_EFFECTIVE_INIT_PRIORITY(decl) \
4108 ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
4109 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
4111 /* Whether a DECL needs a guard to protect it against multiple
4112 initialization. */
4114 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \
4115 || DECL_ONE_ONLY (decl) \
4116 || DECL_WEAK (decl)))
4118 /* Walks the initializer list of a global variable and looks for
4119 temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
4120 and that have their DECL_CONTEXT() == NULL. For each such
4121 temporary variable, set their DECL_CONTEXT() to CTX -- the
4122 initializing function. This is necessary because otherwise some
4123 optimizers (enabled by -O2 -fprofile-arcs) might crash when trying
4124 to refer to a temporary variable that does not have its
4125 DECL_CONTEXT() properly set. */
4127 static tree
4128 fix_temporary_vars_context_r (tree *node,
4129 int * /*unused*/,
4130 void *ctx)
4132 if (TREE_CODE (*node) == BIND_EXPR)
4133 for (tree var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
4134 if (VAR_P (var) && !DECL_NAME (var)
4135 && DECL_ARTIFICIAL (var) && !DECL_CONTEXT (var))
4136 DECL_CONTEXT (var) = tree (ctx);
4138 return NULL_TREE;
4141 /* Set up to handle the initialization or destruction of DECL. If
4142 INITP is nonzero, we are initializing the variable. Otherwise, we
4143 are destroying it. */
4145 static void
4146 one_static_initialization_or_destruction (bool initp, tree decl, tree init)
4148 /* If we are supposed to destruct and there's a trivial destructor,
4149 nothing has to be done. */
4150 gcc_checking_assert (init || !TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)));
4152 /* Trick the compiler into thinking we are at the file and line
4153 where DECL was declared so that error-messages make sense, and so
4154 that the debugger will show somewhat sensible file and line
4155 information. */
4156 input_location = DECL_SOURCE_LOCATION (decl);
4158 /* Make sure temporary variables in the initialiser all have
4159 their DECL_CONTEXT() set to a value different from NULL_TREE.
4160 This can happen when global variables initializers are built.
4161 In that case, the DECL_CONTEXT() of the global variables _AND_ of all
4162 the temporary variables that might have been generated in the
4163 accompanying initializers is NULL_TREE, meaning the variables have been
4164 declared in the global namespace.
4165 What we want to do here is to fix that and make sure the DECL_CONTEXT()
4166 of the temporaries are set to the current function decl. */
4167 cp_walk_tree_without_duplicates (&init,
4168 fix_temporary_vars_context_r,
4169 current_function_decl);
4171 /* Because of:
4173 [class.access.spec]
4175 Access control for implicit calls to the constructors,
4176 the conversion functions, or the destructor called to
4177 create and destroy a static data member is performed as
4178 if these calls appeared in the scope of the member's
4179 class.
4181 we pretend we are in a static member function of the class of
4182 which the DECL is a member. */
4183 if (member_p (decl))
4185 DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
4186 DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
4189 /* Assume we don't need a guard. */
4190 tree guard_if_stmt = NULL_TREE;
4192 /* We need a guard if this is an object with external linkage that
4193 might be initialized in more than one place. (For example, a
4194 static data member of a template, when the data member requires
4195 construction.) */
4196 if (NEEDS_GUARD_P (decl))
4198 tree guard = get_guard (decl);
4199 tree guard_cond;
4201 if (flag_use_cxa_atexit)
4203 /* When using __cxa_atexit, we just check the GUARD as we
4204 would for a local static. We never try to destroy
4205 anything from a static destructor. */
4206 gcc_assert (initp);
4207 guard_cond = get_guard_cond (guard, false);
4209 else
4211 /* If we don't have __cxa_atexit, then we will be running
4212 destructors from .fini sections, or their equivalents.
4213 So, we need to know how many times we've tried to
4214 initialize this object. We do initializations only if
4215 the GUARD was or becomes zero (initp vs !initp
4216 respectively). */
4217 guard_cond = cp_build_unary_op (initp ? POSTINCREMENT_EXPR
4218 : PREDECREMENT_EXPR,
4219 guard,
4220 /*noconvert=*/true,
4221 tf_warning_or_error);
4222 guard_cond = cp_build_binary_op (input_location, EQ_EXPR, guard_cond,
4223 integer_zero_node,
4224 tf_warning_or_error);
4227 guard_if_stmt = begin_if_stmt ();
4228 finish_if_stmt_cond (guard_cond, guard_if_stmt);
4230 if (flag_use_cxa_atexit)
4231 /* Set the GUARD now. */
4232 finish_expr_stmt (set_guard (guard));
4235 /* Perform the initialization or destruction. */
4236 if (initp)
4238 if (init)
4240 finish_expr_stmt (init);
4241 if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
4242 if (varpool_node *vnode = varpool_node::get (decl))
4243 vnode->dynamically_initialized = 1;
4246 /* If we're using __cxa_atexit, register a function that calls the
4247 destructor for the object. */
4248 if (flag_use_cxa_atexit)
4249 finish_expr_stmt (register_dtor_fn (decl));
4251 else
4252 finish_expr_stmt (build_cleanup (decl));
4254 /* Finish the guard if-stmt, if necessary. */
4255 if (guard_if_stmt)
4257 finish_then_clause (guard_if_stmt);
4258 finish_if_stmt (guard_if_stmt);
4261 /* Now that we're done with DECL we don't need to pretend to be a
4262 member of its class any longer. */
4263 DECL_CONTEXT (current_function_decl) = NULL_TREE;
4264 DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
4267 /* Generate code to do the initialization or destruction of the decls in VARS,
4268 a TREE_LIST of VAR_DECL with static storage duration.
4269 Whether initialization or destruction is performed is specified by INITP. */
4271 static void
4272 emit_partial_init_fini_fn (bool initp, unsigned priority, tree vars,
4273 unsigned counter, location_t locus)
4275 input_location = locus;
4276 tree body = start_partial_init_fini_fn (initp, priority, counter);
4278 for (tree node = vars; node; node = TREE_CHAIN (node))
4279 /* Do one initialization or destruction. */
4280 one_static_initialization_or_destruction (initp, TREE_VALUE (node),
4281 TREE_PURPOSE (node));
4283 /* Finish up the static storage duration function for this
4284 round. */
4285 input_location = locus;
4286 finish_partial_init_fini_fn (body);
4289 /* VARS is a list of variables with static storage duration which may
4290 need initialization and/or finalization. Remove those variables
4291 that don't really need to be initialized or finalized, and return
4292 the resulting list. The order in which the variables appear in
4293 VARS is in reverse order of the order in which they should actually
4294 be initialized. That order is preserved. */
4296 static tree
4297 prune_vars_needing_no_initialization (tree *vars)
4299 tree *var = vars;
4300 tree result = NULL_TREE;
4302 while (*var)
4304 tree t = *var;
4305 tree decl = TREE_VALUE (t);
4306 tree init = TREE_PURPOSE (t);
4308 /* Deal gracefully with error. */
4309 if (error_operand_p (decl))
4311 var = &TREE_CHAIN (t);
4312 continue;
4315 /* The only things that can be initialized are variables. */
4316 gcc_assert (VAR_P (decl));
4318 /* If this object is not defined, we don't need to do anything
4319 here. */
4320 if (DECL_EXTERNAL (decl))
4322 var = &TREE_CHAIN (t);
4323 continue;
4326 /* Also, if the initializer already contains errors, we can bail
4327 out now. */
4328 if (init && TREE_CODE (init) == TREE_LIST
4329 && value_member (error_mark_node, init))
4331 var = &TREE_CHAIN (t);
4332 continue;
4335 /* This variable is going to need initialization and/or
4336 finalization, so we add it to the list. */
4337 *var = TREE_CHAIN (t);
4338 TREE_CHAIN (t) = result;
4339 result = t;
4342 return result;
4345 /* Split VAR_LIST by init priority and add into PARTS hash table.
4346 This reverses the variable ordering. */
4348 void
4349 partition_vars_for_init_fini (tree var_list, priority_map_t *(&parts)[2])
4351 for (auto node = var_list; node; node = TREE_CHAIN (node))
4353 tree decl = TREE_VALUE (node);
4354 tree init = TREE_PURPOSE (node);
4355 bool has_cleanup = !TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl));
4356 unsigned priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
4358 if (init || (flag_use_cxa_atexit && has_cleanup))
4360 // Add to initialization list.
4361 if (!parts[true])
4362 parts[true] = priority_map_t::create_ggc ();
4363 auto &slot = parts[true]->get_or_insert (priority);
4364 slot = tree_cons (init, decl, slot);
4367 if (!flag_use_cxa_atexit && has_cleanup)
4369 // Add to finalization list.
4370 if (!parts[false])
4371 parts[false] = priority_map_t::create_ggc ();
4372 auto &slot = parts[false]->get_or_insert (priority);
4373 slot = tree_cons (NULL_TREE, decl, slot);
4378 /* Make sure we have told the back end about all the variables in
4379 VARS. */
4381 static void
4382 write_out_vars (tree vars)
4384 tree v;
4386 for (v = vars; v; v = TREE_CHAIN (v))
4388 tree var = TREE_VALUE (v);
4389 if (!var_finalized_p (var))
4391 import_export_decl (var);
4392 rest_of_decl_compilation (var, 1, 1);
4397 /* Generate a static constructor or destructor that calls the given
4398 init/fini fns at the indicated priority. */
4400 static void
4401 generate_ctor_or_dtor_function (bool initp, unsigned priority,
4402 tree fns, location_t locus)
4404 input_location = locus;
4405 tree body = start_objects (initp, priority, bool (fns));
4407 if (fns)
4409 /* To make sure dynamic construction doesn't access globals from
4410 other compilation units where they might not be yet
4411 constructed, for -fsanitize=address insert
4412 __asan_before_dynamic_init call that prevents access to
4413 either all global variables that need construction in other
4414 compilation units, or at least those that haven't been
4415 initialized yet. Variables that need dynamic construction in
4416 the current compilation unit are kept accessible. */
4417 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4418 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
4420 /* Call the static init/fini functions. */
4421 for (tree node = fns; node; node = TREE_CHAIN (node))
4423 tree fn = TREE_PURPOSE (node);
4425 // We should never find a pure or constant cdtor.
4426 gcc_checking_assert (!(flags_from_decl_or_type (fn)
4427 & (ECF_CONST | ECF_PURE)));
4429 tree call = cp_build_function_call_nary (fn, tf_warning_or_error,
4430 NULL_TREE);
4431 finish_expr_stmt (call);
4434 /* Revert what __asan_before_dynamic_init did by calling
4435 __asan_after_dynamic_init. */
4436 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4437 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
4440 /* Close out the function, and arrange for it to be called at init
4441 or fini time, if non-empty. (Even non-nop module initializer
4442 functions need this, as we cannot guarantee the module is
4443 imported somewhere in the program.) */
4444 expand_or_defer_fn (finish_objects (initp, priority, body, fns != NULL_TREE));
4447 /* Return C++ property of T, based on given operation OP. */
4449 static int
4450 cpp_check (tree t, cpp_operation op)
4452 switch (op)
4454 case HAS_DEPENDENT_TEMPLATE_ARGS:
4456 tree ti = CLASSTYPE_TEMPLATE_INFO (t);
4457 if (!ti)
4458 return 0;
4459 ++processing_template_decl;
4460 const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
4461 --processing_template_decl;
4462 return dep;
4464 case IS_ABSTRACT:
4465 return DECL_PURE_VIRTUAL_P (t);
4466 case IS_ASSIGNMENT_OPERATOR:
4467 return DECL_ASSIGNMENT_OPERATOR_P (t);
4468 case IS_CONSTRUCTOR:
4469 return DECL_CONSTRUCTOR_P (t);
4470 case IS_DESTRUCTOR:
4471 return DECL_DESTRUCTOR_P (t);
4472 case IS_COPY_CONSTRUCTOR:
4473 return DECL_COPY_CONSTRUCTOR_P (t);
4474 case IS_MOVE_CONSTRUCTOR:
4475 return DECL_MOVE_CONSTRUCTOR_P (t);
4476 case IS_TEMPLATE:
4477 return TREE_CODE (t) == TEMPLATE_DECL;
4478 case IS_TRIVIAL:
4479 return trivial_type_p (t);
4480 default:
4481 return 0;
4485 /* Collect source file references recursively, starting from NAMESPC. */
4487 static void
4488 collect_source_refs (tree namespc)
4490 /* Iterate over names in this name space. */
4491 for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4492 if (DECL_IS_UNDECLARED_BUILTIN (t))
4494 else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
4495 collect_source_refs (t);
4496 else
4497 collect_source_ref (DECL_SOURCE_FILE (t));
4500 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4501 starting from NAMESPC. */
4503 static void
4504 collect_ada_namespace (tree namespc, const char *source_file)
4506 tree decl = NAMESPACE_LEVEL (namespc)->names;
4508 /* Collect decls from this namespace. This will skip
4509 NAMESPACE_DECLs (both aliases and regular, it cannot tell). */
4510 collect_ada_nodes (decl, source_file);
4512 /* Now scan for namespace children, and dump them. */
4513 for (; decl; decl = TREE_CHAIN (decl))
4514 if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
4515 collect_ada_namespace (decl, source_file);
4518 /* Returns true iff there is a definition available for variable or
4519 function DECL. */
4521 bool
4522 decl_defined_p (tree decl)
4524 if (TREE_CODE (decl) == FUNCTION_DECL)
4525 return (DECL_INITIAL (decl) != NULL_TREE
4526 /* A pending instantiation of a friend temploid is defined. */
4527 || (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
4528 && DECL_INITIAL (DECL_TEMPLATE_RESULT
4529 (DECL_TI_TEMPLATE (decl)))));
4530 else
4532 gcc_assert (VAR_P (decl));
4533 return !DECL_EXTERNAL (decl);
4537 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4539 [expr.const]
4541 An integral constant-expression can only involve ... const
4542 variables of integral or enumeration types initialized with
4543 constant expressions ...
4545 C++0x also allows constexpr variables and temporaries initialized
4546 with constant expressions. We handle the former here, but the latter
4547 are just folded away in cxx_eval_constant_expression.
4549 The standard does not require that the expression be non-volatile.
4550 G++ implements the proposed correction in DR 457. */
4552 bool
4553 decl_constant_var_p (tree decl)
4555 if (!decl_maybe_constant_var_p (decl))
4556 return false;
4558 /* We don't know if a template static data member is initialized with
4559 a constant expression until we instantiate its initializer. Even
4560 in the case of a constexpr variable, we can't treat it as a
4561 constant until its initializer is complete in case it's used in
4562 its own initializer. */
4563 maybe_instantiate_decl (decl);
4564 return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4567 /* Returns true if DECL could be a symbolic constant variable, depending on
4568 its initializer. */
4570 bool
4571 decl_maybe_constant_var_p (tree decl)
4573 tree type = TREE_TYPE (decl);
4574 if (!VAR_P (decl))
4575 return false;
4576 if (DECL_DECLARED_CONSTEXPR_P (decl) && !TREE_THIS_VOLATILE (decl))
4577 return true;
4578 if (DECL_HAS_VALUE_EXPR_P (decl))
4579 /* A proxy isn't constant. */
4580 return false;
4581 if (TYPE_REF_P (type))
4582 /* References can be constant. */;
4583 else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
4584 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4585 /* And const integers. */;
4586 else
4587 return false;
4589 if (DECL_INITIAL (decl)
4590 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
4591 /* We know the initializer, and it isn't constant. */
4592 return false;
4593 else
4594 return true;
4597 /* Complain that DECL uses a type with no linkage. In C++98 mode this is
4598 called from grokfndecl and grokvardecl; in all modes it is called from
4599 cp_write_global_declarations. */
4601 void
4602 no_linkage_error (tree decl)
4604 if (cxx_dialect >= cxx11
4605 && (decl_defined_p (decl)
4606 /* Treat templates which limit_bad_template_recursion decided
4607 not to instantiate as if they were defined. */
4608 || (errorcount + sorrycount > 0
4609 && DECL_LANG_SPECIFIC (decl)
4610 && DECL_TEMPLATE_INFO (decl)
4611 && warning_suppressed_p (decl /* What warning? */))))
4612 /* In C++11 it's ok if the decl is defined. */
4613 return;
4615 if (DECL_LANG_SPECIFIC (decl) && DECL_MODULE_IMPORT_P (decl))
4616 /* An imported decl is ok. */
4617 return;
4619 tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4620 if (t == NULL_TREE)
4621 /* The type that got us on no_linkage_decls must have gotten a name for
4622 linkage purposes. */;
4623 else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4624 // FIXME: This is now invalid, as a DR to c++98
4625 /* The type might end up having a typedef name for linkage purposes. */
4626 vec_safe_push (no_linkage_decls, decl);
4627 else if (TYPE_UNNAMED_P (t))
4629 bool d = false;
4630 auto_diagnostic_group grp;
4631 if (cxx_dialect >= cxx11)
4632 d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4633 "unnamed type, is used but never defined", decl);
4634 else if (DECL_EXTERN_C_P (decl))
4635 /* Allow this; it's pretty common in C. */;
4636 else if (VAR_P (decl))
4637 /* DRs 132, 319 and 389 seem to indicate types with
4638 no linkage can only be used to declare extern "C"
4639 entities. Since it's not always an error in the
4640 ISO C++ 90 Standard, we only issue a warning. */
4641 d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
4642 "with no linkage used to declare variable %q#D with "
4643 "linkage", decl);
4644 else
4645 d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
4646 "linkage used to declare function %q#D with linkage",
4647 decl);
4648 if (d && is_typedef_decl (TYPE_NAME (t)))
4649 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4650 "to the unqualified type, so it is not used for linkage",
4651 TYPE_NAME (t));
4653 else if (cxx_dialect >= cxx11)
4655 if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
4656 permerror (DECL_SOURCE_LOCATION (decl),
4657 "%q#D, declared using local type "
4658 "%qT, is used but never defined", decl, t);
4660 else if (VAR_P (decl))
4661 warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4662 "used to declare variable %q#D with linkage", t, decl);
4663 else
4664 permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4665 "to declare function %q#D with linkage", t, decl);
4668 /* Collect declarations from all namespaces relevant to SOURCE_FILE. */
4670 static void
4671 collect_all_refs (const char *source_file)
4673 collect_ada_namespace (global_namespace, source_file);
4676 /* Clear DECL_EXTERNAL for NODE. */
4678 static bool
4679 clear_decl_external (struct cgraph_node *node, void * /*data*/)
4681 DECL_EXTERNAL (node->decl) = 0;
4682 return false;
4685 /* Build up the function to run dynamic initializers for thread_local
4686 variables in this translation unit and alias the init functions for the
4687 individual variables to it. */
4689 static void
4690 handle_tls_init (void)
4692 tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4693 if (vars == NULL_TREE)
4694 return;
4696 location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4698 write_out_vars (vars);
4700 tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4701 boolean_type_node);
4702 TREE_PUBLIC (guard) = false;
4703 TREE_STATIC (guard) = true;
4704 DECL_ARTIFICIAL (guard) = true;
4705 DECL_IGNORED_P (guard) = true;
4706 TREE_USED (guard) = true;
4707 CP_DECL_THREAD_LOCAL_P (guard) = true;
4708 set_decl_tls_model (guard, decl_default_tls_model (guard));
4709 pushdecl_top_level_and_finish (guard, NULL_TREE);
4711 tree fn = get_local_tls_init_fn (loc);
4712 start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4713 tree body = begin_function_body ();
4714 tree if_stmt = begin_if_stmt ();
4715 tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4716 tf_warning_or_error);
4717 finish_if_stmt_cond (cond, if_stmt);
4718 finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
4719 boolean_true_node,
4720 tf_warning_or_error));
4721 for (; vars; vars = TREE_CHAIN (vars))
4723 tree var = TREE_VALUE (vars);
4724 tree init = TREE_PURPOSE (vars);
4725 one_static_initialization_or_destruction (/*initp=*/true, var, init);
4727 /* Output init aliases even with -fno-extern-tls-init. */
4728 if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
4730 tree single_init_fn = get_tls_init_fn (var);
4731 if (single_init_fn == NULL_TREE)
4732 continue;
4733 cgraph_node *alias
4734 = cgraph_node::get_create (fn)->create_same_body_alias
4735 (single_init_fn, fn);
4736 gcc_assert (alias != NULL);
4740 finish_then_clause (if_stmt);
4741 finish_if_stmt (if_stmt);
4742 finish_function_body (body);
4743 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4746 /* We're at the end of compilation, so generate any mangling aliases that
4747 we've been saving up, if DECL is going to be output and ID2 isn't
4748 already taken by another declaration. */
4750 static void
4751 generate_mangling_alias (tree decl, tree id2)
4753 struct cgraph_node *n = NULL;
4755 if (TREE_CODE (decl) == FUNCTION_DECL)
4757 n = cgraph_node::get (decl);
4758 if (!n)
4759 /* Don't create an alias to an unreferenced function. */
4760 return;
4763 tree *slot
4764 = mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
4765 INSERT);
4767 /* If there's a declaration already using this mangled name,
4768 don't create a compatibility alias that conflicts. */
4769 if (*slot)
4770 return;
4772 tree alias = make_alias_for (decl, id2);
4773 *slot = alias;
4775 DECL_IGNORED_P (alias) = 1;
4776 TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4777 DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4778 if (vague_linkage_p (decl))
4779 DECL_WEAK (alias) = 1;
4781 if (n)
4782 n->create_same_body_alias (alias, decl);
4783 else
4784 varpool_node::create_extra_name_alias (alias, decl);
4787 /* Note that we might want to emit an alias with the symbol ID2 for DECL at
4788 the end of translation, for compatibility across bugs in the mangling
4789 implementation. */
4791 void
4792 note_mangling_alias (tree decl, tree id2)
4794 if (TARGET_SUPPORTS_ALIASES)
4796 if (!defer_mangling_aliases)
4797 generate_mangling_alias (decl, id2);
4798 else
4800 vec_safe_push (mangling_aliases, decl);
4801 vec_safe_push (mangling_aliases, id2);
4806 /* Emit all mangling aliases that were deferred up to this point. */
4808 void
4809 generate_mangling_aliases ()
4811 while (!vec_safe_is_empty (mangling_aliases))
4813 tree id2 = mangling_aliases->pop();
4814 tree decl = mangling_aliases->pop();
4815 generate_mangling_alias (decl, id2);
4817 defer_mangling_aliases = false;
4820 /* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
4821 set. NEED_WARNING is true if we must warn about collisions. We do
4822 this to spot changes in mangling that may require compatibility
4823 aliases. */
4825 void
4826 record_mangling (tree decl, bool need_warning)
4828 if (!mangled_decls)
4829 mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
4831 gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
4832 tree id = DECL_ASSEMBLER_NAME_RAW (decl);
4833 tree *slot
4834 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4835 INSERT);
4837 /* If this is already an alias, cancel the alias, because the real
4838 decl takes precedence. */
4839 if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
4841 if (symtab_node *n = symtab_node::get (*slot))
4843 if (n->cpp_implicit_alias)
4844 /* Actually removing the node isn't safe if other code is already
4845 holding a pointer to it, so just neutralize it. */
4846 n->reset ();
4848 else
4849 /* analyze_functions might have already removed the alias from the
4850 symbol table if it's internal. */
4851 gcc_checking_assert (!TREE_PUBLIC (*slot));
4853 *slot = NULL_TREE;
4856 if (!*slot)
4857 *slot = decl;
4858 else if (need_warning)
4860 error_at (DECL_SOURCE_LOCATION (decl),
4861 "mangling of %q#D as %qE conflicts with a previous mangle",
4862 decl, id);
4863 inform (DECL_SOURCE_LOCATION (*slot),
4864 "previous mangling %q#D", *slot);
4865 inform (DECL_SOURCE_LOCATION (decl),
4866 "a later %<-fabi-version=%> (or =0)"
4867 " avoids this error with a change in mangling");
4868 *slot = decl;
4872 /* The mangled name of DECL is being forcibly changed to NAME. Remove
4873 any existing knowledge of DECL's mangled name meaning DECL. */
4875 void
4876 overwrite_mangling (tree decl, tree name)
4878 if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
4879 if ((TREE_CODE (decl) == VAR_DECL
4880 || TREE_CODE (decl) == FUNCTION_DECL)
4881 && mangled_decls)
4882 if (tree *slot
4883 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4884 NO_INSERT))
4885 if (*slot == decl)
4887 mangled_decls->clear_slot (slot);
4889 /* If this is an alias, remove it from the symbol table. */
4890 if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
4891 if (symtab_node *n = symtab_node::get (decl))
4892 if (n->cpp_implicit_alias)
4893 n->remove ();
4896 DECL_ASSEMBLER_NAME_RAW (decl) = name;
4899 /* The entire file is now complete. If requested, dump everything
4900 to a file. */
4902 static void
4903 dump_tu (void)
4905 dump_flags_t flags;
4906 if (FILE *stream = dump_begin (raw_dump_id, &flags))
4908 dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4909 dump_end (raw_dump_id, stream);
4913 static location_t locus_at_end_of_parsing;
4915 /* Check the deallocation functions for CODE to see if we want to warn that
4916 only one was defined. */
4918 static void
4919 maybe_warn_sized_delete (enum tree_code code)
4921 tree sized = NULL_TREE;
4922 tree unsized = NULL_TREE;
4924 for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
4925 iter; ++iter)
4927 tree fn = *iter;
4928 /* We're only interested in usual deallocation functions. */
4929 if (!usual_deallocation_fn_p (fn))
4930 continue;
4931 if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4932 unsized = fn;
4933 else
4934 sized = fn;
4936 if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
4937 warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
4938 "the program should also define %qD", sized);
4939 else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
4940 warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
4941 "the program should also define %qD", unsized);
4944 /* Check the global deallocation functions to see if we want to warn about
4945 defining unsized without sized (or vice versa). */
4947 static void
4948 maybe_warn_sized_delete ()
4950 if (!flag_sized_deallocation || !warn_sized_deallocation)
4951 return;
4952 maybe_warn_sized_delete (DELETE_EXPR);
4953 maybe_warn_sized_delete (VEC_DELETE_EXPR);
4956 /* Earlier we left PTRMEM_CST in variable initializers alone so that we could
4957 look them up when evaluating non-type template parameters. Now we need to
4958 lower them to something the back end can understand. */
4960 static void
4961 lower_var_init ()
4963 varpool_node *node;
4964 FOR_EACH_VARIABLE (node)
4966 tree d = node->decl;
4967 if (tree init = DECL_INITIAL (d))
4968 DECL_INITIAL (d) = cplus_expand_constant (init);
4972 /* This routine is called at the end of compilation.
4973 Its job is to create all the code needed to initialize and
4974 destroy the global aggregates. We do the destruction
4975 first, since that way we only need to reverse the decls once. */
4977 void
4978 c_parse_final_cleanups (void)
4980 size_t i;
4981 tree decl;
4983 locus_at_end_of_parsing = input_location;
4984 at_eof = 1;
4986 /* Bad parse errors. Just forget about it. */
4987 if (! global_bindings_p () || current_class_type
4988 || !vec_safe_is_empty (decl_namespace_list))
4989 return;
4991 /* This is the point to write out a PCH if we're doing that.
4992 In that case we do not want to do anything else. */
4993 if (pch_file)
4995 /* Mangle all symbols at PCH creation time. */
4996 symtab_node *node;
4997 FOR_EACH_SYMBOL (node)
4998 if (! is_a <varpool_node *> (node)
4999 || ! DECL_HARD_REGISTER (node->decl))
5000 DECL_ASSEMBLER_NAME (node->decl);
5001 c_common_write_pch ();
5002 dump_tu ();
5003 /* Ensure even the callers don't try to finalize the CU. */
5004 flag_syntax_only = 1;
5005 return;
5008 timevar_stop (TV_PHASE_PARSING);
5009 timevar_start (TV_PHASE_DEFERRED);
5011 symtab->process_same_body_aliases ();
5013 /* Handle -fdump-ada-spec[-slim] */
5014 if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
5016 collect_source_ref (main_input_filename);
5017 if (!flag_dump_ada_spec_slim)
5018 collect_source_refs (global_namespace);
5020 dump_ada_specs (collect_all_refs, cpp_check);
5023 /* FIXME - huh? was input_line -= 1;*/
5025 /* We now have to write out all the stuff we put off writing out.
5026 These include:
5028 o Template specializations that we have not yet instantiated,
5029 but which are needed.
5030 o Initialization and destruction for non-local objects with
5031 static storage duration. (Local objects with static storage
5032 duration are initialized when their scope is first entered,
5033 and are cleaned up via atexit.)
5034 o Virtual function tables.
5036 All of these may cause others to be needed. For example,
5037 instantiating one function may cause another to be needed, and
5038 generating the initializer for an object may cause templates to be
5039 instantiated, etc., etc. */
5041 emit_support_tinfos ();
5043 /* Track vtables we want to emit that refer to consteval functions. */
5044 auto_vec<tree> consteval_vtables;
5046 int retries = 0;
5047 unsigned ssdf_count = 0;
5048 for (bool reconsider = true; reconsider; retries++)
5050 reconsider = false;
5052 /* If there are templates that we've put off instantiating, do
5053 them now. */
5054 instantiate_pending_templates (retries);
5055 ggc_collect ();
5057 if (header_module_p ())
5058 /* A header modules initializations are handled in its
5059 importer. */
5060 continue;
5062 /* Write out virtual tables as required. Writing out the
5063 virtual table for a template class may cause the
5064 instantiation of members of that class. If we write out
5065 vtables then we remove the class from our list so we don't
5066 have to look at it again. */
5067 tree t;
5068 for (i = keyed_classes->length ();
5069 keyed_classes->iterate (--i, &t);)
5070 if (maybe_emit_vtables (t, consteval_vtables))
5072 reconsider = true;
5073 keyed_classes->unordered_remove (i);
5075 /* The input_location may have been changed during marking of
5076 vtable entries. */
5077 input_location = locus_at_end_of_parsing;
5079 /* Write out needed type info variables. We have to be careful
5080 looping through unemitted decls, because emit_tinfo_decl may
5081 cause other variables to be needed. New elements will be
5082 appended, and we remove from the vector those that actually
5083 get emitted. */
5084 for (i = unemitted_tinfo_decls->length ();
5085 unemitted_tinfo_decls->iterate (--i, &t);)
5086 if (DECL_INITIAL (t) || emit_tinfo_decl (t))
5088 reconsider = true;
5089 unemitted_tinfo_decls->unordered_remove (i);
5092 /* The list of objects with static storage duration is built up
5093 in reverse order. We clear STATIC_AGGREGATES so that any new
5094 aggregates added during the initialization of these will be
5095 initialized in the correct order when we next come around the
5096 loop. */
5097 if (tree vars = prune_vars_needing_no_initialization (&static_aggregates))
5099 if (flag_openmp)
5100 /* Add initializer information from VARS into
5101 DYNAMIC_INITIALIZERS. */
5102 for (t = vars; t; t = TREE_CHAIN (t))
5103 hash_map_safe_put<hm_ggc> (dynamic_initializers,
5104 TREE_VALUE (t), TREE_PURPOSE (t));
5106 /* Make sure the back end knows about all the variables. */
5107 write_out_vars (vars);
5109 function_depth++; // Disable GC
5110 priority_map_t *parts[2] = {nullptr, nullptr};
5111 partition_vars_for_init_fini (vars, parts);
5113 for (unsigned initp = 2; initp--;)
5114 if (parts[initp])
5115 for (auto iter : *parts[initp])
5117 auto list = iter.second;
5118 if (initp)
5119 // Partitioning kept the vars in reverse order.
5120 // We only want that for dtors.
5121 list = nreverse (list);
5122 emit_partial_init_fini_fn (initp, iter.first, list,
5123 ssdf_count++,
5124 locus_at_end_of_parsing);
5126 function_depth--; // Re-enable GC
5128 /* All those initializations and finalizations might cause
5129 us to need more inline functions, more template
5130 instantiations, etc. */
5131 reconsider = true;
5134 /* Now do the same for thread_local variables. */
5135 handle_tls_init ();
5137 /* Go through the set of inline functions whose bodies have not
5138 been emitted yet. If out-of-line copies of these functions
5139 are required, emit them. */
5140 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5142 /* Does it need synthesizing? */
5143 if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
5144 && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
5146 /* Even though we're already at the top-level, we push
5147 there again. That way, when we pop back a few lines
5148 hence, all of our state is restored. Otherwise,
5149 finish_function doesn't clean things up, and we end
5150 up with CURRENT_FUNCTION_DECL set. */
5151 push_to_top_level ();
5152 /* The decl's location will mark where it was first
5153 needed. Save that so synthesize method can indicate
5154 where it was needed from, in case of error */
5155 input_location = DECL_SOURCE_LOCATION (decl);
5156 synthesize_method (decl);
5157 pop_from_top_level ();
5158 reconsider = true;
5161 if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
5162 generate_tls_wrapper (decl);
5164 if (!DECL_SAVED_TREE (decl))
5165 continue;
5167 cgraph_node *node = cgraph_node::get_create (decl);
5169 /* We lie to the back end, pretending that some functions
5170 are not defined when they really are. This keeps these
5171 functions from being put out unnecessarily. But, we must
5172 stop lying when the functions are referenced, or if they
5173 are not comdat since they need to be put out now. If
5174 DECL_INTERFACE_KNOWN, then we have already set
5175 DECL_EXTERNAL appropriately, so there's no need to check
5176 again, and we do not want to clear DECL_EXTERNAL if a
5177 previous call to import_export_decl set it.
5179 This is done in a separate for cycle, because if some
5180 deferred function is contained in another deferred
5181 function later in deferred_fns varray,
5182 rest_of_compilation would skip this function and we
5183 really cannot expand the same function twice. */
5184 import_export_decl (decl);
5185 if (DECL_NOT_REALLY_EXTERN (decl)
5186 && DECL_INITIAL (decl)
5187 && decl_needed_p (decl))
5189 if (node->cpp_implicit_alias)
5190 node = node->get_alias_target ();
5192 node->call_for_symbol_thunks_and_aliases (clear_decl_external,
5193 NULL, true);
5194 /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
5195 group, we need to mark all symbols in the same comdat group
5196 that way. */
5197 if (node->same_comdat_group)
5198 for (cgraph_node *next
5199 = dyn_cast<cgraph_node *> (node->same_comdat_group);
5200 next != node;
5201 next = dyn_cast<cgraph_node *> (next->same_comdat_group))
5202 next->call_for_symbol_thunks_and_aliases (clear_decl_external,
5203 NULL, true);
5206 /* If we're going to need to write this function out, and
5207 there's already a body for it, create RTL for it now.
5208 (There might be no body if this is a method we haven't
5209 gotten around to synthesizing yet.) */
5210 if (!DECL_EXTERNAL (decl)
5211 && decl_needed_p (decl)
5212 && !TREE_ASM_WRITTEN (decl)
5213 && !DECL_IMMEDIATE_FUNCTION_P (decl)
5214 && !node->definition)
5216 /* We will output the function; no longer consider it in this
5217 loop. */
5218 DECL_DEFER_OUTPUT (decl) = 0;
5219 /* Generate RTL for this function now that we know we
5220 need it. */
5221 expand_or_defer_fn (decl);
5222 reconsider = true;
5226 if (wrapup_namespace_globals ())
5227 reconsider = true;
5229 /* Static data members are just like namespace-scope globals. */
5230 FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
5232 if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
5233 /* Don't write it out if we haven't seen a definition. */
5234 || DECL_IN_AGGR_P (decl))
5235 continue;
5236 import_export_decl (decl);
5237 /* If this static data member is needed, provide it to the
5238 back end. */
5239 if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
5240 DECL_EXTERNAL (decl) = 0;
5243 if (vec_safe_length (pending_statics) != 0
5244 && wrapup_global_declarations (pending_statics->address (),
5245 pending_statics->length ()))
5246 reconsider = true;
5249 void *module_cookie = finish_module_processing (parse_in);
5251 lower_var_init ();
5253 generate_mangling_aliases ();
5255 /* All used inline functions must have a definition at this point. */
5256 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5258 if (/* Check online inline functions that were actually used. */
5259 DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
5260 /* If the definition actually was available here, then the
5261 fact that the function was not defined merely represents
5262 that for some reason (use of a template repository,
5263 #pragma interface, etc.) we decided not to emit the
5264 definition here. */
5265 && !DECL_INITIAL (decl)
5266 /* A defaulted fn in a header module can be synthesized on
5267 demand later. (In non-header modules we should have
5268 synthesized it above.) */
5269 && !(DECL_DEFAULTED_FN (decl) && header_module_p ())
5270 /* Don't complain if the template was defined. */
5271 && !(DECL_TEMPLATE_INSTANTIATION (decl)
5272 && DECL_INITIAL (DECL_TEMPLATE_RESULT
5273 (template_for_substitution (decl))))
5274 && warning_at (DECL_SOURCE_LOCATION (decl), 0,
5275 "inline function %qD used but never defined", decl))
5276 /* Avoid a duplicate warning from check_global_declaration. */
5277 suppress_warning (decl, OPT_Wunused);
5280 /* So must decls that use a type with no linkage. */
5281 FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
5282 no_linkage_error (decl);
5284 maybe_warn_sized_delete ();
5286 // Place the init fns in the right order. We need to do this now,
5287 // so that any module init will go at the start.
5288 if (static_init_fini_fns[true])
5289 for (auto iter : *static_init_fini_fns[true])
5290 iter.second = nreverse (iter.second);
5292 /* Then, do the Objective-C stuff. This is where all the
5293 Objective-C module stuff gets generated (symtab,
5294 class/protocol/selector lists etc). This must be done after C++
5295 templates, destructors etc. so that selectors used in C++
5296 templates are properly allocated. */
5297 if (c_dialect_objc ())
5298 objc_write_global_declarations ();
5300 bool has_module_inits = module_determine_import_inits ();
5301 bool has_objc_init = c_dialect_objc () && objc_static_init_needed_p ();
5302 if (has_module_inits || has_objc_init)
5304 input_location = locus_at_end_of_parsing;
5305 tree body = start_partial_init_fini_fn (true, DEFAULT_INIT_PRIORITY,
5306 ssdf_count++);
5307 /* For Objective-C++, we may need to initialize metadata found
5308 in this module. This must be done _before_ any other static
5309 initializations. */
5310 if (has_objc_init)
5311 objc_generate_static_init_call (NULL_TREE);
5312 if (has_module_inits)
5313 module_add_import_initializers ();
5314 input_location = locus_at_end_of_parsing;
5315 finish_partial_init_fini_fn (body);
5318 if (module_global_init_needed ())
5320 // Make sure there's a default priority entry.
5321 if (!static_init_fini_fns[true])
5322 static_init_fini_fns[true] = priority_map_t::create_ggc ();
5323 if (static_init_fini_fns[true]->get_or_insert (DEFAULT_INIT_PRIORITY))
5324 has_module_inits = true;
5327 /* Generate initialization and destruction functions for all
5328 priorities for which they are required. They have C-language
5329 linkage. */
5330 push_lang_context (lang_name_c);
5331 for (unsigned initp = 2; initp--;)
5332 if (static_init_fini_fns[initp])
5334 for (auto iter : *static_init_fini_fns[initp])
5335 generate_ctor_or_dtor_function (initp, iter.first, iter.second,
5336 locus_at_end_of_parsing);
5337 static_init_fini_fns[initp] = nullptr;
5339 pop_lang_context ();
5341 fini_modules (parse_in, module_cookie, has_module_inits);
5343 /* Generate any missing aliases. */
5344 maybe_apply_pending_pragma_weaks ();
5346 if (flag_vtable_verify)
5348 vtv_recover_class_info ();
5349 vtv_compute_class_hierarchy_transitive_closure ();
5350 vtv_build_vtable_verify_fndecl ();
5353 perform_deferred_noexcept_checks ();
5355 fini_constexpr ();
5356 cp_tree_c_finish_parsing ();
5357 clear_consteval_vfns (consteval_vtables);
5359 /* The entire file is now complete. If requested, dump everything
5360 to a file. */
5361 dump_tu ();
5363 if (flag_detailed_statistics)
5365 dump_tree_statistics ();
5366 dump_time_statistics ();
5369 timevar_stop (TV_PHASE_DEFERRED);
5370 timevar_start (TV_PHASE_PARSING);
5372 /* Indicate that we're done with front end processing. */
5373 at_eof = 2;
5376 /* Perform any post compilation-proper cleanups for the C++ front-end.
5377 This should really go away. No front-end should need to do
5378 anything past the compilation process. */
5380 void
5381 cxx_post_compilation_parsing_cleanups (void)
5383 timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
5385 if (flag_vtable_verify)
5387 /* Generate the special constructor initialization function that
5388 calls __VLTRegisterPairs, and give it a very high
5389 initialization priority. This must be done after
5390 finalize_compilation_unit so that we have accurate
5391 information about which vtable will actually be emitted. */
5392 vtv_generate_init_routine ();
5395 input_location = locus_at_end_of_parsing;
5397 if (flag_checking)
5398 validate_conversion_obstack ();
5400 timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
5403 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
5404 function to call in parse-tree form; it has not yet been
5405 semantically analyzed. ARGS are the arguments to the function.
5406 They have already been semantically analyzed. This may change
5407 ARGS. */
5409 tree
5410 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
5411 tsubst_flags_t complain)
5413 tree orig_fn;
5414 vec<tree, va_gc> *orig_args = NULL;
5415 tree expr;
5416 tree object;
5418 orig_fn = fn;
5419 object = TREE_OPERAND (fn, 0);
5421 if (processing_template_decl)
5423 gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
5424 || TREE_CODE (fn) == MEMBER_REF);
5425 if (type_dependent_expression_p (fn)
5426 || any_type_dependent_arguments_p (*args))
5427 return build_min_nt_call_vec (fn, *args);
5429 orig_args = make_tree_vector_copy (*args);
5431 /* Transform the arguments and add the implicit "this"
5432 parameter. */
5433 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5435 if (TREE_CODE (fn) == DOTSTAR_EXPR)
5436 object = cp_build_addr_expr (object, complain);
5437 vec_safe_insert (*args, 0, object);
5441 /* A qualified name corresponding to a bound pointer-to-member is
5442 represented as an OFFSET_REF:
5444 struct B { void g(); };
5445 void (B::*p)();
5446 void B::g() { (this->*p)(); } */
5447 if (TREE_CODE (fn) == OFFSET_REF)
5449 tree object_addr = cp_build_addr_expr (object, complain);
5450 fn = TREE_OPERAND (fn, 1);
5451 fn = get_member_function_from_ptrfunc (&object_addr, fn,
5452 complain);
5453 vec_safe_insert (*args, 0, object_addr);
5456 if (CLASS_TYPE_P (TREE_TYPE (fn)))
5457 expr = build_op_call (fn, args, complain);
5458 else
5459 expr = cp_build_function_call_vec (fn, args, complain);
5460 if (processing_template_decl && expr != error_mark_node)
5461 expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
5463 if (orig_args != NULL)
5464 release_tree_vector (orig_args);
5466 return expr;
5470 void
5471 check_default_args (tree x)
5473 tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5474 bool saw_def = false;
5475 bool noted_first_def = false;
5476 int idx_of_first_default_arg = 0;
5477 location_t loc_of_first_default_arg = UNKNOWN_LOCATION;
5478 int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5479 tree fndecl = STRIP_TEMPLATE (x);
5480 auto_diagnostic_group d;
5481 for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5483 if (TREE_PURPOSE (arg))
5485 if (!saw_def)
5487 saw_def = true;
5488 idx_of_first_default_arg = i;
5489 location_t loc = get_fndecl_argument_location (fndecl, i);
5490 if (loc != DECL_SOURCE_LOCATION (x))
5491 loc_of_first_default_arg = loc;
5494 else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
5496 error_at (get_fndecl_argument_location (fndecl, i),
5497 "default argument missing for parameter %P of %q#D", i, x);
5498 if (loc_of_first_default_arg != UNKNOWN_LOCATION
5499 && !noted_first_def)
5501 inform (loc_of_first_default_arg,
5502 "...following parameter %P which has a default argument",
5503 idx_of_first_default_arg);
5504 noted_first_def = true;
5506 TREE_PURPOSE (arg) = error_mark_node;
5511 /* Return true if function DECL can be inlined. This is used to force
5512 instantiation of methods that might be interesting for inlining. */
5513 bool
5514 possibly_inlined_p (tree decl)
5516 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5517 if (DECL_UNINLINABLE (decl))
5518 return false;
5519 if (!optimize)
5520 return DECL_DECLARED_INLINE_P (decl);
5521 /* When optimizing, we might inline everything when flatten
5522 attribute or heuristics inlining for size or autoinlining
5523 is used. */
5524 return true;
5527 /* If DECL is a function or variable template specialization, instantiate
5528 its definition now. */
5530 void
5531 maybe_instantiate_decl (tree decl)
5533 if (VAR_OR_FUNCTION_DECL_P (decl)
5534 && DECL_LANG_SPECIFIC (decl)
5535 && DECL_TEMPLATE_INFO (decl)
5536 && !DECL_DECLARED_CONCEPT_P (decl)
5537 && !uses_template_parms (DECL_TI_ARGS (decl)))
5539 /* Instantiating a function will result in garbage collection. We
5540 must treat this situation as if we were within the body of a
5541 function so as to avoid collecting live data only referenced from
5542 the stack (such as overload resolution candidates). */
5543 ++function_depth;
5544 instantiate_decl (decl, /*defer_ok=*/false,
5545 /*expl_inst_class_mem_p=*/false);
5546 --function_depth;
5550 /* Error if the DECL is unavailable (unless this is currently suppressed).
5551 Maybe warn if DECL is deprecated, subject to COMPLAIN. Returns true if
5552 an error or warning was emitted. */
5554 bool
5555 cp_handle_deprecated_or_unavailable (tree decl, tsubst_flags_t complain)
5557 if (!decl)
5558 return false;
5560 if ((complain & tf_error)
5561 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
5563 if (TREE_UNAVAILABLE (decl))
5565 error_unavailable_use (decl, NULL_TREE);
5566 return true;
5568 else
5570 /* Perhaps this is an unavailable typedef. */
5571 if (TYPE_P (decl)
5572 && TYPE_NAME (decl)
5573 && TREE_UNAVAILABLE (TYPE_NAME (decl)))
5575 decl = TYPE_NAME (decl);
5576 /* Don't error within members of a unavailable type. */
5577 if (TYPE_P (decl)
5578 && currently_open_class (decl))
5579 return false;
5581 error_unavailable_use (decl, NULL_TREE);
5582 return true;
5585 /* Carry on to consider deprecatedness. */
5588 if (!(complain & tf_warning)
5589 || deprecated_state == DEPRECATED_SUPPRESS
5590 || deprecated_state == UNAVAILABLE_DEPRECATED_SUPPRESS)
5591 return false;
5593 if (!TREE_DEPRECATED (decl))
5595 /* Perhaps this is a deprecated typedef. */
5596 if (TYPE_P (decl) && TYPE_NAME (decl))
5597 decl = TYPE_NAME (decl);
5599 if (!TREE_DEPRECATED (decl))
5600 return false;
5603 /* Don't warn within members of a deprecated type. */
5604 if (TYPE_P (decl)
5605 && currently_open_class (decl))
5606 return false;
5608 bool warned = false;
5609 if (cxx_dialect >= cxx11
5610 && DECL_P (decl)
5611 && DECL_ARTIFICIAL (decl)
5612 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5613 && copy_fn_p (decl))
5615 /* Don't warn if the flag was disabled around the class definition
5616 (c++/94492). */
5617 if (warning_enabled_at (DECL_SOURCE_LOCATION (decl),
5618 OPT_Wdeprecated_copy))
5620 auto_diagnostic_group d;
5621 tree ctx = DECL_CONTEXT (decl);
5622 tree other = classtype_has_depr_implicit_copy (ctx);
5623 int opt = (DECL_DESTRUCTOR_P (other)
5624 ? OPT_Wdeprecated_copy_dtor
5625 : OPT_Wdeprecated_copy);
5626 warned = warning (opt, "implicitly-declared %qD is deprecated",
5627 decl);
5628 if (warned)
5629 inform (DECL_SOURCE_LOCATION (other),
5630 "because %qT has user-provided %qD",
5631 ctx, other);
5634 else
5635 warned = warn_deprecated_use (decl, NULL_TREE);
5637 return warned;
5640 /* Like above, but takes into account outer scopes. */
5642 void
5643 cp_warn_deprecated_use_scopes (tree scope)
5645 while (scope
5646 && scope != error_mark_node
5647 && scope != global_namespace)
5649 if ((TREE_CODE (scope) == NAMESPACE_DECL || OVERLOAD_TYPE_P (scope))
5650 && cp_handle_deprecated_or_unavailable (scope))
5651 return;
5652 if (TYPE_P (scope))
5653 scope = CP_TYPE_CONTEXT (scope);
5654 else
5655 scope = CP_DECL_CONTEXT (scope);
5659 /* True if DECL or its enclosing scope have unbound template parameters. */
5661 bool
5662 decl_dependent_p (tree decl)
5664 if (DECL_FUNCTION_SCOPE_P (decl)
5665 || TREE_CODE (decl) == CONST_DECL
5666 || TREE_CODE (decl) == USING_DECL
5667 || TREE_CODE (decl) == FIELD_DECL)
5668 decl = CP_DECL_CONTEXT (decl);
5669 if (tree tinfo = get_template_info (decl))
5670 if (any_dependent_template_arguments_p (TI_ARGS (tinfo)))
5671 return true;
5672 if (LAMBDA_FUNCTION_P (decl)
5673 && dependent_type_p (DECL_CONTEXT (decl)))
5674 return true;
5675 return false;
5678 /* [basic.def.odr] A function is named [and therefore odr-used] by an
5679 expression or conversion if it is the selected member of an overload set in
5680 an overload resolution performed as part of forming that expression or
5681 conversion, unless it is a pure virtual function and either the expression
5682 is not an id-expression naming the function with an explicitly qualified
5683 name or the expression forms a pointer to member.
5685 Mostly, we call mark_used in places that actually do something with a
5686 function, like build_over_call. But in a few places we end up with a
5687 non-overloaded FUNCTION_DECL that we aren't going to do any more with, like
5688 convert_to_void. resolve_nondeduced_context is called in those places,
5689 but it's also called in too many other places. */
5691 bool
5692 mark_single_function (tree expr, tsubst_flags_t complain)
5694 expr = maybe_undo_parenthesized_ref (expr);
5695 expr = tree_strip_any_location_wrapper (expr);
5697 if (is_overloaded_fn (expr) == 1
5698 && !mark_used (expr, complain)
5699 && !(complain & tf_error))
5700 return false;
5701 return true;
5704 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5705 If DECL is a specialization or implicitly declared class member,
5706 generate the actual definition. Return false if something goes
5707 wrong, true otherwise. */
5709 bool
5710 mark_used (tree decl, tsubst_flags_t complain /* = tf_warning_or_error */)
5712 /* If we're just testing conversions or resolving overloads, we
5713 don't want any permanent effects like forcing functions to be
5714 output or instantiating templates. */
5715 if ((complain & tf_conv))
5716 return true;
5718 /* If DECL is a BASELINK for a single function, then treat it just
5719 like the DECL for the function. Otherwise, if the BASELINK is
5720 for an overloaded function, we don't know which function was
5721 actually used until after overload resolution. */
5722 if (BASELINK_P (decl))
5724 tree fns = BASELINK_FUNCTIONS (decl);
5725 if (really_overloaded_fn (fns))
5726 return true;
5727 fns = OVL_FIRST (fns);
5728 if (!mark_used (fns, complain))
5729 return false;
5730 /* We might have deduced its return type. */
5731 TREE_TYPE (decl) = TREE_TYPE (fns);
5732 return true;
5735 if (!DECL_P (decl))
5736 return true;
5738 /* Set TREE_USED for the benefit of -Wunused. */
5739 TREE_USED (decl) = true;
5741 /* And for structured bindings also the underlying decl. */
5742 if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
5743 TREE_USED (DECL_DECOMP_BASE (decl)) = true;
5745 if (TREE_CODE (decl) == TEMPLATE_DECL)
5746 return true;
5748 if (DECL_CLONED_FUNCTION_P (decl))
5749 TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5751 /* Mark enumeration types as used. */
5752 if (TREE_CODE (decl) == CONST_DECL)
5753 used_types_insert (DECL_CONTEXT (decl));
5755 if (TREE_CODE (decl) == FUNCTION_DECL)
5757 if (DECL_MAYBE_DELETED (decl))
5759 ++function_depth;
5760 maybe_synthesize_method (decl);
5761 --function_depth;
5764 if (DECL_DELETED_FN (decl))
5766 if (DECL_ARTIFICIAL (decl)
5767 && DECL_CONV_FN_P (decl)
5768 && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5769 /* We mark a lambda conversion op as deleted if we can't
5770 generate it properly; see maybe_add_lambda_conv_op. */
5771 sorry ("converting lambda that uses %<...%> to function pointer");
5772 else if (complain & tf_error)
5774 error ("use of deleted function %qD", decl);
5775 if (!maybe_explain_implicit_delete (decl))
5776 inform (DECL_SOURCE_LOCATION (decl), "declared here");
5778 return false;
5781 if (!maybe_instantiate_noexcept (decl, complain))
5782 return false;
5785 if (VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl))
5787 if (!DECL_LANG_SPECIFIC (decl))
5788 /* An unresolved dependent local extern. */
5789 return true;
5791 DECL_ODR_USED (decl) = 1;
5792 auto alias = DECL_LOCAL_DECL_ALIAS (decl);
5793 if (!alias || alias == error_mark_node)
5794 return true;
5796 /* Process the underlying decl. */
5797 decl = alias;
5798 TREE_USED (decl) = true;
5801 cp_handle_deprecated_or_unavailable (decl, complain);
5803 /* We can only check DECL_ODR_USED on variables or functions with
5804 DECL_LANG_SPECIFIC set, and these are also the only decls that we
5805 might need special handling for. */
5806 if (!VAR_OR_FUNCTION_DECL_P (decl)
5807 || DECL_LANG_SPECIFIC (decl) == NULL
5808 || DECL_THUNK_P (decl))
5810 if (!decl_dependent_p (decl)
5811 && !require_deduced_type (decl, complain))
5812 return false;
5813 return true;
5816 /* We only want to do this processing once. We don't need to keep trying
5817 to instantiate inline templates, because unit-at-a-time will make sure
5818 we get them compiled before functions that want to inline them. */
5819 if (DECL_ODR_USED (decl))
5820 return true;
5822 if (flag_concepts && TREE_CODE (decl) == FUNCTION_DECL
5823 && !constraints_satisfied_p (decl))
5825 if (complain & tf_error)
5827 auto_diagnostic_group d;
5828 error ("use of function %qD with unsatisfied constraints",
5829 decl);
5830 location_t loc = DECL_SOURCE_LOCATION (decl);
5831 inform (loc, "declared here");
5832 diagnose_constraints (loc, decl, NULL_TREE);
5834 return false;
5837 /* If DECL has a deduced return type, we need to instantiate it now to
5838 find out its type. For OpenMP user defined reductions, we need them
5839 instantiated for reduction clauses which inline them by hand directly. */
5840 if (undeduced_auto_decl (decl)
5841 || (TREE_CODE (decl) == FUNCTION_DECL
5842 && DECL_OMP_DECLARE_REDUCTION_P (decl)))
5843 maybe_instantiate_decl (decl);
5845 if (processing_template_decl || in_template_context)
5846 return true;
5848 /* Check this too in case we're within instantiate_non_dependent_expr. */
5849 if (DECL_TEMPLATE_INFO (decl)
5850 && uses_template_parms (DECL_TI_ARGS (decl)))
5851 return true;
5853 if (!require_deduced_type (decl, complain))
5854 return false;
5856 if (builtin_pack_fn_p (decl))
5858 error ("use of built-in parameter pack %qD outside of a template",
5859 DECL_NAME (decl));
5860 return false;
5863 /* If we don't need a value, then we don't need to synthesize DECL. */
5864 if (cp_unevaluated_operand || in_discarded_stmt)
5865 return true;
5867 DECL_ODR_USED (decl) = 1;
5868 if (DECL_CLONED_FUNCTION_P (decl))
5869 DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5871 /* DR 757: A type without linkage shall not be used as the type of a
5872 variable or function with linkage, unless
5873 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5874 o the variable or function is not used (3.2 [basic.def.odr]) or is
5875 defined in the same translation unit. */
5876 if (cxx_dialect > cxx98
5877 && decl_linkage (decl) != lk_none
5878 && !DECL_EXTERN_C_P (decl)
5879 && !DECL_ARTIFICIAL (decl)
5880 && !decl_defined_p (decl)
5881 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5882 vec_safe_push (no_linkage_decls, decl);
5884 if (TREE_CODE (decl) == FUNCTION_DECL
5885 && DECL_DECLARED_INLINE_P (decl)
5886 && !DECL_INITIAL (decl)
5887 && !DECL_ARTIFICIAL (decl)
5888 && !DECL_PURE_VIRTUAL_P (decl))
5889 /* Remember it, so we can check it was defined. */
5890 note_vague_linkage_fn (decl);
5892 /* Is it a synthesized method that needs to be synthesized? */
5893 if (TREE_CODE (decl) == FUNCTION_DECL
5894 && DECL_DEFAULTED_FN (decl)
5895 /* A function defaulted outside the class is synthesized either by
5896 cp_finish_decl or instantiate_decl. */
5897 && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5898 && ! DECL_INITIAL (decl))
5900 /* Remember the current location for a function we will end up
5901 synthesizing. Then we can inform the user where it was
5902 required in the case of error. */
5903 if (decl_remember_implicit_trigger_p (decl))
5904 DECL_SOURCE_LOCATION (decl) = input_location;
5906 /* Synthesizing an implicitly defined member function will result in
5907 garbage collection. We must treat this situation as if we were
5908 within the body of a function so as to avoid collecting live data
5909 on the stack (such as overload resolution candidates).
5911 We could just let c_parse_final_cleanups handle synthesizing
5912 this function by adding it to deferred_fns, but doing
5913 it at the use site produces better error messages. */
5914 ++function_depth;
5915 synthesize_method (decl);
5916 --function_depth;
5917 /* If this is a synthesized method we don't need to
5918 do the instantiation test below. */
5920 else if (VAR_OR_FUNCTION_DECL_P (decl)
5921 && DECL_TEMPLATE_INFO (decl)
5922 && !DECL_DECLARED_CONCEPT_P (decl)
5923 && (!DECL_EXPLICIT_INSTANTIATION (decl)
5924 || always_instantiate_p (decl)))
5925 /* If this is a function or variable that is an instance of some
5926 template, we now know that we will need to actually do the
5927 instantiation. We check that DECL is not an explicit
5928 instantiation because that is not checked in instantiate_decl.
5930 We put off instantiating functions in order to improve compile
5931 times. Maintaining a stack of active functions is expensive,
5932 and the inliner knows to instantiate any functions it might
5933 need. Therefore, we always try to defer instantiation. */
5935 ++function_depth;
5936 instantiate_decl (decl, /*defer_ok=*/true,
5937 /*expl_inst_class_mem_p=*/false);
5938 --function_depth;
5941 return true;
5944 tree
5945 vtv_start_verification_constructor_init_function (void)
5947 return start_objects (/*initp=*/true, MAX_RESERVED_INIT_PRIORITY - 1, true);
5950 tree
5951 vtv_finish_verification_constructor_init_function (tree body)
5953 return finish_objects (/*initp=*/true, MAX_RESERVED_INIT_PRIORITY - 1, body);
5956 #include "gt-cp-decl2.h"