c++: tweak to (*(fn))() patch [PR104618]
[official-gcc.git] / gcc / cp / decl2.cc
blobe85bb87c9552d6fae1fe959b84a18a5d1d1e82a0
1 /* Process declarations and variables for C++ compiler.
2 Copyright (C) 1988-2022 Free Software Foundation, Inc.
3 Hacked by Michael Tiemann (tiemann@cygnus.com)
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 /* Process declarations and symbol lookup for C++ front end.
23 Also constructs types; the standard scalar types at initialization,
24 and structure, union, array and enum types when they are declared. */
26 /* ??? not all decl nodes are given the most useful possible
27 line numbers. For example, the CONST_DECLs for enum values. */
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "memmodel.h"
33 #include "target.h"
34 #include "cp-tree.h"
35 #include "c-family/c-common.h"
36 #include "timevar.h"
37 #include "stringpool.h"
38 #include "cgraph.h"
39 #include "varasm.h"
40 #include "attribs.h"
41 #include "stor-layout.h"
42 #include "calls.h"
43 #include "decl.h"
44 #include "toplev.h"
45 #include "c-family/c-objc.h"
46 #include "c-family/c-pragma.h"
47 #include "dumpfile.h"
48 #include "intl.h"
49 #include "c-family/c-ada-spec.h"
50 #include "asan.h"
51 #include "optabs-query.h"
53 /* Id for dumping the raw trees. */
54 int raw_dump_id;
56 extern cpp_reader *parse_in;
58 /* This structure contains information about the initializations
59 and/or destructions required for a particular priority level. */
60 typedef struct priority_info_s {
61 /* Nonzero if there have been any initializations at this priority
62 throughout the translation unit. */
63 int initializations_p;
64 /* Nonzero if there have been any destructions at this priority
65 throughout the translation unit. */
66 int destructions_p;
67 } *priority_info;
69 static tree start_objects (int, int);
70 static void finish_objects (int, int, tree);
71 static tree start_static_storage_duration_function (unsigned);
72 static void finish_static_storage_duration_function (tree);
73 static priority_info get_priority_info (int);
74 static void do_static_initialization_or_destruction (tree, bool);
75 static void one_static_initialization_or_destruction (tree, tree, bool);
76 static void generate_ctor_or_dtor_function (bool, int, location_t *);
77 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
78 void *);
79 static tree prune_vars_needing_no_initialization (tree *);
80 static void write_out_vars (tree);
81 static void import_export_class (tree);
82 static tree get_guard_bits (tree);
83 static void determine_visibility_from_class (tree, tree);
84 static bool determine_hidden_inline (tree);
86 /* A list of static class variables. This is needed, because a
87 static class variable can be declared inside the class without
88 an initializer, and then initialized, statically, outside the class. */
89 static GTY(()) vec<tree, va_gc> *pending_statics;
91 /* A list of functions which were declared inline, but which we
92 may need to emit outline anyway. */
93 static GTY(()) vec<tree, va_gc> *deferred_fns;
95 /* A list of decls that use types with no linkage, which we need to make
96 sure are defined. */
97 static GTY(()) vec<tree, va_gc> *no_linkage_decls;
99 /* A vector of alternating decls and identifiers, where the latter
100 is to be an alias for the former if the former is defined. */
101 static GTY(()) vec<tree, va_gc> *mangling_aliases;
103 /* hash traits for declarations. Hashes single decls via
104 DECL_ASSEMBLER_NAME_RAW. */
106 struct mangled_decl_hash : ggc_remove <tree>
108 typedef tree value_type; /* A DECL. */
109 typedef tree compare_type; /* An identifier. */
111 static hashval_t hash (const value_type decl)
113 return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME_RAW (decl));
115 static bool equal (const value_type existing, compare_type candidate)
117 tree name = DECL_ASSEMBLER_NAME_RAW (existing);
118 return candidate == name;
121 static const bool empty_zero_p = true;
122 static inline void mark_empty (value_type &p) {p = NULL_TREE;}
123 static inline bool is_empty (value_type p) {return !p;}
125 static bool is_deleted (value_type e)
127 return e == reinterpret_cast <value_type> (1);
129 static void mark_deleted (value_type &e)
131 e = reinterpret_cast <value_type> (1);
135 /* A hash table of decls keyed by mangled name. Used to figure out if
136 we need compatibility aliases. */
137 static GTY(()) hash_table<mangled_decl_hash> *mangled_decls;
139 /* Nonzero if we're done parsing and into end-of-file activities. */
141 int at_eof;
143 /* True if note_mangling_alias should enqueue mangling aliases for
144 later generation, rather than emitting them right away. */
146 bool defer_mangling_aliases = true;
149 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
150 FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
151 that apply to the function). */
153 tree
154 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
155 cp_ref_qualifier rqual)
157 if (fntype == error_mark_node || ctype == error_mark_node)
158 return error_mark_node;
160 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
162 cp_cv_quals type_quals = quals & ~TYPE_QUAL_RESTRICT;
163 ctype = cp_build_qualified_type (ctype, type_quals);
165 tree newtype
166 = build_method_type_directly (ctype, TREE_TYPE (fntype),
167 (TREE_CODE (fntype) == METHOD_TYPE
168 ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
169 : TYPE_ARG_TYPES (fntype)));
170 if (tree attrs = TYPE_ATTRIBUTES (fntype))
171 newtype = cp_build_type_attribute_variant (newtype, attrs);
172 newtype = build_cp_fntype_variant (newtype, rqual,
173 TYPE_RAISES_EXCEPTIONS (fntype),
174 TYPE_HAS_LATE_RETURN_TYPE (fntype));
176 return newtype;
179 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
180 return type changed to NEW_RET. */
182 tree
183 change_return_type (tree new_ret, tree fntype)
185 if (new_ret == error_mark_node)
186 return fntype;
188 if (same_type_p (new_ret, TREE_TYPE (fntype)))
189 return fntype;
191 tree newtype;
192 tree args = TYPE_ARG_TYPES (fntype);
194 if (TREE_CODE (fntype) == FUNCTION_TYPE)
196 newtype = build_function_type (new_ret, args);
197 newtype = apply_memfn_quals (newtype,
198 type_memfn_quals (fntype));
200 else
201 newtype = build_method_type_directly
202 (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
204 if (tree attrs = TYPE_ATTRIBUTES (fntype))
205 newtype = cp_build_type_attribute_variant (newtype, attrs);
206 newtype = cxx_copy_lang_qualifiers (newtype, fntype);
208 return newtype;
211 /* Build a PARM_DECL of FN with NAME and TYPE, and set DECL_ARG_TYPE
212 appropriately. */
214 tree
215 cp_build_parm_decl (tree fn, tree name, tree type)
217 tree parm = build_decl (input_location,
218 PARM_DECL, name, type);
219 DECL_CONTEXT (parm) = fn;
221 /* DECL_ARG_TYPE is only used by the back end and the back end never
222 sees templates. */
223 if (!processing_template_decl)
224 DECL_ARG_TYPE (parm) = type_passed_as (type);
226 return parm;
229 /* Returns a PARM_DECL of FN for a parameter of the indicated TYPE, with the
230 indicated NAME. */
232 tree
233 build_artificial_parm (tree fn, tree name, tree type)
235 tree parm = cp_build_parm_decl (fn, name, type);
236 DECL_ARTIFICIAL (parm) = 1;
237 /* All our artificial parms are implicitly `const'; they cannot be
238 assigned to. */
239 TREE_READONLY (parm) = 1;
240 return parm;
243 /* Constructors for types with virtual baseclasses need an "in-charge" flag
244 saying whether this constructor is responsible for initialization of
245 virtual baseclasses or not. All destructors also need this "in-charge"
246 flag, which additionally determines whether or not the destructor should
247 free the memory for the object.
249 This function adds the "in-charge" flag to member function FN if
250 appropriate. It is called from grokclassfn and tsubst.
251 FN must be either a constructor or destructor.
253 The in-charge flag follows the 'this' parameter, and is followed by the
254 VTT parm (if any), then the user-written parms. */
256 void
257 maybe_retrofit_in_chrg (tree fn)
259 tree basetype, arg_types, parms, parm, fntype;
261 /* If we've already add the in-charge parameter don't do it again. */
262 if (DECL_HAS_IN_CHARGE_PARM_P (fn))
263 return;
265 /* When processing templates we can't know, in general, whether or
266 not we're going to have virtual baseclasses. */
267 if (processing_template_decl)
268 return;
270 /* We don't need an in-charge parameter for constructors that don't
271 have virtual bases. */
272 if (DECL_CONSTRUCTOR_P (fn)
273 && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
274 return;
276 arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
277 basetype = TREE_TYPE (TREE_VALUE (arg_types));
278 arg_types = TREE_CHAIN (arg_types);
280 parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
282 /* If this is a subobject constructor or destructor, our caller will
283 pass us a pointer to our VTT. */
284 if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
286 parm = build_artificial_parm (fn, vtt_parm_identifier, vtt_parm_type);
288 /* First add it to DECL_ARGUMENTS between 'this' and the real args... */
289 DECL_CHAIN (parm) = parms;
290 parms = parm;
292 /* ...and then to TYPE_ARG_TYPES. */
293 arg_types = hash_tree_chain (vtt_parm_type, arg_types);
295 DECL_HAS_VTT_PARM_P (fn) = 1;
298 /* Then add the in-charge parm (before the VTT parm). */
299 parm = build_artificial_parm (fn, in_charge_identifier, integer_type_node);
300 DECL_CHAIN (parm) = parms;
301 parms = parm;
302 arg_types = hash_tree_chain (integer_type_node, arg_types);
304 /* Insert our new parameter(s) into the list. */
305 DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
307 /* And rebuild the function type. */
308 fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
309 arg_types);
310 if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
311 fntype = (cp_build_type_attribute_variant
312 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
313 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (fn));
314 TREE_TYPE (fn) = fntype;
316 /* Now we've got the in-charge parameter. */
317 DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
320 /* Classes overload their constituent function names automatically.
321 When a function name is declared in a record structure,
322 its name is changed to it overloaded name. Since names for
323 constructors and destructors can conflict, we place a leading
324 '$' for destructors.
326 CNAME is the name of the class we are grokking for.
328 FUNCTION is a FUNCTION_DECL. It was created by `grokdeclarator'.
330 FLAGS contains bits saying what's special about today's
331 arguments. DTOR_FLAG == DESTRUCTOR.
333 If FUNCTION is a destructor, then we must add the `auto-delete' field
334 as a second parameter. There is some hair associated with the fact
335 that we must "declare" this variable in the manner consistent with the
336 way the rest of the arguments were declared.
338 QUALS are the qualifiers for the this pointer. */
340 void
341 grokclassfn (tree ctype, tree function, enum overload_flags flags)
343 tree fn_name = DECL_NAME (function);
345 /* Even within an `extern "C"' block, members get C++ linkage. See
346 [dcl.link] for details. */
347 SET_DECL_LANGUAGE (function, lang_cplusplus);
349 if (fn_name == NULL_TREE)
351 error ("name missing for member function");
352 fn_name = get_identifier ("<anonymous>");
353 DECL_NAME (function) = fn_name;
356 DECL_CONTEXT (function) = ctype;
358 if (flags == DTOR_FLAG)
359 DECL_CXX_DESTRUCTOR_P (function) = 1;
361 if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
362 maybe_retrofit_in_chrg (function);
365 /* Create an ARRAY_REF, checking for the user doing things backwards
366 along the way.
367 If INDEX_EXP is non-NULL, then that is the index expression,
368 otherwise INDEX_EXP_LIST is the list of index expressions. */
370 tree
371 grok_array_decl (location_t loc, tree array_expr, tree index_exp,
372 vec<tree, va_gc> **index_exp_list, tsubst_flags_t complain)
374 tree type;
375 tree expr;
376 tree orig_array_expr = array_expr;
377 tree orig_index_exp = index_exp;
378 vec<tree, va_gc> *orig_index_exp_list
379 = index_exp_list ? *index_exp_list : NULL;
380 tree overload = NULL_TREE;
382 if (error_operand_p (array_expr) || error_operand_p (index_exp))
383 return error_mark_node;
385 if (processing_template_decl)
387 if (type_dependent_expression_p (array_expr)
388 || (index_exp ? type_dependent_expression_p (index_exp)
389 : any_type_dependent_arguments_p (*index_exp_list)))
391 if (index_exp == NULL)
392 index_exp = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
393 *index_exp_list);
394 return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
395 NULL_TREE, NULL_TREE);
397 array_expr = build_non_dependent_expr (array_expr);
398 if (index_exp)
399 index_exp = build_non_dependent_expr (index_exp);
400 else
402 orig_index_exp_list = make_tree_vector_copy (*index_exp_list);
403 make_args_non_dependent (*index_exp_list);
407 type = TREE_TYPE (array_expr);
408 gcc_assert (type);
409 type = non_reference (type);
411 /* If they have an `operator[]', use that. */
412 if (MAYBE_CLASS_TYPE_P (type)
413 || (index_exp && MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
414 || (index_exp == NULL_TREE
415 && !(*index_exp_list)->is_empty ()
416 && MAYBE_CLASS_TYPE_P (TREE_TYPE ((*index_exp_list)->last ()))))
418 if (index_exp)
419 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
420 index_exp, NULL_TREE, NULL_TREE,
421 &overload, complain);
422 else if ((*index_exp_list)->is_empty ())
423 expr = build_op_subscript (loc, array_expr, index_exp_list, &overload,
424 complain);
425 else
427 expr = build_op_subscript (loc, array_expr, index_exp_list,
428 &overload, complain & tf_decltype);
429 if (expr == error_mark_node)
431 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
432 tf_none);
433 if (idx != error_mark_node)
434 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
435 idx, NULL_TREE, NULL_TREE, &overload,
436 complain & tf_decltype);
437 if (expr == error_mark_node)
439 overload = NULL_TREE;
440 expr = build_op_subscript (loc, array_expr, index_exp_list,
441 &overload, complain);
443 else
444 /* If it would be valid albeit deprecated expression in C++20,
445 just pedwarn on it and treat it as if wrapped in (). */
446 pedwarn (loc, OPT_Wcomma_subscript,
447 "top-level comma expression in array subscript "
448 "changed meaning in C++23");
452 else
454 tree p1, p2, i1, i2;
455 bool swapped = false;
457 /* Otherwise, create an ARRAY_REF for a pointer or array type.
458 It is a little-known fact that, if `a' is an array and `i' is
459 an int, you can write `i[a]', which means the same thing as
460 `a[i]'. */
461 if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
462 p1 = array_expr;
463 else
464 p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
466 if (index_exp == NULL_TREE)
468 if ((*index_exp_list)->is_empty ())
470 error_at (loc, "built-in subscript operator without expression "
471 "list");
472 return error_mark_node;
474 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
475 tf_none);
476 if (idx != error_mark_node)
477 /* If it would be valid albeit deprecated expression in C++20,
478 just pedwarn on it and treat it as if wrapped in (). */
479 pedwarn (loc, OPT_Wcomma_subscript,
480 "top-level comma expression in array subscript "
481 "changed meaning in C++23");
482 else
484 error_at (loc, "built-in subscript operator with more than one "
485 "expression in expression list");
486 return error_mark_node;
488 index_exp = idx;
491 if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
492 p2 = index_exp;
493 else
494 p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
496 i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
497 false);
498 i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
499 false);
501 if ((p1 && i2) && (i1 && p2))
502 error ("ambiguous conversion for array subscript");
504 if (p1 && i2)
505 array_expr = p1, index_exp = i2;
506 else if (i1 && p2)
507 swapped = true, array_expr = p2, index_exp = i1;
508 else
510 error_at (loc, "invalid types %<%T[%T]%> for array subscript",
511 type, TREE_TYPE (index_exp));
512 return error_mark_node;
515 if (array_expr == error_mark_node || index_exp == error_mark_node)
516 error ("ambiguous conversion for array subscript");
518 if (TYPE_PTR_P (TREE_TYPE (array_expr)))
519 array_expr = mark_rvalue_use (array_expr);
520 else
521 array_expr = mark_lvalue_use_nonread (array_expr);
522 index_exp = mark_rvalue_use (index_exp);
523 if (swapped
524 && flag_strong_eval_order == 2
525 && (TREE_SIDE_EFFECTS (array_expr) || TREE_SIDE_EFFECTS (index_exp)))
526 expr = build_array_ref (input_location, index_exp, array_expr);
527 else
528 expr = build_array_ref (input_location, array_expr, index_exp);
530 if (processing_template_decl && expr != error_mark_node)
532 if (overload != NULL_TREE)
534 if (orig_index_exp == NULL_TREE)
536 expr = build_min_non_dep_op_overload (expr, overload,
537 orig_array_expr,
538 orig_index_exp_list);
539 release_tree_vector (orig_index_exp_list);
540 return expr;
542 return build_min_non_dep_op_overload (ARRAY_REF, expr, overload,
543 orig_array_expr,
544 orig_index_exp);
547 if (orig_index_exp == NULL_TREE)
549 orig_index_exp
550 = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
551 orig_index_exp_list);
552 release_tree_vector (orig_index_exp_list);
555 return build_min_non_dep (ARRAY_REF, expr, orig_array_expr,
556 orig_index_exp, NULL_TREE, NULL_TREE);
558 return expr;
561 /* Given the cast expression EXP, checking out its validity. Either return
562 an error_mark_node if there was an unavoidable error, return a cast to
563 void for trying to delete a pointer w/ the value 0, or return the
564 call to delete. If DOING_VEC is true, we handle things differently
565 for doing an array delete.
566 Implements ARM $5.3.4. This is called from the parser. */
568 tree
569 delete_sanity (location_t loc, tree exp, tree size, bool doing_vec,
570 int use_global_delete, tsubst_flags_t complain)
572 tree t, type;
574 if (exp == error_mark_node)
575 return exp;
577 if (processing_template_decl)
579 t = build_min (DELETE_EXPR, void_type_node, exp, size);
580 DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
581 DELETE_EXPR_USE_VEC (t) = doing_vec;
582 TREE_SIDE_EFFECTS (t) = 1;
583 SET_EXPR_LOCATION (t, loc);
584 return t;
587 location_t exp_loc = cp_expr_loc_or_loc (exp, loc);
589 /* An array can't have been allocated by new, so complain. */
590 if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
591 && (complain & tf_warning))
592 warning_at (exp_loc, 0, "deleting array %q#E", exp);
594 t = build_expr_type_conversion (WANT_POINTER, exp, true);
596 if (t == NULL_TREE || t == error_mark_node)
598 if (complain & tf_error)
599 error_at (exp_loc,
600 "type %q#T argument given to %<delete%>, expected pointer",
601 TREE_TYPE (exp));
602 return error_mark_node;
605 type = TREE_TYPE (t);
607 /* As of Valley Forge, you can delete a pointer to const. */
609 /* You can't delete functions. */
610 if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
612 if (complain & tf_error)
613 error_at (exp_loc,
614 "cannot delete a function. Only pointer-to-objects are "
615 "valid arguments to %<delete%>");
616 return error_mark_node;
619 /* Deleting ptr to void is undefined behavior [expr.delete/3]. */
620 if (VOID_TYPE_P (TREE_TYPE (type)))
622 if (complain & tf_warning)
623 warning_at (exp_loc, OPT_Wdelete_incomplete,
624 "deleting %qT is undefined", type);
625 doing_vec = 0;
628 /* Deleting a pointer with the value zero is valid and has no effect. */
629 if (integer_zerop (t))
630 return build1_loc (loc, NOP_EXPR, void_type_node, t);
632 if (doing_vec)
633 return build_vec_delete (loc, t, /*maxindex=*/NULL_TREE,
634 sfk_deleting_destructor,
635 use_global_delete, complain);
636 else
637 return build_delete (loc, type, t, sfk_deleting_destructor,
638 LOOKUP_NORMAL, use_global_delete,
639 complain);
642 /* Report an error if the indicated template declaration is not the
643 sort of thing that should be a member template. */
645 void
646 check_member_template (tree tmpl)
648 tree decl;
650 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
651 decl = DECL_TEMPLATE_RESULT (tmpl);
653 if (TREE_CODE (decl) == FUNCTION_DECL
654 || DECL_ALIAS_TEMPLATE_P (tmpl)
655 || (TREE_CODE (decl) == TYPE_DECL
656 && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
658 /* The parser rejects template declarations in local classes
659 (with the exception of generic lambdas). */
660 gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
661 /* The parser rejects any use of virtual in a function template. */
662 gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
663 && DECL_VIRTUAL_P (decl)));
665 /* The debug-information generating code doesn't know what to do
666 with member templates. */
667 DECL_IGNORED_P (tmpl) = 1;
669 else if (variable_template_p (tmpl))
670 /* OK */;
671 else
672 error ("template declaration of %q#D", decl);
675 /* Sanity check: report error if this function FUNCTION is not
676 really a member of the class (CTYPE) it is supposed to belong to.
677 TEMPLATE_PARMS is used to specify the template parameters of a member
678 template passed as FUNCTION_DECL. If the member template is passed as a
679 TEMPLATE_DECL, it can be NULL since the parameters can be extracted
680 from the declaration. If the function is not a function template, it
681 must be NULL.
682 It returns the original declaration for the function, NULL_TREE if
683 no declaration was found, error_mark_node if an error was emitted. */
685 tree
686 check_classfn (tree ctype, tree function, tree template_parms)
688 if (DECL_USE_TEMPLATE (function)
689 && !(TREE_CODE (function) == TEMPLATE_DECL
690 && DECL_TEMPLATE_SPECIALIZATION (function))
691 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
692 /* Since this is a specialization of a member template,
693 we're not going to find the declaration in the class.
694 For example, in:
696 struct S { template <typename T> void f(T); };
697 template <> void S::f(int);
699 we're not going to find `S::f(int)', but there's no
700 reason we should, either. We let our callers know we didn't
701 find the method, but we don't complain. */
702 return NULL_TREE;
704 /* Basic sanity check: for a template function, the template parameters
705 either were not passed, or they are the same of DECL_TEMPLATE_PARMS. */
706 if (TREE_CODE (function) == TEMPLATE_DECL)
708 if (template_parms
709 && !comp_template_parms (template_parms,
710 DECL_TEMPLATE_PARMS (function)))
712 error ("template parameter lists provided don%'t match the "
713 "template parameters of %qD", function);
714 return error_mark_node;
716 template_parms = DECL_TEMPLATE_PARMS (function);
719 /* OK, is this a definition of a member template? */
720 bool is_template = (template_parms != NULL_TREE);
722 /* [temp.mem]
724 A destructor shall not be a member template. */
725 if (DECL_DESTRUCTOR_P (function) && is_template)
727 error ("destructor %qD declared as member template", function);
728 return error_mark_node;
731 /* We must enter the scope here, because conversion operators are
732 named by target type, and type equivalence relies on typenames
733 resolving within the scope of CTYPE. */
734 tree pushed_scope = push_scope (ctype);
735 tree matched = NULL_TREE;
736 tree fns = get_class_binding (ctype, DECL_NAME (function));
738 for (ovl_iterator iter (fns); !matched && iter; ++iter)
740 tree fndecl = *iter;
742 /* A member template definition only matches a member template
743 declaration. */
744 if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
745 continue;
747 if (!DECL_DECLARES_FUNCTION_P (fndecl))
748 continue;
750 tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
751 tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
753 /* We cannot simply call decls_match because this doesn't work
754 for static member functions that are pretending to be
755 methods, and because the name may have been changed by
756 asm("new_name"). */
758 /* Get rid of the this parameter on functions that become
759 static. */
760 if (DECL_STATIC_FUNCTION_P (fndecl)
761 && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
762 p1 = TREE_CHAIN (p1);
764 /* ref-qualifier or absence of same must match. */
765 if (type_memfn_rqual (TREE_TYPE (function))
766 != type_memfn_rqual (TREE_TYPE (fndecl)))
767 continue;
769 // Include constraints in the match.
770 tree c1 = get_constraints (function);
771 tree c2 = get_constraints (fndecl);
773 /* While finding a match, same types and params are not enough
774 if the function is versioned. Also check version ("target")
775 attributes. */
776 if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
777 TREE_TYPE (TREE_TYPE (fndecl)))
778 && compparms (p1, p2)
779 && !targetm.target_option.function_versions (function, fndecl)
780 && (!is_template
781 || comp_template_parms (template_parms,
782 DECL_TEMPLATE_PARMS (fndecl)))
783 && equivalent_constraints (c1, c2)
784 && (DECL_TEMPLATE_SPECIALIZATION (function)
785 == DECL_TEMPLATE_SPECIALIZATION (fndecl))
786 && (!DECL_TEMPLATE_SPECIALIZATION (function)
787 || (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl))))
788 matched = fndecl;
791 if (!matched)
793 if (!COMPLETE_TYPE_P (ctype))
794 cxx_incomplete_type_error (DECL_SOURCE_LOCATION (function),
795 function, ctype);
796 else
798 if (DECL_CONV_FN_P (function))
799 fns = get_class_binding (ctype, conv_op_identifier);
801 error_at (DECL_SOURCE_LOCATION (function),
802 "no declaration matches %q#D", function);
803 if (fns)
804 print_candidates (fns);
805 else if (DECL_CONV_FN_P (function))
806 inform (DECL_SOURCE_LOCATION (function),
807 "no conversion operators declared");
808 else
809 inform (DECL_SOURCE_LOCATION (function),
810 "no functions named %qD", function);
811 inform (DECL_SOURCE_LOCATION (TYPE_NAME (ctype)),
812 "%#qT defined here", ctype);
814 matched = error_mark_node;
817 if (pushed_scope)
818 pop_scope (pushed_scope);
820 return matched;
823 /* DECL is a function with vague linkage. Remember it so that at the
824 end of the translation unit we can decide whether or not to emit
825 it. */
827 void
828 note_vague_linkage_fn (tree decl)
830 if (processing_template_decl)
831 return;
833 DECL_DEFER_OUTPUT (decl) = 1;
834 vec_safe_push (deferred_fns, decl);
837 /* As above, but for variable template instantiations. */
839 void
840 note_variable_template_instantiation (tree decl)
842 vec_safe_push (pending_statics, decl);
845 /* We have just processed the DECL, which is a static data member.
846 The other parameters are as for cp_finish_decl. */
848 void
849 finish_static_data_member_decl (tree decl,
850 tree init, bool init_const_expr_p,
851 tree asmspec_tree,
852 int flags)
854 if (DECL_TEMPLATE_INSTANTIATED (decl))
855 /* We already needed to instantiate this, so the processing in this
856 function is unnecessary/wrong. */
857 return;
859 DECL_CONTEXT (decl) = current_class_type;
861 /* We cannot call pushdecl here, because that would fill in the
862 TREE_CHAIN of our decl. Instead, we modify cp_finish_decl to do
863 the right thing, namely, to put this decl out straight away. */
865 if (! processing_template_decl)
866 vec_safe_push (pending_statics, decl);
868 if (LOCAL_CLASS_P (current_class_type)
869 /* We already complained about the template definition. */
870 && !DECL_TEMPLATE_INSTANTIATION (decl))
871 permerror (DECL_SOURCE_LOCATION (decl),
872 "local class %q#T shall not have static data member %q#D",
873 current_class_type, decl);
874 else
875 for (tree t = current_class_type; TYPE_P (t);
876 t = CP_TYPE_CONTEXT (t))
877 if (TYPE_UNNAMED_P (t))
879 auto_diagnostic_group d;
880 if (permerror (DECL_SOURCE_LOCATION (decl),
881 "static data member %qD in unnamed class", decl))
882 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
883 "unnamed class defined here");
884 break;
887 if (DECL_INLINE_VAR_P (decl) && !DECL_TEMPLATE_INSTANTIATION (decl))
888 /* An inline variable is immediately defined, so don't set DECL_IN_AGGR_P.
889 Except that if decl is a template instantiation, it isn't defined until
890 instantiate_decl. */;
891 else
892 DECL_IN_AGGR_P (decl) = 1;
894 if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
895 && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
896 SET_VAR_HAD_UNKNOWN_BOUND (decl);
898 if (init)
900 /* Similarly to start_decl_1, we want to complete the type in order
901 to do the right thing in cp_apply_type_quals_to_decl, possibly
902 clear TYPE_QUAL_CONST (c++/65579). */
903 tree type = TREE_TYPE (decl) = complete_type (TREE_TYPE (decl));
904 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
907 cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
910 /* DECLARATOR and DECLSPECS correspond to a class member. The other
911 parameters are as for cp_finish_decl. Return the DECL for the
912 class member declared. */
914 tree
915 grokfield (const cp_declarator *declarator,
916 cp_decl_specifier_seq *declspecs,
917 tree init, bool init_const_expr_p,
918 tree asmspec_tree,
919 tree attrlist)
921 tree value;
922 const char *asmspec = 0;
923 int flags;
925 if (init
926 && TREE_CODE (init) == TREE_LIST
927 && TREE_VALUE (init) == error_mark_node
928 && TREE_CHAIN (init) == NULL_TREE)
929 init = NULL_TREE;
931 int initialized;
932 if (init == ridpointers[(int)RID_DELETE])
933 initialized = SD_DELETED;
934 else if (init == ridpointers[(int)RID_DEFAULT])
935 initialized = SD_DEFAULTED;
936 else if (init)
937 initialized = SD_INITIALIZED;
938 else
939 initialized = SD_UNINITIALIZED;
941 value = grokdeclarator (declarator, declspecs, FIELD, initialized, &attrlist);
942 if (! value || value == error_mark_node)
943 /* friend or constructor went bad. */
944 return error_mark_node;
945 if (TREE_TYPE (value) == error_mark_node)
946 return value;
948 if (TREE_CODE (value) == TYPE_DECL && init)
950 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value)),
951 "typedef %qD is initialized (use %qs instead)",
952 value, "decltype");
953 init = NULL_TREE;
956 /* Pass friendly classes back. */
957 if (value == void_type_node)
958 return value;
960 if (DECL_NAME (value)
961 && TREE_CODE (DECL_NAME (value)) == TEMPLATE_ID_EXPR)
963 error_at (declarator->id_loc,
964 "explicit template argument list not allowed");
965 return error_mark_node;
968 /* Stash away type declarations. */
969 if (TREE_CODE (value) == TYPE_DECL)
971 DECL_NONLOCAL (value) = 1;
972 DECL_CONTEXT (value) = current_class_type;
974 if (attrlist)
976 int attrflags = 0;
978 /* If this is a typedef that names the class for linkage purposes
979 (7.1.3p8), apply any attributes directly to the type. */
980 if (OVERLOAD_TYPE_P (TREE_TYPE (value))
981 && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
982 attrflags = ATTR_FLAG_TYPE_IN_PLACE;
984 cplus_decl_attributes (&value, attrlist, attrflags);
987 if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
988 && TREE_TYPE (value) != error_mark_node
989 && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
990 set_underlying_type (value);
992 /* It's important that push_template_decl below follows
993 set_underlying_type above so that the created template
994 carries the properly set type of VALUE. */
995 if (processing_template_decl)
996 value = push_template_decl (value);
998 record_locally_defined_typedef (value);
999 return value;
1002 int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
1004 if (!friendp && DECL_IN_AGGR_P (value))
1006 error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
1007 return void_type_node;
1010 if (asmspec_tree && asmspec_tree != error_mark_node)
1011 asmspec = TREE_STRING_POINTER (asmspec_tree);
1013 if (init)
1015 if (TREE_CODE (value) == FUNCTION_DECL)
1017 if (init == ridpointers[(int)RID_DELETE])
1019 DECL_DELETED_FN (value) = 1;
1020 DECL_DECLARED_INLINE_P (value) = 1;
1022 else if (init == ridpointers[(int)RID_DEFAULT])
1024 if (defaultable_fn_check (value))
1026 DECL_DEFAULTED_FN (value) = 1;
1027 DECL_INITIALIZED_IN_CLASS_P (value) = 1;
1028 DECL_DECLARED_INLINE_P (value) = 1;
1029 /* grokfndecl set this to error_mark_node, but we want to
1030 leave it unset until synthesize_method. */
1031 DECL_INITIAL (value) = NULL_TREE;
1034 else if (TREE_CODE (init) == DEFERRED_PARSE)
1035 error ("invalid initializer for member function %qD", value);
1036 else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
1038 if (integer_zerop (init))
1039 DECL_PURE_VIRTUAL_P (value) = 1;
1040 else if (error_operand_p (init))
1041 ; /* An error has already been reported. */
1042 else
1043 error ("invalid initializer for member function %qD",
1044 value);
1046 else
1048 gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
1049 location_t iloc
1050 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value));
1051 if (friendp)
1052 error_at (iloc, "initializer specified for friend "
1053 "function %qD", value);
1054 else
1055 error_at (iloc, "initializer specified for static "
1056 "member function %qD", value);
1059 else if (TREE_CODE (value) == FIELD_DECL)
1060 /* C++11 NSDMI, keep going. */;
1061 else if (!VAR_P (value))
1062 gcc_unreachable ();
1065 /* Pass friend decls back. */
1066 if ((TREE_CODE (value) == FUNCTION_DECL
1067 || TREE_CODE (value) == TEMPLATE_DECL)
1068 && DECL_CONTEXT (value) != current_class_type)
1070 if (attrlist)
1071 cplus_decl_attributes (&value, attrlist, 0);
1072 return value;
1075 /* Need to set this before push_template_decl. */
1076 if (VAR_P (value))
1077 DECL_CONTEXT (value) = current_class_type;
1079 if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
1081 value = push_template_decl (value);
1082 if (error_operand_p (value))
1083 return error_mark_node;
1086 if (attrlist)
1087 cplus_decl_attributes (&value, attrlist, 0);
1089 if (init && DIRECT_LIST_INIT_P (init))
1090 flags = LOOKUP_NORMAL;
1091 else
1092 flags = LOOKUP_IMPLICIT;
1094 switch (TREE_CODE (value))
1096 case VAR_DECL:
1097 finish_static_data_member_decl (value, init, init_const_expr_p,
1098 asmspec_tree, flags);
1099 return value;
1101 case FIELD_DECL:
1102 if (asmspec)
1103 error ("%<asm%> specifiers are not permitted on non-static data members");
1104 if (DECL_INITIAL (value) == error_mark_node)
1105 init = error_mark_node;
1106 cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1107 NULL_TREE, flags);
1108 DECL_IN_AGGR_P (value) = 1;
1109 return value;
1111 case FUNCTION_DECL:
1112 if (asmspec)
1113 set_user_assembler_name (value, asmspec);
1115 cp_finish_decl (value,
1116 /*init=*/NULL_TREE,
1117 /*init_const_expr_p=*/false,
1118 asmspec_tree, flags);
1120 /* Pass friends back this way. */
1121 if (DECL_UNIQUE_FRIEND_P (value))
1122 return void_type_node;
1124 DECL_IN_AGGR_P (value) = 1;
1125 return value;
1127 default:
1128 gcc_unreachable ();
1130 return NULL_TREE;
1133 /* Like `grokfield', but for bitfields.
1134 WIDTH is the width of the bitfield, a constant expression.
1135 The other parameters are as for grokfield. */
1137 tree
1138 grokbitfield (const cp_declarator *declarator,
1139 cp_decl_specifier_seq *declspecs, tree width, tree init,
1140 tree attrlist)
1142 tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1143 init != NULL_TREE, &attrlist);
1145 if (value == error_mark_node)
1146 return NULL_TREE; /* friends went bad. */
1148 tree type = TREE_TYPE (value);
1149 if (type == error_mark_node)
1150 return value;
1152 /* Pass friendly classes back. */
1153 if (VOID_TYPE_P (value))
1154 return void_type_node;
1156 if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type)
1157 && (INDIRECT_TYPE_P (type) || !dependent_type_p (type)))
1159 error_at (DECL_SOURCE_LOCATION (value),
1160 "bit-field %qD with non-integral type %qT",
1161 value, type);
1162 return error_mark_node;
1165 if (TREE_CODE (value) == TYPE_DECL)
1167 error_at (DECL_SOURCE_LOCATION (value),
1168 "cannot declare %qD to be a bit-field type", value);
1169 return NULL_TREE;
1172 /* Usually, finish_struct_1 catches bitfields with invalid types.
1173 But, in the case of bitfields with function type, we confuse
1174 ourselves into thinking they are member functions, so we must
1175 check here. */
1176 if (TREE_CODE (value) == FUNCTION_DECL)
1178 error_at (DECL_SOURCE_LOCATION (value),
1179 "cannot declare bit-field %qD with function type", value);
1180 return NULL_TREE;
1183 if (TYPE_WARN_IF_NOT_ALIGN (type))
1185 error_at (DECL_SOURCE_LOCATION (value), "cannot declare bit-field "
1186 "%qD with %<warn_if_not_aligned%> type", value);
1187 return NULL_TREE;
1190 if (DECL_IN_AGGR_P (value))
1192 error ("%qD is already defined in the class %qT", value,
1193 DECL_CONTEXT (value));
1194 return void_type_node;
1197 if (TREE_STATIC (value))
1199 error_at (DECL_SOURCE_LOCATION (value),
1200 "static member %qD cannot be a bit-field", value);
1201 return NULL_TREE;
1204 int flags = LOOKUP_IMPLICIT;
1205 if (init && DIRECT_LIST_INIT_P (init))
1206 flags = LOOKUP_NORMAL;
1207 cp_finish_decl (value, init, false, NULL_TREE, flags);
1209 if (width != error_mark_node)
1211 /* The width must be an integer type. */
1212 if (!type_dependent_expression_p (width)
1213 && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1214 error ("width of bit-field %qD has non-integral type %qT", value,
1215 TREE_TYPE (width));
1216 else if (!check_for_bare_parameter_packs (width))
1218 /* Temporarily stash the width in DECL_BIT_FIELD_REPRESENTATIVE.
1219 check_bitfield_decl picks it from there later and sets DECL_SIZE
1220 accordingly. */
1221 DECL_BIT_FIELD_REPRESENTATIVE (value) = width;
1222 SET_DECL_C_BIT_FIELD (value);
1226 DECL_IN_AGGR_P (value) = 1;
1228 if (attrlist)
1229 cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1231 return value;
1235 /* Returns true iff ATTR is an attribute which needs to be applied at
1236 instantiation time rather than template definition time. */
1238 static bool
1239 is_late_template_attribute (tree attr, tree decl)
1241 tree name = get_attribute_name (attr);
1242 tree args = TREE_VALUE (attr);
1243 const struct attribute_spec *spec = lookup_attribute_spec (name);
1244 tree arg;
1246 if (!spec)
1247 /* Unknown attribute. */
1248 return false;
1250 /* Attribute weak handling wants to write out assembly right away. */
1251 if (is_attribute_p ("weak", name))
1252 return true;
1254 /* Attributes used and unused are applied directly to typedefs for the
1255 benefit of maybe_warn_unused_local_typedefs. */
1256 if (TREE_CODE (decl) == TYPE_DECL
1257 && (is_attribute_p ("unused", name)
1258 || is_attribute_p ("used", name)))
1259 return false;
1261 /* Attribute tls_model wants to modify the symtab. */
1262 if (is_attribute_p ("tls_model", name))
1263 return true;
1265 /* #pragma omp declare simd attribute needs to be always deferred. */
1266 if (flag_openmp
1267 && is_attribute_p ("omp declare simd", name))
1268 return true;
1270 if (args == error_mark_node)
1271 return false;
1273 /* An attribute pack is clearly dependent. */
1274 if (args && PACK_EXPANSION_P (args))
1275 return true;
1277 /* If any of the arguments are dependent expressions, we can't evaluate
1278 the attribute until instantiation time. */
1279 for (arg = args; arg; arg = TREE_CHAIN (arg))
1281 tree t = TREE_VALUE (arg);
1283 /* If the first attribute argument is an identifier, only consider
1284 second and following arguments. Attributes like mode, format,
1285 cleanup and several target specific attributes aren't late
1286 just because they have an IDENTIFIER_NODE as first argument. */
1287 if (arg == args && attribute_takes_identifier_p (name)
1288 && identifier_p (t))
1289 continue;
1291 if (value_dependent_expression_p (t))
1292 return true;
1295 if (TREE_CODE (decl) == TYPE_DECL
1296 || TYPE_P (decl)
1297 || spec->type_required)
1299 tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1301 if (!type)
1302 return true;
1304 /* We can't apply any attributes to a completely unknown type until
1305 instantiation time. */
1306 enum tree_code code = TREE_CODE (type);
1307 if (code == TEMPLATE_TYPE_PARM
1308 || code == BOUND_TEMPLATE_TEMPLATE_PARM
1309 || code == TYPENAME_TYPE)
1310 return true;
1311 /* Also defer most attributes on dependent types. This is not
1312 necessary in all cases, but is the better default. */
1313 else if (dependent_type_p (type)
1314 /* But some attributes specifically apply to templates. */
1315 && !is_attribute_p ("abi_tag", name)
1316 && !is_attribute_p ("deprecated", name)
1317 && !is_attribute_p ("visibility", name))
1318 return true;
1319 else
1320 return false;
1322 else
1323 return false;
1326 /* ATTR_P is a list of attributes. Remove any attributes which need to be
1327 applied at instantiation time and return them. If IS_DEPENDENT is true,
1328 the declaration itself is dependent, so all attributes should be applied
1329 at instantiation time. */
1331 tree
1332 splice_template_attributes (tree *attr_p, tree decl)
1334 tree *p = attr_p;
1335 tree late_attrs = NULL_TREE;
1336 tree *q = &late_attrs;
1338 if (!p)
1339 return NULL_TREE;
1341 for (; *p; )
1343 if (is_late_template_attribute (*p, decl))
1345 ATTR_IS_DEPENDENT (*p) = 1;
1346 *q = *p;
1347 *p = TREE_CHAIN (*p);
1348 q = &TREE_CHAIN (*q);
1349 *q = NULL_TREE;
1351 else
1352 p = &TREE_CHAIN (*p);
1355 return late_attrs;
1358 /* Attach any LATE_ATTRS to DECL_P, after the non-dependent attributes have
1359 been applied by a previous call to decl_attributes. */
1361 static void
1362 save_template_attributes (tree late_attrs, tree *decl_p, int flags)
1364 tree *q;
1366 if (!late_attrs)
1367 return;
1369 if (DECL_P (*decl_p))
1370 q = &DECL_ATTRIBUTES (*decl_p);
1371 else
1372 q = &TYPE_ATTRIBUTES (*decl_p);
1374 tree old_attrs = *q;
1376 /* Place the late attributes at the beginning of the attribute
1377 list. */
1378 late_attrs = chainon (late_attrs, *q);
1379 if (*q != late_attrs
1380 && !DECL_P (*decl_p)
1381 && !(flags & ATTR_FLAG_TYPE_IN_PLACE))
1383 if (!dependent_type_p (*decl_p))
1384 *decl_p = cp_build_type_attribute_variant (*decl_p, late_attrs);
1385 else
1387 *decl_p = build_variant_type_copy (*decl_p);
1388 TYPE_ATTRIBUTES (*decl_p) = late_attrs;
1391 else
1392 *q = late_attrs;
1394 if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1396 /* We've added new attributes directly to the main variant, so
1397 now we need to update all of the other variants to include
1398 these new attributes. */
1399 tree variant;
1400 for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1401 variant = TYPE_NEXT_VARIANT (variant))
1403 gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1404 TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1409 /* True if ATTRS contains any dependent attributes that affect type
1410 identity. */
1412 bool
1413 any_dependent_type_attributes_p (tree attrs)
1415 for (tree a = attrs; a; a = TREE_CHAIN (a))
1416 if (ATTR_IS_DEPENDENT (a))
1418 const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (a));
1419 if (as && as->affects_type_identity)
1420 return true;
1422 return false;
1425 /* Return true iff ATTRS are acceptable attributes to be applied in-place
1426 to a typedef which gives a previously unnamed class or enum a name for
1427 linkage purposes. */
1429 bool
1430 attributes_naming_typedef_ok (tree attrs)
1432 for (; attrs; attrs = TREE_CHAIN (attrs))
1434 tree name = get_attribute_name (attrs);
1435 if (is_attribute_p ("vector_size", name))
1436 return false;
1438 return true;
1441 /* Like reconstruct_complex_type, but handle also template trees. */
1443 tree
1444 cp_reconstruct_complex_type (tree type, tree bottom)
1446 tree inner, outer;
1448 if (TYPE_PTR_P (type))
1450 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1451 outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1452 TYPE_REF_CAN_ALIAS_ALL (type));
1454 else if (TYPE_REF_P (type))
1456 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1457 outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1458 TYPE_REF_CAN_ALIAS_ALL (type));
1460 else if (TREE_CODE (type) == ARRAY_TYPE)
1462 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1463 outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1464 /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1465 element type qualification will be handled by the recursive
1466 cp_reconstruct_complex_type call and cp_build_qualified_type
1467 for ARRAY_TYPEs changes the element type. */
1468 return outer;
1470 else if (TREE_CODE (type) == FUNCTION_TYPE)
1472 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1473 outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1474 outer = apply_memfn_quals (outer, type_memfn_quals (type));
1476 else if (TREE_CODE (type) == METHOD_TYPE)
1478 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1479 /* The build_method_type_directly() routine prepends 'this' to argument list,
1480 so we must compensate by getting rid of it. */
1481 outer
1482 = build_method_type_directly
1483 (class_of_this_parm (type), inner,
1484 TREE_CHAIN (TYPE_ARG_TYPES (type)));
1486 else if (TREE_CODE (type) == OFFSET_TYPE)
1488 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1489 outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1491 else
1492 return bottom;
1494 if (TYPE_ATTRIBUTES (type))
1495 outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1496 outer = cp_build_qualified_type (outer, cp_type_quals (type));
1497 outer = cxx_copy_lang_qualifiers (outer, type);
1499 return outer;
1502 /* Replaces any constexpr expression that may be into the attributes
1503 arguments with their reduced value. */
1505 void
1506 cp_check_const_attributes (tree attributes)
1508 if (attributes == error_mark_node)
1509 return;
1511 tree attr;
1512 for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1514 tree arg;
1515 for (arg = TREE_VALUE (attr); arg && TREE_CODE (arg) == TREE_LIST;
1516 arg = TREE_CHAIN (arg))
1518 tree expr = TREE_VALUE (arg);
1519 if (EXPR_P (expr))
1520 TREE_VALUE (arg) = fold_non_dependent_expr (expr);
1525 /* Return true if TYPE is an OpenMP mappable type.
1526 If NOTES is non-zero, emit a note message for each problem. */
1527 static bool
1528 cp_omp_mappable_type_1 (tree type, bool notes)
1530 bool result = true;
1532 /* Mappable type has to be complete. */
1533 if (type == error_mark_node || !COMPLETE_TYPE_P (type))
1535 if (notes && type != error_mark_node)
1537 tree decl = TYPE_MAIN_DECL (type);
1538 inform ((decl ? DECL_SOURCE_LOCATION (decl) : input_location),
1539 "incomplete type %qT is not mappable", type);
1541 result = false;
1543 /* Arrays have mappable type if the elements have mappable type. */
1544 while (TREE_CODE (type) == ARRAY_TYPE)
1545 type = TREE_TYPE (type);
1546 /* All data members must be non-static. */
1547 if (CLASS_TYPE_P (type))
1549 tree field;
1550 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1551 if (VAR_P (field))
1553 if (notes)
1554 inform (DECL_SOURCE_LOCATION (field),
1555 "static field %qD is not mappable", field);
1556 result = false;
1558 /* All fields must have mappable types. */
1559 else if (TREE_CODE (field) == FIELD_DECL
1560 && !cp_omp_mappable_type_1 (TREE_TYPE (field), notes))
1561 result = false;
1563 return result;
1566 /* Return true if TYPE is an OpenMP mappable type. */
1567 bool
1568 cp_omp_mappable_type (tree type)
1570 return cp_omp_mappable_type_1 (type, false);
1573 /* Return true if TYPE is an OpenMP mappable type.
1574 Emit an error messages if not. */
1575 bool
1576 cp_omp_emit_unmappable_type_notes (tree type)
1578 return cp_omp_mappable_type_1 (type, true);
1581 /* Return the last pushed declaration for the symbol DECL or NULL
1582 when no such declaration exists. */
1584 static tree
1585 find_last_decl (tree decl)
1587 tree last_decl = NULL_TREE;
1589 if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
1591 /* Look up the declaration in its scope. */
1592 tree pushed_scope = NULL_TREE;
1593 if (tree ctype = DECL_CONTEXT (decl))
1594 pushed_scope = push_scope (ctype);
1596 last_decl = lookup_name (name);
1598 if (pushed_scope)
1599 pop_scope (pushed_scope);
1601 /* The declaration may be a member conversion operator
1602 or a bunch of overfloads (handle the latter below). */
1603 if (last_decl && BASELINK_P (last_decl))
1604 last_decl = BASELINK_FUNCTIONS (last_decl);
1607 if (!last_decl)
1608 return NULL_TREE;
1610 if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
1612 /* A set of overloads of the same function. */
1613 for (lkp_iterator iter (last_decl); iter; ++iter)
1615 if (TREE_CODE (*iter) == OVERLOAD)
1616 continue;
1618 if (decls_match (decl, *iter, /*record_decls=*/false))
1619 return *iter;
1621 return NULL_TREE;
1624 return NULL_TREE;
1627 /* Like decl_attributes, but handle C++ complexity. */
1629 void
1630 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1632 if (*decl == NULL_TREE || *decl == void_type_node
1633 || *decl == error_mark_node)
1634 return;
1636 /* Add implicit "omp declare target" attribute if requested. */
1637 if (vec_safe_length (scope_chain->omp_declare_target_attribute)
1638 && ((VAR_P (*decl)
1639 && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1640 || TREE_CODE (*decl) == FUNCTION_DECL))
1642 if (VAR_P (*decl)
1643 && DECL_CLASS_SCOPE_P (*decl))
1644 error ("%q+D static data member inside of declare target directive",
1645 *decl);
1646 else if (VAR_P (*decl)
1647 && (processing_template_decl
1648 || !cp_omp_mappable_type (TREE_TYPE (*decl))))
1649 attributes = tree_cons (get_identifier ("omp declare target implicit"),
1650 NULL_TREE, attributes);
1651 else
1653 attributes = tree_cons (get_identifier ("omp declare target"),
1654 NULL_TREE, attributes);
1655 attributes = tree_cons (get_identifier ("omp declare target block"),
1656 NULL_TREE, attributes);
1660 tree late_attrs = NULL_TREE;
1661 if (processing_template_decl)
1663 if (check_for_bare_parameter_packs (attributes))
1664 return;
1665 late_attrs = splice_template_attributes (&attributes, *decl);
1668 cp_check_const_attributes (attributes);
1670 if ((flag_openmp || flag_openmp_simd) && attributes != error_mark_node)
1672 bool diagnosed = false;
1673 for (tree *pa = &attributes; *pa; )
1675 if (get_attribute_namespace (*pa) == omp_identifier)
1677 tree name = get_attribute_name (*pa);
1678 if (is_attribute_p ("directive", name)
1679 || is_attribute_p ("sequence", name))
1681 if (!diagnosed)
1683 error ("%<omp::%E%> not allowed to be specified in this "
1684 "context", name);
1685 diagnosed = true;
1687 *pa = TREE_CHAIN (*pa);
1688 continue;
1691 pa = &TREE_CHAIN (*pa);
1695 if (TREE_CODE (*decl) == TEMPLATE_DECL)
1696 decl = &DECL_TEMPLATE_RESULT (*decl);
1698 if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1700 attributes
1701 = decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1702 decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1703 attributes, flags);
1705 else
1707 tree last_decl = find_last_decl (*decl);
1708 decl_attributes (decl, attributes, flags, last_decl);
1711 if (late_attrs)
1712 save_template_attributes (late_attrs, decl, flags);
1714 /* Propagate deprecation out to the template. */
1715 if (TREE_DEPRECATED (*decl))
1716 if (tree ti = get_template_info (*decl))
1718 tree tmpl = TI_TEMPLATE (ti);
1719 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1720 : DECL_TEMPLATE_RESULT (tmpl));
1721 if (*decl == pattern)
1722 TREE_DEPRECATED (tmpl) = true;
1725 /* Likewise, propagate unavailability out to the template. */
1726 if (TREE_UNAVAILABLE (*decl))
1727 if (tree ti = get_template_info (*decl))
1729 tree tmpl = TI_TEMPLATE (ti);
1730 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1731 : DECL_TEMPLATE_RESULT (tmpl));
1732 if (*decl == pattern)
1733 TREE_UNAVAILABLE (tmpl) = true;
1737 /* Walks through the namespace- or function-scope anonymous union
1738 OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1739 Returns one of the fields for use in the mangled name. */
1741 static tree
1742 build_anon_union_vars (tree type, tree object)
1744 tree main_decl = NULL_TREE;
1745 tree field;
1747 /* Rather than write the code to handle the non-union case,
1748 just give an error. */
1749 if (TREE_CODE (type) != UNION_TYPE)
1751 error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
1752 "anonymous struct not inside named type");
1753 return error_mark_node;
1756 for (field = TYPE_FIELDS (type);
1757 field != NULL_TREE;
1758 field = DECL_CHAIN (field))
1760 tree decl;
1761 tree ref;
1763 if (DECL_ARTIFICIAL (field))
1764 continue;
1765 if (TREE_CODE (field) != FIELD_DECL)
1767 permerror (DECL_SOURCE_LOCATION (field),
1768 "%q#D invalid; an anonymous union can only "
1769 "have non-static data members", field);
1770 continue;
1773 if (TREE_PRIVATE (field))
1774 permerror (DECL_SOURCE_LOCATION (field),
1775 "private member %q#D in anonymous union", field);
1776 else if (TREE_PROTECTED (field))
1777 permerror (DECL_SOURCE_LOCATION (field),
1778 "protected member %q#D in anonymous union", field);
1780 if (processing_template_decl)
1781 ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1782 DECL_NAME (field), NULL_TREE);
1783 else
1784 ref = build_class_member_access_expr (object, field, NULL_TREE,
1785 false, tf_warning_or_error);
1787 if (DECL_NAME (field))
1789 tree base;
1791 decl = build_decl (input_location,
1792 VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1793 DECL_ANON_UNION_VAR_P (decl) = 1;
1794 DECL_ARTIFICIAL (decl) = 1;
1796 base = get_base_address (object);
1797 TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1798 TREE_STATIC (decl) = TREE_STATIC (base);
1799 DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1801 SET_DECL_VALUE_EXPR (decl, ref);
1802 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1804 decl = pushdecl (decl);
1806 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1807 decl = build_anon_union_vars (TREE_TYPE (field), ref);
1808 else
1809 decl = 0;
1811 if (main_decl == NULL_TREE)
1812 main_decl = decl;
1815 return main_decl;
1818 /* Finish off the processing of a UNION_TYPE structure. If the union is an
1819 anonymous union, then all members must be laid out together. PUBLIC_P
1820 is nonzero if this union is not declared static. */
1822 void
1823 finish_anon_union (tree anon_union_decl)
1825 tree type;
1826 tree main_decl;
1827 bool public_p;
1829 if (anon_union_decl == error_mark_node)
1830 return;
1832 type = TREE_TYPE (anon_union_decl);
1833 public_p = TREE_PUBLIC (anon_union_decl);
1835 /* The VAR_DECL's context is the same as the TYPE's context. */
1836 DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1838 if (TYPE_FIELDS (type) == NULL_TREE)
1839 return;
1841 if (public_p)
1843 error ("namespace-scope anonymous aggregates must be static");
1844 return;
1847 main_decl = build_anon_union_vars (type, anon_union_decl);
1848 if (main_decl == error_mark_node)
1849 return;
1850 if (main_decl == NULL_TREE)
1852 pedwarn (input_location, 0, "anonymous union with no members");
1853 return;
1856 if (!processing_template_decl)
1858 /* Use main_decl to set the mangled name. */
1859 DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1860 maybe_commonize_var (anon_union_decl);
1861 if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1863 if (DECL_DISCRIMINATOR_P (anon_union_decl))
1864 determine_local_discriminator (anon_union_decl);
1865 mangle_decl (anon_union_decl);
1867 DECL_NAME (anon_union_decl) = NULL_TREE;
1870 pushdecl (anon_union_decl);
1871 cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1874 /* Auxiliary functions to make type signatures for
1875 `operator new' and `operator delete' correspond to
1876 what compiler will be expecting. */
1878 tree
1879 coerce_new_type (tree type, location_t loc)
1881 int e = 0;
1882 tree args = TYPE_ARG_TYPES (type);
1884 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1886 if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1888 e = 1;
1889 error_at (loc, "%<operator new%> must return type %qT",
1890 ptr_type_node);
1893 if (args && args != void_list_node)
1895 if (TREE_PURPOSE (args))
1897 /* [basic.stc.dynamic.allocation]
1899 The first parameter shall not have an associated default
1900 argument. */
1901 error_at (loc, "the first parameter of %<operator new%> cannot "
1902 "have a default argument");
1903 /* Throw away the default argument. */
1904 TREE_PURPOSE (args) = NULL_TREE;
1907 if (!same_type_p (TREE_VALUE (args), size_type_node))
1909 e = 2;
1910 args = TREE_CHAIN (args);
1913 else
1914 e = 2;
1916 if (e == 2)
1917 permerror (loc, "%<operator new%> takes type %<size_t%> (%qT) "
1918 "as first parameter", size_type_node);
1920 switch (e)
1922 case 2:
1923 args = tree_cons (NULL_TREE, size_type_node, args);
1924 /* Fall through. */
1925 case 1:
1926 type = (cxx_copy_lang_qualifiers
1927 (build_function_type (ptr_type_node, args),
1928 type));
1929 /* Fall through. */
1930 default:;
1932 return type;
1935 void
1936 coerce_delete_type (tree decl, location_t loc)
1938 int e = 0;
1939 tree type = TREE_TYPE (decl);
1940 tree args = TYPE_ARG_TYPES (type);
1942 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1944 if (!same_type_p (TREE_TYPE (type), void_type_node))
1946 e = 1;
1947 error_at (loc, "%<operator delete%> must return type %qT",
1948 void_type_node);
1951 tree ptrtype = ptr_type_node;
1952 if (destroying_delete_p (decl))
1954 if (DECL_CLASS_SCOPE_P (decl))
1955 /* If the function is a destroying operator delete declared in class
1956 type C, the type of its first parameter shall be C*. */
1957 ptrtype = build_pointer_type (DECL_CONTEXT (decl));
1958 else
1959 /* A destroying operator delete shall be a class member function named
1960 operator delete. */
1961 error_at (loc,
1962 "destroying %<operator delete%> must be a member function");
1963 const ovl_op_info_t *op = IDENTIFIER_OVL_OP_INFO (DECL_NAME (decl));
1964 if (op->flags & OVL_OP_FLAG_VEC)
1965 error_at (loc, "%<operator delete[]%> cannot be a destroying delete");
1966 if (!usual_deallocation_fn_p (decl))
1967 error_at (loc, "destroying %<operator delete%> must be a usual "
1968 "deallocation function");
1971 if (!args || args == void_list_node
1972 || !same_type_p (TREE_VALUE (args), ptrtype))
1974 e = 2;
1975 if (args && args != void_list_node)
1976 args = TREE_CHAIN (args);
1977 error_at (loc, "%<operator delete%> takes type %qT as first parameter",
1978 ptrtype);
1980 switch (e)
1982 case 2:
1983 args = tree_cons (NULL_TREE, ptrtype, args);
1984 /* Fall through. */
1985 case 1:
1986 type = (cxx_copy_lang_qualifiers
1987 (build_function_type (void_type_node, args),
1988 type));
1989 /* Fall through. */
1990 default:;
1993 TREE_TYPE (decl) = type;
1996 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
1997 and mark them as needed. */
1999 static void
2000 mark_vtable_entries (tree decl, vec<tree> &consteval_vtables)
2002 /* It's OK for the vtable to refer to deprecated virtual functions. */
2003 warning_sentinel w(warn_deprecated_decl);
2005 bool consteval_seen = false;
2007 for (auto &e: CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
2009 tree fnaddr = e.value;
2011 STRIP_NOPS (fnaddr);
2013 if (TREE_CODE (fnaddr) != ADDR_EXPR
2014 && TREE_CODE (fnaddr) != FDESC_EXPR)
2015 /* This entry is an offset: a virtual base class offset, a
2016 virtual call offset, an RTTI offset, etc. */
2017 continue;
2019 tree fn = TREE_OPERAND (fnaddr, 0);
2020 if (TREE_CODE (fn) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (fn))
2022 if (!consteval_seen)
2024 consteval_seen = true;
2025 consteval_vtables.safe_push (decl);
2027 continue;
2029 TREE_ADDRESSABLE (fn) = 1;
2030 /* When we don't have vcall offsets, we output thunks whenever
2031 we output the vtables that contain them. With vcall offsets,
2032 we know all the thunks we'll need when we emit a virtual
2033 function, so we emit the thunks there instead. */
2034 if (DECL_THUNK_P (fn))
2035 use_thunk (fn, /*emit_p=*/0);
2036 /* Set the location, as marking the function could cause
2037 instantiation. We do not need to preserve the incoming
2038 location, as we're called from c_parse_final_cleanups, which
2039 takes care of that. */
2040 input_location = DECL_SOURCE_LOCATION (fn);
2041 mark_used (fn);
2045 /* Replace any consteval functions in vtables with null pointers. */
2047 static void
2048 clear_consteval_vfns (vec<tree> &consteval_vtables)
2050 for (tree vtable : consteval_vtables)
2051 for (constructor_elt &elt : CONSTRUCTOR_ELTS (DECL_INITIAL (vtable)))
2053 tree fn = cp_get_fndecl_from_callee (elt.value, /*fold*/false);
2054 if (fn && DECL_IMMEDIATE_FUNCTION_P (fn))
2055 elt.value = build_zero_cst (vtable_entry_type);
2059 /* Adjust the TLS model on variable DECL if need be, typically after
2060 the linkage of DECL has been modified. */
2062 static void
2063 adjust_var_decl_tls_model (tree decl)
2065 if (CP_DECL_THREAD_LOCAL_P (decl)
2066 && !lookup_attribute ("tls_model", DECL_ATTRIBUTES (decl)))
2067 set_decl_tls_model (decl, decl_default_tls_model (decl));
2070 /* Set DECL up to have the closest approximation of "initialized common"
2071 linkage available. */
2073 void
2074 comdat_linkage (tree decl)
2076 if (flag_weak)
2077 make_decl_one_only (decl, cxx_comdat_group (decl));
2078 else if (TREE_CODE (decl) == FUNCTION_DECL
2079 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2080 /* We can just emit function and compiler-generated variables
2081 statically; having multiple copies is (for the most part) only
2082 a waste of space.
2084 There are two correctness issues, however: the address of a
2085 template instantiation with external linkage should be the
2086 same, independent of what translation unit asks for the
2087 address, and this will not hold when we emit multiple copies of
2088 the function. However, there's little else we can do.
2090 Also, by default, the typeinfo implementation assumes that
2091 there will be only one copy of the string used as the name for
2092 each type. Therefore, if weak symbols are unavailable, the
2093 run-time library should perform a more conservative check; it
2094 should perform a string comparison, rather than an address
2095 comparison. */
2096 TREE_PUBLIC (decl) = 0;
2097 else
2099 /* Static data member template instantiations, however, cannot
2100 have multiple copies. */
2101 if (DECL_INITIAL (decl) == 0
2102 || DECL_INITIAL (decl) == error_mark_node)
2103 DECL_COMMON (decl) = 1;
2104 else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
2106 DECL_COMMON (decl) = 1;
2107 DECL_INITIAL (decl) = error_mark_node;
2109 else if (!DECL_EXPLICIT_INSTANTIATION (decl))
2111 /* We can't do anything useful; leave vars for explicit
2112 instantiation. */
2113 DECL_EXTERNAL (decl) = 1;
2114 DECL_NOT_REALLY_EXTERN (decl) = 0;
2118 if (TREE_PUBLIC (decl))
2119 DECL_COMDAT (decl) = 1;
2121 if (VAR_P (decl))
2122 adjust_var_decl_tls_model (decl);
2125 /* For win32 we also want to put explicit instantiations in
2126 linkonce sections, so that they will be merged with implicit
2127 instantiations; otherwise we get duplicate symbol errors.
2128 For Darwin we do not want explicit instantiations to be
2129 linkonce. */
2131 void
2132 maybe_make_one_only (tree decl)
2134 /* We used to say that this was not necessary on targets that support weak
2135 symbols, because the implicit instantiations will defer to the explicit
2136 one. However, that's not actually the case in SVR4; a strong definition
2137 after a weak one is an error. Also, not making explicit
2138 instantiations one_only means that we can end up with two copies of
2139 some template instantiations. */
2140 if (! flag_weak)
2141 return;
2143 /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
2144 we can get away with not emitting them if they aren't used. We need
2145 to for variables so that cp_finish_decl will update their linkage,
2146 because their DECL_INITIAL may not have been set properly yet. */
2148 if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
2149 || (! DECL_EXPLICIT_INSTANTIATION (decl)
2150 && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
2152 make_decl_one_only (decl, cxx_comdat_group (decl));
2154 if (VAR_P (decl))
2156 varpool_node *node = varpool_node::get_create (decl);
2157 DECL_COMDAT (decl) = 1;
2158 /* Mark it needed so we don't forget to emit it. */
2159 node->forced_by_abi = true;
2160 TREE_USED (decl) = 1;
2162 adjust_var_decl_tls_model (decl);
2167 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
2168 This predicate will give the right answer during parsing of the
2169 function, which other tests may not. */
2171 bool
2172 vague_linkage_p (tree decl)
2174 if (!TREE_PUBLIC (decl))
2176 /* maybe_thunk_body clears TREE_PUBLIC and DECL_ABSTRACT_P on the
2177 maybe-in-charge 'tor variants; in that case we need to check one of
2178 the "clones" for the real linkage. But only in that case; before
2179 maybe_clone_body we haven't yet copied the linkage to the clones. */
2180 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl)
2181 && !DECL_ABSTRACT_P (decl)
2182 && DECL_CHAIN (decl)
2183 && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
2184 return vague_linkage_p (DECL_CHAIN (decl));
2186 gcc_checking_assert (!DECL_COMDAT (decl));
2187 return false;
2189 /* Unfortunately, import_export_decl has not always been called
2190 before the function is processed, so we cannot simply check
2191 DECL_COMDAT. */
2192 if (DECL_COMDAT (decl)
2193 || (TREE_CODE (decl) == FUNCTION_DECL
2194 && DECL_DECLARED_INLINE_P (decl))
2195 || (DECL_LANG_SPECIFIC (decl)
2196 && DECL_TEMPLATE_INSTANTIATION (decl))
2197 || (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
2198 return true;
2199 else if (DECL_FUNCTION_SCOPE_P (decl))
2200 /* A local static in an inline effectively has vague linkage. */
2201 return (TREE_STATIC (decl)
2202 && vague_linkage_p (DECL_CONTEXT (decl)));
2203 else
2204 return false;
2207 /* Determine whether or not we want to specifically import or export CTYPE,
2208 using various heuristics. */
2210 static void
2211 import_export_class (tree ctype)
2213 /* -1 for imported, 1 for exported. */
2214 int import_export = 0;
2216 /* It only makes sense to call this function at EOF. The reason is
2217 that this function looks at whether or not the first non-inline
2218 non-abstract virtual member function has been defined in this
2219 translation unit. But, we can't possibly know that until we've
2220 seen the entire translation unit. */
2221 gcc_assert (at_eof);
2223 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2224 return;
2226 /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
2227 we will have CLASSTYPE_INTERFACE_ONLY set but not
2228 CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this
2229 heuristic because someone will supply a #pragma implementation
2230 elsewhere, and deducing it here would produce a conflict. */
2231 if (CLASSTYPE_INTERFACE_ONLY (ctype))
2232 return;
2234 if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2235 import_export = -1;
2236 else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2237 import_export = 1;
2238 else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2239 && !flag_implicit_templates)
2240 /* For a template class, without -fimplicit-templates, check the
2241 repository. If the virtual table is assigned to this
2242 translation unit, then export the class; otherwise, import
2243 it. */
2244 import_export = -1;
2245 else if (TYPE_POLYMORPHIC_P (ctype))
2247 /* The ABI specifies that the virtual table and associated
2248 information are emitted with the key method, if any. */
2249 tree method = CLASSTYPE_KEY_METHOD (ctype);
2250 /* If weak symbol support is not available, then we must be
2251 careful not to emit the vtable when the key function is
2252 inline. An inline function can be defined in multiple
2253 translation units. If we were to emit the vtable in each
2254 translation unit containing a definition, we would get
2255 multiple definition errors at link-time. */
2256 if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
2257 import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2260 /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
2261 a definition anywhere else. */
2262 if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
2263 import_export = 0;
2265 /* Allow back ends the chance to overrule the decision. */
2266 if (targetm.cxx.import_export_class)
2267 import_export = targetm.cxx.import_export_class (ctype, import_export);
2269 if (import_export)
2271 SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2272 CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2276 /* Return true if VAR has already been provided to the back end; in that
2277 case VAR should not be modified further by the front end. */
2278 static bool
2279 var_finalized_p (tree var)
2281 return varpool_node::get_create (var)->definition;
2284 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
2285 must be emitted in this translation unit. Mark it as such. */
2287 void
2288 mark_needed (tree decl)
2290 TREE_USED (decl) = 1;
2291 if (TREE_CODE (decl) == FUNCTION_DECL)
2293 /* Extern inline functions don't become needed when referenced.
2294 If we know a method will be emitted in other TU and no new
2295 functions can be marked reachable, just use the external
2296 definition. */
2297 struct cgraph_node *node = cgraph_node::get_create (decl);
2298 node->forced_by_abi = true;
2300 /* #pragma interface can call mark_needed for
2301 maybe-in-charge 'tors; mark the clones as well. */
2302 tree clone;
2303 FOR_EACH_CLONE (clone, decl)
2304 mark_needed (clone);
2306 else if (VAR_P (decl))
2308 varpool_node *node = varpool_node::get_create (decl);
2309 /* C++ frontend use mark_decl_references to force COMDAT variables
2310 to be output that might appear dead otherwise. */
2311 node->forced_by_abi = true;
2315 /* DECL is either a FUNCTION_DECL or a VAR_DECL. This function
2316 returns true if a definition of this entity should be provided in
2317 this object file. Callers use this function to determine whether
2318 or not to let the back end know that a definition of DECL is
2319 available in this translation unit. */
2321 bool
2322 decl_needed_p (tree decl)
2324 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2325 /* This function should only be called at the end of the translation
2326 unit. We cannot be sure of whether or not something will be
2327 COMDAT until that point. */
2328 gcc_assert (at_eof);
2330 /* All entities with external linkage that are not COMDAT/EXTERN should be
2331 emitted; they may be referred to from other object files. */
2332 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2333 return true;
2335 /* Functions marked "dllexport" must be emitted so that they are
2336 visible to other DLLs. */
2337 if (flag_keep_inline_dllexport
2338 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2339 return true;
2341 /* When not optimizing, do not bother to produce definitions for extern
2342 symbols. */
2343 if (DECL_REALLY_EXTERN (decl)
2344 && ((TREE_CODE (decl) != FUNCTION_DECL
2345 && !optimize)
2346 || (TREE_CODE (decl) == FUNCTION_DECL
2347 && !opt_for_fn (decl, optimize)))
2348 && !lookup_attribute ("always_inline", decl))
2349 return false;
2351 /* If this entity was used, let the back end see it; it will decide
2352 whether or not to emit it into the object file. */
2353 if (TREE_USED (decl))
2354 return true;
2356 /* Virtual functions might be needed for devirtualization. */
2357 if (flag_devirtualize
2358 && TREE_CODE (decl) == FUNCTION_DECL
2359 && DECL_VIRTUAL_P (decl))
2360 return true;
2362 /* Otherwise, DECL does not need to be emitted -- yet. A subsequent
2363 reference to DECL might cause it to be emitted later. */
2364 return false;
2367 /* If necessary, write out the vtables for the dynamic class CTYPE.
2368 Returns true if any vtables were emitted. */
2370 static bool
2371 maybe_emit_vtables (tree ctype, vec<tree> &consteval_vtables)
2373 tree vtbl;
2374 tree primary_vtbl;
2375 int needed = 0;
2376 varpool_node *current = NULL, *last = NULL;
2378 /* If the vtables for this class have already been emitted there is
2379 nothing more to do. */
2380 primary_vtbl = CLASSTYPE_VTABLES (ctype);
2381 if (var_finalized_p (primary_vtbl))
2382 return false;
2383 /* Ignore dummy vtables made by get_vtable_decl. */
2384 if (TREE_TYPE (primary_vtbl) == void_type_node)
2385 return false;
2387 /* On some targets, we cannot determine the key method until the end
2388 of the translation unit -- which is when this function is
2389 called. */
2390 if (!targetm.cxx.key_method_may_be_inline ())
2391 determine_key_method (ctype);
2393 /* See if any of the vtables are needed. */
2394 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2396 import_export_decl (vtbl);
2397 if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2398 needed = 1;
2400 if (!needed)
2402 /* If the references to this class' vtables are optimized away,
2403 still emit the appropriate debugging information. See
2404 dfs_debug_mark. */
2405 if (DECL_COMDAT (primary_vtbl)
2406 && CLASSTYPE_DEBUG_REQUESTED (ctype))
2407 note_debug_info_needed (ctype);
2408 return false;
2411 /* The ABI requires that we emit all of the vtables if we emit any
2412 of them. */
2413 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2415 /* Mark entities references from the virtual table as used. */
2416 mark_vtable_entries (vtbl, consteval_vtables);
2418 if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2420 vec<tree, va_gc> *cleanups = NULL;
2421 tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2422 LOOKUP_NORMAL);
2424 /* It had better be all done at compile-time. */
2425 gcc_assert (!expr && !cleanups);
2428 /* Write it out. */
2429 DECL_EXTERNAL (vtbl) = 0;
2430 rest_of_decl_compilation (vtbl, 1, 1);
2432 /* Because we're only doing syntax-checking, we'll never end up
2433 actually marking the variable as written. */
2434 if (flag_syntax_only)
2435 TREE_ASM_WRITTEN (vtbl) = 1;
2436 else if (DECL_ONE_ONLY (vtbl))
2438 current = varpool_node::get_create (vtbl);
2439 if (last)
2440 current->add_to_same_comdat_group (last);
2441 last = current;
2445 /* For abstract classes, the destructor has been removed from the
2446 vtable (in class.cc's build_vtbl_initializer). For a compiler-
2447 generated destructor, it hence might not have been generated in
2448 this translation unit - and with '#pragma interface' it might
2449 never get generated. */
2450 if (CLASSTYPE_PURE_VIRTUALS (ctype)
2451 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype)
2452 && !CLASSTYPE_LAZY_DESTRUCTOR (ctype)
2453 && DECL_DEFAULTED_IN_CLASS_P (CLASSTYPE_DESTRUCTOR (ctype)))
2454 note_vague_linkage_fn (CLASSTYPE_DESTRUCTOR (ctype));
2456 /* Since we're writing out the vtable here, also write the debug
2457 info. */
2458 note_debug_info_needed (ctype);
2460 return true;
2463 /* A special return value from type_visibility meaning internal
2464 linkage. */
2466 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2468 static int expr_visibility (tree);
2469 static int type_visibility (tree);
2471 /* walk_tree helper function for type_visibility. */
2473 static tree
2474 min_vis_r (tree *tp, int *walk_subtrees, void *data)
2476 int *vis_p = (int *)data;
2477 int this_vis = VISIBILITY_DEFAULT;
2478 if (! TYPE_P (*tp))
2479 *walk_subtrees = 0;
2480 else if (OVERLOAD_TYPE_P (*tp)
2481 && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2483 this_vis = VISIBILITY_ANON;
2484 *walk_subtrees = 0;
2486 else if (CLASS_TYPE_P (*tp))
2488 this_vis = CLASSTYPE_VISIBILITY (*tp);
2489 *walk_subtrees = 0;
2491 else if (TREE_CODE (*tp) == ARRAY_TYPE
2492 && uses_template_parms (TYPE_DOMAIN (*tp)))
2493 this_vis = expr_visibility (TYPE_MAX_VALUE (TYPE_DOMAIN (*tp)));
2495 if (this_vis > *vis_p)
2496 *vis_p = this_vis;
2498 /* Tell cp_walk_subtrees to look through typedefs. */
2499 if (*walk_subtrees == 1)
2500 *walk_subtrees = 2;
2502 return NULL;
2505 /* walk_tree helper function for expr_visibility. */
2507 static tree
2508 min_vis_expr_r (tree *tp, int */*walk_subtrees*/, void *data)
2510 int *vis_p = (int *)data;
2511 int tpvis = VISIBILITY_DEFAULT;
2513 switch (TREE_CODE (*tp))
2515 case CAST_EXPR:
2516 case IMPLICIT_CONV_EXPR:
2517 case STATIC_CAST_EXPR:
2518 case REINTERPRET_CAST_EXPR:
2519 case CONST_CAST_EXPR:
2520 case DYNAMIC_CAST_EXPR:
2521 case NEW_EXPR:
2522 case CONSTRUCTOR:
2523 case LAMBDA_EXPR:
2524 tpvis = type_visibility (TREE_TYPE (*tp));
2525 break;
2527 case VAR_DECL:
2528 case FUNCTION_DECL:
2529 if (! TREE_PUBLIC (*tp))
2530 tpvis = VISIBILITY_ANON;
2531 else
2532 tpvis = DECL_VISIBILITY (*tp);
2533 break;
2535 default:
2536 break;
2539 if (tpvis > *vis_p)
2540 *vis_p = tpvis;
2542 return NULL_TREE;
2545 /* Returns the visibility of TYPE, which is the minimum visibility of its
2546 component types. */
2548 static int
2549 type_visibility (tree type)
2551 int vis = VISIBILITY_DEFAULT;
2552 cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2553 return vis;
2556 /* Returns the visibility of an expression EXPR that appears in the signature
2557 of a function template, which is the minimum visibility of names that appear
2558 in its mangling. */
2560 static int
2561 expr_visibility (tree expr)
2563 int vis = VISIBILITY_DEFAULT;
2564 cp_walk_tree_without_duplicates (&expr, min_vis_expr_r, &vis);
2565 return vis;
2568 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
2569 specified (or if VISIBILITY is static). If TMPL is true, this
2570 constraint is for a template argument, and takes precedence
2571 over explicitly-specified visibility on the template. */
2573 static void
2574 constrain_visibility (tree decl, int visibility, bool tmpl)
2576 if (visibility == VISIBILITY_ANON)
2578 /* extern "C" declarations aren't affected by the anonymous
2579 namespace. */
2580 if (!DECL_EXTERN_C_P (decl))
2582 TREE_PUBLIC (decl) = 0;
2583 DECL_WEAK (decl) = 0;
2584 DECL_COMMON (decl) = 0;
2585 DECL_COMDAT (decl) = false;
2586 if (VAR_OR_FUNCTION_DECL_P (decl))
2588 struct symtab_node *snode = symtab_node::get (decl);
2590 if (snode)
2591 snode->set_comdat_group (NULL);
2593 DECL_INTERFACE_KNOWN (decl) = 1;
2594 if (DECL_LANG_SPECIFIC (decl))
2595 DECL_NOT_REALLY_EXTERN (decl) = 1;
2598 else if (visibility > DECL_VISIBILITY (decl)
2599 && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2601 DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2602 /* This visibility was not specified. */
2603 DECL_VISIBILITY_SPECIFIED (decl) = false;
2607 /* Constrain the visibility of DECL based on the visibility of its template
2608 arguments. */
2610 static void
2611 constrain_visibility_for_template (tree decl, tree targs)
2613 /* If this is a template instantiation, check the innermost
2614 template args for visibility constraints. The outer template
2615 args are covered by the class check. */
2616 tree args = INNERMOST_TEMPLATE_ARGS (targs);
2617 int i;
2618 for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2620 int vis = 0;
2622 tree arg = TREE_VEC_ELT (args, i-1);
2623 if (TYPE_P (arg))
2624 vis = type_visibility (arg);
2625 else
2626 vis = expr_visibility (arg);
2627 if (vis)
2628 constrain_visibility (decl, vis, true);
2632 /* Like c_determine_visibility, but with additional C++-specific
2633 behavior.
2635 Function-scope entities can rely on the function's visibility because
2636 it is set in start_preparsed_function.
2638 Class-scope entities cannot rely on the class's visibility until the end
2639 of the enclosing class definition.
2641 Note that because namespaces have multiple independent definitions,
2642 namespace visibility is handled elsewhere using the #pragma visibility
2643 machinery rather than by decorating the namespace declaration.
2645 The goal is for constraints from the type to give a diagnostic, and
2646 other constraints to be applied silently. */
2648 void
2649 determine_visibility (tree decl)
2651 /* Remember that all decls get VISIBILITY_DEFAULT when built. */
2653 /* Only relevant for names with external linkage. */
2654 if (!TREE_PUBLIC (decl))
2655 return;
2657 /* Cloned constructors and destructors get the same visibility as
2658 the underlying function. That should be set up in
2659 maybe_clone_body. */
2660 gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2662 bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2663 enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
2665 /* The decl may be a template instantiation, which could influence
2666 visibilty. */
2667 tree template_decl = NULL_TREE;
2668 if (TREE_CODE (decl) == TYPE_DECL)
2670 if (CLASS_TYPE_P (TREE_TYPE (decl)))
2672 if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
2673 template_decl = decl;
2675 else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2676 template_decl = decl;
2678 else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
2679 template_decl = decl;
2681 if (TREE_CODE (decl) == TYPE_DECL
2682 && LAMBDA_TYPE_P (TREE_TYPE (decl))
2683 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (decl)) != error_mark_node)
2684 if (tree extra = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl)))
2686 /* The lambda's visibility is limited by that of its extra
2687 scope. */
2688 int vis = 0;
2689 if (TYPE_P (extra))
2690 vis = type_visibility (extra);
2691 else
2692 vis = expr_visibility (extra);
2693 constrain_visibility (decl, vis, false);
2696 /* If DECL is a member of a class, visibility specifiers on the
2697 class can influence the visibility of the DECL. */
2698 tree class_type = NULL_TREE;
2699 if (DECL_CLASS_SCOPE_P (decl))
2700 class_type = DECL_CONTEXT (decl);
2701 else
2703 /* Not a class member. */
2705 /* Virtual tables have DECL_CONTEXT set to their associated class,
2706 so they are automatically handled above. */
2707 gcc_assert (!VAR_P (decl)
2708 || !DECL_VTABLE_OR_VTT_P (decl));
2710 if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2712 /* Local statics and classes get the visibility of their
2713 containing function by default, except that
2714 -fvisibility-inlines-hidden doesn't affect them. */
2715 tree fn = DECL_CONTEXT (decl);
2716 if (DECL_VISIBILITY_SPECIFIED (fn))
2718 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2719 DECL_VISIBILITY_SPECIFIED (decl) =
2720 DECL_VISIBILITY_SPECIFIED (fn);
2722 else
2724 if (DECL_CLASS_SCOPE_P (fn))
2725 determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2726 else if (determine_hidden_inline (fn))
2728 DECL_VISIBILITY (decl) = default_visibility;
2729 DECL_VISIBILITY_SPECIFIED (decl) =
2730 visibility_options.inpragma;
2732 else
2734 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2735 DECL_VISIBILITY_SPECIFIED (decl) =
2736 DECL_VISIBILITY_SPECIFIED (fn);
2740 /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2741 but have no TEMPLATE_INFO, so don't try to check it. */
2742 template_decl = NULL_TREE;
2744 else if (VAR_P (decl) && DECL_TINFO_P (decl)
2745 && flag_visibility_ms_compat)
2747 /* Under -fvisibility-ms-compat, types are visible by default,
2748 even though their contents aren't. */
2749 tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2750 int underlying_vis = type_visibility (underlying_type);
2751 if (underlying_vis == VISIBILITY_ANON
2752 || (CLASS_TYPE_P (underlying_type)
2753 && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2754 constrain_visibility (decl, underlying_vis, false);
2755 else
2756 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2758 else if (VAR_P (decl) && DECL_TINFO_P (decl))
2760 /* tinfo visibility is based on the type it's for. */
2761 constrain_visibility
2762 (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2764 /* Give the target a chance to override the visibility associated
2765 with DECL. */
2766 if (TREE_PUBLIC (decl)
2767 && !DECL_REALLY_EXTERN (decl)
2768 && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2769 && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2770 targetm.cxx.determine_class_data_visibility (decl);
2772 else if (template_decl)
2773 /* Template instantiations and specializations get visibility based
2774 on their template unless they override it with an attribute. */;
2775 else if (! DECL_VISIBILITY_SPECIFIED (decl))
2777 if (determine_hidden_inline (decl))
2778 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2779 else
2781 /* Set default visibility to whatever the user supplied with
2782 #pragma GCC visibility or a namespace visibility attribute. */
2783 DECL_VISIBILITY (decl) = default_visibility;
2784 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2789 if (template_decl)
2791 /* If the specialization doesn't specify visibility, use the
2792 visibility from the template. */
2793 tree tinfo = get_template_info (template_decl);
2794 tree args = TI_ARGS (tinfo);
2795 tree attribs = (TREE_CODE (decl) == TYPE_DECL
2796 ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2797 : DECL_ATTRIBUTES (decl));
2798 tree attr = lookup_attribute ("visibility", attribs);
2800 if (args != error_mark_node)
2802 tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2804 if (!DECL_VISIBILITY_SPECIFIED (decl))
2806 if (!attr
2807 && determine_hidden_inline (decl))
2808 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2809 else
2811 DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2812 DECL_VISIBILITY_SPECIFIED (decl)
2813 = DECL_VISIBILITY_SPECIFIED (pattern);
2817 if (args
2818 /* Template argument visibility outweighs #pragma or namespace
2819 visibility, but not an explicit attribute. */
2820 && !attr)
2822 int depth = TMPL_ARGS_DEPTH (args);
2823 if (DECL_VISIBILITY_SPECIFIED (decl))
2825 /* A class template member with explicit visibility
2826 overrides the class visibility, so we need to apply
2827 all the levels of template args directly. */
2828 int i;
2829 for (i = 1; i <= depth; ++i)
2831 tree lev = TMPL_ARGS_LEVEL (args, i);
2832 constrain_visibility_for_template (decl, lev);
2835 else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2836 /* Limit visibility based on its template arguments. */
2837 constrain_visibility_for_template (decl, args);
2842 if (class_type)
2843 determine_visibility_from_class (decl, class_type);
2845 if (decl_anon_ns_mem_p (decl))
2846 /* Names in an anonymous namespace get internal linkage. */
2847 constrain_visibility (decl, VISIBILITY_ANON, false);
2848 else if (TREE_CODE (decl) != TYPE_DECL)
2850 /* Propagate anonymity from type to decl. */
2851 int tvis = type_visibility (TREE_TYPE (decl));
2852 if (tvis == VISIBILITY_ANON
2853 || ! DECL_VISIBILITY_SPECIFIED (decl))
2854 constrain_visibility (decl, tvis, false);
2856 else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2857 /* DR 757: A type without linkage shall not be used as the type of a
2858 variable or function with linkage, unless
2859 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2860 o the variable or function is not used (3.2 [basic.def.odr]) or is
2861 defined in the same translation unit.
2863 Since non-extern "C" decls need to be defined in the same
2864 translation unit, we can make the type internal. */
2865 constrain_visibility (decl, VISIBILITY_ANON, false);
2867 /* If visibility changed and DECL already has DECL_RTL, ensure
2868 symbol flags are updated. */
2869 if ((DECL_VISIBILITY (decl) != orig_visibility
2870 || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2871 && ((VAR_P (decl) && TREE_STATIC (decl))
2872 || TREE_CODE (decl) == FUNCTION_DECL)
2873 && DECL_RTL_SET_P (decl))
2874 make_decl_rtl (decl);
2877 /* By default, static data members and function members receive
2878 the visibility of their containing class. */
2880 static void
2881 determine_visibility_from_class (tree decl, tree class_type)
2883 if (DECL_VISIBILITY_SPECIFIED (decl))
2884 return;
2886 if (determine_hidden_inline (decl))
2887 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2888 else
2890 /* Default to the class visibility. */
2891 DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2892 DECL_VISIBILITY_SPECIFIED (decl)
2893 = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2896 /* Give the target a chance to override the visibility associated
2897 with DECL. */
2898 if (VAR_P (decl)
2899 && TREE_PUBLIC (decl)
2900 && (DECL_TINFO_P (decl) || DECL_VTABLE_OR_VTT_P (decl))
2901 && !DECL_REALLY_EXTERN (decl)
2902 && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2903 targetm.cxx.determine_class_data_visibility (decl);
2906 /* Returns true iff DECL is an inline that should get hidden visibility
2907 because of -fvisibility-inlines-hidden. */
2909 static bool
2910 determine_hidden_inline (tree decl)
2912 return (visibility_options.inlines_hidden
2913 /* Don't do this for inline templates; specializations might not be
2914 inline, and we don't want them to inherit the hidden
2915 visibility. We'll set it here for all inline instantiations. */
2916 && !processing_template_decl
2917 && TREE_CODE (decl) == FUNCTION_DECL
2918 && DECL_DECLARED_INLINE_P (decl)
2919 && (! DECL_LANG_SPECIFIC (decl)
2920 || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2923 /* Constrain the visibility of a class TYPE based on the visibility of its
2924 field types. Warn if any fields require lesser visibility. */
2926 void
2927 constrain_class_visibility (tree type)
2929 tree binfo;
2930 tree t;
2931 int i;
2933 int vis = type_visibility (type);
2935 if (vis == VISIBILITY_ANON
2936 || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2937 return;
2939 /* Don't warn about visibility if the class has explicit visibility. */
2940 if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2941 vis = VISIBILITY_INTERNAL;
2943 for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2944 if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
2945 && !DECL_ARTIFICIAL (t))
2947 tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2948 int subvis = type_visibility (ftype);
2950 if (subvis == VISIBILITY_ANON)
2952 if (!in_main_input_context())
2954 tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
2955 if (nlt)
2957 if (same_type_p (TREE_TYPE (t), nlt))
2958 warning (OPT_Wsubobject_linkage, "\
2959 %qT has a field %qD whose type has no linkage",
2960 type, t);
2961 else
2962 warning (OPT_Wsubobject_linkage, "\
2963 %qT has a field %qD whose type depends on the type %qT which has no linkage",
2964 type, t, nlt);
2966 else
2967 warning (OPT_Wsubobject_linkage, "\
2968 %qT has a field %qD whose type uses the anonymous namespace",
2969 type, t);
2972 else if (MAYBE_CLASS_TYPE_P (ftype)
2973 && vis < VISIBILITY_HIDDEN
2974 && subvis >= VISIBILITY_HIDDEN)
2975 warning (OPT_Wattributes, "\
2976 %qT declared with greater visibility than the type of its field %qD",
2977 type, t);
2980 binfo = TYPE_BINFO (type);
2981 for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
2983 int subvis = type_visibility (TREE_TYPE (t));
2985 if (subvis == VISIBILITY_ANON)
2987 if (!in_main_input_context())
2989 tree nlt = no_linkage_check (TREE_TYPE (t), /*relaxed_p=*/false);
2990 if (nlt)
2992 if (same_type_p (TREE_TYPE (t), nlt))
2993 warning (OPT_Wsubobject_linkage, "\
2994 %qT has a base %qT whose type has no linkage",
2995 type, TREE_TYPE (t));
2996 else
2997 warning (OPT_Wsubobject_linkage, "\
2998 %qT has a base %qT whose type depends on the type %qT which has no linkage",
2999 type, TREE_TYPE (t), nlt);
3001 else
3002 warning (OPT_Wsubobject_linkage, "\
3003 %qT has a base %qT whose type uses the anonymous namespace",
3004 type, TREE_TYPE (t));
3007 else if (vis < VISIBILITY_HIDDEN
3008 && subvis >= VISIBILITY_HIDDEN)
3009 warning (OPT_Wattributes, "\
3010 %qT declared with greater visibility than its base %qT",
3011 type, TREE_TYPE (t));
3015 /* Functions for adjusting the visibility of a tagged type and its nested
3016 types and declarations when it gets a name for linkage purposes from a
3017 typedef. */
3018 // FIXME: It is now a DR for such a class type to contain anything
3019 // other than C. So at minium most of this can probably be deleted.
3021 /* First reset the visibility of all the types. */
3023 static void
3024 reset_type_linkage_1 (tree type)
3026 set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
3027 if (CLASS_TYPE_P (type))
3028 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
3029 if (DECL_IMPLICIT_TYPEDEF_P (member))
3030 reset_type_linkage_1 (TREE_TYPE (member));
3033 /* Then reset the visibility of any static data members or member
3034 functions that use those types. */
3036 static void
3037 reset_decl_linkage (tree decl)
3039 if (TREE_PUBLIC (decl))
3040 return;
3041 if (DECL_CLONED_FUNCTION_P (decl))
3042 return;
3043 TREE_PUBLIC (decl) = true;
3044 DECL_INTERFACE_KNOWN (decl) = false;
3045 determine_visibility (decl);
3046 tentative_decl_linkage (decl);
3049 void
3050 reset_type_linkage (tree type)
3052 reset_type_linkage_1 (type);
3053 if (CLASS_TYPE_P (type))
3055 if (tree vt = CLASSTYPE_VTABLES (type))
3057 tree name = mangle_vtbl_for_type (type);
3058 DECL_NAME (vt) = name;
3059 SET_DECL_ASSEMBLER_NAME (vt, name);
3060 reset_decl_linkage (vt);
3062 if (!ANON_AGGR_TYPE_P (type))
3063 if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
3065 tree name = mangle_typeinfo_for_type (type);
3066 DECL_NAME (ti) = name;
3067 SET_DECL_ASSEMBLER_NAME (ti, name);
3068 TREE_TYPE (name) = type;
3069 reset_decl_linkage (ti);
3071 for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
3073 tree mem = STRIP_TEMPLATE (m);
3074 if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
3075 reset_decl_linkage (mem);
3076 else if (DECL_IMPLICIT_TYPEDEF_P (mem))
3077 reset_type_linkage (TREE_TYPE (mem));
3082 /* Set up our initial idea of what the linkage of DECL should be. */
3084 void
3085 tentative_decl_linkage (tree decl)
3087 if (DECL_INTERFACE_KNOWN (decl))
3088 /* We've already made a decision as to how this function will
3089 be handled. */;
3090 else if (vague_linkage_p (decl))
3092 if (TREE_CODE (decl) == FUNCTION_DECL
3093 && decl_defined_p (decl))
3095 DECL_EXTERNAL (decl) = 1;
3096 DECL_NOT_REALLY_EXTERN (decl) = 1;
3097 note_vague_linkage_fn (decl);
3098 /* A non-template inline function with external linkage will
3099 always be COMDAT. As we must eventually determine the
3100 linkage of all functions, and as that causes writes to
3101 the data mapped in from the PCH file, it's advantageous
3102 to mark the functions at this point. */
3103 if (DECL_DECLARED_INLINE_P (decl)
3104 && (!DECL_IMPLICIT_INSTANTIATION (decl)
3105 || DECL_DEFAULTED_FN (decl)))
3107 /* This function must have external linkage, as
3108 otherwise DECL_INTERFACE_KNOWN would have been
3109 set. */
3110 gcc_assert (TREE_PUBLIC (decl));
3111 comdat_linkage (decl);
3112 DECL_INTERFACE_KNOWN (decl) = 1;
3115 else if (VAR_P (decl))
3116 maybe_commonize_var (decl);
3120 /* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage
3121 for DECL has not already been determined, do so now by setting
3122 DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this
3123 function is called entities with vague linkage whose definitions
3124 are available must have TREE_PUBLIC set.
3126 If this function decides to place DECL in COMDAT, it will set
3127 appropriate flags -- but will not clear DECL_EXTERNAL. It is up to
3128 the caller to decide whether or not to clear DECL_EXTERNAL. Some
3129 callers defer that decision until it is clear that DECL is actually
3130 required. */
3132 void
3133 import_export_decl (tree decl)
3135 bool comdat_p;
3136 bool import_p;
3137 tree class_type = NULL_TREE;
3139 if (DECL_INTERFACE_KNOWN (decl))
3140 return;
3142 /* We cannot determine what linkage to give to an entity with vague
3143 linkage until the end of the file. For example, a virtual table
3144 for a class will be defined if and only if the key method is
3145 defined in this translation unit. */
3146 gcc_assert (at_eof);
3147 /* Object file linkage for explicit instantiations is handled in
3148 mark_decl_instantiated. For static variables in functions with
3149 vague linkage, maybe_commonize_var is used.
3151 Therefore, the only declarations that should be provided to this
3152 function are those with external linkage that are:
3154 * implicit instantiations of function templates
3156 * inline function
3158 * implicit instantiations of static data members of class
3159 templates
3161 * virtual tables
3163 * typeinfo objects
3165 Furthermore, all entities that reach this point must have a
3166 definition available in this translation unit.
3168 The following assertions check these conditions. */
3169 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
3170 /* Any code that creates entities with TREE_PUBLIC cleared should
3171 also set DECL_INTERFACE_KNOWN. */
3172 gcc_assert (TREE_PUBLIC (decl));
3173 if (TREE_CODE (decl) == FUNCTION_DECL)
3174 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3175 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
3176 || DECL_DECLARED_INLINE_P (decl));
3177 else
3178 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3179 || DECL_VTABLE_OR_VTT_P (decl)
3180 || DECL_TINFO_P (decl));
3181 /* Check that a definition of DECL is available in this translation
3182 unit. */
3183 gcc_assert (!DECL_REALLY_EXTERN (decl));
3185 /* Assume that DECL will not have COMDAT linkage. */
3186 comdat_p = false;
3187 /* Assume that DECL will not be imported into this translation
3188 unit. */
3189 import_p = false;
3191 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
3193 class_type = DECL_CONTEXT (decl);
3194 import_export_class (class_type);
3195 if (CLASSTYPE_INTERFACE_KNOWN (class_type)
3196 && CLASSTYPE_INTERFACE_ONLY (class_type))
3197 import_p = true;
3198 else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
3199 && !CLASSTYPE_USE_TEMPLATE (class_type)
3200 && CLASSTYPE_KEY_METHOD (class_type)
3201 && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
3202 /* The ABI requires that all virtual tables be emitted with
3203 COMDAT linkage. However, on systems where COMDAT symbols
3204 don't show up in the table of contents for a static
3205 archive, or on systems without weak symbols (where we
3206 approximate COMDAT linkage by using internal linkage), the
3207 linker will report errors about undefined symbols because
3208 it will not see the virtual table definition. Therefore,
3209 in the case that we know that the virtual table will be
3210 emitted in only one translation unit, we make the virtual
3211 table an ordinary definition with external linkage. */
3212 DECL_EXTERNAL (decl) = 0;
3213 else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
3215 /* CLASS_TYPE is being exported from this translation unit,
3216 so DECL should be defined here. */
3217 if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
3218 /* If a class is declared in a header with the "extern
3219 template" extension, then it will not be instantiated,
3220 even in translation units that would normally require
3221 it. Often such classes are explicitly instantiated in
3222 one translation unit. Therefore, the explicit
3223 instantiation must be made visible to other translation
3224 units. */
3225 DECL_EXTERNAL (decl) = 0;
3226 else
3228 /* The generic C++ ABI says that class data is always
3229 COMDAT, even if there is a key function. Some
3230 variants (e.g., the ARM EABI) says that class data
3231 only has COMDAT linkage if the class data might be
3232 emitted in more than one translation unit. When the
3233 key method can be inline and is inline, we still have
3234 to arrange for comdat even though
3235 class_data_always_comdat is false. */
3236 if (!CLASSTYPE_KEY_METHOD (class_type)
3237 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
3238 || targetm.cxx.class_data_always_comdat ())
3240 /* The ABI requires COMDAT linkage. Normally, we
3241 only emit COMDAT things when they are needed;
3242 make sure that we realize that this entity is
3243 indeed needed. */
3244 comdat_p = true;
3245 mark_needed (decl);
3249 else if (!flag_implicit_templates
3250 && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
3251 import_p = true;
3252 else
3253 comdat_p = true;
3255 else if (VAR_P (decl) && DECL_TINFO_P (decl))
3257 tree type = TREE_TYPE (DECL_NAME (decl));
3258 if (CLASS_TYPE_P (type))
3260 class_type = type;
3261 import_export_class (type);
3262 if (CLASSTYPE_INTERFACE_KNOWN (type)
3263 && TYPE_POLYMORPHIC_P (type)
3264 && CLASSTYPE_INTERFACE_ONLY (type)
3265 /* If -fno-rtti was specified, then we cannot be sure
3266 that RTTI information will be emitted with the
3267 virtual table of the class, so we must emit it
3268 wherever it is used. */
3269 && flag_rtti)
3270 import_p = true;
3271 else
3273 if (CLASSTYPE_INTERFACE_KNOWN (type)
3274 && !CLASSTYPE_INTERFACE_ONLY (type))
3276 comdat_p = (targetm.cxx.class_data_always_comdat ()
3277 || (CLASSTYPE_KEY_METHOD (type)
3278 && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
3279 mark_needed (decl);
3280 if (!flag_weak)
3282 comdat_p = false;
3283 DECL_EXTERNAL (decl) = 0;
3286 else
3287 comdat_p = true;
3290 else
3291 comdat_p = true;
3293 else if (DECL_TEMPLOID_INSTANTIATION (decl))
3295 /* DECL is an implicit instantiation of a function or static
3296 data member. */
3297 if (flag_implicit_templates
3298 || (flag_implicit_inline_templates
3299 && TREE_CODE (decl) == FUNCTION_DECL
3300 && DECL_DECLARED_INLINE_P (decl)))
3301 comdat_p = true;
3302 else
3303 /* If we are not implicitly generating templates, then mark
3304 this entity as undefined in this translation unit. */
3305 import_p = true;
3307 else if (DECL_FUNCTION_MEMBER_P (decl))
3309 if (!DECL_DECLARED_INLINE_P (decl))
3311 tree ctype = DECL_CONTEXT (decl);
3312 import_export_class (ctype);
3313 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
3315 DECL_NOT_REALLY_EXTERN (decl)
3316 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
3317 || (DECL_DECLARED_INLINE_P (decl)
3318 && ! flag_implement_inlines
3319 && !DECL_VINDEX (decl)));
3321 if (!DECL_NOT_REALLY_EXTERN (decl))
3322 DECL_EXTERNAL (decl) = 1;
3324 /* Always make artificials weak. */
3325 if (DECL_ARTIFICIAL (decl) && flag_weak)
3326 comdat_p = true;
3327 else
3328 maybe_make_one_only (decl);
3331 else
3332 comdat_p = true;
3334 else
3335 comdat_p = true;
3337 if (import_p)
3339 /* If we are importing DECL into this translation unit, mark is
3340 an undefined here. */
3341 DECL_EXTERNAL (decl) = 1;
3342 DECL_NOT_REALLY_EXTERN (decl) = 0;
3344 else if (comdat_p)
3346 /* If we decided to put DECL in COMDAT, mark it accordingly at
3347 this point. */
3348 comdat_linkage (decl);
3351 DECL_INTERFACE_KNOWN (decl) = 1;
3354 /* Return an expression that performs the destruction of DECL, which
3355 must be a VAR_DECL whose type has a non-trivial destructor, or is
3356 an array whose (innermost) elements have a non-trivial destructor. */
3358 tree
3359 build_cleanup (tree decl)
3361 tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
3362 gcc_assert (clean != NULL_TREE);
3363 return clean;
3366 /* GUARD is a helper variable for DECL; make them have the same linkage and
3367 visibility. */
3369 void
3370 copy_linkage (tree guard, tree decl)
3372 TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3373 TREE_STATIC (guard) = TREE_STATIC (decl);
3374 DECL_COMMON (guard) = DECL_COMMON (decl);
3375 DECL_COMDAT (guard) = DECL_COMDAT (decl);
3376 if (TREE_STATIC (guard))
3378 CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
3379 set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3380 if (DECL_ONE_ONLY (decl))
3381 make_decl_one_only (guard, cxx_comdat_group (guard));
3382 if (TREE_PUBLIC (decl))
3383 DECL_WEAK (guard) = DECL_WEAK (decl);
3384 /* Also check vague_linkage_p, as DECL_WEAK and DECL_ONE_ONLY might not
3385 be set until import_export_decl at EOF. */
3386 if (vague_linkage_p (decl))
3387 comdat_linkage (guard);
3388 DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3389 DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3393 /* Returns the initialization guard variable for the variable DECL,
3394 which has static storage duration. */
3396 tree
3397 get_guard (tree decl)
3399 tree sname = mangle_guard_variable (decl);
3400 tree guard = get_global_binding (sname);
3401 if (! guard)
3403 tree guard_type;
3405 /* We use a type that is big enough to contain a mutex as well
3406 as an integer counter. */
3407 guard_type = targetm.cxx.guard_type ();
3408 guard = build_decl (DECL_SOURCE_LOCATION (decl),
3409 VAR_DECL, sname, guard_type);
3411 /* The guard should have the same linkage as what it guards. */
3412 copy_linkage (guard, decl);
3414 DECL_ARTIFICIAL (guard) = 1;
3415 DECL_IGNORED_P (guard) = 1;
3416 TREE_USED (guard) = 1;
3417 pushdecl_top_level_and_finish (guard, NULL_TREE);
3419 return guard;
3422 /* Returns true if accessing the GUARD atomic is expensive,
3423 i.e. involves a call to __sync_synchronize or similar.
3424 In this case let __cxa_guard_acquire handle the atomics. */
3426 static bool
3427 is_atomic_expensive_p (machine_mode mode)
3429 if (!flag_inline_atomics)
3430 return true;
3432 if (!can_compare_and_swap_p (mode, false) || !can_atomic_load_p (mode))
3433 return true;
3435 return false;
3438 /* Return an atomic load of src with the appropriate memory model. */
3440 static tree
3441 build_atomic_load_type (tree src, HOST_WIDE_INT model, tree type)
3443 tree ptr_type = build_pointer_type (type);
3444 tree mem_model = build_int_cst (integer_type_node, model);
3445 tree t, addr, val;
3446 unsigned int size;
3447 int fncode;
3449 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
3451 fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
3452 t = builtin_decl_implicit ((enum built_in_function) fncode);
3454 addr = build1 (ADDR_EXPR, ptr_type, src);
3455 val = build_call_expr (t, 2, addr, mem_model);
3456 return val;
3459 /* Return those bits of the GUARD variable that should be set when the
3460 guarded entity is actually initialized. */
3462 static tree
3463 get_guard_bits (tree guard)
3465 if (!targetm.cxx.guard_mask_bit ())
3467 /* We only set the first byte of the guard, in order to leave room
3468 for a mutex in the high-order bits. */
3469 guard = build1 (ADDR_EXPR,
3470 build_pointer_type (TREE_TYPE (guard)),
3471 guard);
3472 guard = build1 (NOP_EXPR,
3473 build_pointer_type (char_type_node),
3474 guard);
3475 guard = build1 (INDIRECT_REF, char_type_node, guard);
3478 return guard;
3481 /* Return an expression which determines whether or not the GUARD
3482 variable has already been initialized. */
3484 tree
3485 get_guard_cond (tree guard, bool thread_safe)
3487 tree guard_value;
3489 if (!thread_safe)
3490 guard = get_guard_bits (guard);
3491 else
3493 tree type = targetm.cxx.guard_mask_bit ()
3494 ? TREE_TYPE (guard) : char_type_node;
3496 if (is_atomic_expensive_p (TYPE_MODE (type)))
3497 guard = integer_zero_node;
3498 else
3499 guard = build_atomic_load_type (guard, MEMMODEL_ACQUIRE, type);
3502 /* Mask off all but the low bit. */
3503 if (targetm.cxx.guard_mask_bit ())
3505 guard_value = integer_one_node;
3506 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3507 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3508 guard = cp_build_binary_op (input_location,
3509 BIT_AND_EXPR, guard, guard_value,
3510 tf_warning_or_error);
3513 guard_value = integer_zero_node;
3514 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3515 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3516 return cp_build_binary_op (input_location,
3517 EQ_EXPR, guard, guard_value,
3518 tf_warning_or_error);
3521 /* Return an expression which sets the GUARD variable, indicating that
3522 the variable being guarded has been initialized. */
3524 tree
3525 set_guard (tree guard)
3527 tree guard_init;
3529 /* Set the GUARD to one. */
3530 guard = get_guard_bits (guard);
3531 guard_init = integer_one_node;
3532 if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3533 guard_init = fold_convert (TREE_TYPE (guard), guard_init);
3534 return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
3535 tf_warning_or_error);
3538 /* Returns true iff we can tell that VAR does not have a dynamic
3539 initializer. */
3541 static bool
3542 var_defined_without_dynamic_init (tree var)
3544 /* constinit vars are guaranteed to not have dynamic initializer,
3545 but still registering the destructor counts as dynamic initialization. */
3546 if (DECL_DECLARED_CONSTINIT_P (var)
3547 && COMPLETE_TYPE_P (TREE_TYPE (var))
3548 && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3549 return true;
3550 /* If it's defined in another TU, we can't tell. */
3551 if (DECL_EXTERNAL (var))
3552 return false;
3553 /* If it has a non-trivial destructor, registering the destructor
3554 counts as dynamic initialization. */
3555 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3556 return false;
3557 /* If it's in this TU, its initializer has been processed, unless
3558 it's a case of self-initialization, then DECL_INITIALIZED_P is
3559 false while the initializer is handled by finish_id_expression. */
3560 if (!DECL_INITIALIZED_P (var))
3561 return false;
3562 /* If it has no initializer or a constant one, it's not dynamic. */
3563 return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3564 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3567 /* Returns true iff VAR is a variable that needs uses to be
3568 wrapped for possible dynamic initialization. */
3570 static bool
3571 var_needs_tls_wrapper (tree var)
3573 return (!error_operand_p (var)
3574 && CP_DECL_THREAD_LOCAL_P (var)
3575 && !DECL_GNU_TLS_P (var)
3576 && !DECL_FUNCTION_SCOPE_P (var)
3577 && !var_defined_without_dynamic_init (var));
3580 /* Get the FUNCTION_DECL for the shared TLS init function for this
3581 translation unit. */
3583 static tree
3584 get_local_tls_init_fn (location_t loc)
3586 tree sname = get_identifier ("__tls_init");
3587 tree fn = get_global_binding (sname);
3588 if (!fn)
3590 fn = build_lang_decl_loc (loc, FUNCTION_DECL, sname,
3591 build_function_type (void_type_node,
3592 void_list_node));
3593 SET_DECL_LANGUAGE (fn, lang_c);
3594 TREE_PUBLIC (fn) = false;
3595 DECL_ARTIFICIAL (fn) = true;
3596 mark_used (fn);
3597 set_global_binding (fn);
3599 return fn;
3602 /* Get a FUNCTION_DECL for the init function for the thread_local
3603 variable VAR. The init function will be an alias to the function
3604 that initializes all the non-local TLS variables in the translation
3605 unit. The init function is only used by the wrapper function. */
3607 static tree
3608 get_tls_init_fn (tree var)
3610 /* Only C++11 TLS vars need this init fn. */
3611 if (!var_needs_tls_wrapper (var))
3612 return NULL_TREE;
3614 /* If -fno-extern-tls-init, assume that we don't need to call
3615 a tls init function for a variable defined in another TU. */
3616 if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3617 return NULL_TREE;
3619 /* If the variable is internal, or if we can't generate aliases,
3620 call the local init function directly. */
3621 if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
3622 return get_local_tls_init_fn (DECL_SOURCE_LOCATION (var));
3624 tree sname = mangle_tls_init_fn (var);
3625 tree fn = get_global_binding (sname);
3626 if (!fn)
3628 fn = build_lang_decl (FUNCTION_DECL, sname,
3629 build_function_type (void_type_node,
3630 void_list_node));
3631 SET_DECL_LANGUAGE (fn, lang_c);
3632 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3633 DECL_ARTIFICIAL (fn) = true;
3634 DECL_COMDAT (fn) = DECL_COMDAT (var);
3635 DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3636 if (DECL_ONE_ONLY (var))
3637 make_decl_one_only (fn, cxx_comdat_group (fn));
3638 if (TREE_PUBLIC (var))
3640 tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3641 /* If the variable is defined somewhere else and might have static
3642 initialization, make the init function a weak reference. */
3643 if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3644 || TYPE_HAS_CONSTEXPR_CTOR (obtype)
3645 || TYPE_HAS_TRIVIAL_DFLT (obtype))
3646 && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3647 && DECL_EXTERNAL (var))
3648 declare_weak (fn);
3649 else
3650 DECL_WEAK (fn) = DECL_WEAK (var);
3652 DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3653 DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3654 DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3655 DECL_IGNORED_P (fn) = 1;
3656 mark_used (fn);
3658 DECL_BEFRIENDING_CLASSES (fn) = var;
3660 set_global_binding (fn);
3662 return fn;
3665 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3666 variable VAR. The wrapper function calls the init function (if any) for
3667 VAR and then returns a reference to VAR. The wrapper function is used
3668 in place of VAR everywhere VAR is mentioned. */
3670 static tree
3671 get_tls_wrapper_fn (tree var)
3673 /* Only C++11 TLS vars need this wrapper fn. */
3674 if (!var_needs_tls_wrapper (var))
3675 return NULL_TREE;
3677 tree sname = mangle_tls_wrapper_fn (var);
3678 tree fn = get_global_binding (sname);
3679 if (!fn)
3681 /* A named rvalue reference is an lvalue, so the wrapper should
3682 always return an lvalue reference. */
3683 tree type = non_reference (TREE_TYPE (var));
3684 type = build_reference_type (type);
3685 tree fntype = build_function_type (type, void_list_node);
3687 fn = build_lang_decl_loc (DECL_SOURCE_LOCATION (var),
3688 FUNCTION_DECL, sname, fntype);
3689 SET_DECL_LANGUAGE (fn, lang_c);
3690 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3691 DECL_ARTIFICIAL (fn) = true;
3692 DECL_IGNORED_P (fn) = 1;
3693 /* The wrapper is inline and emitted everywhere var is used. */
3694 DECL_DECLARED_INLINE_P (fn) = true;
3695 if (TREE_PUBLIC (var))
3697 comdat_linkage (fn);
3698 #ifdef HAVE_GAS_HIDDEN
3699 /* Make the wrapper bind locally; there's no reason to share
3700 the wrapper between multiple shared objects. */
3701 DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3702 DECL_VISIBILITY_SPECIFIED (fn) = true;
3703 #endif
3705 if (!TREE_PUBLIC (fn))
3706 DECL_INTERFACE_KNOWN (fn) = true;
3707 mark_used (fn);
3708 note_vague_linkage_fn (fn);
3710 #if 0
3711 /* We want CSE to commonize calls to the wrapper, but marking it as
3712 pure is unsafe since it has side-effects. I guess we need a new
3713 ECF flag even weaker than ECF_PURE. FIXME! */
3714 DECL_PURE_P (fn) = true;
3715 #endif
3717 DECL_BEFRIENDING_CLASSES (fn) = var;
3719 set_global_binding (fn);
3721 return fn;
3724 /* If EXPR is a thread_local variable that should be wrapped by init
3725 wrapper function, return a call to that function, otherwise return
3726 NULL. */
3728 tree
3729 maybe_get_tls_wrapper_call (tree expr)
3731 if (VAR_P (expr)
3732 && !processing_template_decl
3733 && !cp_unevaluated_operand
3734 && CP_DECL_THREAD_LOCAL_P (expr))
3735 if (tree wrap = get_tls_wrapper_fn (expr))
3736 return build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
3737 return NULL;
3740 /* At EOF, generate the definition for the TLS wrapper function FN:
3742 T& var_wrapper() {
3743 if (init_fn) init_fn();
3744 return var;
3745 } */
3747 static void
3748 generate_tls_wrapper (tree fn)
3750 tree var = DECL_BEFRIENDING_CLASSES (fn);
3752 start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3753 tree body = begin_function_body ();
3754 /* Only call the init fn if there might be one. */
3755 if (tree init_fn = get_tls_init_fn (var))
3757 tree if_stmt = NULL_TREE;
3758 /* If init_fn is a weakref, make sure it exists before calling. */
3759 if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3761 if_stmt = begin_if_stmt ();
3762 tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3763 tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3764 NE_EXPR, addr, nullptr_node,
3765 tf_warning_or_error);
3766 finish_if_stmt_cond (cond, if_stmt);
3768 finish_expr_stmt (build_cxx_call
3769 (init_fn, 0, NULL, tf_warning_or_error));
3770 if (if_stmt)
3772 finish_then_clause (if_stmt);
3773 finish_if_stmt (if_stmt);
3776 else
3777 /* If there's no initialization, the wrapper is a constant function. */
3778 TREE_READONLY (fn) = true;
3779 finish_return_stmt (convert_from_reference (var));
3780 finish_function_body (body);
3781 expand_or_defer_fn (finish_function (/*inline_p=*/false));
3784 /* Start the process of running a particular set of global constructors
3785 or destructors. Subroutine of do_[cd]tors. Also called from
3786 vtv_start_verification_constructor_init_function. */
3788 static tree
3789 start_objects (int method_type, int initp)
3791 /* Make ctor or dtor function. METHOD_TYPE may be 'I' or 'D'. */
3792 int module_init = 0;
3794 if (initp == DEFAULT_INIT_PRIORITY && method_type == 'I')
3795 module_init = module_initializer_kind ();
3797 tree name = NULL_TREE;
3798 if (module_init > 0)
3799 name = mangle_module_global_init (0);
3800 else
3802 char type[14];
3804 unsigned len = sprintf (type, "sub_%c", method_type);
3805 if (initp != DEFAULT_INIT_PRIORITY)
3807 char joiner = '_';
3808 #ifdef JOINER
3809 joiner = JOINER;
3810 #endif
3811 type[len++] = joiner;
3812 sprintf (type + len, "%.5u", initp);
3814 name = get_file_function_name (type);
3817 tree fntype = build_function_type (void_type_node, void_list_node);
3818 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
3819 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
3820 if (module_init > 0)
3822 SET_DECL_ASSEMBLER_NAME (fndecl, name);
3823 TREE_PUBLIC (fndecl) = true;
3824 determine_visibility (fndecl);
3826 else
3827 TREE_PUBLIC (fndecl) = 0;
3828 start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3830 /* Mark as artificial because it's not explicitly in the user's
3831 source code. */
3832 DECL_ARTIFICIAL (current_function_decl) = 1;
3834 /* Mark this declaration as used to avoid spurious warnings. */
3835 TREE_USED (current_function_decl) = 1;
3837 /* Mark this function as a global constructor or destructor. */
3838 if (method_type == 'I')
3839 DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3840 else
3841 DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3843 tree body = begin_compound_stmt (BCS_FN_BODY);
3845 if (module_init > 0)
3847 // 'static bool __in_chrg = false;
3848 // if (__inchrg) return;
3849 // __inchrg = true
3850 tree var = build_lang_decl (VAR_DECL, in_charge_identifier,
3851 boolean_type_node);
3852 DECL_CONTEXT (var) = fndecl;
3853 DECL_ARTIFICIAL (var) = true;
3854 TREE_STATIC (var) = true;
3855 pushdecl (var);
3856 cp_finish_decl (var, NULL_TREE, false, NULL_TREE, 0);
3858 tree if_stmt = begin_if_stmt ();
3859 finish_if_stmt_cond (var, if_stmt);
3860 finish_return_stmt (NULL_TREE);
3861 finish_then_clause (if_stmt);
3862 finish_if_stmt (if_stmt);
3864 tree assign = build2 (MODIFY_EXPR, boolean_type_node,
3865 var, boolean_true_node);
3866 TREE_SIDE_EFFECTS (assign) = true;
3867 finish_expr_stmt (assign);
3870 if (module_init)
3871 module_add_import_initializers ();
3873 return body;
3876 /* Finish the process of running a particular set of global constructors
3877 or destructors. Subroutine of do_[cd]tors. */
3879 static void
3880 finish_objects (int method_type, int initp, tree body)
3882 /* Finish up. */
3883 finish_compound_stmt (body);
3884 tree fn = finish_function (/*inline_p=*/false);
3886 if (method_type == 'I')
3888 DECL_STATIC_CONSTRUCTOR (fn) = 1;
3889 decl_init_priority_insert (fn, initp);
3891 else
3893 DECL_STATIC_DESTRUCTOR (fn) = 1;
3894 decl_fini_priority_insert (fn, initp);
3897 expand_or_defer_fn (fn);
3900 /* The names of the parameters to the function created to handle
3901 initializations and destructions for objects with static storage
3902 duration. */
3903 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
3904 #define PRIORITY_IDENTIFIER "__priority"
3906 /* The name of the function we create to handle initializations and
3907 destructions for objects with static storage duration. */
3908 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3910 /* The declaration for the __INITIALIZE_P argument. */
3911 static GTY(()) tree initialize_p_decl;
3913 /* The declaration for the __PRIORITY argument. */
3914 static GTY(()) tree priority_decl;
3916 /* The declaration for the static storage duration function. */
3917 static GTY(()) tree ssdf_decl;
3919 /* All the static storage duration functions created in this
3920 translation unit. */
3921 static GTY(()) vec<tree, va_gc> *ssdf_decls;
3923 /* A map from priority levels to information about that priority
3924 level. There may be many such levels, so efficient lookup is
3925 important. */
3926 static splay_tree priority_info_map;
3928 /* Begins the generation of the function that will handle all
3929 initialization and destruction of objects with static storage
3930 duration. The function generated takes two parameters of type
3931 `int': __INITIALIZE_P and __PRIORITY. If __INITIALIZE_P is
3932 nonzero, it performs initializations. Otherwise, it performs
3933 destructions. It only performs those initializations or
3934 destructions with the indicated __PRIORITY. The generated function
3935 returns no value.
3937 It is assumed that this function will only be called once per
3938 translation unit. */
3940 static tree
3941 start_static_storage_duration_function (unsigned count)
3943 tree type;
3944 tree body;
3945 char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3947 /* Create the identifier for this function. It will be of the form
3948 SSDF_IDENTIFIER_<number>. */
3949 sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3951 type = build_function_type_list (void_type_node,
3952 integer_type_node, integer_type_node,
3953 NULL_TREE);
3955 /* Create the FUNCTION_DECL itself. */
3956 ssdf_decl = build_lang_decl (FUNCTION_DECL,
3957 get_identifier (id),
3958 type);
3959 TREE_PUBLIC (ssdf_decl) = 0;
3960 DECL_ARTIFICIAL (ssdf_decl) = 1;
3962 /* Put this function in the list of functions to be called from the
3963 static constructors and destructors. */
3964 if (!ssdf_decls)
3966 vec_alloc (ssdf_decls, 32);
3968 /* Take this opportunity to initialize the map from priority
3969 numbers to information about that priority level. */
3970 priority_info_map = splay_tree_new (splay_tree_compare_ints,
3971 /*delete_key_fn=*/0,
3972 /*delete_value_fn=*/
3973 splay_tree_delete_pointers);
3975 /* We always need to generate functions for the
3976 DEFAULT_INIT_PRIORITY so enter it now. That way when we walk
3977 priorities later, we'll be sure to find the
3978 DEFAULT_INIT_PRIORITY. */
3979 get_priority_info (DEFAULT_INIT_PRIORITY);
3982 vec_safe_push (ssdf_decls, ssdf_decl);
3984 /* Create the argument list. */
3985 initialize_p_decl = cp_build_parm_decl
3986 (ssdf_decl, get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
3987 TREE_USED (initialize_p_decl) = 1;
3988 priority_decl = cp_build_parm_decl
3989 (ssdf_decl, get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
3990 TREE_USED (priority_decl) = 1;
3992 DECL_CHAIN (initialize_p_decl) = priority_decl;
3993 DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
3995 /* Put the function in the global scope. */
3996 pushdecl (ssdf_decl);
3998 /* Start the function itself. This is equivalent to declaring the
3999 function as:
4001 static void __ssdf (int __initialize_p, init __priority_p);
4003 It is static because we only need to call this function from the
4004 various constructor and destructor functions for this module. */
4005 start_preparsed_function (ssdf_decl,
4006 /*attrs=*/NULL_TREE,
4007 SF_PRE_PARSED);
4009 /* Set up the scope of the outermost block in the function. */
4010 body = begin_compound_stmt (BCS_FN_BODY);
4012 return body;
4015 /* Finish the generation of the function which performs initialization
4016 and destruction of objects with static storage duration. After
4017 this point, no more such objects can be created. */
4019 static void
4020 finish_static_storage_duration_function (tree body)
4022 /* Close out the function. */
4023 finish_compound_stmt (body);
4024 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4027 /* Return the information about the indicated PRIORITY level. If no
4028 code to handle this level has yet been generated, generate the
4029 appropriate prologue. */
4031 static priority_info
4032 get_priority_info (int priority)
4034 priority_info pi;
4035 splay_tree_node n;
4037 n = splay_tree_lookup (priority_info_map,
4038 (splay_tree_key) priority);
4039 if (!n)
4041 /* Create a new priority information structure, and insert it
4042 into the map. */
4043 pi = XNEW (struct priority_info_s);
4044 pi->initializations_p = 0;
4045 pi->destructions_p = 0;
4046 splay_tree_insert (priority_info_map,
4047 (splay_tree_key) priority,
4048 (splay_tree_value) pi);
4050 else
4051 pi = (priority_info) n->value;
4053 return pi;
4056 /* The effective initialization priority of a DECL. */
4058 #define DECL_EFFECTIVE_INIT_PRIORITY(decl) \
4059 ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
4060 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
4062 /* Whether a DECL needs a guard to protect it against multiple
4063 initialization. */
4065 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \
4066 || DECL_ONE_ONLY (decl) \
4067 || DECL_WEAK (decl)))
4069 /* Called from one_static_initialization_or_destruction(),
4070 via walk_tree.
4071 Walks the initializer list of a global variable and looks for
4072 temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
4073 and that have their DECL_CONTEXT() == NULL.
4074 For each such temporary variable, set their DECL_CONTEXT() to
4075 the current function. This is necessary because otherwise
4076 some optimizers (enabled by -O2 -fprofile-arcs) might crash
4077 when trying to refer to a temporary variable that does not have
4078 it's DECL_CONTECT() properly set. */
4079 static tree
4080 fix_temporary_vars_context_r (tree *node,
4081 int * /*unused*/,
4082 void * /*unused1*/)
4084 gcc_assert (current_function_decl);
4086 if (TREE_CODE (*node) == BIND_EXPR)
4088 tree var;
4090 for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
4091 if (VAR_P (var)
4092 && !DECL_NAME (var)
4093 && DECL_ARTIFICIAL (var)
4094 && !DECL_CONTEXT (var))
4095 DECL_CONTEXT (var) = current_function_decl;
4098 return NULL_TREE;
4101 /* Set up to handle the initialization or destruction of DECL. If
4102 INITP is nonzero, we are initializing the variable. Otherwise, we
4103 are destroying it. */
4105 static void
4106 one_static_initialization_or_destruction (tree decl, tree init, bool initp)
4108 tree guard_if_stmt = NULL_TREE;
4109 tree guard;
4111 /* If we are supposed to destruct and there's a trivial destructor,
4112 nothing has to be done. */
4113 if (!initp
4114 && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
4115 return;
4117 /* Trick the compiler into thinking we are at the file and line
4118 where DECL was declared so that error-messages make sense, and so
4119 that the debugger will show somewhat sensible file and line
4120 information. */
4121 input_location = DECL_SOURCE_LOCATION (decl);
4123 /* Make sure temporary variables in the initialiser all have
4124 their DECL_CONTEXT() set to a value different from NULL_TREE.
4125 This can happen when global variables initializers are built.
4126 In that case, the DECL_CONTEXT() of the global variables _AND_ of all
4127 the temporary variables that might have been generated in the
4128 accompanying initializers is NULL_TREE, meaning the variables have been
4129 declared in the global namespace.
4130 What we want to do here is to fix that and make sure the DECL_CONTEXT()
4131 of the temporaries are set to the current function decl. */
4132 cp_walk_tree_without_duplicates (&init,
4133 fix_temporary_vars_context_r,
4134 NULL);
4136 /* Because of:
4138 [class.access.spec]
4140 Access control for implicit calls to the constructors,
4141 the conversion functions, or the destructor called to
4142 create and destroy a static data member is performed as
4143 if these calls appeared in the scope of the member's
4144 class.
4146 we pretend we are in a static member function of the class of
4147 which the DECL is a member. */
4148 if (member_p (decl))
4150 DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
4151 DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
4154 /* Assume we don't need a guard. */
4155 guard = NULL_TREE;
4156 /* We need a guard if this is an object with external linkage that
4157 might be initialized in more than one place. (For example, a
4158 static data member of a template, when the data member requires
4159 construction.) */
4160 if (NEEDS_GUARD_P (decl))
4162 tree guard_cond;
4164 guard = get_guard (decl);
4166 /* When using __cxa_atexit, we just check the GUARD as we would
4167 for a local static. */
4168 if (flag_use_cxa_atexit)
4170 /* When using __cxa_atexit, we never try to destroy
4171 anything from a static destructor. */
4172 gcc_assert (initp);
4173 guard_cond = get_guard_cond (guard, false);
4175 /* If we don't have __cxa_atexit, then we will be running
4176 destructors from .fini sections, or their equivalents. So,
4177 we need to know how many times we've tried to initialize this
4178 object. We do initializations only if the GUARD is zero,
4179 i.e., if we are the first to initialize the variable. We do
4180 destructions only if the GUARD is one, i.e., if we are the
4181 last to destroy the variable. */
4182 else if (initp)
4183 guard_cond
4184 = cp_build_binary_op (input_location,
4185 EQ_EXPR,
4186 cp_build_unary_op (PREINCREMENT_EXPR,
4187 guard,
4188 /*noconvert=*/true,
4189 tf_warning_or_error),
4190 integer_one_node,
4191 tf_warning_or_error);
4192 else
4193 guard_cond
4194 = cp_build_binary_op (input_location,
4195 EQ_EXPR,
4196 cp_build_unary_op (PREDECREMENT_EXPR,
4197 guard,
4198 /*noconvert=*/true,
4199 tf_warning_or_error),
4200 integer_zero_node,
4201 tf_warning_or_error);
4203 guard_if_stmt = begin_if_stmt ();
4204 finish_if_stmt_cond (guard_cond, guard_if_stmt);
4208 /* If we're using __cxa_atexit, we have not already set the GUARD,
4209 so we must do so now. */
4210 if (guard && initp && flag_use_cxa_atexit)
4211 finish_expr_stmt (set_guard (guard));
4213 /* Perform the initialization or destruction. */
4214 if (initp)
4216 if (init)
4218 finish_expr_stmt (init);
4219 if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
4221 varpool_node *vnode = varpool_node::get (decl);
4222 if (vnode)
4223 vnode->dynamically_initialized = 1;
4227 /* If we're using __cxa_atexit, register a function that calls the
4228 destructor for the object. */
4229 if (flag_use_cxa_atexit)
4230 finish_expr_stmt (register_dtor_fn (decl));
4232 else
4233 finish_expr_stmt (build_cleanup (decl));
4235 /* Finish the guard if-stmt, if necessary. */
4236 if (guard)
4238 finish_then_clause (guard_if_stmt);
4239 finish_if_stmt (guard_if_stmt);
4242 /* Now that we're done with DECL we don't need to pretend to be a
4243 member of its class any longer. */
4244 DECL_CONTEXT (current_function_decl) = NULL_TREE;
4245 DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
4248 /* Generate code to do the initialization or destruction of the decls in VARS,
4249 a TREE_LIST of VAR_DECL with static storage duration.
4250 Whether initialization or destruction is performed is specified by INITP. */
4252 static void
4253 do_static_initialization_or_destruction (tree vars, bool initp)
4255 tree node, init_if_stmt, cond;
4257 /* Build the outer if-stmt to check for initialization or destruction. */
4258 init_if_stmt = begin_if_stmt ();
4259 cond = initp ? integer_one_node : integer_zero_node;
4260 cond = cp_build_binary_op (input_location,
4261 EQ_EXPR,
4262 initialize_p_decl,
4263 cond,
4264 tf_warning_or_error);
4265 finish_if_stmt_cond (cond, init_if_stmt);
4267 /* To make sure dynamic construction doesn't access globals from other
4268 compilation units where they might not be yet constructed, for
4269 -fsanitize=address insert __asan_before_dynamic_init call that
4270 prevents access to either all global variables that need construction
4271 in other compilation units, or at least those that haven't been
4272 initialized yet. Variables that need dynamic construction in
4273 the current compilation unit are kept accessible. */
4274 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4275 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
4277 node = vars;
4278 do {
4279 tree decl = TREE_VALUE (node);
4280 tree priority_if_stmt;
4281 int priority;
4282 priority_info pi;
4284 /* If we don't need a destructor, there's nothing to do. Avoid
4285 creating a possibly empty if-stmt. */
4286 if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
4288 node = TREE_CHAIN (node);
4289 continue;
4292 /* Remember that we had an initialization or finalization at this
4293 priority. */
4294 priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
4295 pi = get_priority_info (priority);
4296 if (initp)
4297 pi->initializations_p = 1;
4298 else
4299 pi->destructions_p = 1;
4301 /* Conditionalize this initialization on being in the right priority
4302 and being initializing/finalizing appropriately. */
4303 priority_if_stmt = begin_if_stmt ();
4304 cond = cp_build_binary_op (input_location,
4305 EQ_EXPR,
4306 priority_decl,
4307 build_int_cst (NULL_TREE, priority),
4308 tf_warning_or_error);
4309 finish_if_stmt_cond (cond, priority_if_stmt);
4311 /* Process initializers with same priority. */
4312 for (; node
4313 && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
4314 node = TREE_CHAIN (node))
4315 /* Do one initialization or destruction. */
4316 one_static_initialization_or_destruction (TREE_VALUE (node),
4317 TREE_PURPOSE (node), initp);
4319 /* Finish up the priority if-stmt body. */
4320 finish_then_clause (priority_if_stmt);
4321 finish_if_stmt (priority_if_stmt);
4323 } while (node);
4325 /* Revert what __asan_before_dynamic_init did by calling
4326 __asan_after_dynamic_init. */
4327 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4328 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
4330 /* Finish up the init/destruct if-stmt body. */
4331 finish_then_clause (init_if_stmt);
4332 finish_if_stmt (init_if_stmt);
4335 /* VARS is a list of variables with static storage duration which may
4336 need initialization and/or finalization. Remove those variables
4337 that don't really need to be initialized or finalized, and return
4338 the resulting list. The order in which the variables appear in
4339 VARS is in reverse order of the order in which they should actually
4340 be initialized. The list we return is in the unreversed order;
4341 i.e., the first variable should be initialized first. */
4343 static tree
4344 prune_vars_needing_no_initialization (tree *vars)
4346 tree *var = vars;
4347 tree result = NULL_TREE;
4349 while (*var)
4351 tree t = *var;
4352 tree decl = TREE_VALUE (t);
4353 tree init = TREE_PURPOSE (t);
4355 /* Deal gracefully with error. */
4356 if (error_operand_p (decl))
4358 var = &TREE_CHAIN (t);
4359 continue;
4362 /* The only things that can be initialized are variables. */
4363 gcc_assert (VAR_P (decl));
4365 /* If this object is not defined, we don't need to do anything
4366 here. */
4367 if (DECL_EXTERNAL (decl))
4369 var = &TREE_CHAIN (t);
4370 continue;
4373 /* Also, if the initializer already contains errors, we can bail
4374 out now. */
4375 if (init && TREE_CODE (init) == TREE_LIST
4376 && value_member (error_mark_node, init))
4378 var = &TREE_CHAIN (t);
4379 continue;
4382 /* This variable is going to need initialization and/or
4383 finalization, so we add it to the list. */
4384 *var = TREE_CHAIN (t);
4385 TREE_CHAIN (t) = result;
4386 result = t;
4389 return result;
4392 /* Make sure we have told the back end about all the variables in
4393 VARS. */
4395 static void
4396 write_out_vars (tree vars)
4398 tree v;
4400 for (v = vars; v; v = TREE_CHAIN (v))
4402 tree var = TREE_VALUE (v);
4403 if (!var_finalized_p (var))
4405 import_export_decl (var);
4406 rest_of_decl_compilation (var, 1, 1);
4411 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
4412 (otherwise) that will initialize all global objects with static
4413 storage duration having the indicated PRIORITY. */
4415 static void
4416 generate_ctor_or_dtor_function (bool constructor_p, int priority,
4417 location_t *locus)
4419 input_location = *locus;
4421 /* We use `I' to indicate initialization and `D' to indicate
4422 destruction. */
4423 char function_key = constructor_p ? 'I' : 'D';
4425 /* We emit the function lazily, to avoid generating empty
4426 global constructors and destructors. */
4427 tree body = NULL_TREE;
4429 if (constructor_p && priority == DEFAULT_INIT_PRIORITY)
4431 bool objc = c_dialect_objc () && objc_static_init_needed_p ();
4433 /* We may have module initialization to emit and/or insert
4434 before other intializations. */
4435 if (module_initializer_kind () || objc)
4436 body = start_objects (function_key, priority);
4438 /* For Objective-C++, we may need to initialize metadata found
4439 in this module. This must be done _before_ any other static
4440 initializations. */
4441 if (objc)
4442 objc_generate_static_init_call (NULL_TREE);
4445 /* Call the static storage duration function with appropriate
4446 arguments. */
4447 tree fndecl;
4448 size_t i;
4449 FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl)
4451 /* Calls to pure or const functions will expand to nothing. */
4452 if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
4454 if (! body)
4455 body = start_objects (function_key, priority);
4457 tree call = cp_build_function_call_nary (fndecl, tf_warning_or_error,
4458 build_int_cst (NULL_TREE,
4459 constructor_p),
4460 build_int_cst (NULL_TREE,
4461 priority),
4462 NULL_TREE);
4463 finish_expr_stmt (call);
4467 /* Close out the function. */
4468 if (body)
4469 finish_objects (function_key, priority, body);
4472 /* Generate constructor and destructor functions for the priority
4473 indicated by N. */
4475 static int
4476 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
4478 location_t *locus = (location_t *) data;
4479 int priority = (int) n->key;
4480 priority_info pi = (priority_info) n->value;
4482 /* Generate the functions themselves, but only if they are really
4483 needed. */
4484 if (pi->initializations_p)
4485 generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
4486 if (pi->destructions_p)
4487 generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
4489 /* Keep iterating. */
4490 return 0;
4493 /* Return C++ property of T, based on given operation OP. */
4495 static int
4496 cpp_check (tree t, cpp_operation op)
4498 switch (op)
4500 case HAS_DEPENDENT_TEMPLATE_ARGS:
4502 tree ti = CLASSTYPE_TEMPLATE_INFO (t);
4503 if (!ti)
4504 return 0;
4505 ++processing_template_decl;
4506 const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
4507 --processing_template_decl;
4508 return dep;
4510 case IS_ABSTRACT:
4511 return DECL_PURE_VIRTUAL_P (t);
4512 case IS_ASSIGNMENT_OPERATOR:
4513 return DECL_ASSIGNMENT_OPERATOR_P (t);
4514 case IS_CONSTRUCTOR:
4515 return DECL_CONSTRUCTOR_P (t);
4516 case IS_DESTRUCTOR:
4517 return DECL_DESTRUCTOR_P (t);
4518 case IS_COPY_CONSTRUCTOR:
4519 return DECL_COPY_CONSTRUCTOR_P (t);
4520 case IS_MOVE_CONSTRUCTOR:
4521 return DECL_MOVE_CONSTRUCTOR_P (t);
4522 case IS_TEMPLATE:
4523 return TREE_CODE (t) == TEMPLATE_DECL;
4524 case IS_TRIVIAL:
4525 return trivial_type_p (t);
4526 default:
4527 return 0;
4531 /* Collect source file references recursively, starting from NAMESPC. */
4533 static void
4534 collect_source_refs (tree namespc)
4536 /* Iterate over names in this name space. */
4537 for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4538 if (DECL_IS_UNDECLARED_BUILTIN (t))
4540 else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
4541 collect_source_refs (t);
4542 else
4543 collect_source_ref (DECL_SOURCE_FILE (t));
4546 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4547 starting from NAMESPC. */
4549 static void
4550 collect_ada_namespace (tree namespc, const char *source_file)
4552 tree decl = NAMESPACE_LEVEL (namespc)->names;
4554 /* Collect decls from this namespace. This will skip
4555 NAMESPACE_DECLs (both aliases and regular, it cannot tell). */
4556 collect_ada_nodes (decl, source_file);
4558 /* Now scan for namespace children, and dump them. */
4559 for (; decl; decl = TREE_CHAIN (decl))
4560 if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
4561 collect_ada_namespace (decl, source_file);
4564 /* Returns true iff there is a definition available for variable or
4565 function DECL. */
4567 bool
4568 decl_defined_p (tree decl)
4570 if (TREE_CODE (decl) == FUNCTION_DECL)
4571 return (DECL_INITIAL (decl) != NULL_TREE
4572 /* A pending instantiation of a friend temploid is defined. */
4573 || (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
4574 && DECL_INITIAL (DECL_TEMPLATE_RESULT
4575 (DECL_TI_TEMPLATE (decl)))));
4576 else
4578 gcc_assert (VAR_P (decl));
4579 return !DECL_EXTERNAL (decl);
4583 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4585 [expr.const]
4587 An integral constant-expression can only involve ... const
4588 variables of integral or enumeration types initialized with
4589 constant expressions ...
4591 C++0x also allows constexpr variables and temporaries initialized
4592 with constant expressions. We handle the former here, but the latter
4593 are just folded away in cxx_eval_constant_expression.
4595 The standard does not require that the expression be non-volatile.
4596 G++ implements the proposed correction in DR 457. */
4598 bool
4599 decl_constant_var_p (tree decl)
4601 if (!decl_maybe_constant_var_p (decl))
4602 return false;
4604 /* We don't know if a template static data member is initialized with
4605 a constant expression until we instantiate its initializer. Even
4606 in the case of a constexpr variable, we can't treat it as a
4607 constant until its initializer is complete in case it's used in
4608 its own initializer. */
4609 maybe_instantiate_decl (decl);
4610 return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4613 /* Returns true if DECL could be a symbolic constant variable, depending on
4614 its initializer. */
4616 bool
4617 decl_maybe_constant_var_p (tree decl)
4619 tree type = TREE_TYPE (decl);
4620 if (!VAR_P (decl))
4621 return false;
4622 if (DECL_DECLARED_CONSTEXPR_P (decl) && !TREE_THIS_VOLATILE (decl))
4623 return true;
4624 if (DECL_HAS_VALUE_EXPR_P (decl))
4625 /* A proxy isn't constant. */
4626 return false;
4627 if (TYPE_REF_P (type))
4628 /* References can be constant. */;
4629 else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
4630 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4631 /* And const integers. */;
4632 else
4633 return false;
4635 if (DECL_INITIAL (decl)
4636 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
4637 /* We know the initializer, and it isn't constant. */
4638 return false;
4639 else
4640 return true;
4643 /* Complain that DECL uses a type with no linkage. In C++98 mode this is
4644 called from grokfndecl and grokvardecl; in all modes it is called from
4645 cp_write_global_declarations. */
4647 void
4648 no_linkage_error (tree decl)
4650 if (cxx_dialect >= cxx11
4651 && (decl_defined_p (decl)
4652 /* Treat templates which limit_bad_template_recursion decided
4653 not to instantiate as if they were defined. */
4654 || (errorcount + sorrycount > 0
4655 && DECL_LANG_SPECIFIC (decl)
4656 && DECL_TEMPLATE_INFO (decl)
4657 && warning_suppressed_p (decl /* What warning? */))))
4658 /* In C++11 it's ok if the decl is defined. */
4659 return;
4661 if (DECL_LANG_SPECIFIC (decl) && DECL_MODULE_IMPORT_P (decl))
4662 /* An imported decl is ok. */
4663 return;
4665 tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4666 if (t == NULL_TREE)
4667 /* The type that got us on no_linkage_decls must have gotten a name for
4668 linkage purposes. */;
4669 else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4670 // FIXME: This is now invalid, as a DR to c++98
4671 /* The type might end up having a typedef name for linkage purposes. */
4672 vec_safe_push (no_linkage_decls, decl);
4673 else if (TYPE_UNNAMED_P (t))
4675 bool d = false;
4676 auto_diagnostic_group grp;
4677 if (cxx_dialect >= cxx11)
4678 d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4679 "unnamed type, is used but never defined", decl);
4680 else if (DECL_EXTERN_C_P (decl))
4681 /* Allow this; it's pretty common in C. */;
4682 else if (VAR_P (decl))
4683 /* DRs 132, 319 and 389 seem to indicate types with
4684 no linkage can only be used to declare extern "C"
4685 entities. Since it's not always an error in the
4686 ISO C++ 90 Standard, we only issue a warning. */
4687 d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
4688 "with no linkage used to declare variable %q#D with "
4689 "linkage", decl);
4690 else
4691 d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
4692 "linkage used to declare function %q#D with linkage",
4693 decl);
4694 if (d && is_typedef_decl (TYPE_NAME (t)))
4695 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4696 "to the unqualified type, so it is not used for linkage",
4697 TYPE_NAME (t));
4699 else if (cxx_dialect >= cxx11)
4701 if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
4702 permerror (DECL_SOURCE_LOCATION (decl),
4703 "%q#D, declared using local type "
4704 "%qT, is used but never defined", decl, t);
4706 else if (VAR_P (decl))
4707 warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4708 "used to declare variable %q#D with linkage", t, decl);
4709 else
4710 permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4711 "to declare function %q#D with linkage", t, decl);
4714 /* Collect declarations from all namespaces relevant to SOURCE_FILE. */
4716 static void
4717 collect_all_refs (const char *source_file)
4719 collect_ada_namespace (global_namespace, source_file);
4722 /* Clear DECL_EXTERNAL for NODE. */
4724 static bool
4725 clear_decl_external (struct cgraph_node *node, void * /*data*/)
4727 DECL_EXTERNAL (node->decl) = 0;
4728 return false;
4731 /* Build up the function to run dynamic initializers for thread_local
4732 variables in this translation unit and alias the init functions for the
4733 individual variables to it. */
4735 static void
4736 handle_tls_init (void)
4738 tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4739 if (vars == NULL_TREE)
4740 return;
4742 location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4744 write_out_vars (vars);
4746 tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4747 boolean_type_node);
4748 TREE_PUBLIC (guard) = false;
4749 TREE_STATIC (guard) = true;
4750 DECL_ARTIFICIAL (guard) = true;
4751 DECL_IGNORED_P (guard) = true;
4752 TREE_USED (guard) = true;
4753 CP_DECL_THREAD_LOCAL_P (guard) = true;
4754 set_decl_tls_model (guard, decl_default_tls_model (guard));
4755 pushdecl_top_level_and_finish (guard, NULL_TREE);
4757 tree fn = get_local_tls_init_fn (loc);
4758 start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4759 tree body = begin_function_body ();
4760 tree if_stmt = begin_if_stmt ();
4761 tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4762 tf_warning_or_error);
4763 finish_if_stmt_cond (cond, if_stmt);
4764 finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
4765 boolean_true_node,
4766 tf_warning_or_error));
4767 for (; vars; vars = TREE_CHAIN (vars))
4769 tree var = TREE_VALUE (vars);
4770 tree init = TREE_PURPOSE (vars);
4771 one_static_initialization_or_destruction (var, init, true);
4773 /* Output init aliases even with -fno-extern-tls-init. */
4774 if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
4776 tree single_init_fn = get_tls_init_fn (var);
4777 if (single_init_fn == NULL_TREE)
4778 continue;
4779 cgraph_node *alias
4780 = cgraph_node::get_create (fn)->create_same_body_alias
4781 (single_init_fn, fn);
4782 gcc_assert (alias != NULL);
4786 finish_then_clause (if_stmt);
4787 finish_if_stmt (if_stmt);
4788 finish_function_body (body);
4789 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4792 /* We're at the end of compilation, so generate any mangling aliases that
4793 we've been saving up, if DECL is going to be output and ID2 isn't
4794 already taken by another declaration. */
4796 static void
4797 generate_mangling_alias (tree decl, tree id2)
4799 struct cgraph_node *n = NULL;
4801 if (TREE_CODE (decl) == FUNCTION_DECL)
4803 n = cgraph_node::get (decl);
4804 if (!n)
4805 /* Don't create an alias to an unreferenced function. */
4806 return;
4809 tree *slot
4810 = mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
4811 INSERT);
4813 /* If there's a declaration already using this mangled name,
4814 don't create a compatibility alias that conflicts. */
4815 if (*slot)
4816 return;
4818 tree alias = make_alias_for (decl, id2);
4819 *slot = alias;
4821 DECL_IGNORED_P (alias) = 1;
4822 TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4823 DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4824 if (vague_linkage_p (decl))
4825 DECL_WEAK (alias) = 1;
4827 if (n)
4828 n->create_same_body_alias (alias, decl);
4829 else
4830 varpool_node::create_extra_name_alias (alias, decl);
4833 /* Note that we might want to emit an alias with the symbol ID2 for DECL at
4834 the end of translation, for compatibility across bugs in the mangling
4835 implementation. */
4837 void
4838 note_mangling_alias (tree decl, tree id2)
4840 if (TARGET_SUPPORTS_ALIASES)
4842 if (!defer_mangling_aliases)
4843 generate_mangling_alias (decl, id2);
4844 else
4846 vec_safe_push (mangling_aliases, decl);
4847 vec_safe_push (mangling_aliases, id2);
4852 /* Emit all mangling aliases that were deferred up to this point. */
4854 void
4855 generate_mangling_aliases ()
4857 while (!vec_safe_is_empty (mangling_aliases))
4859 tree id2 = mangling_aliases->pop();
4860 tree decl = mangling_aliases->pop();
4861 generate_mangling_alias (decl, id2);
4863 defer_mangling_aliases = false;
4866 /* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
4867 set. NEED_WARNING is true if we must warn about collisions. We do
4868 this to spot changes in mangling that may require compatibility
4869 aliases. */
4871 void
4872 record_mangling (tree decl, bool need_warning)
4874 if (!mangled_decls)
4875 mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
4877 gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
4878 tree id = DECL_ASSEMBLER_NAME_RAW (decl);
4879 tree *slot
4880 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4881 INSERT);
4883 /* If this is already an alias, remove the alias, because the real
4884 decl takes precedence. */
4885 if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
4886 if (symtab_node *n = symtab_node::get (*slot))
4887 if (n->cpp_implicit_alias)
4889 n->remove ();
4890 *slot = NULL_TREE;
4893 if (!*slot)
4894 *slot = decl;
4895 else if (need_warning)
4897 error_at (DECL_SOURCE_LOCATION (decl),
4898 "mangling of %q#D as %qE conflicts with a previous mangle",
4899 decl, id);
4900 inform (DECL_SOURCE_LOCATION (*slot),
4901 "previous mangling %q#D", *slot);
4902 inform (DECL_SOURCE_LOCATION (decl),
4903 "a later %<-fabi-version=%> (or =0)"
4904 " avoids this error with a change in mangling");
4905 *slot = decl;
4909 /* The mangled name of DECL is being forcibly changed to NAME. Remove
4910 any existing knowledge of DECL's mangled name meaning DECL. */
4912 void
4913 overwrite_mangling (tree decl, tree name)
4915 if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
4916 if ((TREE_CODE (decl) == VAR_DECL
4917 || TREE_CODE (decl) == FUNCTION_DECL)
4918 && mangled_decls)
4919 if (tree *slot
4920 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4921 NO_INSERT))
4922 if (*slot == decl)
4924 mangled_decls->clear_slot (slot);
4926 /* If this is an alias, remove it from the symbol table. */
4927 if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
4928 if (symtab_node *n = symtab_node::get (decl))
4929 if (n->cpp_implicit_alias)
4930 n->remove ();
4933 DECL_ASSEMBLER_NAME_RAW (decl) = name;
4936 /* The entire file is now complete. If requested, dump everything
4937 to a file. */
4939 static void
4940 dump_tu (void)
4942 dump_flags_t flags;
4943 if (FILE *stream = dump_begin (raw_dump_id, &flags))
4945 dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4946 dump_end (raw_dump_id, stream);
4950 static location_t locus_at_end_of_parsing;
4952 /* Check the deallocation functions for CODE to see if we want to warn that
4953 only one was defined. */
4955 static void
4956 maybe_warn_sized_delete (enum tree_code code)
4958 tree sized = NULL_TREE;
4959 tree unsized = NULL_TREE;
4961 for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
4962 iter; ++iter)
4964 tree fn = *iter;
4965 /* We're only interested in usual deallocation functions. */
4966 if (!usual_deallocation_fn_p (fn))
4967 continue;
4968 if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4969 unsized = fn;
4970 else
4971 sized = fn;
4973 if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
4974 warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
4975 "the program should also define %qD", sized);
4976 else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
4977 warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
4978 "the program should also define %qD", unsized);
4981 /* Check the global deallocation functions to see if we want to warn about
4982 defining unsized without sized (or vice versa). */
4984 static void
4985 maybe_warn_sized_delete ()
4987 if (!flag_sized_deallocation || !warn_sized_deallocation)
4988 return;
4989 maybe_warn_sized_delete (DELETE_EXPR);
4990 maybe_warn_sized_delete (VEC_DELETE_EXPR);
4993 /* Earlier we left PTRMEM_CST in variable initializers alone so that we could
4994 look them up when evaluating non-type template parameters. Now we need to
4995 lower them to something the back end can understand. */
4997 static void
4998 lower_var_init ()
5000 varpool_node *node;
5001 FOR_EACH_VARIABLE (node)
5003 tree d = node->decl;
5004 if (tree init = DECL_INITIAL (d))
5005 DECL_INITIAL (d) = cplus_expand_constant (init);
5009 /* This routine is called at the end of compilation.
5010 Its job is to create all the code needed to initialize and
5011 destroy the global aggregates. We do the destruction
5012 first, since that way we only need to reverse the decls once. */
5014 void
5015 c_parse_final_cleanups (void)
5017 size_t i;
5018 tree decl;
5020 locus_at_end_of_parsing = input_location;
5021 at_eof = 1;
5023 /* Bad parse errors. Just forget about it. */
5024 if (! global_bindings_p () || current_class_type
5025 || !vec_safe_is_empty (decl_namespace_list))
5026 return;
5028 /* This is the point to write out a PCH if we're doing that.
5029 In that case we do not want to do anything else. */
5030 if (pch_file)
5032 /* Mangle all symbols at PCH creation time. */
5033 symtab_node *node;
5034 FOR_EACH_SYMBOL (node)
5035 if (! is_a <varpool_node *> (node)
5036 || ! DECL_HARD_REGISTER (node->decl))
5037 DECL_ASSEMBLER_NAME (node->decl);
5038 c_common_write_pch ();
5039 dump_tu ();
5040 /* Ensure even the callers don't try to finalize the CU. */
5041 flag_syntax_only = 1;
5042 return;
5045 timevar_stop (TV_PHASE_PARSING);
5046 timevar_start (TV_PHASE_DEFERRED);
5048 symtab->process_same_body_aliases ();
5050 /* Handle -fdump-ada-spec[-slim] */
5051 if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
5053 collect_source_ref (main_input_filename);
5054 if (!flag_dump_ada_spec_slim)
5055 collect_source_refs (global_namespace);
5057 dump_ada_specs (collect_all_refs, cpp_check);
5060 /* FIXME - huh? was input_line -= 1;*/
5062 /* We now have to write out all the stuff we put off writing out.
5063 These include:
5065 o Template specializations that we have not yet instantiated,
5066 but which are needed.
5067 o Initialization and destruction for non-local objects with
5068 static storage duration. (Local objects with static storage
5069 duration are initialized when their scope is first entered,
5070 and are cleaned up via atexit.)
5071 o Virtual function tables.
5073 All of these may cause others to be needed. For example,
5074 instantiating one function may cause another to be needed, and
5075 generating the initializer for an object may cause templates to be
5076 instantiated, etc., etc. */
5078 emit_support_tinfos ();
5080 /* Track vtables we want to emit that refer to consteval functions. */
5081 auto_vec<tree> consteval_vtables;
5083 int retries = 0;
5084 unsigned ssdf_count = 0;
5085 for (bool reconsider = true; reconsider; retries++)
5087 reconsider = false;
5089 /* If there are templates that we've put off instantiating, do
5090 them now. */
5091 instantiate_pending_templates (retries);
5092 ggc_collect ();
5094 if (header_module_p ())
5095 /* A header modules initializations are handled in its
5096 importer. */
5097 continue;
5099 /* Write out virtual tables as required. Writing out the
5100 virtual table for a template class may cause the
5101 instantiation of members of that class. If we write out
5102 vtables then we remove the class from our list so we don't
5103 have to look at it again. */
5104 tree t;
5105 for (i = keyed_classes->length ();
5106 keyed_classes->iterate (--i, &t);)
5107 if (maybe_emit_vtables (t, consteval_vtables))
5109 reconsider = true;
5110 keyed_classes->unordered_remove (i);
5112 /* The input_location may have been changed during marking of
5113 vtable entries. */
5114 input_location = locus_at_end_of_parsing;
5116 /* Write out needed type info variables. We have to be careful
5117 looping through unemitted decls, because emit_tinfo_decl may
5118 cause other variables to be needed. New elements will be
5119 appended, and we remove from the vector those that actually
5120 get emitted. */
5121 for (i = unemitted_tinfo_decls->length ();
5122 unemitted_tinfo_decls->iterate (--i, &t);)
5123 if (emit_tinfo_decl (t))
5125 reconsider = true;
5126 unemitted_tinfo_decls->unordered_remove (i);
5129 /* The list of objects with static storage duration is built up
5130 in reverse order. We clear STATIC_AGGREGATES so that any new
5131 aggregates added during the initialization of these will be
5132 initialized in the correct order when we next come around the
5133 loop. */
5134 if (tree vars = prune_vars_needing_no_initialization (&static_aggregates))
5136 if (flag_openmp)
5137 /* Add initializer information from VARS into
5138 DYNAMIC_INITIALIZERS. */
5139 for (t = vars; t; t = TREE_CHAIN (t))
5140 hash_map_safe_put<hm_ggc> (dynamic_initializers,
5141 TREE_VALUE (t), TREE_PURPOSE (t));
5143 /* We need to start a new initialization function each time
5144 through the loop. That's because we need to know which
5145 vtables have been referenced, and TREE_SYMBOL_REFERENCED
5146 isn't computed until a function is finished, and written
5147 out. That's a deficiency in the back end. When this is
5148 fixed, these initialization functions could all become
5149 inline, with resulting performance improvements. */
5150 tree ssdf_body;
5152 /* Make sure the back end knows about all the variables. */
5153 write_out_vars (vars);
5155 /* Set the line and file, so that it is obviously not from
5156 the source file. */
5157 input_location = locus_at_end_of_parsing;
5158 ssdf_body = start_static_storage_duration_function (ssdf_count);
5160 /* First generate code to do all the initializations. */
5161 if (vars)
5162 do_static_initialization_or_destruction (vars, /*initp=*/true);
5164 /* Then, generate code to do all the destructions. Do these
5165 in reverse order so that the most recently constructed
5166 variable is the first destroyed. If we're using
5167 __cxa_atexit, then we don't need to do this; functions
5168 were registered at initialization time to destroy the
5169 local statics. */
5170 if (!flag_use_cxa_atexit && vars)
5172 vars = nreverse (vars);
5173 do_static_initialization_or_destruction (vars, /*initp=*/false);
5175 else
5176 vars = NULL_TREE;
5178 /* Finish up the static storage duration function for this
5179 round. */
5180 input_location = locus_at_end_of_parsing;
5181 finish_static_storage_duration_function (ssdf_body);
5183 /* All those initializations and finalizations might cause
5184 us to need more inline functions, more template
5185 instantiations, etc. */
5186 reconsider = true;
5187 ssdf_count++;
5190 /* Now do the same for thread_local variables. */
5191 handle_tls_init ();
5193 /* Go through the set of inline functions whose bodies have not
5194 been emitted yet. If out-of-line copies of these functions
5195 are required, emit them. */
5196 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5198 /* Does it need synthesizing? */
5199 if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
5200 && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
5202 /* Even though we're already at the top-level, we push
5203 there again. That way, when we pop back a few lines
5204 hence, all of our state is restored. Otherwise,
5205 finish_function doesn't clean things up, and we end
5206 up with CURRENT_FUNCTION_DECL set. */
5207 push_to_top_level ();
5208 /* The decl's location will mark where it was first
5209 needed. Save that so synthesize method can indicate
5210 where it was needed from, in case of error */
5211 input_location = DECL_SOURCE_LOCATION (decl);
5212 synthesize_method (decl);
5213 pop_from_top_level ();
5214 reconsider = true;
5217 if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
5218 generate_tls_wrapper (decl);
5220 if (!DECL_SAVED_TREE (decl))
5221 continue;
5223 cgraph_node *node = cgraph_node::get_create (decl);
5225 /* We lie to the back end, pretending that some functions
5226 are not defined when they really are. This keeps these
5227 functions from being put out unnecessarily. But, we must
5228 stop lying when the functions are referenced, or if they
5229 are not comdat since they need to be put out now. If
5230 DECL_INTERFACE_KNOWN, then we have already set
5231 DECL_EXTERNAL appropriately, so there's no need to check
5232 again, and we do not want to clear DECL_EXTERNAL if a
5233 previous call to import_export_decl set it.
5235 This is done in a separate for cycle, because if some
5236 deferred function is contained in another deferred
5237 function later in deferred_fns varray,
5238 rest_of_compilation would skip this function and we
5239 really cannot expand the same function twice. */
5240 import_export_decl (decl);
5241 if (DECL_NOT_REALLY_EXTERN (decl)
5242 && DECL_INITIAL (decl)
5243 && decl_needed_p (decl))
5245 if (node->cpp_implicit_alias)
5246 node = node->get_alias_target ();
5248 node->call_for_symbol_thunks_and_aliases (clear_decl_external,
5249 NULL, true);
5250 /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
5251 group, we need to mark all symbols in the same comdat group
5252 that way. */
5253 if (node->same_comdat_group)
5254 for (cgraph_node *next
5255 = dyn_cast<cgraph_node *> (node->same_comdat_group);
5256 next != node;
5257 next = dyn_cast<cgraph_node *> (next->same_comdat_group))
5258 next->call_for_symbol_thunks_and_aliases (clear_decl_external,
5259 NULL, true);
5262 /* If we're going to need to write this function out, and
5263 there's already a body for it, create RTL for it now.
5264 (There might be no body if this is a method we haven't
5265 gotten around to synthesizing yet.) */
5266 if (!DECL_EXTERNAL (decl)
5267 && decl_needed_p (decl)
5268 && !TREE_ASM_WRITTEN (decl)
5269 && !DECL_IMMEDIATE_FUNCTION_P (decl)
5270 && !node->definition)
5272 /* We will output the function; no longer consider it in this
5273 loop. */
5274 DECL_DEFER_OUTPUT (decl) = 0;
5275 /* Generate RTL for this function now that we know we
5276 need it. */
5277 expand_or_defer_fn (decl);
5278 reconsider = true;
5282 if (wrapup_namespace_globals ())
5283 reconsider = true;
5285 /* Static data members are just like namespace-scope globals. */
5286 FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
5288 if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
5289 /* Don't write it out if we haven't seen a definition. */
5290 || DECL_IN_AGGR_P (decl))
5291 continue;
5292 import_export_decl (decl);
5293 /* If this static data member is needed, provide it to the
5294 back end. */
5295 if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
5296 DECL_EXTERNAL (decl) = 0;
5299 if (vec_safe_length (pending_statics) != 0
5300 && wrapup_global_declarations (pending_statics->address (),
5301 pending_statics->length ()))
5302 reconsider = true;
5305 finish_module_processing (parse_in);
5307 lower_var_init ();
5309 generate_mangling_aliases ();
5311 /* All used inline functions must have a definition at this point. */
5312 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5314 if (/* Check online inline functions that were actually used. */
5315 DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
5316 /* If the definition actually was available here, then the
5317 fact that the function was not defined merely represents
5318 that for some reason (use of a template repository,
5319 #pragma interface, etc.) we decided not to emit the
5320 definition here. */
5321 && !DECL_INITIAL (decl)
5322 /* A defaulted fn in a header module can be synthesized on
5323 demand later. (In non-header modules we should have
5324 synthesized it above.) */
5325 && !(DECL_DEFAULTED_FN (decl) && header_module_p ())
5326 /* Don't complain if the template was defined. */
5327 && !(DECL_TEMPLATE_INSTANTIATION (decl)
5328 && DECL_INITIAL (DECL_TEMPLATE_RESULT
5329 (template_for_substitution (decl))))
5330 && warning_at (DECL_SOURCE_LOCATION (decl), 0,
5331 "inline function %qD used but never defined", decl))
5332 /* Avoid a duplicate warning from check_global_declaration. */
5333 suppress_warning (decl, OPT_Wunused);
5336 /* So must decls that use a type with no linkage. */
5337 FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
5338 no_linkage_error (decl);
5340 maybe_warn_sized_delete ();
5342 /* Then, do the Objective-C stuff. This is where all the
5343 Objective-C module stuff gets generated (symtab,
5344 class/protocol/selector lists etc). This must be done after C++
5345 templates, destructors etc. so that selectors used in C++
5346 templates are properly allocated. */
5347 if (c_dialect_objc ())
5348 objc_write_global_declarations ();
5350 /* We give C linkage to static constructors and destructors. */
5351 push_lang_context (lang_name_c);
5353 /* Generate initialization and destruction functions for all
5354 priorities for which they are required. */
5355 if (priority_info_map)
5356 splay_tree_foreach (priority_info_map,
5357 generate_ctor_and_dtor_functions_for_priority,
5358 /*data=*/&locus_at_end_of_parsing);
5359 else if ((c_dialect_objc () && objc_static_init_needed_p ())
5360 || module_initializer_kind ())
5361 generate_ctor_or_dtor_function (/*constructor_p=*/true,
5362 DEFAULT_INIT_PRIORITY,
5363 &locus_at_end_of_parsing);
5365 /* We're done with the splay-tree now. */
5366 if (priority_info_map)
5367 splay_tree_delete (priority_info_map);
5369 fini_modules ();
5371 /* Generate any missing aliases. */
5372 maybe_apply_pending_pragma_weaks ();
5374 /* We're done with static constructors, so we can go back to "C++"
5375 linkage now. */
5376 pop_lang_context ();
5378 if (flag_vtable_verify)
5380 vtv_recover_class_info ();
5381 vtv_compute_class_hierarchy_transitive_closure ();
5382 vtv_build_vtable_verify_fndecl ();
5385 perform_deferred_noexcept_checks ();
5387 fini_constexpr ();
5388 cp_tree_c_finish_parsing ();
5389 clear_consteval_vfns (consteval_vtables);
5391 /* The entire file is now complete. If requested, dump everything
5392 to a file. */
5393 dump_tu ();
5395 if (flag_detailed_statistics)
5397 dump_tree_statistics ();
5398 dump_time_statistics ();
5401 timevar_stop (TV_PHASE_DEFERRED);
5402 timevar_start (TV_PHASE_PARSING);
5404 /* Indicate that we're done with front end processing. */
5405 at_eof = 2;
5408 /* Perform any post compilation-proper cleanups for the C++ front-end.
5409 This should really go away. No front-end should need to do
5410 anything past the compilation process. */
5412 void
5413 cxx_post_compilation_parsing_cleanups (void)
5415 timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
5417 if (flag_vtable_verify)
5419 /* Generate the special constructor initialization function that
5420 calls __VLTRegisterPairs, and give it a very high
5421 initialization priority. This must be done after
5422 finalize_compilation_unit so that we have accurate
5423 information about which vtable will actually be emitted. */
5424 vtv_generate_init_routine ();
5427 input_location = locus_at_end_of_parsing;
5429 if (flag_checking)
5430 validate_conversion_obstack ();
5432 timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
5435 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
5436 function to call in parse-tree form; it has not yet been
5437 semantically analyzed. ARGS are the arguments to the function.
5438 They have already been semantically analyzed. This may change
5439 ARGS. */
5441 tree
5442 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
5443 tsubst_flags_t complain)
5445 tree orig_fn;
5446 vec<tree, va_gc> *orig_args = NULL;
5447 tree expr;
5448 tree object;
5450 orig_fn = fn;
5451 object = TREE_OPERAND (fn, 0);
5453 if (processing_template_decl)
5455 gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
5456 || TREE_CODE (fn) == MEMBER_REF);
5457 if (type_dependent_expression_p (fn)
5458 || any_type_dependent_arguments_p (*args))
5459 return build_min_nt_call_vec (fn, *args);
5461 orig_args = make_tree_vector_copy (*args);
5463 /* Transform the arguments and add the implicit "this"
5464 parameter. That must be done before the FN is transformed
5465 because we depend on the form of FN. */
5466 make_args_non_dependent (*args);
5467 object = build_non_dependent_expr (object);
5468 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5470 if (TREE_CODE (fn) == DOTSTAR_EXPR)
5471 object = cp_build_addr_expr (object, complain);
5472 vec_safe_insert (*args, 0, object);
5474 /* Now that the arguments are done, transform FN. */
5475 fn = build_non_dependent_expr (fn);
5478 /* A qualified name corresponding to a bound pointer-to-member is
5479 represented as an OFFSET_REF:
5481 struct B { void g(); };
5482 void (B::*p)();
5483 void B::g() { (this->*p)(); } */
5484 if (TREE_CODE (fn) == OFFSET_REF)
5486 tree object_addr = cp_build_addr_expr (object, complain);
5487 fn = TREE_OPERAND (fn, 1);
5488 fn = get_member_function_from_ptrfunc (&object_addr, fn,
5489 complain);
5490 vec_safe_insert (*args, 0, object_addr);
5493 if (CLASS_TYPE_P (TREE_TYPE (fn)))
5494 expr = build_op_call (fn, args, complain);
5495 else
5496 expr = cp_build_function_call_vec (fn, args, complain);
5497 if (processing_template_decl && expr != error_mark_node)
5498 expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
5500 if (orig_args != NULL)
5501 release_tree_vector (orig_args);
5503 return expr;
5507 void
5508 check_default_args (tree x)
5510 tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5511 bool saw_def = false;
5512 bool noted_first_def = false;
5513 int idx_of_first_default_arg = 0;
5514 location_t loc_of_first_default_arg = UNKNOWN_LOCATION;
5515 int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5516 tree fndecl = STRIP_TEMPLATE (x);
5517 auto_diagnostic_group d;
5518 for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5520 if (TREE_PURPOSE (arg))
5522 if (!saw_def)
5524 saw_def = true;
5525 idx_of_first_default_arg = i;
5526 location_t loc = get_fndecl_argument_location (fndecl, i);
5527 if (loc != DECL_SOURCE_LOCATION (x))
5528 loc_of_first_default_arg = loc;
5531 else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
5533 error_at (get_fndecl_argument_location (fndecl, i),
5534 "default argument missing for parameter %P of %q#D", i, x);
5535 if (loc_of_first_default_arg != UNKNOWN_LOCATION
5536 && !noted_first_def)
5538 inform (loc_of_first_default_arg,
5539 "...following parameter %P which has a default argument",
5540 idx_of_first_default_arg);
5541 noted_first_def = true;
5543 TREE_PURPOSE (arg) = error_mark_node;
5548 /* Return true if function DECL can be inlined. This is used to force
5549 instantiation of methods that might be interesting for inlining. */
5550 bool
5551 possibly_inlined_p (tree decl)
5553 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5554 if (DECL_UNINLINABLE (decl))
5555 return false;
5556 if (!optimize)
5557 return DECL_DECLARED_INLINE_P (decl);
5558 /* When optimizing, we might inline everything when flatten
5559 attribute or heuristics inlining for size or autoinlining
5560 is used. */
5561 return true;
5564 /* Normally, we can wait until instantiation-time to synthesize DECL.
5565 However, if DECL is a static data member initialized with a constant
5566 or a constexpr function, we need it right now because a reference to
5567 such a data member or a call to such function is not value-dependent.
5568 For a function that uses auto in the return type, we need to instantiate
5569 it to find out its type. For OpenMP user defined reductions, we need
5570 them instantiated for reduction clauses which inline them by hand
5571 directly. */
5573 void
5574 maybe_instantiate_decl (tree decl)
5576 if (DECL_LANG_SPECIFIC (decl)
5577 && DECL_TEMPLATE_INFO (decl)
5578 && (decl_maybe_constant_var_p (decl)
5579 || (TREE_CODE (decl) == FUNCTION_DECL
5580 && DECL_OMP_DECLARE_REDUCTION_P (decl))
5581 || undeduced_auto_decl (decl))
5582 && !DECL_DECLARED_CONCEPT_P (decl)
5583 && !uses_template_parms (DECL_TI_ARGS (decl)))
5585 /* Instantiating a function will result in garbage collection. We
5586 must treat this situation as if we were within the body of a
5587 function so as to avoid collecting live data only referenced from
5588 the stack (such as overload resolution candidates). */
5589 ++function_depth;
5590 instantiate_decl (decl, /*defer_ok=*/false,
5591 /*expl_inst_class_mem_p=*/false);
5592 --function_depth;
5596 /* Error if the DECL is unavailable (unless this is currently suppressed).
5597 Maybe warn if DECL is deprecated, subject to COMPLAIN. Returns true if
5598 an error or warning was emitted. */
5600 bool
5601 cp_handle_deprecated_or_unavailable (tree decl, tsubst_flags_t complain)
5603 if (!decl)
5604 return false;
5606 if ((complain & tf_error)
5607 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
5609 if (TREE_UNAVAILABLE (decl))
5611 error_unavailable_use (decl, NULL_TREE);
5612 return true;
5614 else
5616 /* Perhaps this is an unavailable typedef. */
5617 if (TYPE_P (decl)
5618 && TYPE_NAME (decl)
5619 && TREE_UNAVAILABLE (TYPE_NAME (decl)))
5621 decl = TYPE_NAME (decl);
5622 /* Don't error within members of a unavailable type. */
5623 if (TYPE_P (decl)
5624 && currently_open_class (decl))
5625 return false;
5627 error_unavailable_use (decl, NULL_TREE);
5628 return true;
5631 /* Carry on to consider deprecatedness. */
5634 if (!(complain & tf_warning)
5635 || deprecated_state == DEPRECATED_SUPPRESS
5636 || deprecated_state == UNAVAILABLE_DEPRECATED_SUPPRESS)
5637 return false;
5639 if (!TREE_DEPRECATED (decl))
5641 /* Perhaps this is a deprecated typedef. */
5642 if (TYPE_P (decl) && TYPE_NAME (decl))
5643 decl = TYPE_NAME (decl);
5645 if (!TREE_DEPRECATED (decl))
5646 return false;
5649 /* Don't warn within members of a deprecated type. */
5650 if (TYPE_P (decl)
5651 && currently_open_class (decl))
5652 return false;
5654 bool warned = false;
5655 if (cxx_dialect >= cxx11
5656 && DECL_P (decl)
5657 && DECL_ARTIFICIAL (decl)
5658 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5659 && copy_fn_p (decl))
5661 /* Don't warn if the flag was disabled around the class definition
5662 (c++/94492). */
5663 if (warning_enabled_at (DECL_SOURCE_LOCATION (decl),
5664 OPT_Wdeprecated_copy))
5666 auto_diagnostic_group d;
5667 tree ctx = DECL_CONTEXT (decl);
5668 tree other = classtype_has_depr_implicit_copy (ctx);
5669 int opt = (DECL_DESTRUCTOR_P (other)
5670 ? OPT_Wdeprecated_copy_dtor
5671 : OPT_Wdeprecated_copy);
5672 warned = warning (opt, "implicitly-declared %qD is deprecated",
5673 decl);
5674 if (warned)
5675 inform (DECL_SOURCE_LOCATION (other),
5676 "because %qT has user-provided %qD",
5677 ctx, other);
5680 else
5681 warned = warn_deprecated_use (decl, NULL_TREE);
5683 return warned;
5686 /* Like above, but takes into account outer scopes. */
5688 void
5689 cp_warn_deprecated_use_scopes (tree scope)
5691 while (scope
5692 && scope != error_mark_node
5693 && scope != global_namespace)
5695 if ((TREE_CODE (scope) == NAMESPACE_DECL || OVERLOAD_TYPE_P (scope))
5696 && cp_handle_deprecated_or_unavailable (scope))
5697 return;
5698 if (TYPE_P (scope))
5699 scope = CP_TYPE_CONTEXT (scope);
5700 else
5701 scope = CP_DECL_CONTEXT (scope);
5705 /* True if DECL or its enclosing scope have unbound template parameters. */
5707 bool
5708 decl_dependent_p (tree decl)
5710 if (DECL_FUNCTION_SCOPE_P (decl)
5711 || TREE_CODE (decl) == CONST_DECL
5712 || TREE_CODE (decl) == USING_DECL
5713 || TREE_CODE (decl) == FIELD_DECL)
5714 decl = CP_DECL_CONTEXT (decl);
5715 if (tree tinfo = get_template_info (decl))
5716 if (any_dependent_template_arguments_p (TI_ARGS (tinfo)))
5717 return true;
5718 if (LAMBDA_FUNCTION_P (decl)
5719 && dependent_type_p (DECL_CONTEXT (decl)))
5720 return true;
5721 return false;
5724 /* [basic.def.odr] A function is named [and therefore odr-used] by an
5725 expression or conversion if it is the selected member of an overload set in
5726 an overload resolution performed as part of forming that expression or
5727 conversion, unless it is a pure virtual function and either the expression
5728 is not an id-expression naming the function with an explicitly qualified
5729 name or the expression forms a pointer to member.
5731 Mostly, we call mark_used in places that actually do something with a
5732 function, like build_over_call. But in a few places we end up with a
5733 non-overloaded FUNCTION_DECL that we aren't going to do any more with, like
5734 convert_to_void. resolve_nondeduced_context is called in those places,
5735 but it's also called in too many other places. */
5737 bool
5738 mark_single_function (tree expr, tsubst_flags_t complain)
5740 expr = maybe_undo_parenthesized_ref (expr);
5741 expr = tree_strip_any_location_wrapper (expr);
5743 if (is_overloaded_fn (expr) == 1
5744 && !mark_used (expr, complain)
5745 && (complain & tf_error))
5746 return false;
5747 return true;
5750 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5751 If DECL is a specialization or implicitly declared class member,
5752 generate the actual definition. Return false if something goes
5753 wrong, true otherwise. */
5755 bool
5756 mark_used (tree decl, tsubst_flags_t complain)
5758 /* If we're just testing conversions or resolving overloads, we
5759 don't want any permanent effects like forcing functions to be
5760 output or instantiating templates. */
5761 if ((complain & tf_conv))
5762 return true;
5764 /* If DECL is a BASELINK for a single function, then treat it just
5765 like the DECL for the function. Otherwise, if the BASELINK is
5766 for an overloaded function, we don't know which function was
5767 actually used until after overload resolution. */
5768 if (BASELINK_P (decl))
5770 decl = BASELINK_FUNCTIONS (decl);
5771 if (really_overloaded_fn (decl))
5772 return true;
5773 decl = OVL_FIRST (decl);
5776 if (!DECL_P (decl))
5777 return true;
5779 /* Set TREE_USED for the benefit of -Wunused. */
5780 TREE_USED (decl) = true;
5782 /* And for structured bindings also the underlying decl. */
5783 if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
5784 TREE_USED (DECL_DECOMP_BASE (decl)) = true;
5786 if (TREE_CODE (decl) == TEMPLATE_DECL)
5787 return true;
5789 if (DECL_CLONED_FUNCTION_P (decl))
5790 TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5792 /* Mark enumeration types as used. */
5793 if (TREE_CODE (decl) == CONST_DECL)
5794 used_types_insert (DECL_CONTEXT (decl));
5796 if (TREE_CODE (decl) == FUNCTION_DECL)
5798 if (DECL_MAYBE_DELETED (decl))
5800 ++function_depth;
5801 maybe_synthesize_method (decl);
5802 --function_depth;
5805 if (DECL_DELETED_FN (decl))
5807 if (DECL_ARTIFICIAL (decl)
5808 && DECL_CONV_FN_P (decl)
5809 && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5810 /* We mark a lambda conversion op as deleted if we can't
5811 generate it properly; see maybe_add_lambda_conv_op. */
5812 sorry ("converting lambda that uses %<...%> to function pointer");
5813 else if (complain & tf_error)
5815 error ("use of deleted function %qD", decl);
5816 if (!maybe_explain_implicit_delete (decl))
5817 inform (DECL_SOURCE_LOCATION (decl), "declared here");
5819 return false;
5822 if (!maybe_instantiate_noexcept (decl, complain))
5823 return false;
5826 if (VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl))
5828 if (!DECL_LANG_SPECIFIC (decl))
5829 /* An unresolved dependent local extern. */
5830 return true;
5832 DECL_ODR_USED (decl) = 1;
5833 auto alias = DECL_LOCAL_DECL_ALIAS (decl);
5834 if (!alias || alias == error_mark_node)
5835 return true;
5837 /* Process the underlying decl. */
5838 decl = alias;
5839 TREE_USED (decl) = true;
5842 cp_handle_deprecated_or_unavailable (decl, complain);
5844 /* We can only check DECL_ODR_USED on variables or functions with
5845 DECL_LANG_SPECIFIC set, and these are also the only decls that we
5846 might need special handling for. */
5847 if (!VAR_OR_FUNCTION_DECL_P (decl)
5848 || DECL_LANG_SPECIFIC (decl) == NULL
5849 || DECL_THUNK_P (decl))
5851 if (!decl_dependent_p (decl)
5852 && !require_deduced_type (decl, complain))
5853 return false;
5854 return true;
5857 /* We only want to do this processing once. We don't need to keep trying
5858 to instantiate inline templates, because unit-at-a-time will make sure
5859 we get them compiled before functions that want to inline them. */
5860 if (DECL_ODR_USED (decl))
5861 return true;
5863 if (flag_concepts && TREE_CODE (decl) == FUNCTION_DECL
5864 && !constraints_satisfied_p (decl))
5866 if (complain & tf_error)
5868 auto_diagnostic_group d;
5869 error ("use of function %qD with unsatisfied constraints",
5870 decl);
5871 location_t loc = DECL_SOURCE_LOCATION (decl);
5872 inform (loc, "declared here");
5873 diagnose_constraints (loc, decl, NULL_TREE);
5875 return false;
5878 /* Normally, we can wait until instantiation-time to synthesize DECL.
5879 However, if DECL is a static data member initialized with a constant
5880 or a constexpr function, we need it right now because a reference to
5881 such a data member or a call to such function is not value-dependent.
5882 For a function that uses auto in the return type, we need to instantiate
5883 it to find out its type. For OpenMP user defined reductions, we need
5884 them instantiated for reduction clauses which inline them by hand
5885 directly. */
5886 maybe_instantiate_decl (decl);
5888 if (processing_template_decl || in_template_function ())
5889 return true;
5891 /* Check this too in case we're within instantiate_non_dependent_expr. */
5892 if (DECL_TEMPLATE_INFO (decl)
5893 && uses_template_parms (DECL_TI_ARGS (decl)))
5894 return true;
5896 if (!require_deduced_type (decl, complain))
5897 return false;
5899 if (builtin_pack_fn_p (decl))
5901 error ("use of built-in parameter pack %qD outside of a template",
5902 DECL_NAME (decl));
5903 return false;
5906 /* If we don't need a value, then we don't need to synthesize DECL. */
5907 if (cp_unevaluated_operand || in_discarded_stmt)
5908 return true;
5910 DECL_ODR_USED (decl) = 1;
5911 if (DECL_CLONED_FUNCTION_P (decl))
5912 DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5914 /* DR 757: A type without linkage shall not be used as the type of a
5915 variable or function with linkage, unless
5916 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5917 o the variable or function is not used (3.2 [basic.def.odr]) or is
5918 defined in the same translation unit. */
5919 if (cxx_dialect > cxx98
5920 && decl_linkage (decl) != lk_none
5921 && !DECL_EXTERN_C_P (decl)
5922 && !DECL_ARTIFICIAL (decl)
5923 && !decl_defined_p (decl)
5924 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5925 vec_safe_push (no_linkage_decls, decl);
5927 if (TREE_CODE (decl) == FUNCTION_DECL
5928 && DECL_DECLARED_INLINE_P (decl)
5929 && !DECL_INITIAL (decl)
5930 && !DECL_ARTIFICIAL (decl)
5931 && !DECL_PURE_VIRTUAL_P (decl))
5932 /* Remember it, so we can check it was defined. */
5933 note_vague_linkage_fn (decl);
5935 /* Is it a synthesized method that needs to be synthesized? */
5936 if (TREE_CODE (decl) == FUNCTION_DECL
5937 && DECL_DEFAULTED_FN (decl)
5938 /* A function defaulted outside the class is synthesized either by
5939 cp_finish_decl or instantiate_decl. */
5940 && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5941 && ! DECL_INITIAL (decl))
5943 /* Defer virtual destructors so that thunks get the right
5944 linkage. */
5945 if (DECL_VIRTUAL_P (decl) && !at_eof)
5947 note_vague_linkage_fn (decl);
5948 return true;
5951 /* Remember the current location for a function we will end up
5952 synthesizing. Then we can inform the user where it was
5953 required in the case of error. */
5954 if (decl_remember_implicit_trigger_p (decl))
5955 DECL_SOURCE_LOCATION (decl) = input_location;
5957 /* Synthesizing an implicitly defined member function will result in
5958 garbage collection. We must treat this situation as if we were
5959 within the body of a function so as to avoid collecting live data
5960 on the stack (such as overload resolution candidates).
5962 We could just let c_parse_final_cleanups handle synthesizing
5963 this function by adding it to deferred_fns, but doing
5964 it at the use site produces better error messages. */
5965 ++function_depth;
5966 synthesize_method (decl);
5967 --function_depth;
5968 /* If this is a synthesized method we don't need to
5969 do the instantiation test below. */
5971 else if (VAR_OR_FUNCTION_DECL_P (decl)
5972 && DECL_TEMPLATE_INFO (decl)
5973 && !DECL_DECLARED_CONCEPT_P (decl)
5974 && (!DECL_EXPLICIT_INSTANTIATION (decl)
5975 || always_instantiate_p (decl)))
5976 /* If this is a function or variable that is an instance of some
5977 template, we now know that we will need to actually do the
5978 instantiation. We check that DECL is not an explicit
5979 instantiation because that is not checked in instantiate_decl.
5981 We put off instantiating functions in order to improve compile
5982 times. Maintaining a stack of active functions is expensive,
5983 and the inliner knows to instantiate any functions it might
5984 need. Therefore, we always try to defer instantiation. */
5986 ++function_depth;
5987 instantiate_decl (decl, /*defer_ok=*/true,
5988 /*expl_inst_class_mem_p=*/false);
5989 --function_depth;
5992 return true;
5995 bool
5996 mark_used (tree decl)
5998 return mark_used (decl, tf_warning_or_error);
6001 tree
6002 vtv_start_verification_constructor_init_function (void)
6004 return start_objects ('I', MAX_RESERVED_INIT_PRIORITY - 1);
6007 tree
6008 vtv_finish_verification_constructor_init_function (tree function_body)
6010 tree fn;
6012 finish_compound_stmt (function_body);
6013 fn = finish_function (/*inline_p=*/false);
6014 DECL_STATIC_CONSTRUCTOR (fn) = 1;
6015 decl_init_priority_insert (fn, MAX_RESERVED_INIT_PRIORITY - 1);
6017 return fn;
6020 #include "gt-cp-decl2.h"