Fortran: Fix regression caused by r14-10477 [PR59104]
[official-gcc.git] / gcc / cp / decl.cc
blob6b686d75a49f9d368ec70a735b3ed5143faa3bfa
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2024 Free Software Foundation, Inc.
3 Contributed 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 #define INCLUDE_MEMORY
31 #include "system.h"
32 #include "coretypes.h"
33 #include "target.h"
34 #include "c-family/c-target.h"
35 #include "cp-tree.h"
36 #include "timevar.h"
37 #include "stringpool.h"
38 #include "cgraph.h"
39 #include "stor-layout.h"
40 #include "varasm.h"
41 #include "attribs.h"
42 #include "flags.h"
43 #include "tree-iterator.h"
44 #include "decl.h"
45 #include "intl.h"
46 #include "toplev.h"
47 #include "c-family/c-objc.h"
48 #include "c-family/c-pragma.h"
49 #include "c-family/c-ubsan.h"
50 #include "cp/cp-name-hint.h"
51 #include "debug.h"
52 #include "plugin.h"
53 #include "builtins.h"
54 #include "gimplify.h"
55 #include "asan.h"
56 #include "gcc-rich-location.h"
57 #include "langhooks.h"
58 #include "context.h" /* For 'g'. */
59 #include "omp-general.h"
60 #include "omp-offload.h" /* For offload_vars. */
61 #include "opts.h"
62 #include "langhooks-def.h" /* For lhd_simulate_record_decl */
64 /* Possible cases of bad specifiers type used by bad_specifiers. */
65 enum bad_spec_place {
66 BSP_VAR, /* variable */
67 BSP_PARM, /* parameter */
68 BSP_TYPE, /* type */
69 BSP_FIELD /* field */
72 static const char *redeclaration_error_message (tree, tree);
74 static bool decl_jump_unsafe (tree);
75 static void require_complete_types_for_parms (tree);
76 static tree grok_reference_init (tree, tree, tree, int);
77 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
78 int, int, int, bool, int, tree, location_t);
79 static void check_static_variable_definition (tree, tree);
80 static void record_unknown_type (tree, const char *);
81 static int member_function_or_else (tree, tree, enum overload_flags);
82 static tree local_variable_p_walkfn (tree *, int *, void *);
83 static const char *tag_name (enum tag_types);
84 static tree lookup_and_check_tag (enum tag_types, tree, TAG_how, bool);
85 static void maybe_deduce_size_from_array_init (tree, tree);
86 static void layout_var_decl (tree);
87 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
88 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
89 static void copy_type_enum (tree , tree);
90 static void check_function_type (tree, tree);
91 static void begin_destructor_body (void);
92 static void record_key_method_defined (tree);
93 static tree create_array_type_for_decl (tree, tree, tree, location_t);
94 static tree get_atexit_node (void);
95 static tree get_dso_handle_node (void);
96 static tree start_cleanup_fn (bool);
97 static void end_cleanup_fn (void);
98 static tree cp_make_fname_decl (location_t, tree, int);
99 static void initialize_predefined_identifiers (void);
100 static tree check_special_function_return_type
101 (special_function_kind, tree, tree, int, const location_t*);
102 static tree push_cp_library_fn (enum tree_code, tree, int);
103 static tree build_cp_library_fn (tree, enum tree_code, tree, int);
104 static void store_parm_decls (tree);
105 static void initialize_local_var (tree, tree);
106 static void expand_static_init (tree, tree);
107 static location_t smallest_type_location (const cp_decl_specifier_seq*);
108 static bool identify_goto (tree, location_t, const location_t *,
109 diagnostic_t, bool);
111 /* The following symbols are subsumed in the cp_global_trees array, and
112 listed here individually for documentation purposes.
114 C++ extensions
115 tree wchar_decl_node;
117 tree vtable_entry_type;
118 tree delta_type_node;
119 tree __t_desc_type_node;
121 tree class_type_node;
122 tree unknown_type_node;
124 Array type `vtable_entry_type[]'
126 tree vtbl_type_node;
127 tree vtbl_ptr_type_node;
129 Namespaces,
131 tree std_node;
132 tree abi_node;
134 A FUNCTION_DECL which can call `abort'. Not necessarily the
135 one that the user will declare, but sufficient to be called
136 by routines that want to abort the program.
138 tree abort_fndecl;
140 Used by RTTI
141 tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
142 tree tinfo_var_id; */
144 tree cp_global_trees[CPTI_MAX];
146 /* A list of objects which have constructors or destructors
147 which reside in namespace scope. The decl is stored in
148 the TREE_VALUE slot and the initializer is stored
149 in the TREE_PURPOSE slot. */
150 tree static_aggregates;
152 /* Like static_aggregates, but for thread_local variables. */
153 tree tls_aggregates;
155 /* A hash-map mapping from variable decls to the dynamic initializer for
156 the decl. This is currently only used by OpenMP. */
157 decl_tree_map *dynamic_initializers;
159 /* -- end of C++ */
161 /* A node for the integer constant 2. */
163 tree integer_two_node;
165 /* vector of static decls. */
166 vec<tree, va_gc> *static_decls;
168 /* vector of keyed classes. */
169 vec<tree, va_gc> *keyed_classes;
171 /* Used only for jumps to as-yet undefined labels, since jumps to
172 defined labels can have their validity checked immediately. */
174 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
175 struct named_label_use_entry *next;
176 /* The binding level to which this entry is *currently* attached.
177 This is initially the binding level in which the goto appeared,
178 but is modified as scopes are closed. */
179 cp_binding_level *binding_level;
180 /* The head of the names list that was current when the goto appeared,
181 or the inner scope popped. These are the decls that will *not* be
182 skipped when jumping to the label. */
183 tree names_in_scope;
184 /* If the use is a possible destination of a computed goto, a vec of decls
185 that aren't destroyed, filled in by poplevel_named_label_1. */
186 vec<tree,va_gc> *computed_goto;
187 /* The location of the goto, for error reporting. */
188 location_t o_goto_locus;
189 /* True if an OpenMP structured block scope has been closed since
190 the goto appeared. This means that the branch from the label will
191 illegally exit an OpenMP scope. */
192 bool in_omp_scope;
195 /* A list of all LABEL_DECLs in the function that have names. Here so
196 we can clear out their names' definitions at the end of the
197 function, and so we can check the validity of jumps to these labels. */
199 struct GTY((for_user)) named_label_entry {
201 tree name; /* Name of decl. */
203 tree label_decl; /* LABEL_DECL, unless deleted local label. */
205 named_label_entry *outer; /* Outer shadowed chain. */
207 /* The binding level to which the label is *currently* attached.
208 This is initially set to the binding level in which the label
209 is defined, but is modified as scopes are closed. */
210 cp_binding_level *binding_level;
212 /* The head of the names list that was current when the label was
213 defined, or the inner scope popped. These are the decls that will
214 be skipped when jumping to the label. */
215 tree names_in_scope;
217 /* A vector of all decls from all binding levels that would be
218 crossed by a backward branch to the label. */
219 vec<tree, va_gc> *bad_decls;
221 /* A list of uses of the label, before the label is defined. */
222 named_label_use_entry *uses;
224 /* True if we've seen &&label. Appalently we can't use TREE_ADDRESSABLE for
225 this, it has a more specific meaning for LABEL_DECL. */
226 bool addressed;
228 /* The following bits are set after the label is defined, and are
229 updated as scopes are popped. They indicate that a jump to the
230 label will illegally enter a scope of the given flavor. */
231 bool in_try_scope;
232 bool in_catch_scope;
233 bool in_omp_scope;
234 bool in_transaction_scope;
235 bool in_constexpr_if;
236 bool in_consteval_if;
237 bool in_stmt_expr;
240 #define named_labels cp_function_chain->x_named_labels
242 /* The number of function bodies which we are currently processing.
243 (Zero if we are at namespace scope, one inside the body of a
244 function, two inside the body of a function in a local class, etc.) */
245 int function_depth;
247 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
248 bool flag_noexcept_type;
250 /* States indicating how grokdeclarator() should handle declspecs marked
251 with __attribute__((deprecated)). An object declared as
252 __attribute__((deprecated)) suppresses warnings of uses of other
253 deprecated items. */
254 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
257 /* A list of VAR_DECLs whose type was incomplete at the time the
258 variable was declared. */
260 struct GTY(()) incomplete_var {
261 tree decl;
262 tree incomplete_type;
266 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
268 /* Returns the kind of template specialization we are currently
269 processing, given that it's declaration contained N_CLASS_SCOPES
270 explicit scope qualifications. */
272 tmpl_spec_kind
273 current_tmpl_spec_kind (int n_class_scopes)
275 int n_template_parm_scopes = 0;
276 int seen_specialization_p = 0;
277 int innermost_specialization_p = 0;
278 cp_binding_level *b;
280 /* Scan through the template parameter scopes. */
281 for (b = current_binding_level;
282 b->kind == sk_template_parms;
283 b = b->level_chain)
285 /* If we see a specialization scope inside a parameter scope,
286 then something is wrong. That corresponds to a declaration
287 like:
289 template <class T> template <> ...
291 which is always invalid since [temp.expl.spec] forbids the
292 specialization of a class member template if the enclosing
293 class templates are not explicitly specialized as well. */
294 if (b->explicit_spec_p)
296 if (n_template_parm_scopes == 0)
297 innermost_specialization_p = 1;
298 else
299 seen_specialization_p = 1;
301 else if (seen_specialization_p == 1)
302 return tsk_invalid_member_spec;
304 ++n_template_parm_scopes;
307 /* Handle explicit instantiations. */
308 if (processing_explicit_instantiation)
310 if (n_template_parm_scopes != 0)
311 /* We've seen a template parameter list during an explicit
312 instantiation. For example:
314 template <class T> template void f(int);
316 This is erroneous. */
317 return tsk_invalid_expl_inst;
318 else
319 return tsk_expl_inst;
322 if (n_template_parm_scopes < n_class_scopes)
323 /* We've not seen enough template headers to match all the
324 specialized classes present. For example:
326 template <class T> void R<T>::S<T>::f(int);
328 This is invalid; there needs to be one set of template
329 parameters for each class. */
330 return tsk_insufficient_parms;
331 else if (n_template_parm_scopes == n_class_scopes)
332 /* We're processing a non-template declaration (even though it may
333 be a member of a template class.) For example:
335 template <class T> void S<T>::f(int);
337 The `class T' matches the `S<T>', leaving no template headers
338 corresponding to the `f'. */
339 return tsk_none;
340 else if (n_template_parm_scopes > n_class_scopes + 1)
341 /* We've got too many template headers. For example:
343 template <> template <class T> void f (T);
345 There need to be more enclosing classes. */
346 return tsk_excessive_parms;
347 else
348 /* This must be a template. It's of the form:
350 template <class T> template <class U> void S<T>::f(U);
352 This is a specialization if the innermost level was a
353 specialization; otherwise it's just a definition of the
354 template. */
355 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
358 /* Exit the current scope. */
360 void
361 finish_scope (void)
363 poplevel (0, 0, 0);
366 /* When a label goes out of scope, check to see if that label was used
367 in a valid manner, and issue any appropriate warnings or errors. */
369 static void
370 check_label_used (tree label)
372 if (!processing_template_decl)
374 if (DECL_INITIAL (label) == NULL_TREE)
376 location_t location;
378 error ("label %q+D used but not defined", label);
379 location = input_location;
380 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
381 /* Avoid crashing later. */
382 define_label (location, DECL_NAME (label));
384 else
385 warn_for_unused_label (label);
389 /* Helper function to sort named label entries in a vector by DECL_UID. */
391 static int
392 sort_labels (const void *a, const void *b)
394 tree label1 = *(tree const *) a;
395 tree label2 = *(tree const *) b;
397 /* DECL_UIDs can never be equal. */
398 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
401 /* At the end of a function, all labels declared within the function
402 go out of scope. BLOCK is the top-level block for the
403 function. */
405 static void
406 pop_labels (tree block)
408 if (!named_labels)
409 return;
411 /* We need to add the labels to the block chain, so debug
412 information is emitted. But, we want the order to be stable so
413 need to sort them first. Otherwise the debug output could be
414 randomly ordered. I guess it's mostly stable, unless the hash
415 table implementation changes. */
416 auto_vec<tree, 32> labels (named_labels->elements ());
417 hash_table<named_label_hash>::iterator end (named_labels->end ());
418 for (hash_table<named_label_hash>::iterator iter
419 (named_labels->begin ()); iter != end; ++iter)
421 named_label_entry *ent = *iter;
423 gcc_checking_assert (!ent->outer);
424 if (ent->label_decl)
425 labels.quick_push (ent->label_decl);
426 ggc_free (ent);
428 named_labels = NULL;
429 labels.qsort (sort_labels);
431 while (labels.length ())
433 tree label = labels.pop ();
435 DECL_CHAIN (label) = BLOCK_VARS (block);
436 BLOCK_VARS (block) = label;
438 check_label_used (label);
442 /* At the end of a block with local labels, restore the outer definition. */
444 static void
445 pop_local_label (tree id, tree label)
447 check_label_used (label);
448 named_label_entry **slot = named_labels->find_slot_with_hash
449 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
450 named_label_entry *ent = *slot;
452 if (ent->outer)
453 ent = ent->outer;
454 else
456 ent = ggc_cleared_alloc<named_label_entry> ();
457 ent->name = id;
459 *slot = ent;
462 /* The following two routines are used to interface to Objective-C++.
463 The binding level is purposely treated as an opaque type. */
465 void *
466 objc_get_current_scope (void)
468 return current_binding_level;
471 /* The following routine is used by the NeXT-style SJLJ exceptions;
472 variables get marked 'volatile' so as to not be clobbered by
473 _setjmp()/_longjmp() calls. All variables in the current scope,
474 as well as parent scopes up to (but not including) ENCLOSING_BLK
475 shall be thusly marked. */
477 void
478 objc_mark_locals_volatile (void *enclosing_blk)
480 cp_binding_level *scope;
482 for (scope = current_binding_level;
483 scope && scope != enclosing_blk;
484 scope = scope->level_chain)
486 tree decl;
488 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
489 objc_volatilize_decl (decl);
491 /* Do not climb up past the current function. */
492 if (scope->kind == sk_function_parms)
493 break;
497 /* True if B is the level for the condition of a constexpr if. */
499 static bool
500 level_for_constexpr_if (cp_binding_level *b)
502 return (b->kind == sk_cond && b->this_entity
503 && TREE_CODE (b->this_entity) == IF_STMT
504 && IF_STMT_CONSTEXPR_P (b->this_entity));
507 /* True if B is the level for the condition of a consteval if. */
509 static bool
510 level_for_consteval_if (cp_binding_level *b)
512 return (b->kind == sk_cond && b->this_entity
513 && TREE_CODE (b->this_entity) == IF_STMT
514 && IF_STMT_CONSTEVAL_P (b->this_entity));
517 /* True if T is a non-static VAR_DECL that has a non-trivial destructor.
518 See [stmt.dcl]/2. */
520 static bool
521 automatic_var_with_nontrivial_dtor_p (const_tree t)
523 if (error_operand_p (t))
524 return false;
526 return (VAR_P (t)
527 && decl_storage_duration (CONST_CAST_TREE (t)) == dk_auto
528 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (t)));
531 /* Update data for defined and undefined labels when leaving a scope. */
534 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
536 named_label_entry *ent = *slot;
537 cp_binding_level *obl = bl->level_chain;
539 if (ent->binding_level == bl)
541 tree decl;
543 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
544 TREE_LISTs representing OVERLOADs, so be careful. */
545 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
546 ? DECL_CHAIN (decl)
547 : TREE_CHAIN (decl)))
548 if (decl_jump_unsafe (decl))
549 vec_safe_push (ent->bad_decls, decl);
551 ent->binding_level = obl;
552 ent->names_in_scope = obl->names;
553 switch (bl->kind)
555 case sk_try:
556 ent->in_try_scope = true;
557 break;
558 case sk_catch:
559 ent->in_catch_scope = true;
560 break;
561 case sk_omp:
562 ent->in_omp_scope = true;
563 break;
564 case sk_transaction:
565 ent->in_transaction_scope = true;
566 break;
567 case sk_stmt_expr:
568 ent->in_stmt_expr = true;
569 break;
570 case sk_block:
571 if (level_for_constexpr_if (bl->level_chain))
572 ent->in_constexpr_if = true;
573 else if (level_for_consteval_if (bl->level_chain))
574 ent->in_consteval_if = true;
575 break;
576 default:
577 break;
580 else if (ent->uses)
582 struct named_label_use_entry *use;
584 for (use = ent->uses; use ; use = use->next)
585 if (use->binding_level == bl)
587 if (auto &cg = use->computed_goto)
589 if (bl->kind == sk_catch)
590 vec_safe_push (cg, get_identifier ("catch"));
591 for (tree d = use->names_in_scope; d; d = DECL_CHAIN (d))
592 if (automatic_var_with_nontrivial_dtor_p (d))
593 vec_safe_push (cg, d);
596 use->binding_level = obl;
597 use->names_in_scope = obl->names;
598 if (bl->kind == sk_omp)
599 use->in_omp_scope = true;
603 return 1;
606 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
607 when errors were reported, except for -Werror-unused-but-set-*. */
608 static int unused_but_set_errorcount;
610 /* Exit a binding level.
611 Pop the level off, and restore the state of the identifier-decl mappings
612 that were in effect when this level was entered.
614 If KEEP == 1, this level had explicit declarations, so
615 and create a "block" (a BLOCK node) for the level
616 to record its declarations and subblocks for symbol table output.
618 If FUNCTIONBODY is nonzero, this level is the body of a function,
619 so create a block as if KEEP were set and also clear out all
620 label names.
622 If REVERSE is nonzero, reverse the order of decls before putting
623 them into the BLOCK. */
625 tree
626 poplevel (int keep, int reverse, int functionbody)
628 tree link;
629 /* The chain of decls was accumulated in reverse order.
630 Put it into forward order, just for cleanliness. */
631 tree decls;
632 tree subblocks;
633 tree block;
634 tree decl;
635 scope_kind kind;
637 auto_cond_timevar tv (TV_NAME_LOOKUP);
638 restart:
640 block = NULL_TREE;
642 gcc_assert (current_binding_level->kind != sk_class
643 && current_binding_level->kind != sk_namespace);
645 if (current_binding_level->kind == sk_cleanup)
646 functionbody = 0;
647 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
649 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
651 /* We used to use KEEP == 2 to indicate that the new block should go
652 at the beginning of the list of blocks at this binding level,
653 rather than the end. This hack is no longer used. */
654 gcc_assert (keep == 0 || keep == 1);
656 if (current_binding_level->keep)
657 keep = 1;
659 /* Any uses of undefined labels, and any defined labels, now operate
660 under constraints of next binding contour. */
661 if (cfun && !functionbody && named_labels)
662 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
663 (current_binding_level);
665 /* Get the decls in the order they were written.
666 Usually current_binding_level->names is in reverse order.
667 But parameter decls were previously put in forward order. */
669 decls = current_binding_level->names;
670 if (reverse)
672 decls = nreverse (decls);
673 current_binding_level->names = decls;
676 /* If there were any declarations or structure tags in that level,
677 or if this level is a function body,
678 create a BLOCK to record them for the life of this function. */
679 block = NULL_TREE;
680 /* Avoid function body block if possible. */
681 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
682 keep = 0;
683 else if (keep == 1 || functionbody)
684 block = make_node (BLOCK);
685 if (block != NULL_TREE)
687 BLOCK_VARS (block) = decls;
688 BLOCK_SUBBLOCKS (block) = subblocks;
691 /* In each subblock, record that this is its superior. */
692 if (keep >= 0)
693 for (link = subblocks; link; link = BLOCK_CHAIN (link))
694 BLOCK_SUPERCONTEXT (link) = block;
696 /* Before we remove the declarations first check for unused variables. */
697 if ((warn_unused_variable || warn_unused_but_set_variable)
698 && current_binding_level->kind != sk_template_parms
699 && !processing_template_decl)
700 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
702 /* There are cases where D itself is a TREE_LIST. See in
703 push_local_binding where the list of decls returned by
704 getdecls is built. */
705 tree udecl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
706 decl = strip_using_decl (udecl);
708 tree type = TREE_TYPE (decl);
709 if (VAR_P (decl)
710 && (!TREE_USED (decl) || !DECL_READ_P (decl))
711 && !DECL_IN_SYSTEM_HEADER (udecl)
712 /* For structured bindings, consider only real variables, not
713 subobjects. */
714 && (DECL_DECOMPOSITION_P (decl) ? DECL_DECOMP_IS_BASE (decl)
715 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
716 /* Don't warn about name-independent declarations. */
717 && !name_independent_decl_p (decl)
718 && type != error_mark_node
719 && (!CLASS_TYPE_P (type)
720 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
721 || lookup_attribute ("warn_unused",
722 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
724 if (!TREE_USED (decl))
726 if (TREE_CODE (udecl) == USING_DECL)
727 warning_at (DECL_SOURCE_LOCATION (udecl),
728 OPT_Wunused_variable,
729 "unused using-declaration %qD", udecl);
730 else if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
731 warning_at (DECL_SOURCE_LOCATION (decl),
732 OPT_Wunused_variable,
733 "unused structured binding declaration");
734 else
735 warning_at (DECL_SOURCE_LOCATION (decl),
736 OPT_Wunused_variable, "unused variable %qD", decl);
737 suppress_warning (decl, OPT_Wunused_variable);
739 else if (DECL_CONTEXT (decl) == current_function_decl
740 // For -Wunused-but-set-variable leave references alone.
741 && !TYPE_REF_P (TREE_TYPE (decl))
742 && errorcount == unused_but_set_errorcount)
744 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
745 warning_at (DECL_SOURCE_LOCATION (decl),
746 OPT_Wunused_but_set_variable, "structured "
747 "binding declaration set but not used");
748 else
749 warning_at (DECL_SOURCE_LOCATION (decl),
750 OPT_Wunused_but_set_variable,
751 "variable %qD set but not used", decl);
752 unused_but_set_errorcount = errorcount;
757 /* Remove declarations for all the DECLs in this level. */
758 for (link = decls; link; link = TREE_CHAIN (link))
760 tree name;
761 if (TREE_CODE (link) == TREE_LIST)
763 decl = TREE_VALUE (link);
764 name = TREE_PURPOSE (link);
765 gcc_checking_assert (name);
767 else
769 decl = link;
770 name = DECL_NAME (decl);
773 /* Remove the binding. */
774 if (TREE_CODE (decl) == LABEL_DECL)
775 pop_local_label (name, decl);
776 else
777 pop_local_binding (name, decl);
780 /* Restore the IDENTIFIER_TYPE_VALUEs. */
781 for (link = current_binding_level->type_shadowed;
782 link; link = TREE_CHAIN (link))
783 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
785 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
786 list if a `using' declaration put them there. The debugging
787 back ends won't understand OVERLOAD, so we remove them here.
788 Because the BLOCK_VARS are (temporarily) shared with
789 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
790 popped all the bindings. Also remove undeduced 'auto' decls,
791 which LTO doesn't understand, and can't have been used by anything. */
792 if (block)
794 tree* d;
796 for (d = &BLOCK_VARS (block); *d; )
798 if (TREE_CODE (*d) == TREE_LIST
799 || (!processing_template_decl
800 && undeduced_auto_decl (*d)))
801 *d = TREE_CHAIN (*d);
802 else
803 d = &DECL_CHAIN (*d);
807 /* If the level being exited is the top level of a function,
808 check over all the labels. */
809 if (functionbody)
811 if (block)
813 /* Since this is the top level block of a function, the vars are
814 the function's parameters. Don't leave them in the BLOCK
815 because they are found in the FUNCTION_DECL instead. */
816 BLOCK_VARS (block) = 0;
817 pop_labels (block);
819 else
820 pop_labels (subblocks);
823 kind = current_binding_level->kind;
824 if (kind == sk_cleanup)
826 tree stmt;
828 /* If this is a temporary binding created for a cleanup, then we'll
829 have pushed a statement list level. Pop that, create a new
830 BIND_EXPR for the block, and insert it into the stream. */
831 stmt = pop_stmt_list (current_binding_level->statement_list);
832 stmt = c_build_bind_expr (input_location, block, stmt);
833 add_stmt (stmt);
836 leave_scope ();
837 if (functionbody)
839 /* The current function is being defined, so its DECL_INITIAL
840 should be error_mark_node. */
841 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
842 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
843 if (subblocks)
845 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
847 if (BLOCK_SUBBLOCKS (subblocks))
848 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
850 else
851 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
854 else if (block)
855 current_binding_level->blocks
856 = block_chainon (current_binding_level->blocks, block);
858 /* If we did not make a block for the level just exited,
859 any blocks made for inner levels
860 (since they cannot be recorded as subblocks in that level)
861 must be carried forward so they will later become subblocks
862 of something else. */
863 else if (subblocks)
864 current_binding_level->blocks
865 = block_chainon (current_binding_level->blocks, subblocks);
867 /* Each and every BLOCK node created here in `poplevel' is important
868 (e.g. for proper debugging information) so if we created one
869 earlier, mark it as "used". */
870 if (block)
871 TREE_USED (block) = 1;
873 /* All temporary bindings created for cleanups are popped silently. */
874 if (kind == sk_cleanup)
875 goto restart;
877 return block;
880 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
881 /* Diagnose odr-used extern inline variables without definitions
882 in the current TU. */
885 wrapup_namespace_globals ()
887 if (vec<tree, va_gc> *statics = static_decls)
889 for (tree decl : *statics)
891 if (warn_unused_function
892 && TREE_CODE (decl) == FUNCTION_DECL
893 && DECL_INITIAL (decl) == 0
894 && DECL_EXTERNAL (decl)
895 && !TREE_PUBLIC (decl)
896 && !DECL_ARTIFICIAL (decl)
897 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
898 && !warning_suppressed_p (decl, OPT_Wunused_function))
899 warning_at (DECL_SOURCE_LOCATION (decl),
900 OPT_Wunused_function,
901 "%qF declared %<static%> but never defined", decl);
903 if (VAR_P (decl)
904 && DECL_EXTERNAL (decl)
905 && DECL_INLINE_VAR_P (decl)
906 && DECL_ODR_USED (decl))
907 error_at (DECL_SOURCE_LOCATION (decl),
908 "odr-used inline variable %qD is not defined", decl);
911 /* Clear out the list, so we don't rescan next time. */
912 static_decls = NULL;
914 /* Write out any globals that need to be output. */
915 return wrapup_global_declarations (statics->address (),
916 statics->length ());
918 return 0;
921 /* In C++, you don't have to write `struct S' to refer to `S'; you
922 can just use `S'. We accomplish this by creating a TYPE_DECL as
923 if the user had written `typedef struct S S'. Create and return
924 the TYPE_DECL for TYPE. */
926 tree
927 create_implicit_typedef (tree name, tree type)
929 tree decl;
931 decl = build_decl (input_location, TYPE_DECL, name, type);
932 DECL_ARTIFICIAL (decl) = 1;
933 /* There are other implicit type declarations, like the one *within*
934 a class that allows you to write `S::S'. We must distinguish
935 amongst these. */
936 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
937 TYPE_NAME (type) = decl;
938 TYPE_STUB_DECL (type) = decl;
940 return decl;
943 /* Function-scope local entities that need discriminators. Each entry
944 is a {decl,name} pair. VAR_DECLs for anon unions get their name
945 smashed, so we cannot rely on DECL_NAME. */
947 static GTY((deletable)) vec<tree, va_gc> *local_entities;
949 /* Determine the mangling discriminator of local DECL. There are
950 generally very few of these in any particular function. */
952 void
953 determine_local_discriminator (tree decl, tree name)
955 auto_cond_timevar tv (TV_NAME_LOOKUP);
956 retrofit_lang_decl (decl);
957 tree ctx = DECL_CONTEXT (decl);
958 size_t nelts = vec_safe_length (local_entities);
959 if (name == NULL_TREE)
960 name = (TREE_CODE (decl) == TYPE_DECL
961 && TYPE_UNNAMED_P (TREE_TYPE (decl))
962 ? NULL_TREE : DECL_NAME (decl));
963 for (size_t i = 0; i < nelts; i += 2)
965 tree *pair = &(*local_entities)[i];
966 tree d = pair[0];
967 tree n = pair[1];
968 gcc_checking_assert (d != decl);
969 if (name == n
970 && TREE_CODE (decl) == TREE_CODE (d)
971 && ctx == DECL_CONTEXT (d))
973 tree disc = integer_one_node;
974 if (DECL_DISCRIMINATOR (d))
975 disc = build_int_cst (TREE_TYPE (disc),
976 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
977 DECL_DISCRIMINATOR (decl) = disc;
978 /* Replace the saved decl. */
979 pair[0] = decl;
980 decl = NULL_TREE;
981 break;
985 if (decl)
987 vec_safe_reserve (local_entities, 2);
988 local_entities->quick_push (decl);
989 local_entities->quick_push (name);
994 /* True if DECL is a constrained hidden friend as per [temp.friend]/9:
996 A non-template friend declaration with a requires-clause shall be a
997 definition. A friend function template with a constraint that depends on a
998 template parameter from an enclosing template shall be a definition. Such a
999 constrained friend function or function template declaration does not
1000 declare the same function or function template as a declaration in any other
1001 scope.
1003 The ABI calls this a "member-like constrained friend" and mangles it like a
1004 member function to avoid collisions. */
1006 bool
1007 member_like_constrained_friend_p (tree decl)
1009 return (TREE_CODE (decl) == FUNCTION_DECL
1010 && DECL_UNIQUE_FRIEND_P (decl)
1011 && DECL_FRIEND_CONTEXT (decl)
1012 && get_constraints (decl)
1013 && (!DECL_TEMPLATE_INFO (decl)
1014 || !PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
1015 || (uses_outer_template_parms_in_constraints
1016 (most_general_template (decl)))));
1019 /* Returns true if functions FN1 and FN2 have equivalent trailing
1020 requires clauses. */
1022 static bool
1023 function_requirements_equivalent_p (tree newfn, tree oldfn)
1025 /* [temp.friend]/9 "Such a constrained friend function does not declare the
1026 same function as a declaration in any other scope." So no need to
1027 actually compare the requirements. */
1028 if (member_like_constrained_friend_p (newfn)
1029 || member_like_constrained_friend_p (oldfn))
1030 return false;
1032 /* Compare only trailing requirements. */
1033 tree reqs1 = get_trailing_function_requirements (newfn);
1034 tree reqs2 = get_trailing_function_requirements (oldfn);
1035 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
1036 return false;
1038 /* Substitution is needed when friends are involved. */
1039 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
1040 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
1042 return cp_tree_equal (reqs1, reqs2);
1045 /* Two functions of the same name correspond [basic.scope.scope] if
1047 + both declare functions with the same non-object-parameter-type-list,
1048 equivalent ([temp.over.link]) trailing requires-clauses (if any, except as
1049 specified in [temp.friend]), and, if both are non-static members, they have
1050 corresponding object parameters, or
1052 + both declare function templates with equivalent
1053 non-object-parameter-type-lists, return types (if any), template-heads, and
1054 trailing requires-clauses (if any), and, if both are non-static members,
1055 they have corresponding object parameters.
1057 This is a subset of decls_match: it identifies declarations that cannot be
1058 overloaded with one another. This function does not consider DECL_NAME. */
1060 bool
1061 fns_correspond (tree newdecl, tree olddecl)
1063 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1064 return false;
1066 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1068 if (!template_heads_equivalent_p (newdecl, olddecl))
1069 return 0;
1070 newdecl = DECL_TEMPLATE_RESULT (newdecl);
1071 olddecl = DECL_TEMPLATE_RESULT (olddecl);
1074 tree f1 = TREE_TYPE (newdecl);
1075 tree f2 = TREE_TYPE (olddecl);
1077 int rq1 = type_memfn_rqual (f1);
1078 int rq2 = type_memfn_rqual (f2);
1080 /* If only one is a non-static member function, ignore ref-quals. */
1081 if (TREE_CODE (f1) != TREE_CODE (f2))
1082 rq1 = rq2;
1083 /* Two non-static member functions have corresponding object parameters if:
1084 + exactly one is an implicit object member function with no ref-qualifier
1085 and the types of their object parameters ([dcl.fct]), after removing
1086 top-level references, are the same, or
1087 + their object parameters have the same type. */
1088 /* ??? We treat member functions of different classes as corresponding even
1089 though that means the object parameters have different types. */
1090 else if ((rq1 == REF_QUAL_NONE) != (rq2 == REF_QUAL_NONE))
1091 rq1 = rq2;
1093 bool types_match = rq1 == rq2;
1095 if (types_match)
1097 tree p1 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1098 tree p2 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1099 types_match = compparms (p1, p2);
1102 /* Two function declarations match if either has a requires-clause
1103 then both have a requires-clause and their constraints-expressions
1104 are equivalent. */
1105 if (types_match && flag_concepts)
1106 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1108 return types_match;
1111 /* Subroutine of duplicate_decls: return truthvalue of whether
1112 or not types of these decls match.
1114 For C++, we must compare the parameter list so that `int' can match
1115 `int&' in a parameter position, but `int&' is not confused with
1116 `const int&'. */
1119 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
1121 int types_match;
1123 if (newdecl == olddecl)
1124 return 1;
1126 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1127 /* If the two DECLs are not even the same kind of thing, we're not
1128 interested in their types. */
1129 return 0;
1131 gcc_assert (DECL_P (newdecl));
1133 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1135 /* Specializations of different templates are different functions
1136 even if they have the same type. */
1137 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1138 ? DECL_TI_TEMPLATE (newdecl)
1139 : NULL_TREE);
1140 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1141 ? DECL_TI_TEMPLATE (olddecl)
1142 : NULL_TREE);
1143 if (t1 != t2)
1144 return 0;
1146 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1147 && ! (DECL_EXTERN_C_P (newdecl)
1148 && DECL_EXTERN_C_P (olddecl)))
1149 return 0;
1151 /* A new declaration doesn't match a built-in one unless it
1152 is also extern "C". */
1153 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1154 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1155 return 0;
1157 tree f1 = TREE_TYPE (newdecl);
1158 tree f2 = TREE_TYPE (olddecl);
1159 if (TREE_CODE (f1) != TREE_CODE (f2))
1160 return 0;
1162 /* A declaration with deduced return type should use its pre-deduction
1163 type for declaration matching. */
1164 tree r2 = fndecl_declared_return_type (olddecl);
1165 tree r1 = fndecl_declared_return_type (newdecl);
1167 /* For memchr et al, allow const void* return type (as specified by C++)
1168 when we expect void* (as in C). */
1169 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1170 && DECL_EXTERN_C_P (olddecl)
1171 && !same_type_p (r1, r2)
1172 && TREE_CODE (r1) == POINTER_TYPE
1173 && TREE_CODE (r2) == POINTER_TYPE
1174 && comp_ptr_ttypes (TREE_TYPE (r1), TREE_TYPE (r2)))
1175 r2 = r1;
1177 tree p1 = TYPE_ARG_TYPES (f1);
1178 tree p2 = TYPE_ARG_TYPES (f2);
1180 if (same_type_p (r1, r2))
1182 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1183 && fndecl_built_in_p (olddecl))
1185 types_match = self_promoting_args_p (p1);
1186 if (p1 == void_list_node)
1187 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1189 else
1190 types_match =
1191 compparms (p1, p2)
1192 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1193 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1194 || comp_type_attributes (TREE_TYPE (newdecl),
1195 TREE_TYPE (olddecl)) != 0);
1197 else
1198 types_match = 0;
1200 /* Two function declarations match if either has a requires-clause
1201 then both have a requires-clause and their constraints-expressions
1202 are equivalent. */
1203 if (types_match && flag_concepts)
1204 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1206 /* The decls dont match if they correspond to two different versions
1207 of the same function. Disallow extern "C" functions to be
1208 versions for now. */
1209 if (types_match
1210 && !DECL_EXTERN_C_P (newdecl)
1211 && !DECL_EXTERN_C_P (olddecl)
1212 && targetm.target_option.function_versions (newdecl, olddecl))
1214 if (record_versions)
1215 maybe_version_functions (newdecl, olddecl,
1216 (!DECL_FUNCTION_VERSIONED (newdecl)
1217 || !DECL_FUNCTION_VERSIONED (olddecl)));
1218 return 0;
1221 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1223 if (!template_heads_equivalent_p (newdecl, olddecl))
1224 return 0;
1226 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1227 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1229 if (TREE_CODE (newres) != TREE_CODE (oldres))
1230 return 0;
1232 /* Two template types match if they are the same. Otherwise, compare
1233 the underlying declarations. */
1234 if (TREE_CODE (newres) == TYPE_DECL)
1235 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1236 else
1237 types_match = decls_match (newres, oldres);
1239 else
1241 /* Need to check scope for variable declaration (VAR_DECL).
1242 For typedef (TYPE_DECL), scope is ignored. */
1243 if (VAR_P (newdecl)
1244 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1245 /* [dcl.link]
1246 Two declarations for an object with C language linkage
1247 with the same name (ignoring the namespace that qualify
1248 it) that appear in different namespace scopes refer to
1249 the same object. */
1250 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1251 return 0;
1253 if (TREE_TYPE (newdecl) == error_mark_node)
1254 types_match = TREE_TYPE (olddecl) == error_mark_node;
1255 else if (TREE_TYPE (olddecl) == NULL_TREE)
1256 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1257 else if (TREE_TYPE (newdecl) == NULL_TREE)
1258 types_match = 0;
1259 else
1260 types_match = comptypes (TREE_TYPE (newdecl),
1261 TREE_TYPE (olddecl),
1262 COMPARE_REDECLARATION);
1265 return types_match;
1268 /* Mark DECL as versioned if it isn't already. */
1270 static void
1271 maybe_mark_function_versioned (tree decl)
1273 if (!DECL_FUNCTION_VERSIONED (decl))
1275 DECL_FUNCTION_VERSIONED (decl) = 1;
1276 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1277 to include the version marker. */
1278 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1279 mangle_decl (decl);
1283 /* NEWDECL and OLDDECL have identical signatures. If they are
1284 different versions adjust them and return true.
1285 If RECORD is set to true, record function versions. */
1287 bool
1288 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1290 if (!targetm.target_option.function_versions (newdecl, olddecl))
1291 return false;
1293 maybe_mark_function_versioned (olddecl);
1294 if (DECL_LOCAL_DECL_P (olddecl))
1296 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1297 maybe_mark_function_versioned (olddecl);
1300 maybe_mark_function_versioned (newdecl);
1301 if (DECL_LOCAL_DECL_P (newdecl))
1303 /* Unfortunately, we can get here before pushdecl naturally calls
1304 push_local_extern_decl_alias, so we need to call it directly. */
1305 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1306 push_local_extern_decl_alias (newdecl);
1307 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1308 maybe_mark_function_versioned (newdecl);
1311 if (record)
1312 cgraph_node::record_function_versions (olddecl, newdecl);
1314 return true;
1317 /* If NEWDECL is `static' and an `extern' was seen previously,
1318 warn about it. OLDDECL is the previous declaration.
1320 Note that this does not apply to the C++ case of declaring
1321 a variable `extern const' and then later `const'.
1323 Don't complain about built-in functions, since they are beyond
1324 the user's control. */
1326 void
1327 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1329 if (TREE_CODE (newdecl) == TYPE_DECL
1330 || TREE_CODE (newdecl) == TEMPLATE_DECL
1331 || TREE_CODE (newdecl) == CONST_DECL
1332 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1333 return;
1335 /* Don't get confused by static member functions; that's a different
1336 use of `static'. */
1337 if (TREE_CODE (newdecl) == FUNCTION_DECL
1338 && DECL_STATIC_FUNCTION_P (newdecl))
1339 return;
1341 /* If the old declaration was `static', or the new one isn't, then
1342 everything is OK. */
1343 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1344 return;
1346 /* It's OK to declare a builtin function as `static'. */
1347 if (TREE_CODE (olddecl) == FUNCTION_DECL
1348 && DECL_ARTIFICIAL (olddecl))
1349 return;
1351 auto_diagnostic_group d;
1352 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1353 "%qD was declared %<extern%> and later %<static%>", newdecl))
1354 inform (DECL_SOURCE_LOCATION (olddecl),
1355 "previous declaration of %qD", olddecl);
1358 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1359 function templates. If their exception specifications do not
1360 match, issue a diagnostic. */
1362 static void
1363 check_redeclaration_exception_specification (tree new_decl,
1364 tree old_decl)
1366 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1367 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1369 /* Two default specs are equivalent, don't force evaluation. */
1370 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1371 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1372 return;
1374 if (!type_dependent_expression_p (old_decl))
1376 maybe_instantiate_noexcept (new_decl);
1377 maybe_instantiate_noexcept (old_decl);
1379 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1380 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1382 /* [except.spec]
1384 If any declaration of a function has an exception-specification,
1385 all declarations, including the definition and an explicit
1386 specialization, of that function shall have an
1387 exception-specification with the same set of type-ids. */
1388 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1389 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1390 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1392 const char *const msg
1393 = G_("declaration of %qF has a different exception specifier");
1394 bool complained = true;
1395 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1396 auto_diagnostic_group d;
1397 if (DECL_IN_SYSTEM_HEADER (old_decl))
1398 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1399 else if (!flag_exceptions)
1400 /* We used to silently permit mismatched eh specs with
1401 -fno-exceptions, so make them a pedwarn now. */
1402 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1403 else
1404 error_at (new_loc, msg, new_decl);
1405 if (complained)
1406 inform (DECL_SOURCE_LOCATION (old_decl),
1407 "from previous declaration %qF", old_decl);
1411 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1412 Otherwise issue diagnostics. */
1414 static bool
1415 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1417 old_decl = STRIP_TEMPLATE (old_decl);
1418 new_decl = STRIP_TEMPLATE (new_decl);
1419 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1420 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1421 return true;
1422 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1423 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1425 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1426 return true;
1427 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1428 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1429 return true;
1431 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1433 /* With -fimplicit-constexpr, ignore changes in the constexpr
1434 keyword. */
1435 if (flag_implicit_constexpr
1436 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1437 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1438 return true;
1439 if (fndecl_built_in_p (old_decl))
1441 /* Hide a built-in declaration. */
1442 DECL_DECLARED_CONSTEXPR_P (old_decl)
1443 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1444 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1445 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1446 return true;
1448 /* 7.1.5 [dcl.constexpr]
1449 Note: An explicit specialization can differ from the template
1450 declaration with respect to the constexpr specifier. */
1451 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1452 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1453 return true;
1455 const char *kind = "constexpr";
1456 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1457 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1458 kind = "consteval";
1459 error_at (DECL_SOURCE_LOCATION (new_decl),
1460 "redeclaration %qD differs in %qs "
1461 "from previous declaration", new_decl,
1462 kind);
1463 inform (DECL_SOURCE_LOCATION (old_decl),
1464 "previous declaration %qD", old_decl);
1465 return false;
1467 return true;
1470 // If OLDDECL and NEWDECL are concept declarations with the same type
1471 // (i.e., and template parameters), but different requirements,
1472 // emit diagnostics and return true. Otherwise, return false.
1473 static inline bool
1474 check_concept_refinement (tree olddecl, tree newdecl)
1476 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1477 return false;
1479 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1480 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1481 if (TREE_CODE (d1) != TREE_CODE (d2))
1482 return false;
1484 tree t1 = TREE_TYPE (d1);
1485 tree t2 = TREE_TYPE (d2);
1486 if (TREE_CODE (d1) == FUNCTION_DECL)
1488 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1489 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1490 DECL_TEMPLATE_PARMS (newdecl))
1491 && !equivalently_constrained (olddecl, newdecl))
1493 error ("cannot specialize concept %q#D", olddecl);
1494 return true;
1497 return false;
1500 /* DECL is a redeclaration of a function or function template. If
1501 it does have default arguments issue a diagnostic. Note: this
1502 function is used to enforce the requirements in C++11 8.3.6 about
1503 no default arguments in redeclarations. */
1505 static void
1506 check_redeclaration_no_default_args (tree decl)
1508 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1510 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1511 t && t != void_list_node; t = TREE_CHAIN (t))
1512 if (TREE_PURPOSE (t))
1514 permerror (DECL_SOURCE_LOCATION (decl),
1515 "redeclaration of %q#D may not have default "
1516 "arguments", decl);
1517 return;
1521 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1522 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1523 the TEMPLATE_DECLs in case of function templates). This function is used
1524 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1525 "If a friend declaration specifies a default argument expression, that
1526 declaration shall be a definition and shall be the only declaration of
1527 the function or function template in the translation unit." */
1529 static void
1530 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1532 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1533 return;
1535 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1536 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1537 t1 && t1 != void_list_node;
1538 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1539 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1540 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1542 auto_diagnostic_group d;
1543 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1544 "friend declaration of %q#D specifies default "
1545 "arguments and isn%'t the only declaration", newdecl))
1546 inform (DECL_SOURCE_LOCATION (olddecl),
1547 "previous declaration of %q#D", olddecl);
1548 return;
1552 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1553 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1555 static void
1556 merge_attribute_bits (tree newdecl, tree olddecl)
1558 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1559 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1560 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1561 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1562 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1563 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1564 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1565 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1566 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1567 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1568 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1569 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1570 TREE_DEPRECATED (newdecl) |= TREE_DEPRECATED (olddecl);
1571 TREE_DEPRECATED (olddecl) |= TREE_DEPRECATED (newdecl);
1572 TREE_UNAVAILABLE (newdecl) |= TREE_UNAVAILABLE (olddecl);
1573 TREE_UNAVAILABLE (olddecl) |= TREE_UNAVAILABLE (newdecl);
1576 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1577 && lookup_attribute ("gnu_inline", \
1578 DECL_ATTRIBUTES (fn)))
1580 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1581 ambiguates olddecl. Returns true if an error occurs. */
1583 static bool
1584 duplicate_function_template_decls (tree newdecl, tree olddecl)
1586 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1587 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1588 /* Function template declarations can be differentiated by parameter
1589 and return type. */
1590 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1591 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1592 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1593 TREE_TYPE (TREE_TYPE (olddecl))))
1595 /* ... and also by their template-heads and requires-clauses. */
1596 if (template_heads_equivalent_p (newdecl, olddecl)
1597 && function_requirements_equivalent_p (newres, oldres))
1599 error ("ambiguating new declaration %q+#D", newdecl);
1600 inform (DECL_SOURCE_LOCATION (olddecl),
1601 "old declaration %q#D", olddecl);
1602 return true;
1605 /* FIXME: The types are the same but the are differences
1606 in either the template heads or function requirements.
1607 We should be able to diagnose a set of common errors
1608 stemming from these declarations. For example:
1610 template<typename T> requires C void f(...);
1611 template<typename T> void f(...) requires C;
1613 These are functionally equivalent but not equivalent. */
1616 return false;
1619 /* OLD_PARMS is the innermost set of template parameters for some template
1620 declaration, and NEW_PARMS is the corresponding set of template parameters
1621 for a redeclaration of that template. Merge the default arguments within
1622 these two sets of parameters. CLASS_P is true iff the template in
1623 question is a class template. */
1625 bool
1626 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1628 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1629 == TREE_VEC_LENGTH (old_parms));
1630 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1632 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1633 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1634 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1635 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1636 if (error_operand_p (new_parm) || error_operand_p (old_parm))
1637 return false;
1638 if (new_default != NULL_TREE && old_default != NULL_TREE)
1640 auto_diagnostic_group d;
1641 error ("redefinition of default argument for %q+#D", new_parm);
1642 inform (DECL_SOURCE_LOCATION (old_parm),
1643 "original definition appeared here");
1644 return false;
1646 else if (new_default != NULL_TREE)
1647 /* Update the previous template parameters (which are the ones
1648 that will really count) with the new default value. */
1649 old_default = new_default;
1650 else if (class_p && old_default != NULL_TREE)
1651 /* Update the new parameters, too; they'll be used as the
1652 parameters for any members. */
1653 new_default = old_default;
1655 return true;
1658 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1659 If the redeclaration is invalid, a diagnostic is issued, and the
1660 error_mark_node is returned. Otherwise, OLDDECL is returned.
1662 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1663 returned.
1665 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1666 if the old decl was hidden.
1668 Hidden decls can be anticipated builtins, injected friends, or
1669 (coming soon) injected from a local-extern decl. */
1671 tree
1672 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1674 unsigned olddecl_uid = DECL_UID (olddecl);
1675 int types_match = 0;
1676 int new_defines_function = 0;
1677 tree new_template_info;
1678 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1679 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1681 if (newdecl == olddecl)
1682 return olddecl;
1684 types_match = decls_match (newdecl, olddecl);
1686 /* If either the type of the new decl or the type of the old decl is an
1687 error_mark_node, then that implies that we have already issued an
1688 error (earlier) for some bogus type specification, and in that case,
1689 it is rather pointless to harass the user with yet more error message
1690 about the same declaration, so just pretend the types match here. */
1691 if (TREE_TYPE (newdecl) == error_mark_node
1692 || TREE_TYPE (olddecl) == error_mark_node)
1693 return error_mark_node;
1695 /* Check for redeclaration and other discrepancies. */
1696 if (TREE_CODE (olddecl) == FUNCTION_DECL
1697 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1699 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1701 /* Avoid warnings redeclaring built-ins which have not been
1702 explicitly declared. */
1703 if (was_hidden)
1705 if (TREE_PUBLIC (newdecl)
1706 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1707 warning_at (newdecl_loc,
1708 OPT_Wbuiltin_declaration_mismatch,
1709 "built-in function %qD declared as non-function",
1710 newdecl);
1711 return NULL_TREE;
1714 /* If you declare a built-in or predefined function name as static,
1715 the old definition is overridden, but optionally warn this was a
1716 bad choice of name. */
1717 if (! TREE_PUBLIC (newdecl))
1719 warning_at (newdecl_loc,
1720 OPT_Wshadow,
1721 fndecl_built_in_p (olddecl)
1722 ? G_("shadowing built-in function %q#D")
1723 : G_("shadowing library function %q#D"), olddecl);
1724 /* Discard the old built-in function. */
1725 return NULL_TREE;
1727 /* If the built-in is not ansi, then programs can override
1728 it even globally without an error. */
1729 else if (! fndecl_built_in_p (olddecl))
1730 warning_at (newdecl_loc, 0,
1731 "library function %q#D redeclared as non-function %q#D",
1732 olddecl, newdecl);
1733 else
1734 error_at (newdecl_loc,
1735 "declaration of %q#D conflicts with built-in "
1736 "declaration %q#D", newdecl, olddecl);
1737 return NULL_TREE;
1739 else if (!types_match)
1741 /* Avoid warnings redeclaring built-ins which have not been
1742 explicitly declared. */
1743 if (was_hidden)
1745 tree t1, t2;
1747 /* A new declaration doesn't match a built-in one unless it
1748 is also extern "C". */
1749 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1750 gcc_assert (DECL_EXTERN_C_P (olddecl));
1751 if (!DECL_EXTERN_C_P (newdecl))
1752 return NULL_TREE;
1754 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1755 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1756 t1 || t2;
1757 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1759 if (!t1 || !t2)
1760 break;
1761 /* FILE, tm types are not known at the time
1762 we create the builtins. */
1763 for (unsigned i = 0;
1764 i < sizeof (builtin_structptr_types)
1765 / sizeof (builtin_structptr_type);
1766 ++i)
1767 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1769 tree t = TREE_VALUE (t1);
1771 if (TYPE_PTR_P (t)
1772 && TYPE_IDENTIFIER (TREE_TYPE (t))
1773 == get_identifier (builtin_structptr_types[i].str)
1774 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1776 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1778 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1779 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1780 types_match = decls_match (newdecl, olddecl);
1781 if (types_match)
1782 return duplicate_decls (newdecl, olddecl,
1783 hiding, was_hidden);
1784 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1786 goto next_arg;
1789 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1790 break;
1791 next_arg:;
1794 warning_at (newdecl_loc,
1795 OPT_Wbuiltin_declaration_mismatch,
1796 "declaration of %q#D conflicts with built-in "
1797 "declaration %q#D", newdecl, olddecl);
1799 else if ((DECL_EXTERN_C_P (newdecl)
1800 && DECL_EXTERN_C_P (olddecl))
1801 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1802 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1804 /* Don't really override olddecl for __* prefixed builtins
1805 except for __[^b]*_chk, the compiler might be using those
1806 explicitly. */
1807 if (fndecl_built_in_p (olddecl))
1809 tree id = DECL_NAME (olddecl);
1810 const char *name = IDENTIFIER_POINTER (id);
1811 size_t len;
1813 if (name[0] == '_'
1814 && name[1] == '_'
1815 && (startswith (name + 2, "builtin_")
1816 || (len = strlen (name)) <= strlen ("___chk")
1817 || memcmp (name + len - strlen ("_chk"),
1818 "_chk", strlen ("_chk") + 1) != 0))
1820 if (DECL_INITIAL (newdecl))
1822 error_at (newdecl_loc,
1823 "definition of %q#D ambiguates built-in "
1824 "declaration %q#D", newdecl, olddecl);
1825 return error_mark_node;
1827 auto_diagnostic_group d;
1828 if (permerror (newdecl_loc,
1829 "new declaration %q#D ambiguates built-in"
1830 " declaration %q#D", newdecl, olddecl)
1831 && flag_permissive)
1832 inform (newdecl_loc,
1833 "ignoring the %q#D declaration", newdecl);
1834 return flag_permissive ? olddecl : error_mark_node;
1838 /* A near match; override the builtin. */
1840 if (TREE_PUBLIC (newdecl))
1841 warning_at (newdecl_loc,
1842 OPT_Wbuiltin_declaration_mismatch,
1843 "new declaration %q#D ambiguates built-in "
1844 "declaration %q#D", newdecl, olddecl);
1845 else
1846 warning (OPT_Wshadow,
1847 fndecl_built_in_p (olddecl)
1848 ? G_("shadowing built-in function %q#D")
1849 : G_("shadowing library function %q#D"), olddecl);
1851 else
1852 /* Discard the old built-in function. */
1853 return NULL_TREE;
1855 /* Replace the old RTL to avoid problems with inlining. */
1856 COPY_DECL_RTL (newdecl, olddecl);
1858 else
1860 /* Even if the types match, prefer the new declarations type
1861 for built-ins which have not been explicitly declared,
1862 for exception lists, etc... */
1863 tree type = TREE_TYPE (newdecl);
1864 tree attribs = (*targetm.merge_type_attributes)
1865 (TREE_TYPE (olddecl), type);
1867 type = cp_build_type_attribute_variant (type, attribs);
1868 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1871 /* If a function is explicitly declared "throw ()", propagate that to
1872 the corresponding builtin. */
1873 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1874 && was_hidden
1875 && TREE_NOTHROW (newdecl)
1876 && !TREE_NOTHROW (olddecl))
1878 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1879 tree tmpdecl = builtin_decl_explicit (fncode);
1880 if (tmpdecl && tmpdecl != olddecl && types_match)
1881 TREE_NOTHROW (tmpdecl) = 1;
1884 /* Whether or not the builtin can throw exceptions has no
1885 bearing on this declarator. */
1886 TREE_NOTHROW (olddecl) = 0;
1888 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1890 /* If a builtin function is redeclared as `static', merge
1891 the declarations, but make the original one static. */
1892 DECL_THIS_STATIC (olddecl) = 1;
1893 TREE_PUBLIC (olddecl) = 0;
1895 /* Make the old declaration consistent with the new one so
1896 that all remnants of the builtin-ness of this function
1897 will be banished. */
1898 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1899 COPY_DECL_RTL (newdecl, olddecl);
1902 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1904 /* C++ Standard, 3.3, clause 4:
1905 "[Note: a namespace name or a class template name must be unique
1906 in its declarative region (7.3.2, clause 14). ]" */
1907 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1908 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1909 /* Namespace conflicts with not namespace. */;
1910 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1911 || DECL_TYPE_TEMPLATE_P (newdecl))
1912 /* Class template conflicts. */;
1913 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1914 && DECL_TEMPLATE_RESULT (olddecl)
1915 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1916 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1917 && DECL_TEMPLATE_RESULT (newdecl)
1918 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1919 /* Variable template conflicts. */;
1920 else if (concept_definition_p (olddecl)
1921 || concept_definition_p (newdecl))
1922 /* Concept conflicts. */;
1923 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1924 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1925 || (TREE_CODE (olddecl) == FUNCTION_DECL
1926 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1928 /* One is a function and the other is a template
1929 function. */
1930 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1931 return NULL_TREE;
1933 /* There can only be one! */
1934 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1935 && check_raw_literal_operator (olddecl))
1936 error_at (newdecl_loc,
1937 "literal operator %q#D conflicts with"
1938 " raw literal operator", newdecl);
1939 else if (check_raw_literal_operator (newdecl))
1940 error_at (newdecl_loc,
1941 "raw literal operator %q#D conflicts with"
1942 " literal operator template", newdecl);
1943 else
1944 return NULL_TREE;
1946 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1947 return error_mark_node;
1949 else if (DECL_DECOMPOSITION_P (olddecl) || DECL_DECOMPOSITION_P (newdecl))
1950 /* A structured binding must be unique in its declarative region. */;
1951 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1952 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1953 /* One is an implicit typedef, that's ok. */
1954 return NULL_TREE;
1956 error ("%q#D redeclared as different kind of entity", newdecl);
1957 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1959 return error_mark_node;
1961 else if (!types_match)
1963 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1964 /* These are certainly not duplicate declarations; they're
1965 from different scopes. */
1966 return NULL_TREE;
1968 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1970 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1971 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1973 /* The name of a class template may not be declared to refer to
1974 any other template, class, function, object, namespace, value,
1975 or type in the same scope. */
1976 if (TREE_CODE (oldres) == TYPE_DECL
1977 || TREE_CODE (newres) == TYPE_DECL)
1979 error_at (newdecl_loc,
1980 "conflicting declaration of template %q#D", newdecl);
1981 inform (olddecl_loc,
1982 "previous declaration %q#D", olddecl);
1983 return error_mark_node;
1986 else if (TREE_CODE (oldres) == FUNCTION_DECL
1987 && TREE_CODE (newres) == FUNCTION_DECL)
1989 if (duplicate_function_template_decls (newdecl, olddecl))
1990 return error_mark_node;
1991 return NULL_TREE;
1993 else if (check_concept_refinement (olddecl, newdecl))
1994 return error_mark_node;
1995 return NULL_TREE;
1997 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1999 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
2001 error_at (newdecl_loc,
2002 "conflicting declaration of C function %q#D",
2003 newdecl);
2004 inform (olddecl_loc,
2005 "previous declaration %q#D", olddecl);
2006 return error_mark_node;
2008 /* For function versions, params and types match, but they
2009 are not ambiguous. */
2010 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
2011 && !DECL_FUNCTION_VERSIONED (olddecl))
2012 /* Let constrained hidden friends coexist for now, we'll
2013 check satisfaction later. */
2014 && !member_like_constrained_friend_p (newdecl)
2015 && !member_like_constrained_friend_p (olddecl)
2016 // The functions have the same parameter types.
2017 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
2018 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
2019 // And the same constraints.
2020 && equivalently_constrained (newdecl, olddecl))
2022 error_at (newdecl_loc,
2023 "ambiguating new declaration of %q#D", newdecl);
2024 inform (olddecl_loc,
2025 "old declaration %q#D", olddecl);
2026 return error_mark_node;
2028 else
2029 return NULL_TREE;
2031 else
2033 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
2034 inform (olddecl_loc,
2035 "previous declaration as %q#D", olddecl);
2036 return error_mark_node;
2039 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2040 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
2042 /* OMP UDRs are never duplicates. */
2043 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
2044 error_at (newdecl_loc,
2045 "redeclaration of %<pragma omp declare reduction%>");
2046 inform (olddecl_loc,
2047 "previous %<pragma omp declare reduction%> declaration");
2048 return error_mark_node;
2050 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2051 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
2052 && (!DECL_TEMPLATE_INFO (newdecl)
2053 || (DECL_TI_TEMPLATE (newdecl)
2054 != DECL_TI_TEMPLATE (olddecl))))
2055 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
2056 && (!DECL_TEMPLATE_INFO (olddecl)
2057 || (DECL_TI_TEMPLATE (olddecl)
2058 != DECL_TI_TEMPLATE (newdecl))))))
2059 /* It's OK to have a template specialization and a non-template
2060 with the same type, or to have specializations of two
2061 different templates with the same type. Note that if one is a
2062 specialization, and the other is an instantiation of the same
2063 template, that we do not exit at this point. That situation
2064 can occur if we instantiate a template class, and then
2065 specialize one of its methods. This situation is valid, but
2066 the declarations must be merged in the usual way. */
2067 return NULL_TREE;
2068 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2069 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
2070 && !DECL_USE_TEMPLATE (newdecl))
2071 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
2072 && !DECL_USE_TEMPLATE (olddecl))))
2073 /* One of the declarations is a template instantiation, and the
2074 other is not a template at all. That's OK. */
2075 return NULL_TREE;
2076 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2078 /* In [namespace.alias] we have:
2080 In a declarative region, a namespace-alias-definition can be
2081 used to redefine a namespace-alias declared in that declarative
2082 region to refer only to the namespace to which it already
2083 refers.
2085 Therefore, if we encounter a second alias directive for the same
2086 alias, we can just ignore the second directive. */
2087 if (DECL_NAMESPACE_ALIAS (newdecl)
2088 && (DECL_NAMESPACE_ALIAS (newdecl)
2089 == DECL_NAMESPACE_ALIAS (olddecl)))
2090 return olddecl;
2092 /* Leave it to update_binding to merge or report error. */
2093 return NULL_TREE;
2095 else
2097 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
2098 if (errmsg)
2100 auto_diagnostic_group d;
2101 error_at (newdecl_loc, errmsg, newdecl);
2102 if (DECL_NAME (olddecl) != NULL_TREE)
2103 inform (olddecl_loc,
2104 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
2105 ? G_("%q#D previously defined here")
2106 : G_("%q#D previously declared here"), olddecl);
2107 if (cxx_dialect >= cxx26
2108 && DECL_NAME (newdecl)
2109 && id_equal (DECL_NAME (newdecl), "_")
2110 && !name_independent_decl_p (newdecl))
2112 if (TREE_CODE (newdecl) == PARM_DECL)
2113 inform (newdecl_loc,
2114 "parameter declaration is not name-independent");
2115 else if (DECL_DECOMPOSITION_P (newdecl))
2117 if (at_namespace_scope_p ())
2118 inform (newdecl_loc,
2119 "structured binding at namespace scope is not "
2120 "name-independent");
2121 else if (TREE_STATIC (newdecl))
2122 inform (newdecl_loc,
2123 "static structured binding is not "
2124 "name-independent");
2125 else if (DECL_EXTERNAL (newdecl))
2126 inform (newdecl_loc,
2127 "extern structured binding is not "
2128 "name-independent");
2130 else if (at_class_scope_p ()
2131 && VAR_P (newdecl)
2132 && TREE_STATIC (newdecl))
2133 inform (newdecl_loc,
2134 "static data member is not name-independent");
2135 else if (VAR_P (newdecl) && at_namespace_scope_p ())
2136 inform (newdecl_loc,
2137 "variable at namespace scope is not name-independent");
2138 else if (VAR_P (newdecl) && TREE_STATIC (newdecl))
2139 inform (newdecl_loc,
2140 "static variable is not name-independent");
2141 else if (VAR_P (newdecl) && DECL_EXTERNAL (newdecl))
2142 inform (newdecl_loc,
2143 "extern variable is not name-independent");
2145 return error_mark_node;
2147 else if (TREE_CODE (olddecl) == FUNCTION_DECL
2148 && DECL_INITIAL (olddecl) != NULL_TREE
2149 && !prototype_p (TREE_TYPE (olddecl))
2150 && prototype_p (TREE_TYPE (newdecl)))
2152 /* Prototype decl follows defn w/o prototype. */
2153 auto_diagnostic_group d;
2154 if (warning_at (newdecl_loc, 0,
2155 "prototype specified for %q#D", newdecl))
2156 inform (olddecl_loc,
2157 "previous non-prototype definition here");
2159 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
2160 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
2162 /* [dcl.link]
2163 If two declarations of the same function or object
2164 specify different linkage-specifications ..., the program
2165 is ill-formed.... Except for functions with C++ linkage,
2166 a function declaration without a linkage specification
2167 shall not precede the first linkage specification for
2168 that function. A function can be declared without a
2169 linkage specification after an explicit linkage
2170 specification has been seen; the linkage explicitly
2171 specified in the earlier declaration is not affected by
2172 such a function declaration.
2174 DR 563 raises the question why the restrictions on
2175 functions should not also apply to objects. Older
2176 versions of G++ silently ignore the linkage-specification
2177 for this example:
2179 namespace N {
2180 extern int i;
2181 extern "C" int i;
2184 which is clearly wrong. Therefore, we now treat objects
2185 like functions. */
2186 if (current_lang_depth () == 0)
2188 /* There is no explicit linkage-specification, so we use
2189 the linkage from the previous declaration. */
2190 retrofit_lang_decl (newdecl);
2191 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2193 else
2195 auto_diagnostic_group d;
2196 error_at (newdecl_loc,
2197 "conflicting declaration of %q#D with %qL linkage",
2198 newdecl, DECL_LANGUAGE (newdecl));
2199 inform (olddecl_loc,
2200 "previous declaration with %qL linkage",
2201 DECL_LANGUAGE (olddecl));
2205 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2207 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2209 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2210 if (DECL_FUNCTION_MEMBER_P (olddecl)
2211 && (/* grokfndecl passes member function templates too
2212 as FUNCTION_DECLs. */
2213 DECL_TEMPLATE_INFO (olddecl)
2214 /* C++11 8.3.6/6.
2215 Default arguments for a member function of a class
2216 template shall be specified on the initial declaration
2217 of the member function within the class template. */
2218 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2220 check_redeclaration_no_default_args (newdecl);
2222 if (DECL_TEMPLATE_INFO (olddecl)
2223 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2225 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2226 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2227 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2228 tree old_parms
2229 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2230 merge_default_template_args (new_parms, old_parms,
2231 /*class_p=*/false);
2234 else
2236 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2237 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2238 int i = 1;
2240 for (; t1 && t1 != void_list_node;
2241 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2242 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2244 if (simple_cst_equal (TREE_PURPOSE (t1),
2245 TREE_PURPOSE (t2)) == 1)
2247 auto_diagnostic_group d;
2248 if (permerror (newdecl_loc,
2249 "default argument given for parameter "
2250 "%d of %q#D", i, newdecl))
2251 inform (olddecl_loc,
2252 "previous specification in %q#D here",
2253 olddecl);
2255 else
2257 auto_diagnostic_group d;
2258 error_at (newdecl_loc,
2259 "default argument given for parameter %d "
2260 "of %q#D", i, newdecl);
2261 inform (olddecl_loc,
2262 "previous specification in %q#D here",
2263 olddecl);
2267 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2268 argument expression, that declaration... shall be the only
2269 declaration of the function or function template in the
2270 translation unit." */
2271 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2276 /* Do not merge an implicit typedef with an explicit one. In:
2278 class A;
2280 typedef class A A __attribute__ ((foo));
2282 the attribute should apply only to the typedef. */
2283 if (TREE_CODE (olddecl) == TYPE_DECL
2284 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2285 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2286 return NULL_TREE;
2288 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2289 return NULL_TREE;
2291 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2292 return error_mark_node;
2294 if (modules_p ()
2295 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2296 && TREE_CODE (olddecl) != NAMESPACE_DECL)
2298 if (!module_may_redeclare (olddecl, newdecl))
2299 return error_mark_node;
2301 if (!hiding)
2303 /* The old declaration should match the exportingness of the new
2304 declaration. But hidden friend declarations just keep the
2305 exportingness of the old declaration; see CWG2588. */
2306 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2307 if (DECL_LANG_SPECIFIC (not_tmpl)
2308 && DECL_MODULE_ATTACH_P (not_tmpl)
2309 /* Typedefs are not entities and so are OK to be redeclared
2310 as exported: see [module.interface]/p6. */
2311 && TREE_CODE (olddecl) != TYPE_DECL)
2313 if (DECL_MODULE_EXPORT_P (newdecl)
2314 && !DECL_MODULE_EXPORT_P (not_tmpl))
2316 auto_diagnostic_group d;
2317 error ("conflicting exporting for declaration %qD", newdecl);
2318 inform (olddecl_loc,
2319 "previously declared here without exporting");
2322 else if (DECL_MODULE_EXPORT_P (newdecl))
2323 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2327 /* We have committed to returning OLDDECL at this point. */
2329 /* If new decl is `static' and an `extern' was seen previously,
2330 warn about it. */
2331 warn_extern_redeclared_static (newdecl, olddecl);
2333 /* True to merge attributes between the declarations, false to
2334 set OLDDECL's attributes to those of NEWDECL (for template
2335 explicit specializations that specify their own attributes
2336 independent of those specified for the primary template). */
2337 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2338 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2339 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2341 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2343 if (merge_attr)
2345 if (diagnose_mismatched_attributes (olddecl, newdecl))
2346 inform (olddecl_loc, DECL_INITIAL (olddecl)
2347 ? G_("previous definition of %qD here")
2348 : G_("previous declaration of %qD here"), olddecl);
2350 /* [dcl.attr.noreturn]: The first declaration of a function shall
2351 specify the noreturn attribute if any declaration of that function
2352 specifies the noreturn attribute. */
2353 tree a;
2354 if (TREE_THIS_VOLATILE (newdecl)
2355 && !TREE_THIS_VOLATILE (olddecl)
2356 /* This applies to [[noreturn]] only, not its GNU variants. */
2357 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2358 && cxx11_attribute_p (a)
2359 && get_attribute_namespace (a) == NULL_TREE)
2361 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2362 "but its first declaration was not", newdecl);
2363 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2367 /* Now that functions must hold information normally held
2368 by field decls, there is extra work to do so that
2369 declaration information does not get destroyed during
2370 definition. */
2371 if (DECL_VINDEX (olddecl))
2372 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2373 if (DECL_CONTEXT (olddecl))
2374 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2375 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2376 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2377 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2378 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2379 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2380 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2381 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2382 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2383 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2384 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2385 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2386 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2387 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2388 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2390 duplicate_contracts (newdecl, olddecl);
2392 /* Optionally warn about more than one declaration for the same
2393 name, but don't warn about a function declaration followed by a
2394 definition. */
2395 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2396 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2397 /* Don't warn about extern decl followed by definition. */
2398 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2399 /* Don't warn if at least one is/was hidden. */
2400 && !(hiding || was_hidden)
2401 /* Don't warn about declaration followed by specialization. */
2402 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2403 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2405 auto_diagnostic_group d;
2406 if (warning_at (newdecl_loc,
2407 OPT_Wredundant_decls,
2408 "redundant redeclaration of %qD in same scope",
2409 newdecl))
2410 inform (olddecl_loc,
2411 "previous declaration of %qD", olddecl);
2414 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2415 first declaration of the function or, for an explicit specialization
2416 of a function template, the first declaration of that
2417 specialization. */
2418 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2419 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2421 if (DECL_DELETED_FN (newdecl))
2423 auto_diagnostic_group d;
2424 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2425 "is not first declaration", newdecl))
2426 inform (olddecl_loc,
2427 "previous declaration of %qD", olddecl);
2429 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2430 if (DECL_DELETED_FN (olddecl)
2431 && DECL_INITIAL (olddecl)
2432 && TREE_CODE (DECL_INITIAL (olddecl)) == STRING_CST)
2433 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2437 /* Deal with C++: must preserve virtual function table size. */
2438 if (TREE_CODE (olddecl) == TYPE_DECL)
2440 tree newtype = TREE_TYPE (newdecl);
2441 tree oldtype = TREE_TYPE (olddecl);
2443 if (newtype != error_mark_node && oldtype != error_mark_node
2444 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2445 CLASSTYPE_FRIEND_CLASSES (newtype)
2446 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2448 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2451 /* Copy all the DECL_... slots specified in the new decl except for
2452 any that we copy here from the old type. */
2453 if (merge_attr)
2454 DECL_ATTRIBUTES (newdecl)
2455 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2456 else
2457 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2459 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2461 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2462 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2463 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2465 /* The new decl should not already have gathered any
2466 specializations. */
2467 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2469 /* Make sure the contracts are equivalent. */
2470 duplicate_contracts (newdecl, olddecl);
2472 /* Remove contracts from old_result so they aren't appended to
2473 old_result by the merge function. */
2474 remove_contract_attributes (old_result);
2476 DECL_ATTRIBUTES (old_result)
2477 = (*targetm.merge_decl_attributes) (old_result, new_result);
2479 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2481 if (DECL_SOURCE_LOCATION (newdecl)
2482 != DECL_SOURCE_LOCATION (olddecl))
2484 /* Per C++11 8.3.6/4, default arguments cannot be added in
2485 later declarations of a function template. */
2486 check_redeclaration_no_default_args (newdecl);
2487 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2488 argument expression, that declaration... shall be the only
2489 declaration of the function or function template in the
2490 translation unit." */
2491 check_no_redeclaration_friend_default_args
2492 (old_result, new_result);
2494 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2495 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2496 merge_default_template_args (new_parms, old_parms,
2497 /*class_p=*/false);
2499 if (!DECL_UNIQUE_FRIEND_P (new_result))
2500 DECL_UNIQUE_FRIEND_P (old_result) = false;
2502 check_default_args (newdecl);
2504 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2505 && DECL_INITIAL (new_result))
2507 if (DECL_INITIAL (old_result))
2508 DECL_UNINLINABLE (old_result) = 1;
2509 else
2510 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2511 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2512 DECL_NOT_REALLY_EXTERN (old_result)
2513 = DECL_NOT_REALLY_EXTERN (new_result);
2514 DECL_INTERFACE_KNOWN (old_result)
2515 = DECL_INTERFACE_KNOWN (new_result);
2516 DECL_DECLARED_INLINE_P (old_result)
2517 = DECL_DECLARED_INLINE_P (new_result);
2518 DECL_DISREGARD_INLINE_LIMITS (old_result)
2519 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2521 else
2523 DECL_DECLARED_INLINE_P (old_result)
2524 |= DECL_DECLARED_INLINE_P (new_result);
2525 DECL_DISREGARD_INLINE_LIMITS (old_result)
2526 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2527 check_redeclaration_exception_specification (newdecl, olddecl);
2529 merge_attribute_bits (new_result, old_result);
2533 /* If the new declaration is a definition, update the file and
2534 line information on the declaration, and also make
2535 the old declaration the same definition. */
2536 if (DECL_INITIAL (new_result) != NULL_TREE)
2538 DECL_SOURCE_LOCATION (olddecl)
2539 = DECL_SOURCE_LOCATION (old_result)
2540 = DECL_SOURCE_LOCATION (newdecl);
2541 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2542 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2544 DECL_ARGUMENTS (old_result) = DECL_ARGUMENTS (new_result);
2545 for (tree p = DECL_ARGUMENTS (old_result); p; p = DECL_CHAIN (p))
2546 DECL_CONTEXT (p) = old_result;
2548 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2549 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2553 return olddecl;
2556 if (types_match)
2558 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2559 check_redeclaration_exception_specification (newdecl, olddecl);
2561 /* Automatically handles default parameters. */
2562 tree oldtype = TREE_TYPE (olddecl);
2563 tree newtype;
2565 /* For typedefs use the old type, as the new type's DECL_NAME points
2566 at newdecl, which will be ggc_freed. */
2567 if (TREE_CODE (newdecl) == TYPE_DECL)
2569 /* But NEWTYPE might have an attribute, honor that. */
2570 tree tem = TREE_TYPE (newdecl);
2571 newtype = oldtype;
2573 if (TYPE_USER_ALIGN (tem))
2575 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2576 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2577 TYPE_USER_ALIGN (newtype) = true;
2580 /* And remove the new type from the variants list. */
2581 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2583 tree remove = TREE_TYPE (newdecl);
2584 if (TYPE_MAIN_VARIANT (remove) == remove)
2586 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2587 /* If remove is the main variant, no need to remove that
2588 from the list. One of the DECL_ORIGINAL_TYPE
2589 variants, e.g. created for aligned attribute, might still
2590 refer to the newdecl TYPE_DECL though, so remove that one
2591 in that case. */
2592 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2593 if (orig != remove)
2594 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2595 t = TYPE_MAIN_VARIANT (t))
2596 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2598 TYPE_NEXT_VARIANT (t)
2599 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2600 break;
2603 else
2604 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2605 t = TYPE_NEXT_VARIANT (t))
2606 if (TYPE_NEXT_VARIANT (t) == remove)
2608 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2609 break;
2613 else if (merge_attr)
2614 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2615 else
2616 newtype = TREE_TYPE (newdecl);
2618 if (VAR_P (newdecl))
2620 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2621 /* For already initialized vars, TREE_READONLY could have been
2622 cleared in cp_finish_decl, because the var needs runtime
2623 initialization or destruction. Make sure not to set
2624 TREE_READONLY on it again. */
2625 if (DECL_INITIALIZED_P (olddecl)
2626 && !DECL_EXTERNAL (olddecl)
2627 && !TREE_READONLY (olddecl))
2628 TREE_READONLY (newdecl) = 0;
2629 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2630 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2631 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2632 if (DECL_DEPENDENT_INIT_P (olddecl))
2633 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2634 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2635 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2636 DECL_DECLARED_CONSTEXPR_P (newdecl)
2637 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2638 DECL_DECLARED_CONSTINIT_P (newdecl)
2639 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2641 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2642 if (DECL_LANG_SPECIFIC (olddecl)
2643 && CP_DECL_THREADPRIVATE_P (olddecl))
2645 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2646 retrofit_lang_decl (newdecl);
2647 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2651 /* An explicit specialization of a function template or of a member
2652 function of a class template can be declared transaction_safe
2653 independently of whether the corresponding template entity is declared
2654 transaction_safe. */
2655 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2656 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2657 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2658 && tx_safe_fn_type_p (newtype)
2659 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2660 newtype = tx_unsafe_fn_variant (newtype);
2662 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2664 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2665 check_default_args (newdecl);
2667 /* Lay the type out, unless already done. */
2668 if (! same_type_p (newtype, oldtype)
2669 && TREE_TYPE (newdecl) != error_mark_node
2670 && !(processing_template_decl && uses_template_parms (newdecl)))
2671 layout_type (TREE_TYPE (newdecl));
2673 if ((VAR_P (newdecl)
2674 || TREE_CODE (newdecl) == PARM_DECL
2675 || TREE_CODE (newdecl) == RESULT_DECL
2676 || TREE_CODE (newdecl) == FIELD_DECL
2677 || TREE_CODE (newdecl) == TYPE_DECL)
2678 && !(processing_template_decl && uses_template_parms (newdecl)))
2679 layout_decl (newdecl, 0);
2681 /* Merge deprecatedness. */
2682 if (TREE_DEPRECATED (newdecl))
2683 TREE_DEPRECATED (olddecl) = 1;
2685 /* Merge unavailability. */
2686 if (TREE_UNAVAILABLE (newdecl))
2687 TREE_UNAVAILABLE (olddecl) = 1;
2689 /* Preserve function specific target and optimization options */
2690 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2692 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2693 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2694 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2695 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2697 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2698 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2699 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2700 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2702 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2703 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2705 else
2707 /* Merge the const type qualifier. */
2708 if (TREE_READONLY (newdecl))
2709 TREE_READONLY (olddecl) = 1;
2710 /* Merge the volatile type qualifier. */
2711 if (TREE_THIS_VOLATILE (newdecl))
2712 TREE_THIS_VOLATILE (olddecl) = 1;
2715 /* Merge the initialization information. */
2716 if (DECL_INITIAL (newdecl) == NULL_TREE
2717 && DECL_INITIAL (olddecl) != NULL_TREE)
2719 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2720 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2721 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2723 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2724 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2728 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2730 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2731 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2732 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2733 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2734 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2735 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2736 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2737 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2738 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2740 if (merge_attr)
2741 merge_attribute_bits (newdecl, olddecl);
2742 else
2744 /* Merge the noreturn bit. */
2745 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2746 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2747 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2748 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2749 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2751 /* Keep the old RTL. */
2752 COPY_DECL_RTL (olddecl, newdecl);
2754 else if (VAR_P (newdecl)
2755 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2757 /* Keep the old RTL. We cannot keep the old RTL if the old
2758 declaration was for an incomplete object and the new
2759 declaration is not since many attributes of the RTL will
2760 change. */
2761 COPY_DECL_RTL (olddecl, newdecl);
2764 /* If cannot merge, then use the new type and qualifiers,
2765 and don't preserve the old rtl. */
2766 else
2768 /* Clean out any memory we had of the old declaration. */
2769 tree oldstatic = value_member (olddecl, static_aggregates);
2770 if (oldstatic)
2771 TREE_VALUE (oldstatic) = error_mark_node;
2773 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2774 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2775 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2776 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2777 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2780 /* Merge the storage class information. */
2781 merge_weak (newdecl, olddecl);
2783 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2784 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2785 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2786 if (! DECL_EXTERNAL (olddecl))
2787 DECL_EXTERNAL (newdecl) = 0;
2788 if (! DECL_COMDAT (olddecl))
2789 DECL_COMDAT (newdecl) = 0;
2791 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2793 if (!DECL_LOCAL_DECL_P (olddecl))
2794 /* This can happen if olddecl was brought in from the
2795 enclosing namespace via a using-decl. The new decl is
2796 then not a block-scope extern at all. */
2797 DECL_LOCAL_DECL_P (newdecl) = false;
2798 else
2800 retrofit_lang_decl (newdecl);
2801 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2802 = DECL_LOCAL_DECL_ALIAS (olddecl);
2803 if (alias != error_mark_node)
2805 DECL_ATTRIBUTES (alias)
2806 = (*targetm.merge_decl_attributes) (alias, newdecl);
2807 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2808 merge_attribute_bits (newdecl, alias);
2813 new_template_info = NULL_TREE;
2814 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2816 bool new_redefines_gnu_inline = false;
2818 if (new_defines_function
2819 && ((DECL_INTERFACE_KNOWN (olddecl)
2820 && TREE_CODE (olddecl) == FUNCTION_DECL)
2821 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2822 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2823 == FUNCTION_DECL))))
2824 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2826 if (!new_redefines_gnu_inline)
2828 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2829 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2830 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2833 if (TREE_CODE (newdecl) != TYPE_DECL)
2835 DECL_TEMPLATE_INSTANTIATED (newdecl)
2836 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2837 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2839 /* If the OLDDECL is an instantiation and/or specialization,
2840 then the NEWDECL must be too. But, it may not yet be marked
2841 as such if the caller has created NEWDECL, but has not yet
2842 figured out that it is a redeclaration. */
2843 if (!DECL_USE_TEMPLATE (newdecl))
2844 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2846 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2847 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2848 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2851 /* Don't really know how much of the language-specific
2852 values we should copy from old to new. */
2853 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2855 if (LANG_DECL_HAS_MIN (newdecl))
2857 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2858 if (DECL_TEMPLATE_INFO (newdecl))
2860 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2861 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2862 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2863 /* Remember the presence of explicit specialization args. */
2864 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2865 = TINFO_USED_TEMPLATE_ID (new_template_info);
2868 /* We don't want to copy template info from a non-templated friend
2869 (PR105761), but these shouldn't have DECL_TEMPLATE_INFO now. */
2870 gcc_checking_assert (!DECL_TEMPLATE_INFO (olddecl)
2871 || !non_templated_friend_p (olddecl));
2872 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2875 if (DECL_DECLARES_FUNCTION_P (newdecl))
2877 /* Only functions have these fields. */
2878 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2879 DECL_BEFRIENDING_CLASSES (newdecl)
2880 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2881 DECL_BEFRIENDING_CLASSES (olddecl));
2882 /* DECL_THUNKS is only valid for virtual functions,
2883 otherwise it is a DECL_FRIEND_CONTEXT. */
2884 if (DECL_VIRTUAL_P (newdecl))
2885 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2886 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2887 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2889 else if (VAR_P (newdecl))
2891 /* Only variables have this field. */
2892 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2893 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2897 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2899 tree parm;
2901 /* Merge parameter attributes. */
2902 tree oldarg, newarg;
2903 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2904 oldarg && newarg;
2905 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2907 DECL_ATTRIBUTES (newarg)
2908 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2909 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2912 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2913 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2915 /* If newdecl is not a specialization, then it is not a
2916 template-related function at all. And that means that we
2917 should have exited above, returning 0. */
2918 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2920 if (DECL_ODR_USED (olddecl))
2921 /* From [temp.expl.spec]:
2923 If a template, a member template or the member of a class
2924 template is explicitly specialized then that
2925 specialization shall be declared before the first use of
2926 that specialization that would cause an implicit
2927 instantiation to take place, in every translation unit in
2928 which such a use occurs. */
2929 error ("explicit specialization of %qD after first use",
2930 olddecl);
2932 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2933 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2934 && DECL_DECLARED_INLINE_P (newdecl));
2936 /* Don't propagate visibility from the template to the
2937 specialization here. We'll do that in determine_visibility if
2938 appropriate. */
2939 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2941 /* [temp.expl.spec/14] We don't inline explicit specialization
2942 just because the primary template says so. */
2943 gcc_assert (!merge_attr);
2945 DECL_DECLARED_INLINE_P (olddecl)
2946 = DECL_DECLARED_INLINE_P (newdecl);
2948 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2949 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2951 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2953 else if (new_defines_function && DECL_INITIAL (olddecl))
2955 /* Never inline re-defined extern inline functions.
2956 FIXME: this could be better handled by keeping both
2957 function as separate declarations. */
2958 DECL_UNINLINABLE (newdecl) = 1;
2960 else
2962 if (DECL_PENDING_INLINE_P (olddecl))
2964 DECL_PENDING_INLINE_P (newdecl) = 1;
2965 DECL_PENDING_INLINE_INFO (newdecl)
2966 = DECL_PENDING_INLINE_INFO (olddecl);
2968 else if (DECL_PENDING_INLINE_P (newdecl))
2970 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2971 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2972 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2974 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2976 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2977 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2979 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2980 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2981 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2982 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2985 /* Preserve abstractness on cloned [cd]tors. */
2986 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2988 /* Update newdecl's parms to point at olddecl. */
2989 for (parm = DECL_ARGUMENTS (newdecl); parm;
2990 parm = DECL_CHAIN (parm))
2991 DECL_CONTEXT (parm) = olddecl;
2993 if (! types_match)
2995 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2996 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2997 COPY_DECL_RTL (newdecl, olddecl);
2999 if (! types_match || new_defines_function)
3001 /* These are the final DECL_ARGUMENTS that will be used within the
3002 body; update any references to old DECL_ARGUMENTS in the
3003 contracts, if present. */
3004 if (tree contracts = DECL_CONTRACTS (newdecl))
3005 remap_contracts (olddecl, newdecl, contracts, true);
3007 /* These need to be copied so that the names are available.
3008 Note that if the types do match, we'll preserve inline
3009 info and other bits, but if not, we won't. */
3010 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
3011 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
3013 /* In some cases, duplicate_contracts will remove contracts from
3014 OLDDECL, to avoid duplications. Sometimes, the contracts end up
3015 shared. If we removed them, re-add them. */
3016 if (!DECL_CONTRACTS (olddecl))
3017 copy_contract_attributes (olddecl, newdecl);
3019 /* If redeclaring a builtin function, it stays built in
3020 if newdecl is a gnu_inline definition, or if newdecl is just
3021 a declaration. */
3022 if (fndecl_built_in_p (olddecl)
3023 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
3025 copy_decl_built_in_function (newdecl, olddecl);
3026 /* If we're keeping the built-in definition, keep the rtl,
3027 regardless of declaration matches. */
3028 COPY_DECL_RTL (olddecl, newdecl);
3029 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
3031 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
3032 if (builtin_decl_explicit_p (fncode))
3034 /* A compatible prototype of these builtin functions
3035 is seen, assume the runtime implements it with
3036 the expected semantics. */
3037 switch (fncode)
3039 case BUILT_IN_STPCPY:
3040 set_builtin_decl_implicit_p (fncode, true);
3041 break;
3042 default:
3043 set_builtin_decl_declared_p (fncode, true);
3044 break;
3048 copy_attributes_to_builtin (newdecl);
3051 if (new_defines_function)
3052 /* If defining a function declared with other language
3053 linkage, use the previously declared language linkage. */
3054 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
3055 else if (types_match)
3057 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
3058 /* Don't clear out the arguments if we're just redeclaring a
3059 function. */
3060 if (DECL_ARGUMENTS (olddecl))
3062 /* If we removed contracts from previous definition, re-attach
3063 them. Otherwise, rewrite the contracts so they match the
3064 parameters of the new declaration. */
3065 if (DECL_INITIAL (olddecl)
3066 && DECL_CONTRACTS (newdecl)
3067 && !DECL_CONTRACTS (olddecl))
3068 copy_contract_attributes (olddecl, newdecl);
3069 else
3071 /* Temporarily undo the re-contexting of parameters so we can
3072 actually remap parameters. The inliner won't replace
3073 parameters if we don't do this. */
3074 tree args = DECL_ARGUMENTS (newdecl);
3075 for (tree p = args; p; p = DECL_CHAIN (p))
3076 DECL_CONTEXT (p) = newdecl;
3078 /* Save new argument names for use in contracts parsing,
3079 unless we've already started parsing the body of olddecl
3080 (particular issues arise when newdecl is from a prior
3081 friend decl with no argument names, see
3082 modules/contracts-tpl-friend-1). */
3083 if (tree contracts = DECL_CONTRACTS (olddecl))
3084 remap_contracts (newdecl, olddecl, contracts, true);
3086 /* And reverse this operation again. */
3087 for (tree p = args; p; p = DECL_CHAIN (p))
3088 DECL_CONTEXT (p) = olddecl;
3091 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
3095 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
3096 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
3098 /* Now preserve various other info from the definition. */
3099 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
3100 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
3101 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
3102 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
3104 /* Warn about conflicting visibility specifications. */
3105 if (DECL_VISIBILITY_SPECIFIED (olddecl)
3106 && DECL_VISIBILITY_SPECIFIED (newdecl)
3107 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
3109 auto_diagnostic_group d;
3110 if (warning_at (newdecl_loc, OPT_Wattributes,
3111 "%qD: visibility attribute ignored because it "
3112 "conflicts with previous declaration", newdecl))
3113 inform (olddecl_loc,
3114 "previous declaration of %qD", olddecl);
3116 /* Choose the declaration which specified visibility. */
3117 if (DECL_VISIBILITY_SPECIFIED (olddecl))
3119 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
3120 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
3122 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
3123 so keep this behavior. */
3124 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
3126 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
3127 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
3129 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
3130 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
3132 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
3133 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
3135 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
3136 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
3137 DECL_USER_ALIGN (newdecl) = 1;
3139 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
3140 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
3141 > DECL_WARN_IF_NOT_ALIGN (newdecl))
3142 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
3143 DECL_WARN_IF_NOT_ALIGN (olddecl));
3144 if (TREE_CODE (newdecl) == FIELD_DECL)
3145 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
3147 /* Merge module entity mapping information. */
3148 if (DECL_LANG_SPECIFIC (olddecl)
3149 && (DECL_MODULE_ENTITY_P (olddecl)
3150 || DECL_MODULE_KEYED_DECLS_P (olddecl)))
3152 retrofit_lang_decl (newdecl);
3153 DECL_MODULE_ENTITY_P (newdecl) = DECL_MODULE_ENTITY_P (olddecl);
3154 DECL_MODULE_KEYED_DECLS_P (newdecl) = DECL_MODULE_KEYED_DECLS_P (olddecl);
3157 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
3158 with that from NEWDECL below. */
3159 if (DECL_LANG_SPECIFIC (olddecl))
3161 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
3162 != DECL_LANG_SPECIFIC (newdecl));
3163 ggc_free (DECL_LANG_SPECIFIC (olddecl));
3166 /* Merge the USED information. */
3167 if (TREE_USED (olddecl))
3168 TREE_USED (newdecl) = 1;
3169 else if (TREE_USED (newdecl))
3170 TREE_USED (olddecl) = 1;
3172 if (VAR_P (newdecl))
3174 if (DECL_READ_P (olddecl))
3175 DECL_READ_P (newdecl) = 1;
3176 else if (DECL_READ_P (newdecl))
3177 DECL_READ_P (olddecl) = 1;
3180 if (DECL_PRESERVE_P (olddecl))
3181 DECL_PRESERVE_P (newdecl) = 1;
3182 else if (DECL_PRESERVE_P (newdecl))
3183 DECL_PRESERVE_P (olddecl) = 1;
3185 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
3186 to olddecl and deleted. */
3187 if (TREE_CODE (newdecl) == FUNCTION_DECL
3188 && DECL_FUNCTION_VERSIONED (olddecl))
3190 /* Set the flag for newdecl so that it gets copied to olddecl. */
3191 DECL_FUNCTION_VERSIONED (newdecl) = 1;
3192 /* newdecl will be purged after copying to olddecl and is no longer
3193 a version. */
3194 cgraph_node::delete_function_version_by_decl (newdecl);
3197 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3199 int function_size;
3200 struct symtab_node *snode = symtab_node::get (olddecl);
3202 function_size = sizeof (struct tree_decl_common);
3204 memcpy ((char *) olddecl + sizeof (struct tree_common),
3205 (char *) newdecl + sizeof (struct tree_common),
3206 function_size - sizeof (struct tree_common));
3208 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3209 (char *) newdecl + sizeof (struct tree_decl_common),
3210 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
3212 /* Preserve symtab node mapping. */
3213 olddecl->decl_with_vis.symtab_node = snode;
3215 if (new_template_info)
3216 /* If newdecl is a template instantiation, it is possible that
3217 the following sequence of events has occurred:
3219 o A friend function was declared in a class template. The
3220 class template was instantiated.
3222 o The instantiation of the friend declaration was
3223 recorded on the instantiation list, and is newdecl.
3225 o Later, however, instantiate_class_template called pushdecl
3226 on the newdecl to perform name injection. But, pushdecl in
3227 turn called duplicate_decls when it discovered that another
3228 declaration of a global function with the same name already
3229 existed.
3231 o Here, in duplicate_decls, we decided to clobber newdecl.
3233 If we're going to do that, we'd better make sure that
3234 olddecl, and not newdecl, is on the list of
3235 instantiations so that if we try to do the instantiation
3236 again we won't get the clobbered declaration. */
3237 reregister_specialization (newdecl,
3238 new_template_info,
3239 olddecl);
3241 else
3243 size_t size = tree_code_size (TREE_CODE (newdecl));
3245 memcpy ((char *) olddecl + sizeof (struct tree_common),
3246 (char *) newdecl + sizeof (struct tree_common),
3247 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
3249 switch (TREE_CODE (newdecl))
3251 case LABEL_DECL:
3252 case VAR_DECL:
3253 case RESULT_DECL:
3254 case PARM_DECL:
3255 case FIELD_DECL:
3256 case TYPE_DECL:
3257 case CONST_DECL:
3259 struct symtab_node *snode = NULL;
3261 if (VAR_P (newdecl)
3262 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3263 || DECL_EXTERNAL (olddecl)))
3264 snode = symtab_node::get (olddecl);
3265 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3266 (char *) newdecl + sizeof (struct tree_decl_common),
3267 size - sizeof (struct tree_decl_common)
3268 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3269 if (VAR_P (newdecl))
3270 olddecl->decl_with_vis.symtab_node = snode;
3272 break;
3273 default:
3274 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3275 (char *) newdecl + sizeof (struct tree_decl_common),
3276 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3277 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3278 break;
3282 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3284 if (DECL_EXTERNAL (olddecl)
3285 || TREE_PUBLIC (olddecl)
3286 || TREE_STATIC (olddecl))
3288 /* Merge the section attribute.
3289 We want to issue an error if the sections conflict but that must be
3290 done later in decl_attributes since we are called before attributes
3291 are assigned. */
3292 if (DECL_SECTION_NAME (newdecl) != NULL)
3293 set_decl_section_name (olddecl, newdecl);
3295 if (DECL_ONE_ONLY (newdecl))
3297 struct symtab_node *oldsym, *newsym;
3298 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3299 oldsym = cgraph_node::get_create (olddecl);
3300 else
3301 oldsym = varpool_node::get_create (olddecl);
3302 newsym = symtab_node::get (newdecl);
3303 oldsym->set_comdat_group (newsym->get_comdat_group ());
3307 if (VAR_P (newdecl)
3308 && CP_DECL_THREAD_LOCAL_P (newdecl))
3310 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3311 if (!processing_template_decl)
3312 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3316 DECL_UID (olddecl) = olddecl_uid;
3318 /* NEWDECL contains the merged attribute lists.
3319 Update OLDDECL to be the same. */
3320 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3322 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3323 so that encode_section_info has a chance to look at the new decl
3324 flags and attributes. */
3325 if (DECL_RTL_SET_P (olddecl)
3326 && (TREE_CODE (olddecl) == FUNCTION_DECL
3327 || (VAR_P (olddecl)
3328 && TREE_STATIC (olddecl))))
3329 make_decl_rtl (olddecl);
3331 /* The NEWDECL will no longer be needed. Because every out-of-class
3332 declaration of a member results in a call to duplicate_decls,
3333 freeing these nodes represents in a significant savings.
3335 Before releasing the node, be sore to remove function from symbol
3336 table that might have been inserted there to record comdat group.
3337 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3338 structure is shared in between newdecl and oldecl. */
3339 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3340 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3341 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3343 struct symtab_node *snode = symtab_node::get (newdecl);
3344 if (snode)
3345 snode->remove ();
3348 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3350 tree clone;
3351 FOR_EACH_CLONE (clone, olddecl)
3353 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3354 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3358 /* Remove the associated constraints for newdecl, if any, before
3359 reclaiming memory. */
3360 if (flag_concepts)
3361 remove_constraints (newdecl);
3363 /* And similarly for any module tracking data. */
3364 if (modules_p ())
3365 remove_defining_module (newdecl);
3367 ggc_free (newdecl);
3369 return olddecl;
3372 /* Return zero if the declaration NEWDECL is valid
3373 when the declaration OLDDECL (assumed to be for the same name)
3374 has already been seen.
3375 Otherwise return an error message format string with a %s
3376 where the identifier should go. */
3378 static const char *
3379 redeclaration_error_message (tree newdecl, tree olddecl)
3381 if (TREE_CODE (newdecl) == TYPE_DECL)
3383 /* Because C++ can put things into name space for free,
3384 constructs like "typedef struct foo { ... } foo"
3385 would look like an erroneous redeclaration. */
3386 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3387 return NULL;
3388 else
3389 return G_("redefinition of %q#D");
3391 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3393 /* If this is a pure function, its olddecl will actually be
3394 the original initialization to `0' (which we force to call
3395 abort()). Don't complain about redefinition in this case. */
3396 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3397 && DECL_INITIAL (olddecl) == NULL_TREE)
3398 return NULL;
3400 /* If both functions come from different namespaces, this is not
3401 a redeclaration - this is a conflict with a used function. */
3402 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3403 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3404 && ! decls_match (olddecl, newdecl))
3405 return G_("%qD conflicts with used function");
3407 /* We'll complain about linkage mismatches in
3408 warn_extern_redeclared_static. */
3410 /* Defining the same name twice is no good. */
3411 if (decl_defined_p (olddecl)
3412 && decl_defined_p (newdecl))
3414 if (DECL_NAME (olddecl) == NULL_TREE)
3415 return G_("%q#D not declared in class");
3416 else if (!GNU_INLINE_P (olddecl)
3417 || GNU_INLINE_P (newdecl))
3418 return G_("redefinition of %q#D");
3421 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3423 bool olda = GNU_INLINE_P (olddecl);
3424 bool newa = GNU_INLINE_P (newdecl);
3426 if (olda != newa)
3428 if (newa)
3429 return G_("%q+D redeclared inline with "
3430 "%<gnu_inline%> attribute");
3431 else
3432 return G_("%q+D redeclared inline without "
3433 "%<gnu_inline%> attribute");
3437 /* [class.compare.default]: A definition of a comparison operator as
3438 defaulted that appears in a class shall be the first declaration of
3439 that function. */
3440 special_function_kind sfk = special_function_p (olddecl);
3441 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3442 return G_("comparison operator %q+D defaulted after "
3443 "its first declaration");
3445 check_abi_tag_redeclaration
3446 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3447 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3449 return NULL;
3451 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3453 tree nt, ot;
3455 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3456 return G_("redefinition of %q#D");
3458 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3459 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3460 DECL_TEMPLATE_RESULT (olddecl));
3462 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3463 return NULL;
3465 nt = DECL_TEMPLATE_RESULT (newdecl);
3466 if (DECL_TEMPLATE_INFO (nt))
3467 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3468 ot = DECL_TEMPLATE_RESULT (olddecl);
3469 if (DECL_TEMPLATE_INFO (ot))
3470 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3471 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3472 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3473 return G_("redefinition of %q#D");
3475 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3477 bool olda = GNU_INLINE_P (ot);
3478 bool newa = GNU_INLINE_P (nt);
3480 if (olda != newa)
3482 if (newa)
3483 return G_("%q+D redeclared inline with "
3484 "%<gnu_inline%> attribute");
3485 else
3486 return G_("%q+D redeclared inline without "
3487 "%<gnu_inline%> attribute");
3491 /* Core issue #226 (C++11):
3493 If a friend function template declaration specifies a
3494 default template-argument, that declaration shall be a
3495 definition and shall be the only declaration of the
3496 function template in the translation unit. */
3497 if ((cxx_dialect != cxx98)
3498 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3499 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3500 /*is_primary=*/true,
3501 /*is_partial=*/false,
3502 /*is_friend_decl=*/2))
3503 return G_("redeclaration of friend %q#D "
3504 "may not have default template arguments");
3506 return NULL;
3508 else if (VAR_P (newdecl)
3509 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3510 != CP_DECL_THREAD_LOCAL_P (olddecl))
3511 && (! DECL_LANG_SPECIFIC (olddecl)
3512 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3513 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3515 /* Only variables can be thread-local, and all declarations must
3516 agree on this property. */
3517 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3518 return G_("thread-local declaration of %q#D follows "
3519 "non-thread-local declaration");
3520 else
3521 return G_("non-thread-local declaration of %q#D follows "
3522 "thread-local declaration");
3524 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3526 /* The objects have been declared at namespace scope. If either
3527 is a member of an anonymous union, then this is an invalid
3528 redeclaration. For example:
3530 int i;
3531 union { int i; };
3533 is invalid. */
3534 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3535 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3536 return G_("redeclaration of %q#D");
3537 /* If at least one declaration is a reference, there is no
3538 conflict. For example:
3540 int i = 3;
3541 extern int i;
3543 is valid. */
3544 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3545 return NULL;
3547 /* Static data member declared outside a class definition
3548 if the variable is defined within the class with constexpr
3549 specifier is declaration rather than definition (and
3550 deprecated). */
3551 if (cxx_dialect >= cxx17
3552 && VAR_P (olddecl)
3553 && DECL_CLASS_SCOPE_P (olddecl)
3554 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3555 && !DECL_INITIAL (newdecl))
3557 DECL_EXTERNAL (newdecl) = 1;
3558 /* For now, only warn with explicit -Wdeprecated. */
3559 if (OPTION_SET_P (warn_deprecated))
3561 auto_diagnostic_group d;
3562 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3563 "redundant redeclaration of %<constexpr%> "
3564 "static data member %qD", newdecl))
3565 inform (DECL_SOURCE_LOCATION (olddecl),
3566 "previous declaration of %qD", olddecl);
3568 return NULL;
3571 /* Reject two definitions. */
3572 return G_("redefinition of %q#D");
3574 else
3576 /* Objects declared with block scope: */
3577 /* Reject two definitions, and reject a definition
3578 together with an external reference. */
3579 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3580 return G_("redeclaration of %q#D");
3581 return NULL;
3586 /* Hash and equality functions for the named_label table. */
3588 hashval_t
3589 named_label_hash::hash (const value_type entry)
3591 return IDENTIFIER_HASH_VALUE (entry->name);
3594 bool
3595 named_label_hash::equal (const value_type entry, compare_type name)
3597 return name == entry->name;
3600 /* Look for a label named ID in the current function. If one cannot
3601 be found, create one. Return the named_label_entry, or NULL on
3602 failure. */
3604 static named_label_entry *
3605 lookup_label_1 (tree id, bool making_local_p)
3607 auto_cond_timevar tv (TV_NAME_LOOKUP);
3609 /* You can't use labels at global scope. */
3610 if (current_function_decl == NULL_TREE)
3612 error ("label %qE referenced outside of any function", id);
3613 return NULL;
3616 if (!named_labels)
3617 named_labels = hash_table<named_label_hash>::create_ggc (13);
3619 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3620 named_label_entry **slot
3621 = named_labels->find_slot_with_hash (id, hash, INSERT);
3622 named_label_entry *old = *slot;
3624 if (old && old->label_decl)
3626 if (!making_local_p)
3627 return old;
3629 if (old->binding_level == current_binding_level)
3631 error ("local label %qE conflicts with existing label", id);
3632 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3633 return NULL;
3637 /* We are making a new decl, create or reuse the named_label_entry */
3638 named_label_entry *ent = NULL;
3639 if (old && !old->label_decl)
3640 ent = old;
3641 else
3643 ent = ggc_cleared_alloc<named_label_entry> ();
3644 ent->name = id;
3645 ent->outer = old;
3646 *slot = ent;
3649 /* Now create the LABEL_DECL. */
3650 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3652 DECL_CONTEXT (decl) = current_function_decl;
3653 SET_DECL_MODE (decl, VOIDmode);
3654 if (making_local_p)
3656 C_DECLARED_LABEL_FLAG (decl) = true;
3657 DECL_CHAIN (decl) = current_binding_level->names;
3658 current_binding_level->names = decl;
3661 ent->label_decl = decl;
3663 return ent;
3666 /* Wrapper for lookup_label_1. */
3668 tree
3669 lookup_label (tree id)
3671 named_label_entry *ent = lookup_label_1 (id, false);
3672 return ent ? ent->label_decl : NULL_TREE;
3675 /* Remember that we've seen &&ID. */
3677 void
3678 mark_label_addressed (tree id)
3680 named_label_entry *ent = lookup_label_1 (id, false);
3681 ent->addressed = true;
3684 tree
3685 declare_local_label (tree id)
3687 named_label_entry *ent = lookup_label_1 (id, true);
3688 return ent ? ent->label_decl : NULL_TREE;
3691 /* Returns true if it is ill-formed to jump past the declaration of DECL. */
3693 static bool
3694 decl_jump_unsafe (tree decl)
3696 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3697 with automatic storage duration is not in scope to a point where it is
3698 in scope is ill-formed unless the variable has scalar type, class type
3699 with a trivial default constructor and a trivial destructor, a
3700 cv-qualified version of one of these types, or an array of one of the
3701 preceding types and is declared without an initializer (8.5). */
3702 tree type = TREE_TYPE (decl);
3704 return (type != error_mark_node
3705 && VAR_P (decl)
3706 && !TREE_STATIC (decl)
3707 && (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3708 || variably_modified_type_p (type, NULL_TREE)));
3711 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3712 to the user. */
3714 static bool
3715 identify_goto (tree decl, location_t loc, const location_t *locus,
3716 diagnostic_t diag_kind, bool computed)
3718 if (computed)
3719 diag_kind = DK_WARNING;
3720 bool complained
3721 = emit_diagnostic (diag_kind, loc, 0,
3722 decl ? G_("jump to label %qD")
3723 : G_("jump to case label"), decl);
3724 if (complained && locus)
3726 if (computed)
3727 inform (*locus, " as a possible target of computed goto");
3728 else
3729 inform (*locus, " from here");
3731 return complained;
3734 /* Check that a single previously seen jump to a newly defined label
3735 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3736 the jump context; NAMES are the names in scope in LEVEL at the jump
3737 context; LOCUS is the source position of the jump or 0. COMPUTED
3738 is a vec of decls if the jump is a computed goto. Returns
3739 true if all is well. */
3741 static bool
3742 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3743 bool exited_omp, const location_t *locus,
3744 vec<tree,va_gc> *computed)
3746 cp_binding_level *b;
3747 bool complained = false;
3748 int identified = 0;
3749 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3750 bool saw_ceif = false, saw_se = false;
3752 if (exited_omp)
3754 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3755 computed);
3756 if (complained)
3757 inform (input_location, " exits OpenMP structured block");
3758 saw_omp = true;
3759 identified = 2;
3762 for (b = current_binding_level; b ; b = b->level_chain)
3764 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3766 for (new_decls = b->names; new_decls != old_decls;
3767 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3768 : TREE_CHAIN (new_decls)))
3770 bool problem = decl_jump_unsafe (new_decls);
3771 if (! problem)
3772 continue;
3774 if (!identified)
3776 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3777 computed);
3778 identified = 2;
3780 if (complained)
3781 inform (DECL_SOURCE_LOCATION (new_decls),
3782 " crosses initialization of %q#D", new_decls);
3785 if (b == level)
3786 break;
3788 const char *inf = NULL;
3789 location_t loc = input_location;
3790 switch (b->kind)
3792 case sk_try:
3793 if (!saw_eh)
3794 inf = G_(" enters %<try%> block");
3795 saw_eh = true;
3796 break;
3798 case sk_catch:
3799 if (!saw_eh)
3800 inf = G_(" enters %<catch%> block");
3801 saw_eh = true;
3802 break;
3804 case sk_omp:
3805 if (!saw_omp)
3806 inf = G_(" enters OpenMP structured block");
3807 saw_omp = true;
3808 break;
3810 case sk_transaction:
3811 if (!saw_tm)
3812 inf = G_(" enters synchronized or atomic statement");
3813 saw_tm = true;
3814 break;
3816 case sk_stmt_expr:
3817 if (!saw_se)
3818 inf = G_(" enters statement expression");
3819 saw_se = true;
3820 break;
3822 case sk_block:
3823 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3825 inf = G_(" enters %<constexpr if%> statement");
3826 loc = EXPR_LOCATION (b->level_chain->this_entity);
3827 saw_cxif = true;
3829 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3831 inf = G_(" enters %<consteval if%> statement");
3832 loc = EXPR_LOCATION (b->level_chain->this_entity);
3833 saw_ceif = true;
3835 break;
3837 default:
3838 break;
3841 if (inf)
3843 if (identified < 2)
3844 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3845 computed);
3846 identified = 2;
3847 if (complained)
3848 inform (loc, inf);
3852 if (!vec_safe_is_empty (computed))
3854 if (!identified)
3855 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3856 computed);
3857 identified = 2;
3858 if (complained)
3859 for (tree d : computed)
3861 if (DECL_P (d))
3862 inform (DECL_SOURCE_LOCATION (d), " does not destroy %qD", d);
3863 else if (d == get_identifier ("catch"))
3864 inform (*locus, " does not clean up handled exception");
3868 return !identified;
3871 static void
3872 check_previous_goto (tree decl, struct named_label_use_entry *use)
3874 check_previous_goto_1 (decl, use->binding_level,
3875 use->names_in_scope, use->in_omp_scope,
3876 &use->o_goto_locus, use->computed_goto);
3879 static bool
3880 check_switch_goto (cp_binding_level* level)
3882 return check_previous_goto_1 (NULL_TREE, level, level->names,
3883 false, NULL, nullptr);
3886 /* Check that a new jump to a label ENT is OK. COMPUTED is true
3887 if this is a possible target of a computed goto. */
3889 void
3890 check_goto_1 (named_label_entry *ent, bool computed)
3892 tree decl = ent->label_decl;
3894 /* If the label hasn't been defined yet, defer checking. */
3895 if (! DECL_INITIAL (decl))
3897 /* Don't bother creating another use if the last goto had the
3898 same data, and will therefore create the same set of errors. */
3899 if (ent->uses
3900 && ent->uses->names_in_scope == current_binding_level->names)
3901 return;
3903 named_label_use_entry *new_use
3904 = ggc_alloc<named_label_use_entry> ();
3905 new_use->binding_level = current_binding_level;
3906 new_use->names_in_scope = current_binding_level->names;
3907 new_use->o_goto_locus = input_location;
3908 new_use->in_omp_scope = false;
3909 new_use->computed_goto = computed ? make_tree_vector () : nullptr;
3911 new_use->next = ent->uses;
3912 ent->uses = new_use;
3913 return;
3916 bool saw_catch = false, complained = false;
3917 int identified = 0;
3918 tree bad;
3919 unsigned ix;
3921 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3922 || ent->in_constexpr_if || ent->in_consteval_if
3923 || ent->in_omp_scope || ent->in_stmt_expr
3924 || !vec_safe_is_empty (ent->bad_decls))
3926 diagnostic_t diag_kind = DK_PERMERROR;
3927 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3928 || ent->in_consteval_if || ent->in_transaction_scope
3929 || ent->in_omp_scope || ent->in_stmt_expr)
3930 diag_kind = DK_ERROR;
3931 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3932 &input_location, diag_kind, computed);
3933 identified = 1 + (diag_kind == DK_ERROR);
3936 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3938 bool problem = decl_jump_unsafe (bad);
3940 if (problem && DECL_ARTIFICIAL (bad))
3942 /* Can't skip init of __exception_info. */
3943 if (identified == 1)
3945 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3946 &input_location, DK_ERROR, computed);
3947 identified = 2;
3949 if (complained)
3950 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3951 saw_catch = true;
3953 else if (complained)
3954 inform (DECL_SOURCE_LOCATION (bad),
3955 " skips initialization of %q#D", bad);
3958 if (complained)
3960 if (ent->in_try_scope)
3961 inform (input_location, " enters %<try%> block");
3962 else if (ent->in_catch_scope && !saw_catch)
3963 inform (input_location, " enters %<catch%> block");
3964 else if (ent->in_transaction_scope)
3965 inform (input_location, " enters synchronized or atomic statement");
3966 else if (ent->in_constexpr_if)
3967 inform (input_location, " enters %<constexpr if%> statement");
3968 else if (ent->in_consteval_if)
3969 inform (input_location, " enters %<consteval if%> statement");
3970 else if (ent->in_stmt_expr)
3971 inform (input_location, " enters statement expression");
3974 if (ent->in_omp_scope)
3976 if (complained)
3977 inform (input_location, " enters OpenMP structured block");
3979 else if (flag_openmp)
3980 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3982 if (b == ent->binding_level)
3983 break;
3984 if (b->kind == sk_omp)
3986 if (identified < 2)
3988 complained = identify_goto (decl,
3989 DECL_SOURCE_LOCATION (decl),
3990 &input_location, DK_ERROR,
3991 computed);
3992 identified = 2;
3994 if (complained)
3995 inform (input_location, " exits OpenMP structured block");
3996 break;
4000 /* Warn if a computed goto might involve a local variable going out of scope
4001 without being cleaned up. */
4002 if (computed)
4004 auto level = ent->binding_level;
4005 auto names = ent->names_in_scope;
4006 for (auto b = current_binding_level; ; b = b->level_chain)
4008 if (b->kind == sk_catch)
4010 if (!identified)
4012 complained
4013 = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
4014 &input_location, DK_ERROR, computed);
4015 identified = 2;
4017 if (complained)
4018 inform (input_location,
4019 " does not clean up handled exception");
4021 tree end = b == level ? names : NULL_TREE;
4022 for (tree d = b->names; d != end; d = DECL_CHAIN (d))
4024 if (automatic_var_with_nontrivial_dtor_p (d))
4026 if (!identified)
4028 complained
4029 = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
4030 &input_location, DK_ERROR, computed);
4031 identified = 2;
4033 if (complained)
4034 inform (DECL_SOURCE_LOCATION (d),
4035 " does not destroy %qD", d);
4038 if (b == level)
4039 break;
4044 /* Check that a new jump to a label DECL is OK. Called by
4045 finish_goto_stmt. */
4047 void
4048 check_goto (tree decl)
4050 if (!named_labels)
4051 return;
4052 if (TREE_CODE (decl) != LABEL_DECL)
4054 /* We don't know where a computed goto is jumping,
4055 so check all addressable labels. */
4056 for (auto iter = named_labels->begin ();
4057 iter != named_labels->end ();
4058 ++iter)
4060 auto ent = *iter;
4061 if (ent->addressed)
4062 check_goto_1 (ent, true);
4065 else
4067 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
4068 named_label_entry **slot
4069 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
4070 named_label_entry *ent = *slot;
4071 check_goto_1 (ent, false);
4075 /* Check that a return is ok wrt OpenMP structured blocks.
4076 Called by finish_return_stmt. Returns true if all is well. */
4078 bool
4079 check_omp_return (void)
4081 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
4082 if (b->kind == sk_omp)
4084 error ("invalid exit from OpenMP structured block");
4085 return false;
4087 else if (b->kind == sk_function_parms)
4088 break;
4089 return true;
4092 /* Define a label, specifying the location in the source file.
4093 Return the LABEL_DECL node for the label. */
4095 tree
4096 define_label (location_t location, tree name)
4098 auto_cond_timevar tv (TV_NAME_LOOKUP);
4100 /* After labels, make any new cleanups in the function go into their
4101 own new (temporary) binding contour. */
4102 for (cp_binding_level *p = current_binding_level;
4103 p->kind != sk_function_parms;
4104 p = p->level_chain)
4105 p->more_cleanups_ok = 0;
4107 named_label_entry *ent = lookup_label_1 (name, false);
4108 tree decl = ent->label_decl;
4110 if (DECL_INITIAL (decl) != NULL_TREE)
4112 error ("duplicate label %qD", decl);
4113 return error_mark_node;
4115 else
4117 /* Mark label as having been defined. */
4118 DECL_INITIAL (decl) = error_mark_node;
4119 /* Say where in the source. */
4120 DECL_SOURCE_LOCATION (decl) = location;
4122 ent->binding_level = current_binding_level;
4123 ent->names_in_scope = current_binding_level->names;
4125 for (named_label_use_entry *use = ent->uses; use; use = use->next)
4126 check_previous_goto (decl, use);
4127 ent->uses = NULL;
4130 return decl;
4133 struct cp_switch
4135 cp_binding_level *level;
4136 struct cp_switch *next;
4137 /* The SWITCH_STMT being built. */
4138 tree switch_stmt;
4139 /* A splay-tree mapping the low element of a case range to the high
4140 element, or NULL_TREE if there is no high element. Used to
4141 determine whether or not a new case label duplicates an old case
4142 label. We need a tree, rather than simply a hash table, because
4143 of the GNU case range extension. */
4144 splay_tree cases;
4145 /* Remember whether a default: case label has been seen. */
4146 bool has_default_p;
4147 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
4148 bool break_stmt_seen_p;
4149 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
4150 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
4151 bool in_loop_body_p;
4154 /* A stack of the currently active switch statements. The innermost
4155 switch statement is on the top of the stack. There is no need to
4156 mark the stack for garbage collection because it is only active
4157 during the processing of the body of a function, and we never
4158 collect at that point. */
4160 static struct cp_switch *switch_stack;
4162 /* Called right after a switch-statement condition is parsed.
4163 SWITCH_STMT is the switch statement being parsed. */
4165 void
4166 push_switch (tree switch_stmt)
4168 struct cp_switch *p = XNEW (struct cp_switch);
4169 p->level = current_binding_level;
4170 p->next = switch_stack;
4171 p->switch_stmt = switch_stmt;
4172 p->cases = splay_tree_new (case_compare, NULL, NULL);
4173 p->has_default_p = false;
4174 p->break_stmt_seen_p = false;
4175 p->in_loop_body_p = false;
4176 switch_stack = p;
4179 void
4180 pop_switch (void)
4182 struct cp_switch *cs = switch_stack;
4184 /* Emit warnings as needed. */
4185 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
4186 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
4187 const bool bool_cond_p
4188 = (SWITCH_STMT_TYPE (cs->switch_stmt)
4189 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
4190 if (!processing_template_decl)
4191 c_do_switch_warnings (cs->cases, switch_location,
4192 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
4193 bool_cond_p);
4195 /* For the benefit of block_may_fallthru remember if the switch body
4196 case labels cover all possible values and if there are break; stmts. */
4197 if (cs->has_default_p
4198 || (!processing_template_decl
4199 && c_switch_covers_all_cases_p (cs->cases,
4200 SWITCH_STMT_TYPE (cs->switch_stmt))))
4201 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
4202 if (!cs->break_stmt_seen_p)
4203 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
4204 /* Now that we're done with the switch warnings, set the switch type
4205 to the type of the condition if the index type was of scoped enum type.
4206 (Such types don't participate in the integer promotions.) We do this
4207 because of bit-fields whose declared type is a scoped enum type:
4208 gimplification will use the lowered index type, but convert the
4209 case values to SWITCH_STMT_TYPE, which would have been the declared type
4210 and verify_gimple_switch doesn't accept that. */
4211 if (is_bitfield_expr_with_lowered_type (cond))
4212 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
4213 gcc_assert (!cs->in_loop_body_p);
4214 splay_tree_delete (cs->cases);
4215 switch_stack = switch_stack->next;
4216 free (cs);
4219 /* Note that a BREAK_STMT is about to be added. If it is inside of
4220 a SWITCH_STMT and not inside of a loop body inside of it, note
4221 in switch_stack we've seen a BREAK_STMT. */
4223 void
4224 note_break_stmt (void)
4226 if (switch_stack && !switch_stack->in_loop_body_p)
4227 switch_stack->break_stmt_seen_p = true;
4230 /* Note the start of processing of an iteration statement's body.
4231 The note_break_stmt function will do nothing while processing it.
4232 Return a flag that should be passed to note_iteration_stmt_body_end. */
4234 bool
4235 note_iteration_stmt_body_start (void)
4237 if (!switch_stack)
4238 return false;
4239 bool ret = switch_stack->in_loop_body_p;
4240 switch_stack->in_loop_body_p = true;
4241 return ret;
4244 /* Note the end of processing of an iteration statement's body. */
4246 void
4247 note_iteration_stmt_body_end (bool prev)
4249 if (switch_stack)
4250 switch_stack->in_loop_body_p = prev;
4253 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
4254 condition. Note that if TYPE and VALUE are already integral we don't
4255 really do the conversion because the language-independent
4256 warning/optimization code will work better that way. */
4258 static tree
4259 case_conversion (tree type, tree value)
4261 if (value == NULL_TREE)
4262 return value;
4264 value = mark_rvalue_use (value);
4266 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
4267 type = type_promotes_to (type);
4269 tree ovalue = value;
4270 /* The constant-expression VALUE shall be a converted constant expression
4271 of the adjusted type of the switch condition, which doesn't allow
4272 narrowing conversions. */
4273 value = build_converted_constant_expr (type, value, tf_warning_or_error);
4275 if (cxx_dialect >= cxx11
4276 && (SCOPED_ENUM_P (type)
4277 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
4278 /* Use the converted value. */;
4279 else
4280 /* The already integral case. */
4281 value = ovalue;
4283 return cxx_constant_value (value);
4286 /* Note that we've seen a definition of a case label, and complain if this
4287 is a bad place for one. */
4289 tree
4290 finish_case_label (location_t loc, tree low_value, tree high_value)
4292 tree cond, r;
4293 cp_binding_level *p;
4294 tree type;
4296 if (low_value == NULL_TREE && high_value == NULL_TREE)
4297 switch_stack->has_default_p = true;
4299 if (processing_template_decl)
4301 tree label;
4303 /* For templates, just add the case label; we'll do semantic
4304 analysis at instantiation-time. */
4305 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
4306 return add_stmt (build_case_label (low_value, high_value, label));
4309 /* Find the condition on which this switch statement depends. */
4310 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
4311 if (cond && TREE_CODE (cond) == TREE_LIST)
4312 cond = TREE_VALUE (cond);
4314 if (!check_switch_goto (switch_stack->level))
4315 return error_mark_node;
4317 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
4318 if (type == error_mark_node)
4319 return error_mark_node;
4321 low_value = case_conversion (type, low_value);
4322 high_value = case_conversion (type, high_value);
4324 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
4326 /* After labels, make any new cleanups in the function go into their
4327 own new (temporary) binding contour. */
4328 for (p = current_binding_level;
4329 p->kind != sk_function_parms;
4330 p = p->level_chain)
4331 p->more_cleanups_ok = 0;
4333 return r;
4336 struct typename_info {
4337 tree scope;
4338 tree name;
4339 tree template_id;
4340 bool enum_p;
4341 bool class_p;
4344 struct typename_hasher : ggc_ptr_hash<tree_node>
4346 typedef typename_info *compare_type;
4348 /* Hash a TYPENAME_TYPE. */
4350 static hashval_t
4351 hash (tree context, tree fullname)
4353 hashval_t hash = 0;
4354 hash = iterative_hash_object (context, hash);
4355 hash = iterative_hash_object (fullname, hash);
4356 return hash;
4359 static hashval_t
4360 hash (const typename_info *ti)
4362 return typename_hasher::hash (ti->scope, ti->template_id);
4365 static hashval_t
4366 hash (tree t)
4368 return typename_hasher::hash (TYPE_CONTEXT (t), TYPENAME_TYPE_FULLNAME (t));
4371 /* Compare two TYPENAME_TYPEs. */
4373 static bool
4374 equal (tree t1, const typename_info *t2)
4376 return (TYPE_IDENTIFIER (t1) == t2->name
4377 && TYPE_CONTEXT (t1) == t2->scope
4378 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4379 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4380 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4384 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4385 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4387 Returns the new TYPENAME_TYPE. */
4389 static GTY (()) hash_table<typename_hasher> *typename_htab;
4391 tree
4392 build_typename_type (tree context, tree name, tree fullname,
4393 enum tag_types tag_type)
4395 typename_info ti;
4397 if (typename_htab == NULL)
4398 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4400 ti.scope = FROB_CONTEXT (context);
4401 ti.name = name;
4402 ti.template_id = fullname;
4403 ti.enum_p = tag_type == enum_type;
4404 ti.class_p = (tag_type == class_type
4405 || tag_type == record_type
4406 || tag_type == union_type);
4407 hashval_t hash = typename_hasher::hash (&ti);
4409 /* See if we already have this type. */
4410 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4411 tree t = *e;
4412 if (*e)
4413 t = *e;
4414 else
4416 /* Build the TYPENAME_TYPE. */
4417 t = cxx_make_type (TYPENAME_TYPE);
4418 TYPE_CONTEXT (t) = ti.scope;
4419 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4420 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4421 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4423 /* Build the corresponding TYPE_DECL. */
4424 tree d = build_decl (input_location, TYPE_DECL, name, t);
4425 TYPE_NAME (t) = d;
4426 TYPE_STUB_DECL (t) = d;
4427 DECL_CONTEXT (d) = ti.scope;
4428 DECL_ARTIFICIAL (d) = 1;
4430 /* Store it in the hash table. */
4431 *e = t;
4433 /* TYPENAME_TYPEs must always be compared structurally, because
4434 they may or may not resolve down to another type depending on
4435 the currently open classes. */
4436 SET_TYPE_STRUCTURAL_EQUALITY (t);
4439 return t;
4442 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4443 provided to name the type. Returns an appropriate type, unless an
4444 error occurs, in which case error_mark_node is returned. If we
4445 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4446 return that, rather than the _TYPE it corresponds to, in other
4447 cases we look through the type decl. If TF_ERROR is set, complain
4448 about errors, otherwise be quiet. */
4450 tree
4451 make_typename_type (tree context, tree name, enum tag_types tag_type,
4452 tsubst_flags_t complain)
4454 tree fullname;
4455 tree t;
4456 bool want_template;
4458 if (name == error_mark_node
4459 || context == NULL_TREE
4460 || context == error_mark_node)
4461 return error_mark_node;
4463 if (TYPE_P (name))
4465 if (!(TYPE_LANG_SPECIFIC (name)
4466 && (CLASSTYPE_IS_TEMPLATE (name)
4467 || CLASSTYPE_USE_TEMPLATE (name))))
4468 name = TYPE_IDENTIFIER (name);
4469 else
4470 /* Create a TEMPLATE_ID_EXPR for the type. */
4471 name = build_nt (TEMPLATE_ID_EXPR,
4472 CLASSTYPE_TI_TEMPLATE (name),
4473 CLASSTYPE_TI_ARGS (name));
4475 else if (TREE_CODE (name) == TYPE_DECL)
4476 name = DECL_NAME (name);
4478 fullname = name;
4480 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4482 name = TREE_OPERAND (name, 0);
4483 if (DECL_TYPE_TEMPLATE_P (name))
4484 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4485 if (TREE_CODE (name) != IDENTIFIER_NODE)
4487 if (complain & tf_error)
4488 error ("%qD is not a type", name);
4489 return error_mark_node;
4492 if (TREE_CODE (name) == TEMPLATE_DECL)
4494 if (complain & tf_error)
4495 error ("%qD used without template arguments", name);
4496 return error_mark_node;
4498 else if (is_overloaded_fn (name))
4500 if (complain & tf_error)
4501 error ("%qD is a function, not a type", name);
4502 return error_mark_node;
4504 gcc_assert (identifier_p (name));
4505 gcc_assert (TYPE_P (context));
4507 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4508 /* This can happen for C++17 variadic using (c++/88986). */;
4509 else if (!MAYBE_CLASS_TYPE_P (context))
4511 if (complain & tf_error)
4512 error ("%q#T is not a class", context);
4513 return error_mark_node;
4516 /* When the CONTEXT is a dependent type, NAME could refer to a
4517 dependent base class of CONTEXT. But look inside it anyway
4518 if CONTEXT is a currently open scope, in case it refers to a
4519 member of the current instantiation or a non-dependent base;
4520 lookup will stop when we hit a dependent base. */
4521 if (!dependent_scope_p (context))
4523 /* We generally don't ignore non-types during TYPENAME_TYPE lookup
4524 (as per [temp.res.general]/3), unless
4525 - the tag corresponds to a class-key or 'enum' so
4526 [basic.lookup.elab] applies, or
4527 - the tag corresponds to scope_type or tf_qualifying_scope is
4528 set so [basic.lookup.qual]/1 applies.
4529 TODO: If we'd set/track the scope_type tag thoroughly on all
4530 TYPENAME_TYPEs that are followed by :: then we wouldn't need the
4531 tf_qualifying_scope flag. */
4532 bool want_type = (tag_type != none_type && tag_type != typename_type)
4533 || (complain & tf_qualifying_scope);
4534 t = lookup_member (context, name, /*protect=*/2, want_type, complain);
4536 else
4537 t = NULL_TREE;
4539 if ((!t || TREE_CODE (t) == TREE_LIST) && dependentish_scope_p (context))
4540 return build_typename_type (context, name, fullname, tag_type);
4542 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4544 if (!t)
4546 if (complain & tf_error)
4548 if (!COMPLETE_TYPE_P (context))
4549 cxx_incomplete_type_error (NULL_TREE, context);
4550 else
4551 error (want_template ? G_("no class template named %q#T in %q#T")
4552 : G_("no type named %q#T in %q#T"), name, context);
4554 return error_mark_node;
4557 /* Pull out the template from an injected-class-name (or multiple). */
4558 if (want_template)
4559 t = maybe_get_template_decl_from_type_decl (t);
4561 if (TREE_CODE (t) == TREE_LIST)
4563 if (complain & tf_error)
4565 error ("lookup of %qT in %qT is ambiguous", name, context);
4566 print_candidates (t);
4568 return error_mark_node;
4571 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4573 if (complain & tf_error)
4574 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4575 context, name, t);
4576 return error_mark_node;
4578 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4580 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4581 && DECL_TYPE_TEMPLATE_P (t))
4582 /* The caller permits this typename-specifier to name a template
4583 (because it appears in a CTAD-enabled context). */;
4584 else
4586 if (complain & tf_error)
4587 error ("%<typename %T::%D%> names %q#D, which is not a type",
4588 context, name, t);
4589 return error_mark_node;
4593 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4594 context, complain))
4595 return error_mark_node;
4597 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4598 return make_template_placeholder (t);
4600 if (want_template)
4602 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4603 NULL_TREE, context,
4604 complain | tf_user);
4605 if (t == error_mark_node)
4606 return error_mark_node;
4607 t = TYPE_NAME (t);
4610 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4611 t = TREE_TYPE (t);
4613 maybe_record_typedef_use (t);
4615 return t;
4618 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4619 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4620 in which case error_mark_node is returned.
4622 If PARM_LIST is non-NULL, also make sure that the template parameter
4623 list of TEMPLATE_DECL matches.
4625 If COMPLAIN zero, don't complain about any errors that occur. */
4627 tree
4628 make_unbound_class_template (tree context, tree name, tree parm_list,
4629 tsubst_flags_t complain)
4631 if (TYPE_P (name))
4632 name = TYPE_IDENTIFIER (name);
4633 else if (DECL_P (name))
4634 name = DECL_NAME (name);
4635 gcc_assert (identifier_p (name));
4637 if (!dependent_type_p (context)
4638 || currently_open_class (context))
4640 tree tmpl = NULL_TREE;
4642 if (MAYBE_CLASS_TYPE_P (context))
4643 tmpl = lookup_field (context, name, 0, false);
4645 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4646 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4648 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4650 if (complain & tf_error)
4651 error ("no class template named %q#T in %q#T", name, context);
4652 return error_mark_node;
4655 if (parm_list
4656 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4658 if (complain & tf_error)
4660 error ("template parameters do not match template %qD", tmpl);
4661 inform (DECL_SOURCE_LOCATION (tmpl),
4662 "%qD declared here", tmpl);
4664 return error_mark_node;
4667 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4668 complain))
4669 return error_mark_node;
4671 return tmpl;
4674 return make_unbound_class_template_raw (context, name, parm_list);
4677 /* Build an UNBOUND_CLASS_TEMPLATE. */
4679 tree
4680 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4682 /* Build the UNBOUND_CLASS_TEMPLATE. */
4683 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4684 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4685 TREE_TYPE (t) = NULL_TREE;
4686 SET_TYPE_STRUCTURAL_EQUALITY (t);
4688 /* Build the corresponding TEMPLATE_DECL. */
4689 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4690 TYPE_NAME (t) = d;
4691 TYPE_STUB_DECL (t) = d;
4692 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4693 DECL_ARTIFICIAL (d) = 1;
4694 DECL_TEMPLATE_PARMS (d) = parm_list;
4696 return t;
4701 /* Push the declarations of builtin types into the global namespace.
4702 RID_INDEX is the index of the builtin type in the array
4703 RID_POINTERS. NAME is the name used when looking up the builtin
4704 type. TYPE is the _TYPE node for the builtin type.
4706 The calls to set_global_binding below should be
4707 eliminated. Built-in types should not be looked up name; their
4708 names are keywords that the parser can recognize. However, there
4709 is code in c-common.cc that uses identifier_global_value to look up
4710 built-in types by name. */
4712 void
4713 record_builtin_type (enum rid rid_index,
4714 const char* name,
4715 tree type)
4717 tree decl = NULL_TREE;
4719 if (name)
4721 tree tname = get_identifier (name);
4722 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4723 DECL_ARTIFICIAL (tdecl) = 1;
4724 set_global_binding (tdecl);
4725 decl = tdecl;
4728 if ((int) rid_index < (int) RID_MAX)
4729 if (tree rname = ridpointers[(int) rid_index])
4730 if (!decl || DECL_NAME (decl) != rname)
4732 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4733 DECL_ARTIFICIAL (rdecl) = 1;
4734 set_global_binding (rdecl);
4735 if (!decl)
4736 decl = rdecl;
4739 if (decl)
4741 if (!TYPE_NAME (type))
4742 TYPE_NAME (type) = decl;
4743 debug_hooks->type_decl (decl, 0);
4747 /* Push a type into the namespace so that the back ends ignore it. */
4749 static void
4750 record_unknown_type (tree type, const char* name)
4752 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4753 TYPE_DECL, get_identifier (name), type));
4754 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4755 DECL_IGNORED_P (decl) = 1;
4756 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4757 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4758 SET_TYPE_ALIGN (type, 1);
4759 TYPE_USER_ALIGN (type) = 0;
4760 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4763 /* Create all the predefined identifiers. */
4765 static void
4766 initialize_predefined_identifiers (void)
4768 struct predefined_identifier
4770 const char *name; /* Name. */
4771 tree *node; /* Node to store it in. */
4772 cp_identifier_kind kind; /* Kind of identifier. */
4775 /* A table of identifiers to create at startup. */
4776 static const predefined_identifier predefined_identifiers[] = {
4777 {"C++", &lang_name_cplusplus, cik_normal},
4778 {"C", &lang_name_c, cik_normal},
4779 /* Some of these names have a trailing space so that it is
4780 impossible for them to conflict with names written by users. */
4781 {"__ct ", &ctor_identifier, cik_ctor},
4782 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4783 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4784 {"__dt ", &dtor_identifier, cik_dtor},
4785 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4786 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4787 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4788 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4789 {"__in_chrg", &in_charge_identifier, cik_normal},
4790 {"__as_base ", &as_base_identifier, cik_normal},
4791 {"this", &this_identifier, cik_normal},
4792 {"__delta", &delta_identifier, cik_normal},
4793 {"__pfn", &pfn_identifier, cik_normal},
4794 {"_vptr", &vptr_identifier, cik_normal},
4795 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4796 {"::", &global_identifier, cik_normal},
4797 /* The demangler expects anonymous namespaces to be called
4798 something starting with '_GLOBAL__N_'. It no longer needs
4799 to be unique to the TU. */
4800 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4801 {"auto", &auto_identifier, cik_normal},
4802 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4803 {"initializer_list", &init_list_identifier, cik_normal},
4804 {"__for_range ", &for_range__identifier, cik_normal},
4805 {"__for_begin ", &for_begin__identifier, cik_normal},
4806 {"__for_end ", &for_end__identifier, cik_normal},
4807 {"__for_range", &for_range_identifier, cik_normal},
4808 {"__for_begin", &for_begin_identifier, cik_normal},
4809 {"__for_end", &for_end_identifier, cik_normal},
4810 {"abi_tag", &abi_tag_identifier, cik_normal},
4811 {"aligned", &aligned_identifier, cik_normal},
4812 {"begin", &begin_identifier, cik_normal},
4813 {"end", &end_identifier, cik_normal},
4814 {"get", &get__identifier, cik_normal},
4815 {"gnu", &gnu_identifier, cik_normal},
4816 {"tuple_element", &tuple_element_identifier, cik_normal},
4817 {"tuple_size", &tuple_size_identifier, cik_normal},
4818 {"type", &type_identifier, cik_normal},
4819 {"value", &value_identifier, cik_normal},
4820 {"_FUN", &fun_identifier, cik_normal},
4821 {"__closure", &closure_identifier, cik_normal},
4822 {"heap uninit", &heap_uninit_identifier, cik_normal},
4823 {"heap ", &heap_identifier, cik_normal},
4824 {"heap deleted", &heap_deleted_identifier, cik_normal},
4825 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4826 {"heap []", &heap_vec_identifier, cik_normal},
4827 {"omp", &omp_identifier, cik_normal},
4828 {NULL, NULL, cik_normal}
4831 for (const predefined_identifier *pid = predefined_identifiers;
4832 pid->name; ++pid)
4834 *pid->node = get_identifier (pid->name);
4835 /* Some of these identifiers already have a special kind. */
4836 if (pid->kind != cik_normal)
4837 set_identifier_kind (*pid->node, pid->kind);
4841 /* Create the predefined scalar types of C,
4842 and some nodes representing standard constants (0, 1, (void *)0).
4843 Initialize the global binding level.
4844 Make definitions for built-in primitive functions. */
4846 void
4847 cxx_init_decl_processing (void)
4849 tree void_ftype;
4850 tree void_ftype_ptr;
4852 /* Create all the identifiers we need. */
4853 initialize_predefined_identifiers ();
4855 /* Create the global variables. */
4856 push_to_top_level ();
4858 current_function_decl = NULL_TREE;
4859 current_binding_level = NULL;
4860 /* Enter the global namespace. */
4861 gcc_assert (global_namespace == NULL_TREE);
4862 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4863 void_type_node);
4864 TREE_PUBLIC (global_namespace) = true;
4865 DECL_MODULE_EXPORT_P (global_namespace) = true;
4866 DECL_CONTEXT (global_namespace)
4867 = build_translation_unit_decl (get_identifier (main_input_filename));
4868 /* Remember whether we want the empty class passing ABI change warning
4869 in this TU. */
4870 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4871 = warn_abi && abi_version_crosses (12);
4872 debug_hooks->register_main_translation_unit
4873 (DECL_CONTEXT (global_namespace));
4874 begin_scope (sk_namespace, global_namespace);
4875 current_namespace = global_namespace;
4877 if (flag_visibility_ms_compat)
4878 default_visibility = VISIBILITY_HIDDEN;
4880 /* Initially, C. */
4881 current_lang_name = lang_name_c;
4883 /* Create the `std' namespace. */
4884 push_namespace (get_identifier ("std"));
4885 std_node = current_namespace;
4886 pop_namespace ();
4888 flag_noexcept_type = (cxx_dialect >= cxx17);
4890 c_common_nodes_and_builtins ();
4892 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4893 tree decl
4894 = add_builtin_function ("__builtin_is_constant_evaluated",
4895 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4896 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4897 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4899 /* The concrete return type of __builtin_source_location is
4900 const std::source_location::__impl*, but we can't form the type
4901 at this point. So we initially declare it with an auto return
4902 type which we then "deduce" from require_deduced_type upon first use. */
4903 tree auto_ftype = build_function_type_list (make_auto (), NULL_TREE);
4904 decl = add_builtin_function ("__builtin_source_location",
4905 auto_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4906 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4907 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4909 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4910 NULL_TREE);
4911 decl
4912 = add_builtin_function ("__builtin_is_corresponding_member",
4913 bool_vaftype,
4914 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4915 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4916 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4918 decl
4919 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4920 bool_vaftype,
4921 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4922 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4923 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4925 integer_two_node = build_int_cst (NULL_TREE, 2);
4927 /* Guess at the initial static decls size. */
4928 vec_alloc (static_decls, 500);
4930 /* ... and keyed classes. */
4931 vec_alloc (keyed_classes, 100);
4933 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4934 truthvalue_type_node = boolean_type_node;
4935 truthvalue_false_node = boolean_false_node;
4936 truthvalue_true_node = boolean_true_node;
4938 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4939 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4940 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4941 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4942 NULL_TREE);
4944 #if 0
4945 record_builtin_type (RID_MAX, NULL, string_type_node);
4946 #endif
4948 delta_type_node = ptrdiff_type_node;
4949 vtable_index_type = ptrdiff_type_node;
4951 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4952 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4953 void_ftype_ptr = build_function_type_list (void_type_node,
4954 ptr_type_node, NULL_TREE);
4955 void_ftype_ptr
4956 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4958 /* Create the conversion operator marker. This operator's DECL_NAME
4959 is in the identifier table, so we can use identifier equality to
4960 find it. */
4961 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4962 void_ftype);
4964 /* C++ extensions */
4966 unknown_type_node = make_node (LANG_TYPE);
4967 record_unknown_type (unknown_type_node, "unknown type");
4969 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4970 TREE_TYPE (unknown_type_node) = unknown_type_node;
4972 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4973 result. */
4974 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4975 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4977 init_list_type_node = make_node (LANG_TYPE);
4978 record_unknown_type (init_list_type_node, "init list");
4980 /* Used when parsing to distinguish parameter-lists () and (void). */
4981 explicit_void_list_node = build_tree_list (NULL_TREE, void_type_node);
4984 /* Make sure we get a unique function type, so we can give
4985 its pointer type a name. (This wins for gdb.) */
4986 tree vfunc_type = make_node (FUNCTION_TYPE);
4987 TREE_TYPE (vfunc_type) = integer_type_node;
4988 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4989 layout_type (vfunc_type);
4991 vtable_entry_type = build_pointer_type (vfunc_type);
4993 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4995 vtbl_type_node
4996 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4997 layout_type (vtbl_type_node);
4998 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4999 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
5000 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
5001 layout_type (vtbl_ptr_type_node);
5002 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
5004 push_namespace (get_identifier ("__cxxabiv1"));
5005 abi_node = current_namespace;
5006 pop_namespace ();
5008 any_targ_node = make_node (LANG_TYPE);
5009 record_unknown_type (any_targ_node, "any type");
5011 /* Now, C++. */
5012 current_lang_name = lang_name_cplusplus;
5014 if (aligned_new_threshold > 1
5015 && !pow2p_hwi (aligned_new_threshold))
5017 error ("%<-faligned-new=%d%> is not a power of two",
5018 aligned_new_threshold);
5019 aligned_new_threshold = 1;
5021 if (aligned_new_threshold == -1)
5022 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
5023 if (aligned_new_threshold == 1)
5024 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
5027 tree newattrs, extvisattr;
5028 tree newtype, deltype;
5029 tree ptr_ftype_sizetype;
5030 tree new_eh_spec;
5032 ptr_ftype_sizetype
5033 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
5034 if (cxx_dialect == cxx98)
5036 tree bad_alloc_id;
5037 tree bad_alloc_type_node;
5038 tree bad_alloc_decl;
5040 push_nested_namespace (std_node);
5041 bad_alloc_id = get_identifier ("bad_alloc");
5042 bad_alloc_type_node = make_class_type (RECORD_TYPE);
5043 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
5044 bad_alloc_decl
5045 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
5046 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
5047 pop_nested_namespace (std_node);
5049 new_eh_spec
5050 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
5052 else
5053 new_eh_spec = noexcept_false_spec;
5055 /* Ensure attribs.cc is initialized. */
5056 init_attributes ();
5058 extvisattr = build_tree_list (get_identifier ("externally_visible"),
5059 NULL_TREE);
5060 newattrs = tree_cons (get_identifier ("alloc_size"),
5061 build_tree_list (NULL_TREE, integer_one_node),
5062 extvisattr);
5063 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
5064 newtype = build_exception_variant (newtype, new_eh_spec);
5065 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
5066 deltype = build_exception_variant (deltype, empty_except_spec);
5067 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
5068 DECL_IS_MALLOC (opnew) = 1;
5069 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5070 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5071 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
5072 DECL_IS_MALLOC (opnew) = 1;
5073 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5074 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5075 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5076 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5077 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5078 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5079 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5080 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5081 if (flag_sized_deallocation)
5083 /* Also push the sized deallocation variants:
5084 void operator delete(void*, std::size_t) throw();
5085 void operator delete[](void*, std::size_t) throw(); */
5086 tree void_ftype_ptr_size
5087 = build_function_type_list (void_type_node, ptr_type_node,
5088 size_type_node, NULL_TREE);
5089 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
5090 extvisattr);
5091 deltype = build_exception_variant (deltype, empty_except_spec);
5092 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5093 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5094 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5095 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5096 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5097 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5100 if (aligned_new_threshold)
5102 push_nested_namespace (std_node);
5103 tree align_id = get_identifier ("align_val_t");
5104 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
5105 NULL_TREE, /*scoped*/true, NULL);
5106 pop_nested_namespace (std_node);
5108 /* operator new (size_t, align_val_t); */
5109 newtype = build_function_type_list (ptr_type_node, size_type_node,
5110 align_type_node, NULL_TREE);
5111 newtype = cp_build_type_attribute_variant (newtype, newattrs);
5112 newtype = build_exception_variant (newtype, new_eh_spec);
5113 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
5114 DECL_IS_MALLOC (opnew) = 1;
5115 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5116 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5117 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
5118 DECL_IS_MALLOC (opnew) = 1;
5119 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5120 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5122 /* operator delete (void *, align_val_t); */
5123 deltype = build_function_type_list (void_type_node, ptr_type_node,
5124 align_type_node, NULL_TREE);
5125 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
5126 deltype = build_exception_variant (deltype, empty_except_spec);
5127 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5128 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5129 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5130 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5131 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5132 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5134 if (flag_sized_deallocation)
5136 /* operator delete (void *, size_t, align_val_t); */
5137 deltype = build_function_type_list (void_type_node, ptr_type_node,
5138 size_type_node, align_type_node,
5139 NULL_TREE);
5140 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
5141 deltype = build_exception_variant (deltype, empty_except_spec);
5142 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5143 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5144 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5145 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5146 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5147 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5151 /* C++-specific nullptr initialization. */
5152 if (abi_version_at_least (9))
5153 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
5154 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
5157 if (! supports_one_only ())
5158 flag_weak = 0;
5160 abort_fndecl
5161 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
5162 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
5163 if (flag_weak)
5164 /* If no definition is available, resolve references to NULL. */
5165 declare_weak (abort_fndecl);
5167 /* Perform other language dependent initializations. */
5168 init_class_processing ();
5169 init_rtti_processing ();
5170 init_template_processing ();
5172 if (flag_exceptions)
5173 init_exception_processing ();
5175 if (flag_contracts)
5176 init_terminate_fn ();
5178 if (modules_p ())
5179 init_modules (parse_in);
5181 make_fname_decl = cp_make_fname_decl;
5182 start_fname_decls ();
5184 /* Show we use EH for cleanups. */
5185 if (flag_exceptions)
5186 using_eh_for_cleanups ();
5188 /* Check that the hardware interference sizes are at least
5189 alignof(max_align_t), as required by the standard. */
5190 const int max_align = max_align_t_align () / BITS_PER_UNIT;
5191 if (OPTION_SET_P (param_destruct_interfere_size))
5193 if (param_destruct_interfere_size < max_align)
5194 error ("%<--param destructive-interference-size=%d%> is less than "
5195 "%d", param_destruct_interfere_size, max_align);
5196 else if (param_destruct_interfere_size < param_l1_cache_line_size)
5197 warning (OPT_Winterference_size,
5198 "%<--param destructive-interference-size=%d%> "
5199 "is less than %<--param l1-cache-line-size=%d%>",
5200 param_destruct_interfere_size, param_l1_cache_line_size);
5202 else if (param_destruct_interfere_size)
5203 /* Assume the internal value is OK. */;
5204 else if (param_l1_cache_line_size >= max_align)
5205 param_destruct_interfere_size = param_l1_cache_line_size;
5206 /* else leave it unset. */
5208 if (OPTION_SET_P (param_construct_interfere_size))
5210 if (param_construct_interfere_size < max_align)
5211 error ("%<--param constructive-interference-size=%d%> is less than "
5212 "%d", param_construct_interfere_size, max_align);
5213 else if (param_construct_interfere_size > param_l1_cache_line_size
5214 && param_l1_cache_line_size >= max_align)
5215 warning (OPT_Winterference_size,
5216 "%<--param constructive-interference-size=%d%> "
5217 "is greater than %<--param l1-cache-line-size=%d%>",
5218 param_construct_interfere_size, param_l1_cache_line_size);
5220 else if (param_construct_interfere_size)
5221 /* Assume the internal value is OK. */;
5222 else if (param_l1_cache_line_size >= max_align)
5223 param_construct_interfere_size = param_l1_cache_line_size;
5226 /* Enter an abi node in global-module context. returns a cookie to
5227 give to pop_abi_namespace. */
5229 unsigned
5230 push_abi_namespace (tree node)
5232 push_nested_namespace (node);
5233 push_visibility ("default", 2);
5234 unsigned flags = module_kind;
5235 module_kind = 0;
5236 return flags;
5239 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
5240 you. */
5242 void
5243 pop_abi_namespace (unsigned flags, tree node)
5245 module_kind = flags;
5246 pop_visibility (2);
5247 pop_nested_namespace (node);
5250 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
5251 the decl, LOC is the location to give the decl, NAME is the
5252 initialization string and TYPE_DEP indicates whether NAME depended
5253 on the type of the function. We make use of that to detect
5254 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
5255 at the point of first use, so we mustn't push the decl now. */
5257 static tree
5258 cp_make_fname_decl (location_t loc, tree id, int type_dep)
5260 tree domain = NULL_TREE;
5261 tree init = NULL_TREE;
5263 if (!(type_dep && current_function_decl && in_template_context))
5265 const char *name = NULL;
5266 bool release_name = false;
5268 if (current_function_decl == NULL_TREE)
5269 name = "top level";
5270 else if (type_dep == 0)
5272 /* __FUNCTION__ */
5273 name = fname_as_string (type_dep);
5274 release_name = true;
5276 else
5278 /* __PRETTY_FUNCTION__ */
5279 gcc_checking_assert (type_dep == 1);
5280 name = cxx_printable_name (current_function_decl, 2);
5283 size_t length = strlen (name);
5284 domain = build_index_type (size_int (length));
5285 init = build_string (length + 1, name);
5286 if (release_name)
5287 free (const_cast<char *> (name));
5290 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
5291 type = build_cplus_array_type (type, domain);
5293 if (init)
5294 TREE_TYPE (init) = type;
5295 else
5296 init = error_mark_node;
5298 tree decl = build_decl (loc, VAR_DECL, id, type);
5300 TREE_READONLY (decl) = 1;
5301 DECL_ARTIFICIAL (decl) = 1;
5302 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
5303 TREE_STATIC (decl) = 1;
5305 TREE_USED (decl) = 1;
5307 SET_DECL_VALUE_EXPR (decl, init);
5308 DECL_HAS_VALUE_EXPR_P (decl) = 1;
5309 /* For decl_constant_var_p. */
5310 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5312 if (current_function_decl)
5314 DECL_CONTEXT (decl) = current_function_decl;
5315 decl = pushdecl_outermost_localscope (decl);
5316 if (decl != error_mark_node)
5317 add_decl_expr (decl);
5319 else
5321 DECL_THIS_STATIC (decl) = true;
5322 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
5325 return decl;
5328 /* Install DECL as a builtin function at current global scope. Return
5329 the new decl (if we found an existing version). Also installs it
5330 into ::std, if it's not '_*'. */
5332 tree
5333 cxx_builtin_function (tree decl)
5335 retrofit_lang_decl (decl);
5337 DECL_ARTIFICIAL (decl) = 1;
5338 SET_DECL_LANGUAGE (decl, lang_c);
5339 /* Runtime library routines are, by definition, available in an
5340 external shared object. */
5341 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5342 DECL_VISIBILITY_SPECIFIED (decl) = 1;
5344 tree id = DECL_NAME (decl);
5345 const char *name = IDENTIFIER_POINTER (id);
5346 bool hiding = false;
5347 if (name[0] != '_' || name[1] != '_')
5348 /* In the user's namespace, it must be declared before use. */
5349 hiding = true;
5350 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
5351 && !startswith (name + 2, "builtin_")
5352 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
5353 "_chk", strlen ("_chk") + 1))
5354 /* Treat __*_chk fortification functions as anticipated as well,
5355 unless they are __builtin_*_chk. */
5356 hiding = true;
5358 /* All builtins that don't begin with an '_' should additionally
5359 go in the 'std' namespace. */
5360 if (name[0] != '_')
5362 tree std_decl = copy_decl (decl);
5364 push_nested_namespace (std_node);
5365 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5366 pushdecl (std_decl, hiding);
5367 pop_nested_namespace (std_node);
5370 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5371 decl = pushdecl (decl, hiding);
5373 return decl;
5376 /* Like cxx_builtin_function, but guarantee the function is added to the global
5377 scope. This is to allow function specific options to add new machine
5378 dependent builtins when the target ISA changes via attribute((target(...)))
5379 which saves space on program startup if the program does not use non-generic
5380 ISAs. */
5382 tree
5383 cxx_builtin_function_ext_scope (tree decl)
5385 push_nested_namespace (global_namespace);
5386 decl = cxx_builtin_function (decl);
5387 pop_nested_namespace (global_namespace);
5389 return decl;
5392 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5394 tree
5395 cxx_simulate_builtin_function_decl (tree decl)
5397 retrofit_lang_decl (decl);
5399 DECL_ARTIFICIAL (decl) = 1;
5400 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5401 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5402 return pushdecl (decl);
5405 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5406 function. Not called directly. */
5408 static tree
5409 build_library_fn (tree name, enum tree_code operator_code, tree type,
5410 int ecf_flags)
5412 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5413 DECL_EXTERNAL (fn) = 1;
5414 TREE_PUBLIC (fn) = 1;
5415 DECL_ARTIFICIAL (fn) = 1;
5416 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5417 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5418 SET_DECL_LANGUAGE (fn, lang_c);
5419 /* Runtime library routines are, by definition, available in an
5420 external shared object. */
5421 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5422 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5423 set_call_expr_flags (fn, ecf_flags);
5424 return fn;
5427 /* Returns the _DECL for a library function with C++ linkage. */
5429 static tree
5430 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5431 int ecf_flags)
5433 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5434 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5435 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5436 return fn;
5439 /* Like build_library_fn, but takes a C string instead of an
5440 IDENTIFIER_NODE. */
5442 tree
5443 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5445 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5448 /* Like build_cp_library_fn, but takes a C string instead of an
5449 IDENTIFIER_NODE. */
5451 tree
5452 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5454 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5455 ecf_flags);
5458 /* Like build_library_fn, but also pushes the function so that we will
5459 be able to find it via get_global_binding. Also, the function
5460 may throw exceptions listed in RAISES. */
5462 tree
5463 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5465 if (raises)
5466 type = build_exception_variant (type, raises);
5468 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5469 return pushdecl_top_level (fn);
5472 /* Like build_cp_library_fn, but also pushes the function so that it
5473 will be found by normal lookup. */
5475 static tree
5476 push_cp_library_fn (enum tree_code operator_code, tree type,
5477 int ecf_flags)
5479 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5480 operator_code, type, ecf_flags);
5481 pushdecl (fn);
5482 if (flag_tm)
5483 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5484 return fn;
5487 /* Like push_library_fn, but also note that this function throws
5488 and does not return. Used for __throw_foo and the like. */
5490 tree
5491 push_throw_library_fn (tree name, tree type)
5493 tree fn = push_library_fn (name, type, NULL_TREE,
5494 ECF_NORETURN | ECF_XTHROW | ECF_COLD);
5495 return fn;
5498 /* When we call finish_struct for an anonymous union, we create
5499 default copy constructors and such. But, an anonymous union
5500 shouldn't have such things; this function undoes the damage to the
5501 anonymous union type T.
5503 (The reason that we create the synthesized methods is that we don't
5504 distinguish `union { int i; }' from `typedef union { int i; } U'.
5505 The first is an anonymous union; the second is just an ordinary
5506 union type.) */
5508 void
5509 fixup_anonymous_aggr (tree t)
5511 /* Wipe out memory of synthesized methods. */
5512 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5513 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5514 TYPE_HAS_COPY_CTOR (t) = 0;
5515 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5516 TYPE_HAS_COPY_ASSIGN (t) = 0;
5517 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5519 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5520 invalid members. */
5521 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5523 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5524 *prev_p = DECL_CHAIN (probe);
5525 else
5526 prev_p = &DECL_CHAIN (probe);
5528 if (DECL_ARTIFICIAL (probe)
5529 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5530 || TYPE_ANON_P (TREE_TYPE (probe))))
5531 continue;
5533 if (TREE_CODE (probe) != FIELD_DECL
5534 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5536 /* We already complained about static data members in
5537 finish_static_data_member_decl. */
5538 if (!VAR_P (probe))
5540 auto_diagnostic_group d;
5541 if (permerror (DECL_SOURCE_LOCATION (probe),
5542 TREE_CODE (t) == UNION_TYPE
5543 ? "%q#D invalid; an anonymous union may "
5544 "only have public non-static data members"
5545 : "%q#D invalid; an anonymous struct may "
5546 "only have public non-static data members", probe))
5548 static bool hint;
5549 if (flag_permissive && !hint)
5551 hint = true;
5552 inform (DECL_SOURCE_LOCATION (probe),
5553 "this flexibility is deprecated and will be "
5554 "removed");
5561 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5562 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5563 unsigned store = 0;
5564 for (tree elt : vec)
5565 if (!is_overloaded_fn (elt))
5566 (*vec)[store++] = elt;
5567 vec_safe_truncate (vec, store);
5569 /* Wipe RTTI info. */
5570 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5572 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5573 assignment operators (because they cannot have these methods themselves).
5574 For anonymous unions this is already checked because they are not allowed
5575 in any union, otherwise we have to check it. */
5576 if (TREE_CODE (t) != UNION_TYPE)
5578 tree field, type;
5580 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5582 error_at (location_of (t), "anonymous struct with base classes");
5583 /* Avoid ICE after error on anon-struct9.C. */
5584 TYPE_NEEDS_CONSTRUCTING (t) = false;
5587 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5588 if (TREE_CODE (field) == FIELD_DECL)
5590 type = TREE_TYPE (field);
5591 if (CLASS_TYPE_P (type))
5593 if (TYPE_NEEDS_CONSTRUCTING (type))
5594 error ("member %q+#D with constructor not allowed "
5595 "in anonymous aggregate", field);
5596 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5597 error ("member %q+#D with destructor not allowed "
5598 "in anonymous aggregate", field);
5599 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5600 error ("member %q+#D with copy assignment operator "
5601 "not allowed in anonymous aggregate", field);
5607 /* Warn for an attribute located at LOCATION that appertains to the
5608 class type CLASS_TYPE that has not been properly placed after its
5609 class-key, in it class-specifier. */
5611 void
5612 warn_misplaced_attr_for_class_type (location_t location,
5613 tree class_type)
5615 gcc_assert (OVERLOAD_TYPE_P (class_type));
5617 auto_diagnostic_group d;
5618 if (warning_at (location, OPT_Wattributes,
5619 "attribute ignored in declaration "
5620 "of %q#T", class_type))
5621 inform (location,
5622 "attribute for %q#T must follow the %qs keyword",
5623 class_type, class_key_or_enum_as_string (class_type));
5626 /* Returns the cv-qualifiers that apply to the type specified
5627 by the DECLSPECS. */
5629 static int
5630 get_type_quals (const cp_decl_specifier_seq *declspecs)
5632 int type_quals = TYPE_UNQUALIFIED;
5634 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5635 type_quals |= TYPE_QUAL_CONST;
5636 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5637 type_quals |= TYPE_QUAL_VOLATILE;
5638 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5639 type_quals |= TYPE_QUAL_RESTRICT;
5641 return type_quals;
5644 /* Make sure that a declaration with no declarator is well-formed, i.e.
5645 just declares a tagged type or anonymous union.
5647 Returns the type declared; or NULL_TREE if none. */
5649 tree
5650 check_tag_decl (cp_decl_specifier_seq *declspecs,
5651 bool explicit_type_instantiation_p)
5653 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5654 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5655 /* If a class, struct, or enum type is declared by the DECLSPECS
5656 (i.e, if a class-specifier, enum-specifier, or non-typename
5657 elaborated-type-specifier appears in the DECLSPECS),
5658 DECLARED_TYPE is set to the corresponding type. */
5659 tree declared_type = NULL_TREE;
5660 bool error_p = false;
5662 if (declspecs->multiple_types_p)
5663 error_at (smallest_type_location (declspecs),
5664 "multiple types in one declaration");
5665 else if (declspecs->redefined_builtin_type)
5667 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5668 if (!in_system_header_at (loc))
5669 permerror (loc, "redeclaration of C++ built-in type %qT",
5670 declspecs->redefined_builtin_type);
5671 return NULL_TREE;
5674 if (declspecs->type
5675 && TYPE_P (declspecs->type)
5676 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5677 && MAYBE_CLASS_TYPE_P (declspecs->type))
5678 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5679 declared_type = declspecs->type;
5680 else if (declspecs->type == error_mark_node)
5681 error_p = true;
5683 if (type_uses_auto (declared_type))
5685 error_at (declspecs->locations[ds_type_spec],
5686 "%<auto%> can only be specified for variables "
5687 "or function declarations");
5688 return error_mark_node;
5691 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5692 declared_type = NULL_TREE;
5694 if (!declared_type && !saw_friend && !error_p)
5695 permerror (input_location, "declaration does not declare anything");
5696 /* Check for an anonymous union. */
5697 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5698 && TYPE_UNNAMED_P (declared_type))
5700 /* 7/3 In a simple-declaration, the optional init-declarator-list
5701 can be omitted only when declaring a class (clause 9) or
5702 enumeration (7.2), that is, when the decl-specifier-seq contains
5703 either a class-specifier, an elaborated-type-specifier with
5704 a class-key (9.1), or an enum-specifier. In these cases and
5705 whenever a class-specifier or enum-specifier is present in the
5706 decl-specifier-seq, the identifiers in these specifiers are among
5707 the names being declared by the declaration (as class-name,
5708 enum-names, or enumerators, depending on the syntax). In such
5709 cases, and except for the declaration of an unnamed bit-field (9.6),
5710 the decl-specifier-seq shall introduce one or more names into the
5711 program, or shall redeclare a name introduced by a previous
5712 declaration. [Example:
5713 enum { }; // ill-formed
5714 typedef class { }; // ill-formed
5715 --end example] */
5716 if (saw_typedef)
5718 error_at (declspecs->locations[ds_typedef],
5719 "missing type-name in typedef-declaration");
5720 return NULL_TREE;
5722 /* Anonymous unions are objects, so they can have specifiers. */;
5723 SET_ANON_AGGR_TYPE_P (declared_type);
5725 if (TREE_CODE (declared_type) != UNION_TYPE)
5726 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5727 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5730 else
5732 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5733 error_at (declspecs->locations[ds_inline],
5734 "%<inline%> can only be specified for functions");
5735 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5736 error_at (declspecs->locations[ds_virtual],
5737 "%<virtual%> can only be specified for functions");
5738 else if (saw_friend
5739 && (!current_class_type
5740 || current_scope () != current_class_type))
5741 error_at (declspecs->locations[ds_friend],
5742 "%<friend%> can only be specified inside a class");
5743 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5744 error_at (declspecs->locations[ds_explicit],
5745 "%<explicit%> can only be specified for constructors");
5746 else if (declspecs->storage_class)
5747 error_at (declspecs->locations[ds_storage_class],
5748 "a storage class can only be specified for objects "
5749 "and functions");
5750 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5751 error_at (declspecs->locations[ds_const],
5752 "%<const%> can only be specified for objects and "
5753 "functions");
5754 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5755 error_at (declspecs->locations[ds_volatile],
5756 "%<volatile%> can only be specified for objects and "
5757 "functions");
5758 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5759 error_at (declspecs->locations[ds_restrict],
5760 "%<__restrict%> can only be specified for objects and "
5761 "functions");
5762 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5763 error_at (declspecs->locations[ds_thread],
5764 "%<__thread%> can only be specified for objects "
5765 "and functions");
5766 else if (saw_typedef)
5767 warning_at (declspecs->locations[ds_typedef], 0,
5768 "%<typedef%> was ignored in this declaration");
5769 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5770 error_at (declspecs->locations[ds_constexpr],
5771 "%qs cannot be used for type declarations", "constexpr");
5772 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5773 error_at (declspecs->locations[ds_constinit],
5774 "%qs cannot be used for type declarations", "constinit");
5775 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5776 error_at (declspecs->locations[ds_consteval],
5777 "%qs cannot be used for type declarations", "consteval");
5780 if (declspecs->attributes && warn_attributes && declared_type)
5782 location_t loc;
5783 if (!CLASS_TYPE_P (declared_type)
5784 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5785 /* For a non-template class, use the name location. */
5786 loc = location_of (declared_type);
5787 else
5788 /* For a template class (an explicit instantiation), use the
5789 current location. */
5790 loc = input_location;
5792 if (explicit_type_instantiation_p)
5793 /* [dcl.attr.grammar]/4:
5795 No attribute-specifier-seq shall appertain to an explicit
5796 instantiation. */
5798 if (warning_at (loc, OPT_Wattributes,
5799 "attribute ignored in explicit instantiation %q#T",
5800 declared_type))
5801 inform (loc,
5802 "no attribute can be applied to "
5803 "an explicit instantiation");
5805 else
5806 warn_misplaced_attr_for_class_type (loc, declared_type);
5809 /* Diagnose invalid application of contracts, if any. */
5810 if (find_contract (declspecs->attributes))
5811 diagnose_misapplied_contracts (declspecs->attributes);
5812 else
5813 diagnose_misapplied_contracts (declspecs->std_attributes);
5815 return declared_type;
5818 /* Called when a declaration is seen that contains no names to declare.
5819 If its type is a reference to a structure, union or enum inherited
5820 from a containing scope, shadow that tag name for the current scope
5821 with a forward reference.
5822 If its type defines a new named structure or union
5823 or defines an enum, it is valid but we need not do anything here.
5824 Otherwise, it is an error.
5826 C++: may have to grok the declspecs to learn about static,
5827 complain for anonymous unions.
5829 Returns the TYPE declared -- or NULL_TREE if none. */
5831 tree
5832 shadow_tag (cp_decl_specifier_seq *declspecs)
5834 tree t = check_tag_decl (declspecs,
5835 /*explicit_type_instantiation_p=*/false);
5837 if (!t)
5838 return NULL_TREE;
5840 t = maybe_process_partial_specialization (t);
5841 if (t == error_mark_node)
5842 return NULL_TREE;
5844 /* This is where the variables in an anonymous union are
5845 declared. An anonymous union declaration looks like:
5846 union { ... } ;
5847 because there is no declarator after the union, the parser
5848 sends that declaration here. */
5849 if (ANON_AGGR_TYPE_P (t))
5851 fixup_anonymous_aggr (t);
5853 if (TYPE_FIELDS (t))
5855 tree decl = grokdeclarator (/*declarator=*/NULL,
5856 declspecs, NORMAL, 0, NULL);
5857 finish_anon_union (decl);
5861 return t;
5864 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5866 tree
5867 groktypename (cp_decl_specifier_seq *type_specifiers,
5868 const cp_declarator *declarator,
5869 bool is_template_arg)
5871 tree attrs;
5872 tree type;
5873 enum decl_context context
5874 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5875 attrs = type_specifiers->attributes;
5876 type_specifiers->attributes = NULL_TREE;
5877 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5878 if (attrs && type != error_mark_node)
5880 if (CLASS_TYPE_P (type))
5881 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5882 "outside of definition", type);
5883 else if (MAYBE_CLASS_TYPE_P (type))
5884 /* A template type parameter or other dependent type. */
5885 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5886 "type %qT without an associated declaration", type);
5887 else
5888 cplus_decl_attributes (&type, attrs, 0);
5890 return type;
5893 /* Process a DECLARATOR for a function-scope or namespace-scope
5894 variable or function declaration.
5895 (Function definitions go through start_function; class member
5896 declarations appearing in the body of the class go through
5897 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5898 If an error occurs, the error_mark_node is returned instead.
5900 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5901 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5902 for an explicitly defaulted function, or SD_DELETED for an explicitly
5903 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5904 implicitly initialized via a default constructor. It can also be
5905 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5906 mark the new decl as DECL_DECOMPOSITION_P.
5908 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5909 declaration.
5911 The scope represented by the context of the returned DECL is pushed
5912 (if it is not the global namespace) and is assigned to
5913 *PUSHED_SCOPE_P. The caller is then responsible for calling
5914 pop_scope on *PUSHED_SCOPE_P if it is set. */
5916 tree
5917 start_decl (const cp_declarator *declarator,
5918 cp_decl_specifier_seq *declspecs,
5919 int initialized,
5920 tree attributes,
5921 tree prefix_attributes,
5922 tree *pushed_scope_p)
5924 tree decl;
5925 tree context;
5926 bool was_public;
5927 int flags;
5928 bool alias;
5929 tree initial;
5931 *pushed_scope_p = NULL_TREE;
5933 if (prefix_attributes != error_mark_node)
5934 attributes = attr_chainon (attributes, prefix_attributes);
5936 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5937 &attributes);
5939 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5940 || decl == error_mark_node
5941 || prefix_attributes == error_mark_node)
5942 return error_mark_node;
5944 context = CP_DECL_CONTEXT (decl);
5945 if (context != global_namespace)
5946 *pushed_scope_p = push_scope (context);
5948 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5950 error_at (DECL_SOURCE_LOCATION (decl),
5951 "typedef %qD is initialized (use %qs instead)",
5952 decl, "decltype");
5953 return error_mark_node;
5956 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5957 with attribute validation. */
5958 initial = DECL_INITIAL (decl);
5960 if (initialized)
5962 if (! toplevel_bindings_p ()
5963 && DECL_EXTERNAL (decl))
5964 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5965 decl);
5966 DECL_EXTERNAL (decl) = 0;
5967 if (toplevel_bindings_p ())
5968 TREE_STATIC (decl) = 1;
5969 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5970 even though we might not yet have the initializer expression. */
5971 if (!DECL_INITIAL (decl))
5972 DECL_INITIAL (decl) = error_mark_node;
5974 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5976 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5977 record_key_method_defined (decl);
5979 /* If this is a typedef that names the class for linkage purposes
5980 (7.1.3p8), apply any attributes directly to the type. */
5981 if (TREE_CODE (decl) == TYPE_DECL
5982 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5983 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5984 flags = ATTR_FLAG_TYPE_IN_PLACE;
5985 else
5986 flags = 0;
5988 /* Set attributes here so if duplicate decl, will have proper attributes. */
5989 cplus_decl_attributes (&decl, attributes, flags);
5991 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5992 assist with attribute validation. */
5993 DECL_INITIAL (decl) = initial;
5995 /* Dllimported symbols cannot be defined. Static data members (which
5996 can be initialized in-class and dllimported) go through grokfield,
5997 not here, so we don't need to exclude those decls when checking for
5998 a definition. */
5999 if (initialized && DECL_DLLIMPORT_P (decl))
6001 error_at (DECL_SOURCE_LOCATION (decl),
6002 "definition of %q#D is marked %<dllimport%>", decl);
6003 DECL_DLLIMPORT_P (decl) = 0;
6006 /* If #pragma weak was used, mark the decl weak now. */
6007 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
6008 maybe_apply_pragma_weak (decl);
6010 if (TREE_CODE (decl) == FUNCTION_DECL
6011 && DECL_DECLARED_INLINE_P (decl)
6012 && DECL_UNINLINABLE (decl)
6013 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
6014 warning_at (DECL_SOURCE_LOCATION (decl), 0,
6015 "inline function %qD given attribute %qs", decl, "noinline");
6017 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
6019 bool this_tmpl = (current_template_depth
6020 > template_class_depth (context));
6021 if (VAR_P (decl))
6023 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
6024 if (field == NULL_TREE
6025 || !(VAR_P (field) || variable_template_p (field)))
6026 error ("%q+#D is not a static data member of %q#T", decl, context);
6027 else if (variable_template_p (field)
6028 && (DECL_LANG_SPECIFIC (decl)
6029 && DECL_TEMPLATE_SPECIALIZATION (decl)))
6030 /* OK, specialization was already checked. */;
6031 else if (variable_template_p (field) && !this_tmpl)
6033 error_at (DECL_SOURCE_LOCATION (decl),
6034 "non-member-template declaration of %qD", decl);
6035 inform (DECL_SOURCE_LOCATION (field), "does not match "
6036 "member template declaration here");
6037 return error_mark_node;
6039 else
6041 if (variable_template_p (field))
6042 field = DECL_TEMPLATE_RESULT (field);
6044 if (DECL_CONTEXT (field) != context)
6046 if (!same_type_p (DECL_CONTEXT (field), context))
6047 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
6048 "to be defined as %<%T::%D%>",
6049 DECL_CONTEXT (field), DECL_NAME (decl),
6050 context, DECL_NAME (decl));
6051 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
6053 /* Static data member are tricky; an in-class initialization
6054 still doesn't provide a definition, so the in-class
6055 declaration will have DECL_EXTERNAL set, but will have an
6056 initialization. Thus, duplicate_decls won't warn
6057 about this situation, and so we check here. */
6058 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
6059 error ("duplicate initialization of %qD", decl);
6060 field = duplicate_decls (decl, field);
6061 if (field == error_mark_node)
6062 return error_mark_node;
6063 else if (field)
6064 decl = field;
6067 else
6069 tree field = check_classfn (context, decl,
6070 this_tmpl
6071 ? current_template_parms
6072 : NULL_TREE);
6073 if (field && field != error_mark_node
6074 && duplicate_decls (decl, field))
6075 decl = field;
6078 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
6079 DECL_IN_AGGR_P (decl) = 0;
6080 /* Do not mark DECL as an explicit specialization if it was not
6081 already marked as an instantiation; a declaration should
6082 never be marked as a specialization unless we know what
6083 template is being specialized. */
6084 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
6086 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
6087 if (TREE_CODE (decl) == FUNCTION_DECL)
6088 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
6089 && DECL_DECLARED_INLINE_P (decl));
6090 else
6091 DECL_COMDAT (decl) = false;
6093 /* [temp.expl.spec] An explicit specialization of a static data
6094 member of a template is a definition if the declaration
6095 includes an initializer; otherwise, it is a declaration.
6097 We check for processing_specialization so this only applies
6098 to the new specialization syntax. */
6099 if (!initialized && processing_specialization)
6100 DECL_EXTERNAL (decl) = 1;
6103 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
6104 /* Aliases are definitions. */
6105 && !alias)
6107 if (DECL_VIRTUAL_P (decl) || !flag_contracts)
6108 permerror (declarator->id_loc,
6109 "declaration of %q#D outside of class is not definition",
6110 decl);
6111 else if (flag_contract_strict_declarations)
6112 warning_at (declarator->id_loc, OPT_fcontract_strict_declarations_,
6113 "declaration of %q#D outside of class is not definition",
6114 decl);
6118 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
6119 if (initialized == SD_DECOMPOSITION)
6120 fit_decomposition_lang_decl (decl, NULL_TREE);
6122 was_public = TREE_PUBLIC (decl);
6124 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
6125 && current_function_decl)
6127 /* A function-scope decl of some namespace-scope decl. */
6128 DECL_LOCAL_DECL_P (decl) = true;
6129 if (named_module_attach_p ())
6130 error_at (declarator->id_loc,
6131 "block-scope extern declaration %q#D must not be"
6132 " attached to a named module", decl);
6135 /* Enter this declaration into the symbol table. Don't push the plain
6136 VAR_DECL for a variable template. */
6137 if (!template_parm_scope_p ()
6138 || !VAR_P (decl))
6139 decl = maybe_push_decl (decl);
6141 if (processing_template_decl)
6142 decl = push_template_decl (decl);
6144 if (decl == error_mark_node)
6145 return error_mark_node;
6147 if (VAR_P (decl)
6148 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
6149 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
6150 /* But not templated variables. */
6151 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
6153 /* This is a const variable with implicit 'static'. Set
6154 DECL_THIS_STATIC so we can tell it from variables that are
6155 !TREE_PUBLIC because of the anonymous namespace. */
6156 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
6157 DECL_THIS_STATIC (decl) = 1;
6160 if (current_function_decl && VAR_P (decl)
6161 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
6162 && cxx_dialect < cxx23)
6164 bool ok = false;
6165 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
6166 error_at (DECL_SOURCE_LOCATION (decl),
6167 "%qD defined %<thread_local%> in %qs function only "
6168 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
6169 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
6170 ? "consteval" : "constexpr");
6171 else if (TREE_STATIC (decl))
6172 error_at (DECL_SOURCE_LOCATION (decl),
6173 "%qD defined %<static%> in %qs function only available "
6174 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
6175 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
6176 ? "consteval" : "constexpr");
6177 else
6178 ok = true;
6179 if (!ok)
6180 cp_function_chain->invalid_constexpr = true;
6183 if (!processing_template_decl && VAR_P (decl))
6184 start_decl_1 (decl, initialized);
6186 return decl;
6189 /* Process the declaration of a variable DECL. INITIALIZED is true
6190 iff DECL is explicitly initialized. (INITIALIZED is false if the
6191 variable is initialized via an implicitly-called constructor.)
6192 This function must be called for ordinary variables (including, for
6193 example, implicit instantiations of templates), but must not be
6194 called for template declarations. */
6196 void
6197 start_decl_1 (tree decl, bool initialized)
6199 gcc_checking_assert (!processing_template_decl);
6201 if (error_operand_p (decl))
6202 return;
6204 gcc_checking_assert (VAR_P (decl));
6206 tree type = TREE_TYPE (decl);
6207 bool complete_p = COMPLETE_TYPE_P (type);
6208 bool aggregate_definition_p
6209 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
6211 /* If an explicit initializer is present, or if this is a definition
6212 of an aggregate, then we need a complete type at this point.
6213 (Scalars are always complete types, so there is nothing to
6214 check.) This code just sets COMPLETE_P; errors (if necessary)
6215 are issued below. */
6216 if ((initialized || aggregate_definition_p)
6217 && !complete_p
6218 && COMPLETE_TYPE_P (complete_type (type)))
6220 complete_p = true;
6221 /* We will not yet have set TREE_READONLY on DECL if the type
6222 was "const", but incomplete, before this point. But, now, we
6223 have a complete type, so we can try again. */
6224 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
6227 if (initialized)
6228 /* Is it valid for this decl to have an initializer at all? */
6230 /* Don't allow initializations for incomplete types except for
6231 arrays which might be completed by the initialization. */
6232 if (complete_p)
6233 ; /* A complete type is ok. */
6234 else if (type_uses_auto (type))
6235 ; /* An auto type is ok. */
6236 else if (TREE_CODE (type) != ARRAY_TYPE)
6238 auto_diagnostic_group d;
6239 error ("variable %q#D has initializer but incomplete type", decl);
6240 maybe_suggest_missing_header (input_location,
6241 TYPE_IDENTIFIER (type),
6242 CP_TYPE_CONTEXT (type));
6243 type = TREE_TYPE (decl) = error_mark_node;
6245 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
6247 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
6248 error ("elements of array %q#D have incomplete type", decl);
6249 /* else we already gave an error in start_decl. */
6252 else if (aggregate_definition_p && !complete_p)
6254 if (type_uses_auto (type))
6255 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
6256 else
6258 auto_diagnostic_group d;
6259 error ("aggregate %q#D has incomplete type and cannot be defined",
6260 decl);
6261 maybe_suggest_missing_header (input_location,
6262 TYPE_IDENTIFIER (type),
6263 CP_TYPE_CONTEXT (type));
6264 /* Change the type so that assemble_variable will give
6265 DECL an rtl we can live with: (mem (const_int 0)). */
6266 type = TREE_TYPE (decl) = error_mark_node;
6270 /* Create a new scope to hold this declaration if necessary.
6271 Whether or not a new scope is necessary cannot be determined
6272 until after the type has been completed; if the type is a
6273 specialization of a class template it is not until after
6274 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
6275 will be set correctly. */
6276 maybe_push_cleanup_level (type);
6279 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
6280 C++20 P0960. TYPE is the type of the object we're initializing. */
6282 tree
6283 do_aggregate_paren_init (tree init, tree type)
6285 tree val = TREE_VALUE (init);
6287 if (TREE_CHAIN (init) == NULL_TREE)
6289 /* If the list has a single element and it's a string literal,
6290 then it's the initializer for the array as a whole. */
6291 if (TREE_CODE (type) == ARRAY_TYPE
6292 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6293 && TREE_CODE (tree_strip_any_location_wrapper (val))
6294 == STRING_CST)
6295 return val;
6296 /* Handle non-standard extensions like compound literals. This also
6297 prevents triggering aggregate parenthesized-initialization in
6298 compiler-generated code for =default. */
6299 else if (same_type_ignoring_top_level_qualifiers_p (type,
6300 TREE_TYPE (val)))
6301 return val;
6304 init = build_constructor_from_list (init_list_type_node, init);
6305 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6306 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6307 return init;
6310 /* Handle initialization of references. DECL, TYPE, and INIT have the
6311 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
6312 but will be set to a new CLEANUP_STMT if a temporary is created
6313 that must be destroyed subsequently.
6315 Returns an initializer expression to use to initialize DECL, or
6316 NULL if the initialization can be performed statically.
6318 Quotes on semantics can be found in ARM 8.4.3. */
6320 static tree
6321 grok_reference_init (tree decl, tree type, tree init, int flags)
6323 if (init == NULL_TREE)
6325 if ((DECL_LANG_SPECIFIC (decl) == 0
6326 || DECL_IN_AGGR_P (decl) == 0)
6327 && ! DECL_THIS_EXTERN (decl))
6328 error_at (DECL_SOURCE_LOCATION (decl),
6329 "%qD declared as reference but not initialized", decl);
6330 return NULL_TREE;
6333 tree ttype = TREE_TYPE (type);
6334 if (TREE_CODE (init) == TREE_LIST)
6336 /* This handles (C++20 only) code like
6338 const A& r(1, 2, 3);
6340 where we treat the parenthesized list as a CONSTRUCTOR. */
6341 if (TREE_TYPE (init) == NULL_TREE
6342 && CP_AGGREGATE_TYPE_P (ttype)
6343 && !DECL_DECOMPOSITION_P (decl)
6344 && (cxx_dialect >= cxx20))
6346 /* We don't know yet if we should treat const A& r(1) as
6347 const A& r{1}. */
6348 if (list_length (init) == 1)
6350 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
6351 init = build_x_compound_expr_from_list (init, ELK_INIT,
6352 tf_warning_or_error);
6354 /* If the list had more than one element, the code is ill-formed
6355 pre-C++20, so we can build a constructor right away. */
6356 else
6357 init = do_aggregate_paren_init (init, ttype);
6359 else
6360 init = build_x_compound_expr_from_list (init, ELK_INIT,
6361 tf_warning_or_error);
6364 if (TREE_CODE (ttype) != ARRAY_TYPE
6365 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
6366 /* Note: default conversion is only called in very special cases. */
6367 init = decay_conversion (init, tf_warning_or_error);
6369 /* check_initializer handles this for non-reference variables, but for
6370 references we need to do it here or the initializer will get the
6371 incomplete array type and confuse later calls to
6372 cp_complete_array_type. */
6373 if (TREE_CODE (ttype) == ARRAY_TYPE
6374 && TYPE_DOMAIN (ttype) == NULL_TREE
6375 && (BRACE_ENCLOSED_INITIALIZER_P (init)
6376 || TREE_CODE (init) == STRING_CST))
6378 cp_complete_array_type (&ttype, init, false);
6379 if (ttype != TREE_TYPE (type))
6380 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6383 /* Convert INIT to the reference type TYPE. This may involve the
6384 creation of a temporary, whose lifetime must be the same as that
6385 of the reference. If so, a DECL_EXPR for the temporary will be
6386 added just after the DECL_EXPR for DECL. That's why we don't set
6387 DECL_INITIAL for local references (instead assigning to them
6388 explicitly); we need to allow the temporary to be initialized
6389 first. */
6390 return initialize_reference (type, init, flags,
6391 tf_warning_or_error);
6394 /* Designated initializers in arrays are not supported in GNU C++.
6395 The parser cannot detect this error since it does not know whether
6396 a given brace-enclosed initializer is for a class type or for an
6397 array. This function checks that CE does not use a designated
6398 initializer. If it does, an error is issued. Returns true if CE
6399 is valid, i.e., does not have a designated initializer. */
6401 bool
6402 check_array_designated_initializer (constructor_elt *ce,
6403 unsigned HOST_WIDE_INT index)
6405 /* Designated initializers for array elements are not supported. */
6406 if (ce->index)
6408 /* The parser only allows identifiers as designated
6409 initializers. */
6410 if (ce->index == error_mark_node)
6412 error ("name used in a GNU-style designated "
6413 "initializer for an array");
6414 return false;
6416 else if (identifier_p (ce->index))
6418 error ("name %qD used in a GNU-style designated "
6419 "initializer for an array", ce->index);
6420 return false;
6423 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6424 ce->index, true);
6425 if (ce_index
6426 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6427 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6428 == INTEGER_CST))
6430 /* A C99 designator is OK if it matches the current index. */
6431 if (wi::to_wide (ce_index) == index)
6433 ce->index = ce_index;
6434 return true;
6436 else
6437 sorry ("non-trivial designated initializers not supported");
6439 else
6440 error_at (cp_expr_loc_or_input_loc (ce->index),
6441 "C99 designator %qE is not an integral constant-expression",
6442 ce->index);
6444 return false;
6447 return true;
6450 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6451 array until we finish parsing the initializer. If that's the
6452 situation we're in, update DECL accordingly. */
6454 static void
6455 maybe_deduce_size_from_array_init (tree decl, tree init)
6457 tree type = TREE_TYPE (decl);
6459 if (TREE_CODE (type) == ARRAY_TYPE
6460 && TYPE_DOMAIN (type) == NULL_TREE
6461 && TREE_CODE (decl) != TYPE_DECL)
6463 /* do_default is really a C-ism to deal with tentative definitions.
6464 But let's leave it here to ease the eventual merge. */
6465 int do_default = !DECL_EXTERNAL (decl);
6466 tree initializer = init ? init : DECL_INITIAL (decl);
6467 int failure = 0;
6469 /* Check that there are no designated initializers in INIT, as
6470 those are not supported in GNU C++, and as the middle-end
6471 will crash if presented with a non-numeric designated
6472 initializer. */
6473 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6475 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6476 constructor_elt *ce;
6477 HOST_WIDE_INT i;
6478 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6480 if (instantiation_dependent_expression_p (ce->index))
6481 return;
6482 if (!check_array_designated_initializer (ce, i))
6483 failure = 1;
6484 /* If an un-designated initializer is type-dependent, we can't
6485 check brace elision yet. */
6486 if (ce->index == NULL_TREE
6487 && type_dependent_expression_p (ce->value))
6488 return;
6492 if (failure)
6493 TREE_TYPE (decl) = error_mark_node;
6494 else
6496 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6497 do_default);
6498 if (failure == 1)
6500 error_at (cp_expr_loc_or_loc (initializer,
6501 DECL_SOURCE_LOCATION (decl)),
6502 "initializer fails to determine size of %qD", decl);
6504 else if (failure == 2)
6506 if (do_default)
6508 error_at (DECL_SOURCE_LOCATION (decl),
6509 "array size missing in %qD", decl);
6511 /* If a `static' var's size isn't known, make it extern as
6512 well as static, so it does not get allocated. If it's not
6513 `static', then don't mark it extern; finish_incomplete_decl
6514 will give it a default size and it will get allocated. */
6515 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6516 DECL_EXTERNAL (decl) = 1;
6518 else if (failure == 3)
6520 error_at (DECL_SOURCE_LOCATION (decl),
6521 "zero-size array %qD", decl);
6525 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6527 relayout_decl (decl);
6531 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6532 any appropriate error messages regarding the layout. */
6534 static void
6535 layout_var_decl (tree decl)
6537 tree type;
6539 type = TREE_TYPE (decl);
6540 if (type == error_mark_node)
6541 return;
6543 /* If we haven't already laid out this declaration, do so now.
6544 Note that we must not call complete type for an external object
6545 because it's type might involve templates that we are not
6546 supposed to instantiate yet. (And it's perfectly valid to say
6547 `extern X x' for some incomplete type `X'.) */
6548 if (!DECL_EXTERNAL (decl))
6549 complete_type (type);
6550 if (!DECL_SIZE (decl)
6551 && TREE_TYPE (decl) != error_mark_node
6552 && complete_or_array_type_p (type))
6553 layout_decl (decl, 0);
6555 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6557 /* An automatic variable with an incomplete type: that is an error.
6558 Don't talk about array types here, since we took care of that
6559 message in grokdeclarator. */
6560 error_at (DECL_SOURCE_LOCATION (decl),
6561 "storage size of %qD isn%'t known", decl);
6562 TREE_TYPE (decl) = error_mark_node;
6564 #if 0
6565 /* Keep this code around in case we later want to control debug info
6566 based on whether a type is "used". (jason 1999-11-11) */
6568 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6569 /* Let debugger know it should output info for this type. */
6570 note_debug_info_needed (ttype);
6572 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6573 note_debug_info_needed (DECL_CONTEXT (decl));
6574 #endif
6576 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6577 && DECL_SIZE (decl) != NULL_TREE
6578 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6580 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6581 && !DECL_LOCAL_DECL_P (decl))
6582 constant_expression_warning (DECL_SIZE (decl));
6583 else
6585 error_at (DECL_SOURCE_LOCATION (decl),
6586 "storage size of %qD isn%'t constant", decl);
6587 TREE_TYPE (decl) = error_mark_node;
6588 type = error_mark_node;
6592 /* If the final element initializes a flexible array field, adjust
6593 the size of the DECL with the initializer based on whether the
6594 DECL is a union or a structure. */
6595 if (type != error_mark_node
6596 && DECL_INITIAL (decl)
6597 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6598 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6599 && DECL_SIZE (decl) != NULL_TREE
6600 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6601 && COMPLETE_TYPE_P (type)
6602 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6603 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6605 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6606 if (elt.index)
6608 tree itype = TREE_TYPE (elt.index);
6609 tree vtype = TREE_TYPE (elt.value);
6610 if (TREE_CODE (itype) == ARRAY_TYPE
6611 && TYPE_DOMAIN (itype) == NULL
6612 && TREE_CODE (vtype) == ARRAY_TYPE
6613 && COMPLETE_TYPE_P (vtype))
6615 /* For a structure, add the size of the initializer to the DECL's
6616 size. */
6617 if (TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE)
6619 DECL_SIZE (decl)
6620 = size_binop (PLUS_EXPR, DECL_SIZE (decl),
6621 TYPE_SIZE (vtype));
6622 DECL_SIZE_UNIT (decl)
6623 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6624 TYPE_SIZE_UNIT (vtype));
6626 /* For a union, the DECL's size is the maximum of the current size
6627 and the size of the initializer. */
6628 else
6630 DECL_SIZE (decl)
6631 = size_binop (MAX_EXPR, DECL_SIZE (decl),
6632 TYPE_SIZE (vtype));
6633 DECL_SIZE_UNIT (decl)
6634 = size_binop (MAX_EXPR, DECL_SIZE_UNIT (decl),
6635 TYPE_SIZE_UNIT (vtype));
6642 /* If a local static variable is declared in an inline function, or if
6643 we have a weak definition, we must endeavor to create only one
6644 instance of the variable at link-time. */
6646 void
6647 maybe_commonize_var (tree decl)
6649 /* Don't mess with __FUNCTION__ and similar. But do handle structured
6650 bindings. */
6651 if (DECL_ARTIFICIAL (decl) && !DECL_DECOMPOSITION_P (decl))
6652 return;
6654 /* Static data in a function with comdat linkage also has comdat
6655 linkage. */
6656 if ((TREE_STATIC (decl)
6657 && DECL_FUNCTION_SCOPE_P (decl)
6658 && vague_linkage_p (DECL_CONTEXT (decl)))
6659 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6661 if (flag_weak)
6663 /* With weak symbols, we simply make the variable COMDAT;
6664 that will cause copies in multiple translations units to
6665 be merged. */
6666 comdat_linkage (decl);
6668 else
6670 if (DECL_INITIAL (decl) == NULL_TREE
6671 || DECL_INITIAL (decl) == error_mark_node)
6673 /* Without weak symbols, we can use COMMON to merge
6674 uninitialized variables. */
6675 TREE_PUBLIC (decl) = 1;
6676 DECL_COMMON (decl) = 1;
6678 else
6680 /* While for initialized variables, we must use internal
6681 linkage -- which means that multiple copies will not
6682 be merged. */
6683 TREE_PUBLIC (decl) = 0;
6684 DECL_COMMON (decl) = 0;
6685 DECL_INTERFACE_KNOWN (decl) = 1;
6686 const char *msg;
6687 if (DECL_INLINE_VAR_P (decl))
6688 msg = G_("sorry: semantics of inline variable "
6689 "%q#D are wrong (you%'ll wind up with "
6690 "multiple copies)");
6691 else
6692 msg = G_("sorry: semantics of inline function "
6693 "static data %q#D are wrong (you%'ll wind "
6694 "up with multiple copies)");
6695 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6696 msg, decl))
6697 inform (DECL_SOURCE_LOCATION (decl),
6698 "you can work around this by removing the initializer");
6704 /* Issue an error message if DECL is an uninitialized const variable.
6705 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6706 context from potential_constant_expression. Returns true if all is well,
6707 false otherwise. */
6709 bool
6710 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6711 tsubst_flags_t complain)
6713 tree type = strip_array_types (TREE_TYPE (decl));
6715 /* ``Unless explicitly declared extern, a const object does not have
6716 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6717 7.1.6 */
6718 if (VAR_P (decl)
6719 && !TYPE_REF_P (type)
6720 && (CP_TYPE_CONST_P (type)
6721 /* C++20 permits trivial default initialization in constexpr
6722 context (P1331R2). */
6723 || (cxx_dialect < cxx20
6724 && (constexpr_context_p
6725 || var_in_constexpr_fn (decl))))
6726 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6728 tree field = default_init_uninitialized_part (type);
6729 if (!field)
6730 return true;
6732 bool show_notes = true;
6734 if (!constexpr_context_p || cxx_dialect >= cxx20)
6736 if (CP_TYPE_CONST_P (type))
6738 if (complain & tf_error)
6739 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6740 "uninitialized %<const %D%>", decl);
6742 else
6744 if (!is_instantiation_of_constexpr (current_function_decl)
6745 && (complain & tf_error))
6746 error_at (DECL_SOURCE_LOCATION (decl),
6747 "uninitialized variable %qD in %<constexpr%> "
6748 "function", decl);
6749 else
6750 show_notes = false;
6751 cp_function_chain->invalid_constexpr = true;
6754 else if (complain & tf_error)
6755 error_at (DECL_SOURCE_LOCATION (decl),
6756 "uninitialized variable %qD in %<constexpr%> context",
6757 decl);
6759 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6761 tree defaulted_ctor;
6763 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6764 "%q#T has no user-provided default constructor", type);
6765 defaulted_ctor = in_class_defaulted_default_constructor (type);
6766 if (defaulted_ctor)
6767 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6768 "constructor is not user-provided because it is "
6769 "explicitly defaulted in the class body");
6770 inform (DECL_SOURCE_LOCATION (field),
6771 "and the implicitly-defined constructor does not "
6772 "initialize %q#D", field);
6775 return false;
6778 return true;
6781 /* Structure holding the current initializer being processed by reshape_init.
6782 CUR is a pointer to the current element being processed, END is a pointer
6783 after the last element present in the initializer. */
6784 struct reshape_iter
6786 constructor_elt *cur;
6787 constructor_elt *end;
6790 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6792 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6793 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6794 initialized as if for an aggregate class. If there are no more such fields,
6795 the return value will be NULL. */
6797 tree
6798 next_aggregate_field (tree field)
6800 while (field
6801 && (TREE_CODE (field) != FIELD_DECL
6802 || DECL_UNNAMED_BIT_FIELD (field)
6803 || (DECL_ARTIFICIAL (field)
6804 /* In C++17, aggregates can have bases. */
6805 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6806 field = DECL_CHAIN (field);
6808 return field;
6811 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6812 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6813 to a subobject. If there are no more such fields, the return value will be
6814 NULL. */
6816 tree
6817 next_subobject_field (tree field)
6819 while (field
6820 && (TREE_CODE (field) != FIELD_DECL
6821 || DECL_UNNAMED_BIT_FIELD (field)
6822 || (DECL_ARTIFICIAL (field)
6823 && !DECL_FIELD_IS_BASE (field)
6824 && !DECL_VIRTUAL_P (field))))
6825 field = DECL_CHAIN (field);
6827 return field;
6830 /* Return true for [dcl.init.list] direct-list-initialization from
6831 single element of enumeration with a fixed underlying type. */
6833 bool
6834 is_direct_enum_init (tree type, tree init)
6836 if (cxx_dialect >= cxx17
6837 && TREE_CODE (type) == ENUMERAL_TYPE
6838 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6839 && TREE_CODE (init) == CONSTRUCTOR
6840 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6841 && CONSTRUCTOR_NELTS (init) == 1
6842 /* DR 2374: The single element needs to be implicitly
6843 convertible to the underlying type of the enum. */
6844 && !type_dependent_expression_p (CONSTRUCTOR_ELT (init, 0)->value)
6845 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6846 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6847 CONSTRUCTOR_ELT (init, 0)->value,
6848 LOOKUP_IMPLICIT, tf_none))
6849 return true;
6850 return false;
6853 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6854 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6855 INTEGER_CST representing the size of the array minus one (the maximum index),
6856 or NULL_TREE if the array was declared without specifying the size. D is
6857 the iterator within the constructor. */
6859 static tree
6860 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6861 tree first_initializer_p, tsubst_flags_t complain)
6863 tree new_init;
6864 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6865 unsigned HOST_WIDE_INT max_index_cst = 0;
6866 unsigned HOST_WIDE_INT index;
6868 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6869 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6870 to build a new one. But don't reuse if not complaining; if this is
6871 tentative, we might also reshape to another type (95319). */
6872 bool reuse = (first_initializer_p
6873 && (complain & tf_error)
6874 && !CP_AGGREGATE_TYPE_P (elt_type)
6875 && !TREE_SIDE_EFFECTS (first_initializer_p));
6876 if (reuse)
6877 new_init = first_initializer_p;
6878 else
6879 new_init = build_constructor (init_list_type_node, NULL);
6881 if (sized_array_p)
6883 /* Minus 1 is used for zero sized arrays. */
6884 if (integer_all_onesp (max_index))
6885 return new_init;
6887 if (tree_fits_uhwi_p (max_index))
6888 max_index_cst = tree_to_uhwi (max_index);
6889 /* sizetype is sign extended, not zero extended. */
6890 else
6891 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6894 /* Loop until there are no more initializers. */
6895 for (index = 0;
6896 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6897 ++index)
6899 tree elt_init;
6900 constructor_elt *old_cur = d->cur;
6902 if (d->cur->index)
6903 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6904 check_array_designated_initializer (d->cur, index);
6905 elt_init = reshape_init_r (elt_type, d,
6906 /*first_initializer_p=*/NULL_TREE,
6907 complain);
6908 if (elt_init == error_mark_node)
6909 return error_mark_node;
6910 tree idx = size_int (index);
6911 if (reuse)
6913 old_cur->index = idx;
6914 old_cur->value = elt_init;
6916 else
6917 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6918 idx, elt_init);
6919 if (!TREE_CONSTANT (elt_init))
6920 TREE_CONSTANT (new_init) = false;
6922 /* This can happen with an invalid initializer (c++/54501). */
6923 if (d->cur == old_cur && !sized_array_p)
6924 break;
6927 return new_init;
6930 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6931 Parameters are the same of reshape_init_r. */
6933 static tree
6934 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6935 tsubst_flags_t complain)
6937 tree max_index = NULL_TREE;
6939 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6941 if (TYPE_DOMAIN (type))
6942 max_index = array_type_nelts (type);
6944 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6945 first_initializer_p, complain);
6948 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6949 Parameters are the same of reshape_init_r. */
6951 static tree
6952 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6954 tree max_index = NULL_TREE;
6956 gcc_assert (VECTOR_TYPE_P (type));
6958 if (COMPOUND_LITERAL_P (d->cur->value))
6960 tree value = d->cur->value;
6961 if (!same_type_p (TREE_TYPE (value), type))
6963 if (complain & tf_error)
6964 error ("invalid type %qT as initializer for a vector of type %qT",
6965 TREE_TYPE (d->cur->value), type);
6966 value = error_mark_node;
6968 ++d->cur;
6969 return value;
6972 /* For a vector, we initialize it as an array of the appropriate size. */
6973 if (VECTOR_TYPE_P (type))
6974 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6976 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6977 NULL_TREE, complain);
6980 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6981 INIT, in isolation from any designator or other initializers. */
6983 static tree
6984 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
6986 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
6987 calling reshape_init, but this way can just live on the stack. */
6988 constructor_elt elt = { /*index=*/NULL_TREE, init };
6989 reshape_iter iter = { &elt, &elt + 1 };
6990 return reshape_init_r (type, &iter,
6991 /*first_initializer_p=*/NULL_TREE,
6992 complain);
6995 /* Subroutine of reshape_init_r, processes the initializers for classes
6996 or union. Parameters are the same of reshape_init_r. */
6998 static tree
6999 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
7000 tsubst_flags_t complain)
7002 tree field;
7003 tree new_init;
7005 gcc_assert (CLASS_TYPE_P (type));
7007 /* The initializer for a class is always a CONSTRUCTOR. */
7008 new_init = build_constructor (init_list_type_node, NULL);
7010 int binfo_idx = -1;
7011 tree binfo = TYPE_BINFO (type);
7012 tree base_binfo = NULL_TREE;
7013 if (cxx_dialect >= cxx17 && uses_template_parms (type))
7015 /* We get here from maybe_aggr_guide for C++20 class template argument
7016 deduction. In this case we need to look through the binfo because a
7017 template doesn't have base fields. */
7018 binfo_idx = 0;
7019 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
7021 if (base_binfo)
7022 field = base_binfo;
7023 else
7024 field = next_aggregate_field (TYPE_FIELDS (type));
7026 if (!field)
7028 /* [dcl.init.aggr]
7030 An initializer for an aggregate member that is an
7031 empty class shall have the form of an empty
7032 initializer-list {}. */
7033 if (!first_initializer_p)
7035 if (complain & tf_error)
7036 error ("initializer for %qT must be brace-enclosed", type);
7037 return error_mark_node;
7039 return new_init;
7042 /* For C++20 CTAD, handle pack expansions in the base list. */
7043 tree last_was_pack_expansion = NULL_TREE;
7045 /* Loop through the initializable fields, gathering initializers. */
7046 while (d->cur != d->end)
7048 tree field_init;
7049 constructor_elt *old_cur = d->cur;
7050 bool direct_desig = false;
7052 /* Handle C++20 designated initializers. */
7053 if (d->cur->index)
7055 if (d->cur->index == error_mark_node)
7056 return error_mark_node;
7058 if (TREE_CODE (d->cur->index) == FIELD_DECL)
7060 /* We already reshaped this; we should have returned early from
7061 reshape_init. */
7062 gcc_checking_assert (false);
7063 if (field != d->cur->index)
7065 if (tree id = DECL_NAME (d->cur->index))
7066 gcc_checking_assert (d->cur->index
7067 == get_class_binding (type, id));
7068 field = d->cur->index;
7071 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7073 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
7074 field = get_class_binding (type, d->cur->index);
7075 direct_desig = true;
7077 else
7079 if (complain & tf_error)
7080 error ("%<[%E] =%> used in a GNU-style designated initializer"
7081 " for class %qT", d->cur->index, type);
7082 return error_mark_node;
7085 if (!field && ANON_AGGR_TYPE_P (type))
7086 /* Apparently the designator isn't for a member of this anonymous
7087 struct, so head back to the enclosing class. */
7088 break;
7090 if (!field || TREE_CODE (field) != FIELD_DECL)
7092 if (complain & tf_error)
7094 if (field && TREE_CODE (field) == TREE_LIST)
7096 error ("request for member %qD is ambiguous",
7097 d->cur->index);
7098 print_candidates (field);
7100 else
7101 error ("%qT has no non-static data member named %qD", type,
7102 d->cur->index);
7104 return error_mark_node;
7107 /* If the element is an anonymous union object and the initializer
7108 list is a designated-initializer-list, the anonymous union object
7109 is initialized by the designated-initializer-list { D }, where D
7110 is the designated-initializer-clause naming a member of the
7111 anonymous union object. */
7112 tree ictx = DECL_CONTEXT (field);
7113 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
7115 /* Find the anon aggr that is a direct member of TYPE. */
7116 while (ANON_AGGR_TYPE_P (ictx))
7118 tree cctx = TYPE_CONTEXT (ictx);
7119 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
7120 goto found;
7121 ictx = cctx;
7124 /* Not found, e.g. FIELD is a member of a base class. */
7125 if (complain & tf_error)
7126 error ("%qD is not a direct member of %qT", field, type);
7127 return error_mark_node;
7129 found:
7130 /* Now find the TYPE member with that anon aggr type. */
7131 tree aafield = TYPE_FIELDS (type);
7132 for (; aafield; aafield = TREE_CHAIN (aafield))
7133 if (TREE_TYPE (aafield) == ictx)
7134 break;
7135 gcc_assert (aafield);
7136 field = aafield;
7137 direct_desig = false;
7141 /* If we processed all the member of the class, we are done. */
7142 if (!field)
7143 break;
7145 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
7146 ? field : NULL_TREE);
7147 if (last_was_pack_expansion)
7148 /* Each non-trailing aggregate element that is a pack expansion is
7149 assumed to correspond to no elements of the initializer list. */
7150 goto continue_;
7152 if (direct_desig)
7154 /* The designated field F is initialized from this one element.
7156 Note that we don't want to do this if we found the designator
7157 inside an anon aggr above; we use the normal code to implement:
7159 "If the element is an anonymous union member and the initializer
7160 list is a brace-enclosed designated- initializer-list, the element
7161 is initialized by the designated-initializer-list { D }, where D
7162 is the designated- initializer-clause naming a member of the
7163 anonymous union member." */
7164 field_init = reshape_single_init (TREE_TYPE (field),
7165 d->cur->value, complain);
7166 d->cur++;
7168 else
7169 field_init = reshape_init_r (TREE_TYPE (field), d,
7170 /*first_initializer_p=*/NULL_TREE,
7171 complain);
7173 if (field_init == error_mark_node)
7174 return error_mark_node;
7176 if (d->cur == old_cur && d->cur->index)
7178 /* This can happen with an invalid initializer for a flexible
7179 array member (c++/54441). */
7180 if (complain & tf_error)
7181 error ("invalid initializer for %q#D", field);
7182 return error_mark_node;
7185 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
7187 /* [dcl.init.aggr]
7189 When a union is initialized with a brace-enclosed
7190 initializer, the braces shall only contain an
7191 initializer for the first member of the union. */
7192 if (TREE_CODE (type) == UNION_TYPE)
7193 break;
7195 continue_:
7196 if (base_binfo)
7198 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
7199 field = base_binfo;
7200 else
7201 field = next_aggregate_field (TYPE_FIELDS (type));
7203 else
7204 field = next_aggregate_field (DECL_CHAIN (field));
7207 /* A trailing aggregate element that is a pack expansion is assumed to
7208 correspond to all remaining elements of the initializer list (if any). */
7209 if (last_was_pack_expansion)
7211 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
7212 last_was_pack_expansion, d->cur->value);
7213 while (d->cur != d->end)
7214 d->cur++;
7217 return new_init;
7220 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
7221 designators are not valid; either complain or return true to indicate
7222 that reshape_init_r should return error_mark_node. */
7224 static bool
7225 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
7227 if (d->cur->index)
7229 if (complain & tf_error)
7230 error_at (cp_expr_loc_or_input_loc (d->cur->index),
7231 "C99 designator %qE outside aggregate initializer",
7232 d->cur->index);
7233 else
7234 return true;
7236 return false;
7239 /* Subroutine of reshape_init, which processes a single initializer (part of
7240 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
7241 iterator within the CONSTRUCTOR which points to the initializer to process.
7242 If this is the first initializer of the outermost CONSTRUCTOR node,
7243 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
7245 static tree
7246 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
7247 tsubst_flags_t complain)
7249 tree init = d->cur->value;
7251 if (error_operand_p (init))
7252 return error_mark_node;
7254 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
7255 && has_designator_problem (d, complain))
7256 return error_mark_node;
7258 tree stripped_init = tree_strip_any_location_wrapper (init);
7260 if (TREE_CODE (type) == COMPLEX_TYPE)
7262 /* A complex type can be initialized from one or two initializers,
7263 but braces are not elided. */
7264 d->cur++;
7265 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
7267 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
7269 if (complain & tf_error)
7270 error ("too many initializers for %qT", type);
7271 else
7272 return error_mark_node;
7275 else if (first_initializer_p && d->cur != d->end)
7277 vec<constructor_elt, va_gc> *v = 0;
7278 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
7279 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
7280 if (has_designator_problem (d, complain))
7281 return error_mark_node;
7282 d->cur++;
7283 init = build_constructor (init_list_type_node, v);
7285 return init;
7288 /* A non-aggregate type is always initialized with a single
7289 initializer. */
7290 if (!CP_AGGREGATE_TYPE_P (type)
7291 /* As is an array with dependent bound, which we can see
7292 during C++20 aggregate CTAD. */
7293 || (cxx_dialect >= cxx20
7294 && TREE_CODE (type) == ARRAY_TYPE
7295 && uses_template_parms (TYPE_DOMAIN (type))))
7297 /* It is invalid to initialize a non-aggregate type with a
7298 brace-enclosed initializer before C++0x.
7299 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
7300 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
7301 a CONSTRUCTOR (with a record type). */
7302 if (TREE_CODE (stripped_init) == CONSTRUCTOR
7303 /* Don't complain about a capture-init. */
7304 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
7305 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
7307 if (SCALAR_TYPE_P (type))
7309 if (cxx_dialect < cxx11)
7311 if (complain & tf_error)
7312 error ("braces around scalar initializer for type %qT",
7313 type);
7314 init = error_mark_node;
7316 else if (first_initializer_p
7317 || (CONSTRUCTOR_NELTS (stripped_init) > 0
7318 && (BRACE_ENCLOSED_INITIALIZER_P
7319 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
7321 if (complain & tf_error)
7322 error ("too many braces around scalar initializer "
7323 "for type %qT", type);
7324 init = error_mark_node;
7327 else
7328 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7331 d->cur++;
7332 return init;
7335 /* "If T is a class type and the initializer list has a single element of
7336 type cv U, where U is T or a class derived from T, the object is
7337 initialized from that element." Even if T is an aggregate. */
7338 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
7339 && first_initializer_p
7340 /* But not if it's a designated init. */
7341 && !d->cur->index
7342 && d->end - d->cur == 1
7343 && reference_related_p (type, TREE_TYPE (init)))
7345 d->cur++;
7346 return init;
7349 /* [dcl.init.aggr]
7351 All implicit type conversions (clause _conv_) are considered when
7352 initializing the aggregate member with an initializer from an
7353 initializer-list. If the initializer can initialize a member,
7354 the member is initialized. Otherwise, if the member is itself a
7355 non-empty subaggregate, brace elision is assumed and the
7356 initializer is considered for the initialization of the first
7357 member of the subaggregate. */
7358 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
7359 /* But don't try this for the first initializer, since that would be
7360 looking through the outermost braces; A a2 = { a1 }; is not a
7361 valid aggregate initialization. */
7362 && !first_initializer_p
7363 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
7364 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
7365 complain)))
7367 d->cur++;
7368 return init;
7371 /* [dcl.init.string]
7373 A char array (whether plain char, signed char, or unsigned char)
7374 can be initialized by a string-literal (optionally enclosed in
7375 braces); a wchar_t array can be initialized by a wide
7376 string-literal (optionally enclosed in braces). */
7377 if (TREE_CODE (type) == ARRAY_TYPE
7378 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
7380 tree str_init = init;
7381 tree stripped_str_init = stripped_init;
7382 reshape_iter stripd = {};
7384 /* Strip one level of braces if and only if they enclose a single
7385 element (as allowed by [dcl.init.string]). */
7386 if (!first_initializer_p
7387 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
7388 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
7390 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
7391 str_init = stripd.cur->value;
7392 stripped_str_init = tree_strip_any_location_wrapper (str_init);
7395 /* If it's a string literal, then it's the initializer for the array
7396 as a whole. Otherwise, continue with normal initialization for
7397 array types (one value per array element). */
7398 if (TREE_CODE (stripped_str_init) == STRING_CST)
7400 if ((first_initializer_p && has_designator_problem (d, complain))
7401 || (stripd.cur && has_designator_problem (&stripd, complain)))
7402 return error_mark_node;
7403 d->cur++;
7404 return str_init;
7408 /* The following cases are about aggregates. If we are not within a full
7409 initializer already, and there is not a CONSTRUCTOR, it means that there
7410 is a missing set of braces (that is, we are processing the case for
7411 which reshape_init exists). */
7412 bool braces_elided_p = false;
7413 if (!first_initializer_p)
7415 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7417 tree init_type = TREE_TYPE (init);
7418 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7419 /* There is no need to call reshape_init for pointer-to-member
7420 function initializers, as they are always constructed correctly
7421 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7422 which is missing outermost braces. We should warn below, and
7423 one of the routines below will wrap it in additional { }. */;
7424 /* For a nested compound literal, proceed to specialized routines,
7425 to handle initialization of arrays and similar. */
7426 else if (COMPOUND_LITERAL_P (stripped_init))
7427 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7428 /* If we have an unresolved designator, we need to find the member it
7429 designates within TYPE, so proceed to the routines below. For
7430 FIELD_DECL or INTEGER_CST designators, we're already initializing
7431 the designated element. */
7432 else if (d->cur->index
7433 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7434 /* Brace elision with designators is only permitted for anonymous
7435 aggregates. */
7436 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7437 /* A CONSTRUCTOR of the target's type is a previously
7438 digested initializer. */
7439 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7441 ++d->cur;
7442 return init;
7444 else
7446 /* Something that hasn't been reshaped yet. */
7447 ++d->cur;
7448 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7449 return reshape_init (type, init, complain);
7453 if (complain & tf_warning)
7454 warning (OPT_Wmissing_braces,
7455 "missing braces around initializer for %qT",
7456 type);
7457 braces_elided_p = true;
7460 /* Dispatch to specialized routines. */
7461 tree new_init;
7462 if (CLASS_TYPE_P (type))
7463 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7464 else if (TREE_CODE (type) == ARRAY_TYPE)
7465 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7466 else if (VECTOR_TYPE_P (type))
7467 new_init = reshape_init_vector (type, d, complain);
7468 else
7469 gcc_unreachable();
7471 if (braces_elided_p
7472 && TREE_CODE (new_init) == CONSTRUCTOR)
7473 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7475 return new_init;
7478 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7479 brace-enclosed aggregate initializer.
7481 INIT is the CONSTRUCTOR containing the list of initializers describing
7482 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7483 It may not presently match the shape of the TYPE; for example:
7485 struct S { int a; int b; };
7486 struct S a[] = { 1, 2, 3, 4 };
7488 Here INIT will hold a vector of four elements, rather than a
7489 vector of two elements, each itself a vector of two elements. This
7490 routine transforms INIT from the former form into the latter. The
7491 revised CONSTRUCTOR node is returned. */
7493 tree
7494 reshape_init (tree type, tree init, tsubst_flags_t complain)
7496 vec<constructor_elt, va_gc> *v;
7497 reshape_iter d;
7498 tree new_init;
7500 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7502 v = CONSTRUCTOR_ELTS (init);
7504 /* An empty constructor does not need reshaping, and it is always a valid
7505 initializer. */
7506 if (vec_safe_is_empty (v))
7507 return init;
7509 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7510 /* Already reshaped. */
7511 return init;
7513 /* Brace elision is not performed for a CONSTRUCTOR representing
7514 parenthesized aggregate initialization. */
7515 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7517 tree elt = (*v)[0].value;
7518 /* If we're initializing a char array from a string-literal that is
7519 enclosed in braces, unwrap it here. */
7520 if (TREE_CODE (type) == ARRAY_TYPE
7521 && vec_safe_length (v) == 1
7522 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7523 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7524 return elt;
7525 return init;
7528 /* Handle [dcl.init.list] direct-list-initialization from
7529 single element of enumeration with a fixed underlying type. */
7530 if (is_direct_enum_init (type, init))
7532 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7533 type = cv_unqualified (type);
7534 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7536 warning_sentinel w (warn_useless_cast);
7537 warning_sentinel w2 (warn_ignored_qualifiers);
7538 return cp_build_c_cast (input_location, type, elt,
7539 tf_warning_or_error);
7541 else
7542 return error_mark_node;
7545 /* Recurse on this CONSTRUCTOR. */
7546 d.cur = &(*v)[0];
7547 d.end = d.cur + v->length ();
7549 new_init = reshape_init_r (type, &d, init, complain);
7550 if (new_init == error_mark_node)
7551 return error_mark_node;
7553 /* Make sure all the element of the constructor were used. Otherwise,
7554 issue an error about exceeding initializers. */
7555 if (d.cur != d.end)
7557 if (complain & tf_error)
7558 error ("too many initializers for %qT", type);
7559 return error_mark_node;
7562 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7563 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7564 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7565 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7566 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7567 gcc_checking_assert (CONSTRUCTOR_IS_DESIGNATED_INIT (new_init)
7568 || seen_error ());
7570 return new_init;
7573 /* Verify array initializer. Returns true if errors have been reported. */
7575 bool
7576 check_array_initializer (tree decl, tree type, tree init)
7578 tree element_type = TREE_TYPE (type);
7580 /* Structured binding when initialized with an array type needs
7581 to have complete type. */
7582 if (decl
7583 && DECL_DECOMPOSITION_P (decl)
7584 && DECL_DECOMP_IS_BASE (decl)
7585 && !COMPLETE_TYPE_P (type))
7587 error_at (DECL_SOURCE_LOCATION (decl),
7588 "structured binding has incomplete type %qT", type);
7589 TREE_TYPE (decl) = error_mark_node;
7590 return true;
7593 /* The array type itself need not be complete, because the
7594 initializer may tell us how many elements are in the array.
7595 But, the elements of the array must be complete. */
7596 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7598 if (decl)
7599 error_at (DECL_SOURCE_LOCATION (decl),
7600 "elements of array %q#D have incomplete type", decl);
7601 else
7602 error ("elements of array %q#T have incomplete type", type);
7603 return true;
7606 location_t loc = (decl ? location_of (decl) : input_location);
7607 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7608 return true;
7610 /* A compound literal can't have variable size. */
7611 if (init && !decl
7612 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7613 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7615 error ("variable-sized compound literal");
7616 return true;
7618 return false;
7621 /* Subroutine of check_initializer; args are passed down from that function.
7622 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7624 static tree
7625 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7627 gcc_assert (stmts_are_full_exprs_p ());
7628 if (init)
7629 maybe_warn_pessimizing_move (init, TREE_TYPE (decl), /*return_p*/false);
7630 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7633 /* Verify INIT (the initializer for DECL), and record the
7634 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7635 grok_reference_init.
7637 If the return value is non-NULL, it is an expression that must be
7638 evaluated dynamically to initialize DECL. */
7640 static tree
7641 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7643 tree type;
7644 tree init_code = NULL;
7645 tree core_type;
7647 /* Things that are going to be initialized need to have complete
7648 type. */
7649 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7651 if (DECL_HAS_VALUE_EXPR_P (decl))
7653 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7654 it doesn't have storage to be initialized. */
7655 gcc_assert (init == NULL_TREE);
7656 return NULL_TREE;
7659 if (type == error_mark_node)
7660 /* We will have already complained. */
7661 return NULL_TREE;
7663 if (TREE_CODE (type) == ARRAY_TYPE)
7665 if (check_array_initializer (decl, type, init))
7666 return NULL_TREE;
7668 else if (!COMPLETE_TYPE_P (type))
7670 error_at (DECL_SOURCE_LOCATION (decl),
7671 "%q#D has incomplete type", decl);
7672 TREE_TYPE (decl) = error_mark_node;
7673 return NULL_TREE;
7675 else
7676 /* There is no way to make a variable-sized class type in GNU C++. */
7677 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7679 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7681 int init_len = CONSTRUCTOR_NELTS (init);
7682 if (SCALAR_TYPE_P (type))
7684 if (init_len == 0)
7686 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7687 init = build_zero_init (type, NULL_TREE, false);
7689 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7691 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7692 "scalar object %qD requires one element in "
7693 "initializer", decl);
7694 TREE_TYPE (decl) = error_mark_node;
7695 return NULL_TREE;
7700 if (TREE_CODE (decl) == CONST_DECL)
7702 gcc_assert (!TYPE_REF_P (type));
7704 DECL_INITIAL (decl) = init;
7706 gcc_assert (init != NULL_TREE);
7707 init = NULL_TREE;
7709 else if (!init && DECL_REALLY_EXTERN (decl))
7711 else if (init || type_build_ctor_call (type)
7712 || TYPE_REF_P (type))
7714 if (TYPE_REF_P (type))
7716 init = grok_reference_init (decl, type, init, flags);
7717 flags |= LOOKUP_ALREADY_DIGESTED;
7719 else if (!init)
7720 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7721 tf_warning_or_error);
7722 /* Do not reshape constructors of vectors (they don't need to be
7723 reshaped. */
7724 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7726 if (is_std_init_list (type))
7728 init = perform_implicit_conversion (type, init,
7729 tf_warning_or_error);
7730 flags |= LOOKUP_ALREADY_DIGESTED;
7732 else if (TYPE_NON_AGGREGATE_CLASS (type))
7734 /* Don't reshape if the class has constructors. */
7735 if (cxx_dialect == cxx98)
7736 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7737 "in C++98 %qD must be initialized by "
7738 "constructor, not by %<{...}%>",
7739 decl);
7741 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7743 error ("opaque vector types cannot be initialized");
7744 init = error_mark_node;
7746 else
7748 init = reshape_init (type, init, tf_warning_or_error);
7749 flags |= LOOKUP_NO_NARROWING;
7752 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7753 is initialized as follows..." So handle things like
7755 int a[](1, 2, 3);
7757 which is permitted in C++20 by P0960. */
7758 else if (TREE_CODE (init) == TREE_LIST
7759 && TREE_TYPE (init) == NULL_TREE
7760 && TREE_CODE (type) == ARRAY_TYPE
7761 && !DECL_DECOMPOSITION_P (decl)
7762 && (cxx_dialect >= cxx20))
7763 init = do_aggregate_paren_init (init, type);
7764 else if (TREE_CODE (init) == TREE_LIST
7765 && TREE_TYPE (init) != unknown_type_node
7766 && !MAYBE_CLASS_TYPE_P (type))
7768 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7770 /* We get here with code like `int a (2);' */
7771 init = build_x_compound_expr_from_list (init, ELK_INIT,
7772 tf_warning_or_error);
7775 /* If DECL has an array type without a specific bound, deduce the
7776 array size from the initializer. */
7777 maybe_deduce_size_from_array_init (decl, init);
7778 type = TREE_TYPE (decl);
7779 if (type == error_mark_node)
7780 return NULL_TREE;
7782 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7783 && !(flags & LOOKUP_ALREADY_DIGESTED)
7784 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7785 && CP_AGGREGATE_TYPE_P (type)
7786 && (CLASS_TYPE_P (type)
7787 /* The call to build_aggr_init below could end up
7788 calling build_vec_init, which may break when we
7789 are processing a template. */
7790 || processing_template_decl
7791 || !TYPE_NEEDS_CONSTRUCTING (type)
7792 || type_has_extended_temps (type))))
7793 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7795 init_code = build_aggr_init_full_exprs (decl, init, flags);
7797 /* A constructor call is a non-trivial initializer even if
7798 it isn't explicitly written. */
7799 if (TREE_SIDE_EFFECTS (init_code))
7800 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7802 /* If this is a constexpr initializer, expand_default_init will
7803 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7804 case, pull the initializer back out and pass it down into
7805 store_init_value. */
7806 while (true)
7808 if (TREE_CODE (init_code) == EXPR_STMT
7809 || TREE_CODE (init_code) == STMT_EXPR
7810 || TREE_CODE (init_code) == CONVERT_EXPR)
7811 init_code = TREE_OPERAND (init_code, 0);
7812 else if (TREE_CODE (init_code) == BIND_EXPR)
7813 init_code = BIND_EXPR_BODY (init_code);
7814 else
7815 break;
7817 if (TREE_CODE (init_code) == INIT_EXPR)
7819 /* In C++20, the call to build_aggr_init could have created
7820 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7821 A(1, 2). */
7822 tree rhs = TREE_OPERAND (init_code, 1);
7823 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7824 /* Avoid leaking TARGET_EXPR into template trees. */
7825 rhs = build_implicit_conv_flags (type, init, flags);
7826 init = rhs;
7828 init_code = NULL_TREE;
7829 /* Don't call digest_init; it's unnecessary and will complain
7830 about aggregate initialization of non-aggregate classes. */
7831 flags |= LOOKUP_ALREADY_DIGESTED;
7833 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7834 || DECL_DECLARED_CONSTINIT_P (decl))
7836 /* Declared constexpr or constinit, but no suitable initializer;
7837 massage init appropriately so we can pass it into
7838 store_init_value for the error. */
7839 tree new_init = NULL_TREE;
7840 if (!processing_template_decl
7841 && TREE_CODE (init_code) == CALL_EXPR)
7842 new_init = build_cplus_new (type, init_code, tf_none);
7843 else if (CLASS_TYPE_P (type)
7844 && (!init || TREE_CODE (init) == TREE_LIST))
7845 new_init = build_functional_cast (input_location, type,
7846 init, tf_none);
7847 if (new_init)
7849 init = new_init;
7850 if (TREE_CODE (init) == TARGET_EXPR
7851 && !(flags & LOOKUP_ONLYCONVERTING))
7852 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7854 init_code = NULL_TREE;
7856 else
7857 init = NULL_TREE;
7860 if (init && TREE_CODE (init) != TREE_VEC)
7862 init_code = store_init_value (decl, init, cleanups, flags);
7864 if (DECL_INITIAL (decl)
7865 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7866 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7868 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7869 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7870 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7871 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7874 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7875 && DECL_INITIAL (decl)
7876 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7877 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7878 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7879 DECL_SOURCE_LOCATION (decl)),
7880 0, "array %qD initialized by parenthesized "
7881 "string literal %qE",
7882 decl, DECL_INITIAL (decl));
7883 init = NULL_TREE;
7886 else
7888 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7889 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7890 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7891 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7892 /*complain=*/true);
7894 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7895 tf_warning_or_error);
7898 if (init && init != error_mark_node)
7899 init_code = cp_build_init_expr (decl, init);
7901 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7902 && init_code != error_mark_node)
7903 init_code = NULL_TREE;
7905 if (init_code)
7907 /* We might have set these in cp_finish_decl. */
7908 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7909 TREE_CONSTANT (decl) = false;
7912 if (init_code
7913 && DECL_IN_AGGR_P (decl)
7914 && DECL_INITIALIZED_IN_CLASS_P (decl))
7916 static int explained = 0;
7918 if (cxx_dialect < cxx11)
7919 error ("initializer invalid for static member with constructor");
7920 else if (cxx_dialect < cxx17)
7921 error ("non-constant in-class initialization invalid for static "
7922 "member %qD", decl);
7923 else
7924 error ("non-constant in-class initialization invalid for non-inline "
7925 "static member %qD", decl);
7926 if (!explained)
7928 inform (input_location,
7929 "(an out of class initialization is required)");
7930 explained = 1;
7932 return NULL_TREE;
7935 return init_code;
7938 /* If DECL is not a local variable, give it RTL. */
7940 static void
7941 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7943 int toplev = toplevel_bindings_p ();
7944 int defer_p;
7946 /* Set the DECL_ASSEMBLER_NAME for the object. */
7947 if (asmspec)
7949 /* The `register' keyword, when used together with an
7950 asm-specification, indicates that the variable should be
7951 placed in a particular register. */
7952 if (VAR_P (decl) && DECL_REGISTER (decl))
7954 set_user_assembler_name (decl, asmspec);
7955 DECL_HARD_REGISTER (decl) = 1;
7957 else
7959 if (TREE_CODE (decl) == FUNCTION_DECL
7960 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7961 set_builtin_user_assembler_name (decl, asmspec);
7962 set_user_assembler_name (decl, asmspec);
7963 if (DECL_LOCAL_DECL_P (decl))
7964 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7965 /* We have to propagate the name to the ns-alias.
7966 This is horrible, as we're affecting a
7967 possibly-shared decl. Again, a one-true-decl
7968 model breaks down. */
7969 if (ns_decl != error_mark_node)
7970 set_user_assembler_name (ns_decl, asmspec);
7974 /* Handle non-variables up front. */
7975 if (!VAR_P (decl))
7977 rest_of_decl_compilation (decl, toplev, at_eof);
7978 return;
7981 /* If we see a class member here, it should be a static data
7982 member. */
7983 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7985 gcc_assert (TREE_STATIC (decl));
7986 /* An in-class declaration of a static data member should be
7987 external; it is only a declaration, and not a definition. */
7988 if (init == NULL_TREE)
7989 gcc_assert (DECL_EXTERNAL (decl)
7990 || !TREE_PUBLIC (decl));
7993 /* We don't create any RTL for local variables. */
7994 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7995 return;
7997 /* We defer emission of local statics until the corresponding
7998 DECL_EXPR is expanded. But with constexpr its function might never
7999 be expanded, so go ahead and tell cgraph about the variable now. */
8000 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
8001 && !var_in_maybe_constexpr_fn (decl))
8002 || DECL_VIRTUAL_P (decl));
8004 /* Defer template instantiations. */
8005 if (DECL_LANG_SPECIFIC (decl)
8006 && DECL_IMPLICIT_INSTANTIATION (decl))
8007 defer_p = 1;
8009 /* If we're not deferring, go ahead and assemble the variable. */
8010 if (!defer_p)
8011 rest_of_decl_compilation (decl, toplev, at_eof);
8014 /* walk_tree helper for wrap_temporary_cleanups, below. */
8016 static tree
8017 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
8019 /* Stop at types or full-expression boundaries. */
8020 if (TYPE_P (*stmt_p)
8021 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
8023 *walk_subtrees = 0;
8024 return NULL_TREE;
8027 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
8029 tree guard = (tree)data;
8030 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
8032 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
8033 && !expr_noexcept_p (tcleanup, tf_none))
8035 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
8036 /* Tell honor_protect_cleanup_actions to handle this as a separate
8037 cleanup. */
8038 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
8039 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
8043 return NULL_TREE;
8046 /* We're initializing a local variable which has a cleanup GUARD. If there
8047 are any temporaries used in the initializer INIT of this variable, we
8048 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
8049 variable will be cleaned up properly if one of them throws.
8051 Unfortunately, there's no way to express this properly in terms of
8052 nesting, as the regions for the temporaries overlap the region for the
8053 variable itself; if there are two temporaries, the variable needs to be
8054 the first thing destroyed if either of the temporary destructors throws.
8055 However, we only want to run the variable's cleanup if it actually got
8056 constructed. So we need to guard the temporary cleanups with the
8057 variable's cleanup if they are run on the normal path, but not if they
8058 are run on the exceptional path. We implement this by telling
8059 honor_protect_cleanup_actions to strip the variable cleanup from the
8060 exceptional path.
8062 Another approach could be to make the variable cleanup region enclose
8063 initialization, but depend on a flag to indicate that the variable is
8064 initialized; that's effectively what we do for arrays. But the current
8065 approach works fine for non-arrays, and has no code overhead in the usual
8066 case where the temporary destructors are noexcept. */
8068 static void
8069 wrap_temporary_cleanups (tree init, tree guard)
8071 if (TREE_CODE (guard) == BIND_EXPR)
8073 /* An array cleanup region already encloses any temporary cleanups,
8074 don't wrap it around them again. */
8075 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
8076 return;
8078 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
8081 /* Generate code to initialize DECL (a local variable). */
8083 static void
8084 initialize_local_var (tree decl, tree init)
8086 tree type = TREE_TYPE (decl);
8087 tree cleanup;
8088 int already_used;
8090 gcc_assert (VAR_P (decl)
8091 || TREE_CODE (decl) == RESULT_DECL);
8092 gcc_assert (!TREE_STATIC (decl));
8094 if (DECL_SIZE (decl) == NULL_TREE)
8096 /* If we used it already as memory, it must stay in memory. */
8097 DECL_INITIAL (decl) = NULL_TREE;
8098 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
8099 return;
8102 if (type == error_mark_node)
8103 return;
8105 /* Compute and store the initial value. */
8106 already_used = TREE_USED (decl) || TREE_USED (type);
8107 if (TREE_USED (type))
8108 DECL_READ_P (decl) = 1;
8110 /* Generate a cleanup, if necessary. */
8111 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8113 /* Perform the initialization. */
8114 if (init)
8116 tree rinit = (TREE_CODE (init) == INIT_EXPR
8117 ? TREE_OPERAND (init, 1) : NULL_TREE);
8118 if (rinit && !TREE_SIDE_EFFECTS (rinit)
8119 && TREE_OPERAND (init, 0) == decl)
8121 /* Stick simple initializers in DECL_INITIAL so that
8122 -Wno-init-self works (c++/34772). */
8123 DECL_INITIAL (decl) = rinit;
8125 if (warn_init_self && TYPE_REF_P (type))
8127 STRIP_NOPS (rinit);
8128 if (rinit == decl)
8129 warning_at (DECL_SOURCE_LOCATION (decl),
8130 OPT_Winit_self,
8131 "reference %qD is initialized with itself", decl);
8134 else
8136 int saved_stmts_are_full_exprs_p;
8138 /* If we're only initializing a single object, guard the
8139 destructors of any temporaries used in its initializer with
8140 its destructor. */
8141 if (cleanup)
8142 wrap_temporary_cleanups (init, cleanup);
8144 gcc_assert (building_stmt_list_p ());
8145 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
8146 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
8147 finish_expr_stmt (init);
8148 current_stmt_tree ()->stmts_are_full_exprs_p =
8149 saved_stmts_are_full_exprs_p;
8153 /* Set this to 0 so we can tell whether an aggregate which was
8154 initialized was ever used. Don't do this if it has a
8155 destructor, so we don't complain about the 'resource
8156 allocation is initialization' idiom. Now set
8157 attribute((unused)) on types so decls of that type will be
8158 marked used. (see TREE_USED, above.) */
8159 if (TYPE_NEEDS_CONSTRUCTING (type)
8160 && ! already_used
8161 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8162 && DECL_NAME (decl))
8163 TREE_USED (decl) = 0;
8164 else if (already_used)
8165 TREE_USED (decl) = 1;
8167 if (cleanup)
8168 finish_decl_cleanup (decl, cleanup);
8171 /* DECL is a VAR_DECL for a compiler-generated variable with static
8172 storage duration (like a virtual table) whose initializer is a
8173 compile-time constant. Initialize the variable and provide it to the
8174 back end. */
8176 void
8177 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
8179 tree init;
8180 gcc_assert (DECL_ARTIFICIAL (decl));
8181 init = build_constructor (TREE_TYPE (decl), v);
8182 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
8183 DECL_INITIAL (decl) = init;
8184 DECL_INITIALIZED_P (decl) = 1;
8185 /* Mark the decl as constexpr so that we can access its content
8186 at compile time. */
8187 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
8188 DECL_DECLARED_CONSTEXPR_P (decl) = true;
8189 determine_visibility (decl);
8190 layout_var_decl (decl);
8191 maybe_commonize_var (decl);
8192 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
8195 /* INIT is the initializer for a variable, as represented by the
8196 parser. Returns true iff INIT is value-dependent. */
8198 static bool
8199 value_dependent_init_p (tree init)
8201 if (TREE_CODE (init) == TREE_LIST)
8202 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
8203 return any_value_dependent_elements_p (init);
8204 else if (TREE_CODE (init) == CONSTRUCTOR)
8205 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
8207 if (dependent_type_p (TREE_TYPE (init)))
8208 return true;
8210 vec<constructor_elt, va_gc> *elts;
8211 size_t nelts;
8212 size_t i;
8214 elts = CONSTRUCTOR_ELTS (init);
8215 nelts = vec_safe_length (elts);
8216 for (i = 0; i < nelts; ++i)
8217 if (value_dependent_init_p ((*elts)[i].value))
8218 return true;
8220 else
8221 /* It must be a simple expression, e.g., int i = 3; */
8222 return value_dependent_expression_p (init);
8224 return false;
8227 // Returns true if a DECL is VAR_DECL with the concept specifier.
8228 static inline bool
8229 is_concept_var (tree decl)
8231 return (VAR_P (decl)
8232 // Not all variables have DECL_LANG_SPECIFIC.
8233 && DECL_LANG_SPECIFIC (decl)
8234 && DECL_DECLARED_CONCEPT_P (decl));
8237 /* A helper function to be called via walk_tree. If any label exists
8238 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
8240 static tree
8241 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
8243 if (TYPE_P (*tp))
8244 *walk_subtrees = 0;
8245 if (TREE_CODE (*tp) == LABEL_DECL)
8246 cfun->has_forced_label_in_static = 1;
8247 return NULL_TREE;
8250 /* Return true if DECL has either a trivial destructor, or for C++20
8251 is constexpr and has a constexpr destructor. */
8253 static bool
8254 decl_maybe_constant_destruction (tree decl, tree type)
8256 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8257 || (cxx_dialect >= cxx20
8258 && VAR_P (decl)
8259 && DECL_DECLARED_CONSTEXPR_P (decl)
8260 && type_has_constexpr_destructor (strip_array_types (type))));
8263 static tree declare_simd_adjust_this (tree *, int *, void *);
8265 /* Helper function of omp_declare_variant_finalize. Finalize one
8266 "omp declare variant base" attribute. Return true if it should be
8267 removed. */
8269 static bool
8270 omp_declare_variant_finalize_one (tree decl, tree attr)
8272 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8274 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
8275 DECL_ARGUMENTS (decl), NULL);
8276 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
8277 DECL_ARGUMENTS (decl), NULL);
8280 tree ctx = TREE_VALUE (TREE_VALUE (attr));
8281 tree simd = omp_get_context_selector (ctx, OMP_TRAIT_SET_CONSTRUCT,
8282 OMP_TRAIT_CONSTRUCT_SIMD);
8283 if (simd)
8285 TREE_VALUE (simd)
8286 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
8287 OMP_TS_PROPERTIES (simd));
8288 /* FIXME, adjusting simd args unimplemented. */
8289 return true;
8292 tree chain = TREE_CHAIN (TREE_VALUE (attr));
8293 location_t varid_loc
8294 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
8295 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
8296 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
8297 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
8299 location_t save_loc = input_location;
8300 input_location = varid_loc;
8302 releasing_vec args;
8303 tree parm = DECL_ARGUMENTS (decl);
8304 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8305 parm = DECL_CHAIN (parm);
8306 for (; parm; parm = DECL_CHAIN (parm))
8307 if (type_dependent_expression_p (parm))
8308 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
8309 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
8310 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
8311 else
8312 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
8314 bool koenig_p = false;
8315 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
8317 if (identifier_p (variant)
8318 /* In C++20, we may need to perform ADL for a template
8319 name. */
8320 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
8321 && identifier_p (TREE_OPERAND (variant, 0))))
8323 if (!args->is_empty ())
8325 koenig_p = true;
8326 if (!any_type_dependent_arguments_p (args))
8327 variant = perform_koenig_lookup (variant, args,
8328 tf_warning_or_error);
8330 else
8331 variant = unqualified_fn_lookup_error (variant);
8333 else if (!args->is_empty () && is_overloaded_fn (variant))
8335 tree fn = get_first_fn (variant);
8336 fn = STRIP_TEMPLATE (fn);
8337 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
8338 || DECL_FUNCTION_MEMBER_P (fn)
8339 || DECL_LOCAL_DECL_P (fn)))
8341 koenig_p = true;
8342 if (!any_type_dependent_arguments_p (args))
8343 variant = perform_koenig_lookup (variant, args,
8344 tf_warning_or_error);
8349 if (idk == CP_ID_KIND_QUALIFIED)
8350 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
8351 koenig_p, tf_warning_or_error);
8352 else
8353 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
8354 koenig_p, tf_warning_or_error);
8355 if (variant == error_mark_node && !processing_template_decl)
8356 return true;
8358 variant = cp_get_callee_fndecl_nofold (variant);
8359 input_location = save_loc;
8361 if (variant)
8363 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
8364 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
8366 error_at (varid_loc, "variant %qD and base %qD have incompatible "
8367 "types", variant, decl);
8368 return true;
8370 if (fndecl_built_in_p (variant)
8371 && (startswith (varname, "__builtin_")
8372 || startswith (varname, "__sync_")
8373 || startswith (varname, "__atomic_")))
8375 error_at (varid_loc, "variant %qD is a built-in", variant);
8376 return true;
8378 else
8380 tree construct
8381 = omp_get_context_selector_list (ctx, OMP_TRAIT_SET_CONSTRUCT);
8382 omp_mark_declare_variant (match_loc, variant, construct);
8383 if (!omp_context_selector_matches (ctx))
8384 return true;
8385 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
8388 else if (!processing_template_decl)
8390 error_at (varid_loc, "could not find variant declaration");
8391 return true;
8394 return false;
8397 /* Helper function, finish up "omp declare variant base" attribute
8398 now that there is a DECL. ATTR is the first "omp declare variant base"
8399 attribute. */
8401 void
8402 omp_declare_variant_finalize (tree decl, tree attr)
8404 size_t attr_len = strlen ("omp declare variant base");
8405 tree *list = &DECL_ATTRIBUTES (decl);
8406 bool remove_all = false;
8407 location_t match_loc = DECL_SOURCE_LOCATION (decl);
8408 if (TREE_CHAIN (TREE_VALUE (attr))
8409 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
8410 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
8411 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
8412 if (DECL_CONSTRUCTOR_P (decl))
8414 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
8415 remove_all = true;
8417 else if (DECL_DESTRUCTOR_P (decl))
8419 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8420 remove_all = true;
8422 else if (DECL_DEFAULTED_FN (decl))
8424 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8425 remove_all = true;
8427 else if (DECL_DELETED_FN (decl))
8429 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8430 remove_all = true;
8432 else if (DECL_VIRTUAL_P (decl))
8434 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8435 remove_all = true;
8437 /* This loop is like private_lookup_attribute, except that it works
8438 with tree * rather than tree, as we might want to remove the
8439 attributes that are diagnosed as errorneous. */
8440 while (*list)
8442 tree attr = get_attribute_name (*list);
8443 size_t ident_len = IDENTIFIER_LENGTH (attr);
8444 if (cmp_attribs ("omp declare variant base", attr_len,
8445 IDENTIFIER_POINTER (attr), ident_len))
8447 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8449 *list = TREE_CHAIN (*list);
8450 continue;
8453 list = &TREE_CHAIN (*list);
8457 static void cp_maybe_mangle_decomp (tree, cp_decomp *);
8459 /* Finish processing of a declaration;
8460 install its line number and initial value.
8461 If the length of an array type is not known before,
8462 it must be determined now, from the initial value, or it is an error.
8464 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8465 true, then INIT is an integral constant expression.
8467 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8468 if the (init) syntax was used.
8470 DECOMP is first identifier's DECL and identifier count in a structured
8471 bindings, nullptr if not a structured binding. */
8473 void
8474 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8475 tree asmspec_tree, int flags, cp_decomp *decomp)
8477 vec<tree, va_gc> *cleanups = NULL;
8478 const char *asmspec = NULL;
8479 int was_readonly = 0;
8480 bool var_definition_p = false;
8481 tree auto_node;
8483 if (decl == error_mark_node)
8484 return;
8485 else if (! decl)
8487 if (init)
8488 error ("assignment (not initialization) in declaration");
8489 return;
8492 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8493 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8494 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8496 tree type = TREE_TYPE (decl);
8497 if (type == error_mark_node)
8498 return;
8500 if (VAR_P (decl) && is_copy_initialization (init))
8501 flags |= LOOKUP_ONLYCONVERTING;
8503 /* Warn about register storage specifiers except when in GNU global
8504 or local register variable extension. */
8505 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8507 if (cxx_dialect >= cxx17)
8508 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8509 "ISO C++17 does not allow %<register%> storage "
8510 "class specifier");
8511 else
8512 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8513 "%<register%> storage class specifier used");
8516 /* If a name was specified, get the string. */
8517 if (at_namespace_scope_p ())
8518 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8519 if (asmspec_tree && asmspec_tree != error_mark_node)
8520 asmspec = TREE_STRING_POINTER (asmspec_tree);
8522 bool in_class_decl
8523 = (current_class_type
8524 && CP_DECL_CONTEXT (decl) == current_class_type
8525 && TYPE_BEING_DEFINED (current_class_type)
8526 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8528 if (in_class_decl
8529 && (DECL_INITIAL (decl) || init))
8530 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8532 if (VAR_P (decl)
8533 && (auto_node = type_uses_auto (type)))
8535 tree d_init;
8536 if (init == NULL_TREE)
8538 if (DECL_LANG_SPECIFIC (decl)
8539 && DECL_TEMPLATE_INSTANTIATION (decl)
8540 && !DECL_TEMPLATE_INSTANTIATED (decl))
8542 /* init is null because we're deferring instantiating the
8543 initializer until we need it. Well, we need it now. */
8544 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8545 return;
8548 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8549 /* Class deduction with no initializer is OK. */;
8550 else
8552 /* Ordinary auto deduction without an initializer, a situation
8553 which grokdeclarator already detects and rejects for the most
8554 part. But we can still get here if we're instantiating a
8555 variable template before we've fully parsed (and attached) its
8556 initializer, e.g. template<class> auto x = x<int>; */
8557 error_at (DECL_SOURCE_LOCATION (decl),
8558 "declaration of %q#D has no initializer", decl);
8559 TREE_TYPE (decl) = error_mark_node;
8560 return;
8563 d_init = init;
8564 if (d_init)
8566 if (TREE_CODE (d_init) == TREE_LIST
8567 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8568 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8569 tf_warning_or_error);
8570 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8571 /* Force auto deduction now. Use tf_none to avoid redundant warnings
8572 on deprecated-14.C. */
8573 mark_single_function (d_init, tf_none);
8575 enum auto_deduction_context adc = adc_variable_type;
8576 if (DECL_DECOMPOSITION_P (decl))
8577 adc = adc_decomp_type;
8578 tree outer_targs = NULL_TREE;
8579 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8580 && DECL_LANG_SPECIFIC (decl)
8581 && DECL_TEMPLATE_INFO (decl)
8582 && !DECL_FUNCTION_SCOPE_P (decl))
8583 /* The outer template arguments might be needed for satisfaction.
8584 (For function scope variables, do_auto_deduction will obtain the
8585 outer template arguments from current_function_decl.) */
8586 outer_targs = DECL_TI_ARGS (decl);
8587 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8588 tf_warning_or_error, adc,
8589 outer_targs, flags);
8590 if (type == error_mark_node)
8591 return;
8592 if (TREE_CODE (type) == FUNCTION_TYPE)
8594 error ("initializer for %<decltype(auto) %D%> has function type; "
8595 "did you forget the %<()%>?", decl);
8596 TREE_TYPE (decl) = error_mark_node;
8597 return;
8599 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8600 if (!processing_template_decl
8601 && !type_uses_auto (type)
8602 && !COMPLETE_TYPE_P (complete_type (type)))
8604 error_at (location_of (decl),
8605 "deduced type %qT for %qD is incomplete", type, decl);
8606 cxx_incomplete_type_inform (type);
8607 TREE_TYPE (decl) = error_mark_node;
8608 return;
8610 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8612 /* Update the type of the corresponding TEMPLATE_DECL to match. */
8613 if (DECL_LANG_SPECIFIC (decl)
8614 && DECL_TEMPLATE_INFO (decl)
8615 && DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) == decl)
8616 TREE_TYPE (DECL_TI_TEMPLATE (decl)) = type;
8619 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8621 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8622 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8624 init = NULL_TREE;
8625 DECL_EXTERNAL (decl) = 1;
8629 if (VAR_P (decl)
8630 && DECL_CLASS_SCOPE_P (decl)
8631 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8632 TCTX_STATIC_STORAGE, type)
8633 && DECL_INITIALIZED_IN_CLASS_P (decl))
8634 check_static_variable_definition (decl, type);
8636 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8638 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8639 ? TCTX_THREAD_STORAGE
8640 : TCTX_STATIC_STORAGE);
8641 verify_type_context (input_location, context, TREE_TYPE (decl));
8644 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8646 tree clone;
8647 if (init == ridpointers[(int)RID_DELETE]
8648 || (TREE_CODE (init) == STRING_CST
8649 && TREE_TYPE (init) == ridpointers[(int)RID_DELETE]))
8651 /* FIXME check this is 1st decl. */
8652 DECL_DELETED_FN (decl) = 1;
8653 DECL_DECLARED_INLINE_P (decl) = 1;
8654 DECL_INITIAL (decl)
8655 = TREE_CODE (init) == STRING_CST ? init : error_mark_node;
8656 FOR_EACH_CLONE (clone, decl)
8658 DECL_DELETED_FN (clone) = 1;
8659 DECL_DECLARED_INLINE_P (clone) = 1;
8660 DECL_INITIAL (clone) = DECL_INITIAL (decl);
8662 init = NULL_TREE;
8664 else if (init == ridpointers[(int)RID_DEFAULT])
8666 if (defaultable_fn_check (decl))
8667 DECL_DEFAULTED_FN (decl) = 1;
8668 else
8669 DECL_INITIAL (decl) = NULL_TREE;
8673 if (init && VAR_P (decl))
8675 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8676 /* If DECL is a reference, then we want to know whether init is a
8677 reference constant; init_const_expr_p as passed tells us whether
8678 it's an rvalue constant. */
8679 if (TYPE_REF_P (type))
8680 init_const_expr_p = potential_constant_expression (init);
8681 if (init_const_expr_p)
8683 /* Set these flags now for templates. We'll update the flags in
8684 store_init_value for instantiations. */
8685 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8686 if (decl_maybe_constant_var_p (decl)
8687 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8688 && !TYPE_REF_P (type))
8689 TREE_CONSTANT (decl) = true;
8691 /* This is handled mostly by gimplify.cc, but we have to deal with
8692 not warning about int x = x; as it is a GCC extension to turn off
8693 this warning but only if warn_init_self is zero. */
8694 if (!DECL_EXTERNAL (decl)
8695 && !TREE_STATIC (decl)
8696 && decl == tree_strip_any_location_wrapper (init)
8697 && !warning_enabled_at (DECL_SOURCE_LOCATION (decl), OPT_Winit_self))
8698 suppress_warning (decl, OPT_Winit_self);
8700 else if (VAR_P (decl)
8701 && COMPLETE_TYPE_P (type)
8702 && !TYPE_REF_P (type)
8703 && !dependent_type_p (type)
8704 && is_really_empty_class (type, /*ignore_vptr*/false))
8705 /* We have no initializer but there's nothing to initialize anyway.
8706 Treat DECL as constant due to c++/109876. */
8707 TREE_CONSTANT (decl) = true;
8709 if (flag_openmp
8710 && TREE_CODE (decl) == FUNCTION_DECL
8711 /* #pragma omp declare variant on methods handled in finish_struct
8712 instead. */
8713 && (!DECL_OBJECT_MEMBER_FUNCTION_P (decl)
8714 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8715 if (tree attr = lookup_attribute ("omp declare variant base",
8716 DECL_ATTRIBUTES (decl)))
8717 omp_declare_variant_finalize (decl, attr);
8719 if (processing_template_decl)
8721 bool type_dependent_p;
8723 /* Add this declaration to the statement-tree. */
8724 if (at_function_scope_p ())
8725 add_decl_expr (decl);
8727 type_dependent_p = dependent_type_p (type);
8729 if (check_for_bare_parameter_packs (init))
8731 init = NULL_TREE;
8732 DECL_INITIAL (decl) = NULL_TREE;
8735 /* Generally, initializers in templates are expanded when the
8736 template is instantiated. But, if DECL is a variable constant
8737 then it can be used in future constant expressions, so its value
8738 must be available. */
8740 bool dep_init = false;
8742 if (!VAR_P (decl) || type_dependent_p)
8743 /* We can't do anything if the decl has dependent type. */;
8744 else if (!init && is_concept_var (decl))
8746 error ("variable concept has no initializer");
8747 init = boolean_true_node;
8749 else if (init
8750 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8751 && !TYPE_REF_P (type)
8752 && decl_maybe_constant_var_p (decl)
8753 && !(dep_init = value_dependent_init_p (init)))
8755 /* This variable seems to be a non-dependent constant, so process
8756 its initializer. If check_initializer returns non-null the
8757 initialization wasn't constant after all. */
8758 tree init_code;
8759 cleanups = make_tree_vector ();
8760 init_code = check_initializer (decl, init, flags, &cleanups);
8761 if (init_code == NULL_TREE)
8762 init = NULL_TREE;
8763 release_tree_vector (cleanups);
8765 else
8767 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8768 /* Try to deduce array size. */
8769 maybe_deduce_size_from_array_init (decl, init);
8770 /* And complain about multiple initializers. */
8771 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8772 && !MAYBE_CLASS_TYPE_P (type))
8773 init = build_x_compound_expr_from_list (init, ELK_INIT,
8774 tf_warning_or_error);
8777 if (init)
8778 DECL_INITIAL (decl) = init;
8780 if (dep_init)
8782 retrofit_lang_decl (decl);
8783 SET_DECL_DEPENDENT_INIT_P (decl, true);
8786 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8788 set_user_assembler_name (decl, asmspec);
8789 DECL_HARD_REGISTER (decl) = 1;
8791 return;
8794 /* Just store non-static data member initializers for later. */
8795 if (init && TREE_CODE (decl) == FIELD_DECL)
8796 DECL_INITIAL (decl) = init;
8798 /* Take care of TYPE_DECLs up front. */
8799 if (TREE_CODE (decl) == TYPE_DECL)
8801 if (type != error_mark_node
8802 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8804 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8805 warning (0, "shadowing previous type declaration of %q#D", decl);
8806 set_identifier_type_value (DECL_NAME (decl), decl);
8809 /* If we have installed this as the canonical typedef for this
8810 type, and that type has not been defined yet, delay emitting
8811 the debug information for it, as we will emit it later. */
8812 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8813 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8814 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8816 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8817 at_eof);
8818 return;
8821 /* A reference will be modified here, as it is initialized. */
8822 if (! DECL_EXTERNAL (decl)
8823 && TREE_READONLY (decl)
8824 && TYPE_REF_P (type))
8826 was_readonly = 1;
8827 TREE_READONLY (decl) = 0;
8830 /* This needs to happen before extend_ref_init_temps. */
8831 if (VAR_OR_FUNCTION_DECL_P (decl))
8833 if (VAR_P (decl))
8834 maybe_commonize_var (decl);
8835 determine_visibility (decl);
8838 if (VAR_P (decl))
8840 duration_kind dk = decl_storage_duration (decl);
8841 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8842 only to a declaration of a variable with static or thread storage
8843 duration." */
8844 if (DECL_DECLARED_CONSTINIT_P (decl)
8845 && !(dk == dk_thread || dk == dk_static))
8847 error_at (DECL_SOURCE_LOCATION (decl),
8848 "%<constinit%> can only be applied to a variable with "
8849 "static or thread storage duration");
8850 return;
8853 if (decomp)
8854 cp_maybe_mangle_decomp (decl, decomp);
8856 /* If this is a local variable that will need a mangled name,
8857 register it now. We must do this before processing the
8858 initializer for the variable, since the initialization might
8859 require a guard variable, and since the mangled name of the
8860 guard variable will depend on the mangled name of this
8861 variable. */
8862 if (DECL_FUNCTION_SCOPE_P (decl)
8863 && TREE_STATIC (decl)
8864 && !DECL_ARTIFICIAL (decl))
8866 /* The variable holding an anonymous union will have had its
8867 discriminator set in finish_anon_union, after which it's
8868 NAME will have been cleared. */
8869 if (DECL_NAME (decl))
8870 determine_local_discriminator (decl);
8871 /* Normally has_forced_label_in_static is set during GIMPLE
8872 lowering, but [cd]tors are never actually compiled directly.
8873 We need to set this early so we can deal with the label
8874 address extension. */
8875 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8876 || DECL_DESTRUCTOR_P (current_function_decl))
8877 && init)
8879 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8880 add_local_decl (cfun, decl);
8882 /* And make sure it's in the symbol table for
8883 c_parse_final_cleanups to find. */
8884 varpool_node::get_create (decl);
8887 /* Convert the initializer to the type of DECL, if we have not
8888 already initialized DECL. */
8889 if (!DECL_INITIALIZED_P (decl)
8890 /* If !DECL_EXTERNAL then DECL is being defined. In the
8891 case of a static data member initialized inside the
8892 class-specifier, there can be an initializer even if DECL
8893 is *not* defined. */
8894 && (!DECL_EXTERNAL (decl) || init))
8896 cleanups = make_tree_vector ();
8897 init = check_initializer (decl, init, flags, &cleanups);
8899 /* Handle:
8901 [dcl.init]
8903 The memory occupied by any object of static storage
8904 duration is zero-initialized at program startup before
8905 any other initialization takes place.
8907 We cannot create an appropriate initializer until after
8908 the type of DECL is finalized. If DECL_INITIAL is set,
8909 then the DECL is statically initialized, and any
8910 necessary zero-initialization has already been performed. */
8911 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8912 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8913 /*nelts=*/NULL_TREE,
8914 /*static_storage_p=*/true);
8915 /* Remember that the initialization for this variable has
8916 taken place. */
8917 DECL_INITIALIZED_P (decl) = 1;
8918 /* This declaration is the definition of this variable,
8919 unless we are initializing a static data member within
8920 the class specifier. */
8921 if (!DECL_EXTERNAL (decl))
8922 var_definition_p = true;
8924 /* If the variable has an array type, lay out the type, even if
8925 there is no initializer. It is valid to index through the
8926 array, and we must get TYPE_ALIGN set correctly on the array
8927 type. */
8928 else if (TREE_CODE (type) == ARRAY_TYPE)
8929 layout_type (type);
8931 if (TREE_STATIC (decl)
8932 && !at_function_scope_p ()
8933 && current_function_decl == NULL)
8934 /* So decl is a global variable or a static member of a
8935 non local class. Record the types it uses
8936 so that we can decide later to emit debug info for them. */
8937 record_types_used_by_current_var_decl (decl);
8940 /* Add this declaration to the statement-tree. This needs to happen
8941 after the call to check_initializer so that the DECL_EXPR for a
8942 reference temp is added before the DECL_EXPR for the reference itself. */
8943 if (DECL_FUNCTION_SCOPE_P (decl))
8945 /* If we're building a variable sized type, and we might be
8946 reachable other than via the top of the current binding
8947 level, then create a new BIND_EXPR so that we deallocate
8948 the object at the right time. */
8949 if (VAR_P (decl)
8950 && DECL_SIZE (decl)
8951 && !TREE_CONSTANT (DECL_SIZE (decl))
8952 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8954 tree bind;
8955 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8956 TREE_SIDE_EFFECTS (bind) = 1;
8957 add_stmt (bind);
8958 BIND_EXPR_BODY (bind) = push_stmt_list ();
8960 add_decl_expr (decl);
8963 /* Let the middle end know about variables and functions -- but not
8964 static data members in uninstantiated class templates. */
8965 if (VAR_OR_FUNCTION_DECL_P (decl))
8967 if (VAR_P (decl))
8969 layout_var_decl (decl);
8970 if (!flag_weak)
8971 /* Check again now that we have an initializer. */
8972 maybe_commonize_var (decl);
8973 /* A class-scope constexpr variable with an out-of-class declaration.
8974 C++17 makes them implicitly inline, but still force it out. */
8975 if (DECL_INLINE_VAR_P (decl)
8976 && !DECL_VAR_DECLARED_INLINE_P (decl)
8977 && !DECL_TEMPLATE_INSTANTIATION (decl)
8978 && !in_class_decl)
8979 mark_needed (decl);
8982 if (var_definition_p
8983 /* With -fmerge-all-constants, gimplify_init_constructor
8984 might add TREE_STATIC to aggregate variables. */
8985 && (TREE_STATIC (decl)
8986 || (flag_merge_constants >= 2
8987 && AGGREGATE_TYPE_P (type))))
8989 /* If a TREE_READONLY variable needs initialization
8990 at runtime, it is no longer readonly and we need to
8991 avoid MEM_READONLY_P being set on RTL created for it. */
8992 if (init)
8994 if (TREE_READONLY (decl))
8995 TREE_READONLY (decl) = 0;
8996 was_readonly = 0;
8998 else if (was_readonly)
8999 TREE_READONLY (decl) = 1;
9001 /* Likewise if it needs destruction. */
9002 if (!decl_maybe_constant_destruction (decl, type))
9003 TREE_READONLY (decl) = 0;
9005 else if (VAR_P (decl)
9006 && CP_DECL_THREAD_LOCAL_P (decl)
9007 && (!DECL_EXTERNAL (decl) || flag_extern_tls_init)
9008 && (was_readonly || TREE_READONLY (decl))
9009 && var_needs_tls_wrapper (decl))
9011 /* TLS variables need dynamic initialization by the TLS wrapper
9012 function, we don't want to hoist accesses to it before the
9013 wrapper. */
9014 was_readonly = 0;
9015 TREE_READONLY (decl) = 0;
9018 make_rtl_for_nonlocal_decl (decl, init, asmspec);
9020 /* Check for abstractness of the type. */
9021 if (var_definition_p)
9022 abstract_virtuals_error (decl, type);
9024 if (TREE_TYPE (decl) == error_mark_node)
9025 /* No initialization required. */
9027 else if (TREE_CODE (decl) == FUNCTION_DECL)
9029 if (init)
9031 if (init == ridpointers[(int)RID_DEFAULT])
9033 /* An out-of-class default definition is defined at
9034 the point where it is explicitly defaulted. */
9035 if (DECL_DELETED_FN (decl))
9036 maybe_explain_implicit_delete (decl);
9037 else if (DECL_INITIAL (decl) == error_mark_node)
9038 synthesize_method (decl);
9040 else
9041 error_at (cp_expr_loc_or_loc (init,
9042 DECL_SOURCE_LOCATION (decl)),
9043 "function %q#D is initialized like a variable",
9044 decl);
9046 /* else no initialization required. */
9048 else if (DECL_EXTERNAL (decl)
9049 && ! (DECL_LANG_SPECIFIC (decl)
9050 && DECL_NOT_REALLY_EXTERN (decl)))
9052 /* check_initializer will have done any constant initialization. */
9054 /* A variable definition. */
9055 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
9056 /* Initialize the local variable. */
9057 initialize_local_var (decl, init);
9059 /* If a variable is defined, and then a subsequent
9060 definition with external linkage is encountered, we will
9061 get here twice for the same variable. We want to avoid
9062 calling expand_static_init more than once. For variables
9063 that are not static data members, we can call
9064 expand_static_init only when we actually process the
9065 initializer. It is not legal to redeclare a static data
9066 member, so this issue does not arise in that case. */
9067 else if (var_definition_p && TREE_STATIC (decl))
9068 expand_static_init (decl, init);
9071 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
9072 reference, insert it in the statement-tree now. */
9073 if (cleanups)
9075 for (tree t : *cleanups)
9077 push_cleanup (NULL_TREE, t, false);
9078 /* As in initialize_local_var. */
9079 wrap_temporary_cleanups (init, t);
9081 release_tree_vector (cleanups);
9084 if (was_readonly)
9085 TREE_READONLY (decl) = 1;
9087 if (flag_openmp
9088 && VAR_P (decl)
9089 && lookup_attribute ("omp declare target implicit",
9090 DECL_ATTRIBUTES (decl)))
9092 DECL_ATTRIBUTES (decl)
9093 = remove_attribute ("omp declare target implicit",
9094 DECL_ATTRIBUTES (decl));
9095 complete_type (TREE_TYPE (decl));
9096 if (!omp_mappable_type (TREE_TYPE (decl)))
9098 error ("%q+D in declare target directive does not have mappable"
9099 " type", decl);
9100 if (TREE_TYPE (decl) != error_mark_node
9101 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
9102 cxx_incomplete_type_inform (TREE_TYPE (decl));
9104 else if (!lookup_attribute ("omp declare target",
9105 DECL_ATTRIBUTES (decl))
9106 && !lookup_attribute ("omp declare target link",
9107 DECL_ATTRIBUTES (decl)))
9109 DECL_ATTRIBUTES (decl)
9110 = tree_cons (get_identifier ("omp declare target"),
9111 NULL_TREE, DECL_ATTRIBUTES (decl));
9112 symtab_node *node = symtab_node::get (decl);
9113 if (node != NULL)
9115 node->offloadable = 1;
9116 if (ENABLE_OFFLOADING)
9118 g->have_offload = true;
9119 if (is_a <varpool_node *> (node))
9120 vec_safe_push (offload_vars, decl);
9126 /* This is the last point we can lower alignment so give the target the
9127 chance to do so. */
9128 if (VAR_P (decl)
9129 && !is_global_var (decl)
9130 && !DECL_HARD_REGISTER (decl))
9131 targetm.lower_local_decl_alignment (decl);
9133 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
9136 /* For class TYPE return itself or some its bases that contain
9137 any direct non-static data members. Return error_mark_node if an
9138 error has been diagnosed. */
9140 static tree
9141 find_decomp_class_base (location_t loc, tree type, tree ret)
9143 bool member_seen = false;
9144 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9145 if (TREE_CODE (field) != FIELD_DECL
9146 || DECL_ARTIFICIAL (field)
9147 || DECL_UNNAMED_BIT_FIELD (field))
9148 continue;
9149 else if (ret)
9150 return type;
9151 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
9153 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
9154 error_at (loc, "cannot decompose class type %qT because it has an "
9155 "anonymous struct member", type);
9156 else
9157 error_at (loc, "cannot decompose class type %qT because it has an "
9158 "anonymous union member", type);
9159 inform (DECL_SOURCE_LOCATION (field), "declared here");
9160 return error_mark_node;
9162 else if (!accessible_p (type, field, true))
9164 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
9165 field, type);
9166 inform (DECL_SOURCE_LOCATION (field),
9167 TREE_PRIVATE (field)
9168 ? G_("declared private here")
9169 : G_("declared protected here"));
9170 return error_mark_node;
9172 else
9173 member_seen = true;
9175 tree base_binfo, binfo;
9176 tree orig_ret = ret;
9177 int i;
9178 if (member_seen)
9179 ret = type;
9180 for (binfo = TYPE_BINFO (type), i = 0;
9181 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
9183 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
9184 if (t == error_mark_node)
9185 return error_mark_node;
9186 if (t != NULL_TREE && t != ret)
9188 if (ret == type)
9190 error_at (loc, "cannot decompose class type %qT: both it and "
9191 "its base class %qT have non-static data members",
9192 type, t);
9193 return error_mark_node;
9195 else if (orig_ret != NULL_TREE)
9196 return t;
9197 else if (ret != NULL_TREE)
9199 error_at (loc, "cannot decompose class type %qT: its base "
9200 "classes %qT and %qT have non-static data "
9201 "members", type, ret, t);
9202 return error_mark_node;
9204 else
9205 ret = t;
9208 return ret;
9211 /* Return std::tuple_size<TYPE>::value. */
9213 static tree
9214 get_tuple_size (tree type)
9216 tree args = make_tree_vec (1);
9217 TREE_VEC_ELT (args, 0) = type;
9218 tree inst = lookup_template_class (tuple_size_identifier, args,
9219 /*in_decl*/NULL_TREE,
9220 /*context*/std_node,
9221 tf_none);
9222 inst = complete_type (inst);
9223 if (inst == error_mark_node
9224 || !COMPLETE_TYPE_P (inst)
9225 || !CLASS_TYPE_P (type))
9226 return NULL_TREE;
9227 tree val = lookup_qualified_name (inst, value_identifier,
9228 LOOK_want::NORMAL, /*complain*/false);
9229 if (val == error_mark_node)
9230 return NULL_TREE;
9231 if (VAR_P (val) || TREE_CODE (val) == CONST_DECL)
9232 val = maybe_constant_value (val);
9233 if (TREE_CODE (val) == INTEGER_CST)
9234 return val;
9235 else
9236 return error_mark_node;
9239 /* Return std::tuple_element<I,TYPE>::type. */
9241 static tree
9242 get_tuple_element_type (tree type, unsigned i)
9244 tree args = make_tree_vec (2);
9245 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
9246 TREE_VEC_ELT (args, 1) = type;
9247 tree inst = lookup_template_class (tuple_element_identifier, args,
9248 /*in_decl*/NULL_TREE,
9249 /*context*/std_node,
9250 tf_warning_or_error);
9251 return make_typename_type (inst, type_identifier,
9252 none_type, tf_warning_or_error);
9255 /* Return e.get<i>() or get<i>(e). */
9257 static tree
9258 get_tuple_decomp_init (tree decl, unsigned i)
9260 tree targs = make_tree_vec (1);
9261 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
9263 tree etype = TREE_TYPE (decl);
9264 tree e = convert_from_reference (decl);
9266 /* [The id-expression] e is an lvalue if the type of the entity e is an
9267 lvalue reference and an xvalue otherwise. */
9268 if (!TYPE_REF_P (etype)
9269 || TYPE_REF_IS_RVALUE (etype))
9270 e = move (e);
9272 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
9273 LOOK_want::NORMAL, /*complain*/false);
9274 bool use_member_get = false;
9276 /* To use a member get, member lookup must find at least one
9277 declaration that is a function template
9278 whose first template parameter is a non-type parameter. */
9279 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
9281 tree fn = *iter;
9282 if (TREE_CODE (fn) == TEMPLATE_DECL)
9284 tree tparms = DECL_TEMPLATE_PARMS (fn);
9285 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
9286 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
9288 use_member_get = true;
9289 break;
9294 if (use_member_get)
9296 fns = lookup_template_function (fns, targs);
9297 return build_new_method_call (e, fns, /*args*/NULL,
9298 /*path*/NULL_TREE, LOOKUP_NORMAL,
9299 /*fn_p*/NULL, tf_warning_or_error);
9301 else
9303 releasing_vec args (make_tree_vector_single (e));
9304 fns = lookup_template_function (get__identifier, targs);
9305 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
9306 return finish_call_expr (fns, &args, /*novirt*/false,
9307 /*koenig*/true, tf_warning_or_error);
9311 /* It's impossible to recover the decltype of a tuple decomposition variable
9312 based on the actual type of the variable, so store it in a hash table. */
9314 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
9316 tree
9317 lookup_decomp_type (tree v)
9319 if (tree *slot = decomp_type_table->get (v))
9320 return *slot;
9321 return NULL_TREE;
9324 /* Mangle a decomposition declaration if needed. Arguments like
9325 in cp_finish_decomp. */
9327 static void
9328 cp_maybe_mangle_decomp (tree decl, cp_decomp *decomp)
9330 if (!processing_template_decl
9331 && !error_operand_p (decl)
9332 && TREE_STATIC (decl))
9334 auto_vec<tree, 16> v;
9335 v.safe_grow (decomp->count, true);
9336 tree d = decomp->decl;
9337 for (unsigned int i = 0; i < decomp->count; i++, d = DECL_CHAIN (d))
9338 v[decomp->count - i - 1] = d;
9339 if (DECL_FUNCTION_SCOPE_P (decl))
9341 size_t sz = 3;
9342 for (unsigned int i = 0; i < decomp->count; ++i)
9343 sz += IDENTIFIER_LENGTH (DECL_NAME (v[i])) + 1;
9344 char *name = XALLOCAVEC (char, sz);
9345 name[0] = 'D';
9346 name[1] = 'C';
9347 char *p = name + 2;
9348 for (unsigned int i = 0; i < decomp->count; ++i)
9350 size_t len = IDENTIFIER_LENGTH (DECL_NAME (v[i]));
9351 *p++ = ' ';
9352 memcpy (p, IDENTIFIER_POINTER (DECL_NAME (v[i])), len);
9353 p += len;
9355 *p = '\0';
9356 determine_local_discriminator (decl, get_identifier (name));
9358 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
9359 maybe_apply_pragma_weak (decl);
9363 /* Finish a decomposition declaration. DECL is the underlying declaration
9364 "e", FIRST is the head of a chain of decls for the individual identifiers
9365 chained through DECL_CHAIN in reverse order and COUNT is the number of
9366 those decls. */
9368 void
9369 cp_finish_decomp (tree decl, cp_decomp *decomp)
9371 tree first = decomp->decl;
9372 unsigned count = decomp->count;
9373 if (error_operand_p (decl))
9375 error_out:
9376 while (count--)
9378 TREE_TYPE (first) = error_mark_node;
9379 if (DECL_HAS_VALUE_EXPR_P (first))
9381 SET_DECL_VALUE_EXPR (first, NULL_TREE);
9382 DECL_HAS_VALUE_EXPR_P (first) = 0;
9384 first = DECL_CHAIN (first);
9386 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
9387 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
9388 return;
9391 location_t loc = DECL_SOURCE_LOCATION (decl);
9392 if (type_dependent_expression_p (decl)
9393 /* This happens for range for when not in templates.
9394 Still add the DECL_VALUE_EXPRs for later processing. */
9395 || (!processing_template_decl
9396 && type_uses_auto (TREE_TYPE (decl))))
9398 for (unsigned int i = 0; i < count; i++)
9400 if (!DECL_HAS_VALUE_EXPR_P (first))
9402 tree v = build_nt (ARRAY_REF, decl,
9403 size_int (count - i - 1),
9404 NULL_TREE, NULL_TREE);
9405 SET_DECL_VALUE_EXPR (first, v);
9406 DECL_HAS_VALUE_EXPR_P (first) = 1;
9408 if (processing_template_decl)
9409 fit_decomposition_lang_decl (first, decl);
9410 first = DECL_CHAIN (first);
9412 return;
9415 auto_vec<tree, 16> v;
9416 v.safe_grow (count, true);
9417 tree d = first;
9418 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9420 v[count - i - 1] = d;
9421 fit_decomposition_lang_decl (d, decl);
9424 tree type = TREE_TYPE (decl);
9425 tree dexp = decl;
9427 if (TYPE_REF_P (type))
9429 dexp = convert_from_reference (dexp);
9430 type = complete_type (TREE_TYPE (type));
9431 if (type == error_mark_node)
9432 goto error_out;
9433 if (!COMPLETE_TYPE_P (type))
9435 error_at (loc, "structured binding refers to incomplete type %qT",
9436 type);
9437 goto error_out;
9441 tree eltype = NULL_TREE;
9442 unsigned HOST_WIDE_INT eltscnt = 0;
9443 if (TREE_CODE (type) == ARRAY_TYPE)
9445 tree nelts;
9446 nelts = array_type_nelts_top (type);
9447 if (nelts == error_mark_node)
9448 goto error_out;
9449 if (DECL_DECOMP_BASE (decl))
9451 error_at (loc, "array initializer for structured binding "
9452 "declaration in condition");
9453 goto error_out;
9455 if (!tree_fits_uhwi_p (nelts))
9457 error_at (loc, "cannot decompose variable length array %qT", type);
9458 goto error_out;
9460 eltscnt = tree_to_uhwi (nelts);
9461 if (count != eltscnt)
9463 cnt_mismatch:
9464 if (count > eltscnt)
9465 error_n (loc, count,
9466 "%u name provided for structured binding",
9467 "%u names provided for structured binding", count);
9468 else
9469 error_n (loc, count,
9470 "only %u name provided for structured binding",
9471 "only %u names provided for structured binding", count);
9472 inform_n (loc, eltscnt,
9473 "while %qT decomposes into %wu element",
9474 "while %qT decomposes into %wu elements",
9475 type, eltscnt);
9476 goto error_out;
9478 eltype = TREE_TYPE (type);
9479 for (unsigned int i = 0; i < count; i++)
9481 TREE_TYPE (v[i]) = eltype;
9482 layout_decl (v[i], 0);
9483 if (processing_template_decl)
9484 continue;
9485 tree t = unshare_expr (dexp);
9486 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9487 SET_DECL_VALUE_EXPR (v[i], t);
9488 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9491 /* 2 GNU extensions. */
9492 else if (TREE_CODE (type) == COMPLEX_TYPE)
9494 eltscnt = 2;
9495 if (count != eltscnt)
9496 goto cnt_mismatch;
9497 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9498 for (unsigned int i = 0; i < count; i++)
9500 TREE_TYPE (v[i]) = eltype;
9501 layout_decl (v[i], 0);
9502 if (processing_template_decl)
9503 continue;
9504 tree t = unshare_expr (dexp);
9505 t = build1 (i ? IMAGPART_EXPR : REALPART_EXPR, eltype, t);
9506 SET_DECL_VALUE_EXPR (v[i], t);
9507 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9510 else if (TREE_CODE (type) == VECTOR_TYPE)
9512 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9514 error_at (loc, "cannot decompose variable length vector %qT", type);
9515 goto error_out;
9517 if (count != eltscnt)
9518 goto cnt_mismatch;
9519 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9520 for (unsigned int i = 0; i < count; i++)
9522 TREE_TYPE (v[i]) = eltype;
9523 layout_decl (v[i], 0);
9524 if (processing_template_decl)
9525 continue;
9526 tree t = unshare_expr (dexp);
9527 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9528 &t, size_int (i));
9529 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9530 SET_DECL_VALUE_EXPR (v[i], t);
9531 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9534 else if (tree tsize = get_tuple_size (type))
9536 if (tsize == error_mark_node)
9538 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9539 "constant expression", type);
9540 goto error_out;
9542 if (!tree_fits_uhwi_p (tsize))
9544 error_n (loc, count,
9545 "%u name provided for structured binding",
9546 "%u names provided for structured binding", count);
9547 inform (loc, "while %qT decomposes into %E elements",
9548 type, tsize);
9549 goto error_out;
9551 eltscnt = tree_to_uhwi (tsize);
9552 if (count != eltscnt)
9553 goto cnt_mismatch;
9554 if (!processing_template_decl && DECL_DECOMP_BASE (decl))
9556 /* For structured bindings used in conditions we need to evaluate
9557 the conversion of decl (aka e in the standard) to bool or
9558 integral/enumeral type (the latter for switch conditions)
9559 before the get methods. */
9560 tree cond = convert_from_reference (decl);
9561 if (integer_onep (DECL_DECOMP_BASE (decl)))
9562 /* switch condition. */
9563 cond = build_expr_type_conversion (WANT_INT | WANT_ENUM,
9564 cond, true);
9565 else
9566 /* if/while/for condition. */
9567 cond = contextual_conv_bool (cond, tf_warning_or_error);
9568 if (cond && !error_operand_p (cond))
9570 /* Wrap that value into a TARGET_EXPR, emit it right
9571 away and save for later uses in the cp_parse_condition
9572 or its instantiation. */
9573 cond = get_target_expr (cond);
9574 add_stmt (cond);
9575 DECL_DECOMP_BASE (decl) = cond;
9578 int save_read = DECL_READ_P (decl);
9579 for (unsigned i = 0; i < count; ++i)
9581 location_t sloc = input_location;
9582 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9584 input_location = dloc;
9585 tree init = get_tuple_decomp_init (decl, i);
9586 tree eltype = (init == error_mark_node ? error_mark_node
9587 : get_tuple_element_type (type, i));
9588 input_location = sloc;
9590 if (VOID_TYPE_P (eltype))
9592 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9593 i, type);
9594 eltype = error_mark_node;
9596 if (init == error_mark_node || eltype == error_mark_node)
9598 inform (dloc, "in initialization of structured binding "
9599 "variable %qD", v[i]);
9600 goto error_out;
9602 /* Save the decltype away before reference collapse. */
9603 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9604 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9605 TREE_TYPE (v[i]) = eltype;
9606 layout_decl (v[i], 0);
9607 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9609 /* In this case the names are variables, not just proxies. */
9610 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9611 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9613 if (!processing_template_decl)
9615 copy_linkage (v[i], decl);
9616 cp_finish_decl (v[i], init, /*constexpr*/false,
9617 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9620 /* Ignore reads from the underlying decl performed during initialization
9621 of the individual variables. If those will be read, we'll mark
9622 the underlying decl as read at that point. */
9623 DECL_READ_P (decl) = save_read;
9625 else if (TREE_CODE (type) == UNION_TYPE)
9627 error_at (loc, "cannot decompose union type %qT", type);
9628 goto error_out;
9630 else if (!CLASS_TYPE_P (type))
9632 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9633 goto error_out;
9635 else if (LAMBDA_TYPE_P (type))
9637 error_at (loc, "cannot decompose lambda closure type %qT", type);
9638 goto error_out;
9640 else if (processing_template_decl && complete_type (type) == error_mark_node)
9641 goto error_out;
9642 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9643 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9644 type);
9645 else
9647 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9648 if (btype == error_mark_node)
9649 goto error_out;
9650 else if (btype == NULL_TREE)
9652 error_at (loc, "cannot decompose class type %qT without non-static "
9653 "data members", type);
9654 goto error_out;
9656 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9657 if (TREE_CODE (field) != FIELD_DECL
9658 || DECL_ARTIFICIAL (field)
9659 || DECL_UNNAMED_BIT_FIELD (field))
9660 continue;
9661 else
9662 eltscnt++;
9663 if (count != eltscnt)
9664 goto cnt_mismatch;
9665 tree t = dexp;
9666 if (type != btype)
9668 t = convert_to_base (t, btype, /*check_access*/true,
9669 /*nonnull*/false, tf_warning_or_error);
9670 type = btype;
9672 unsigned int i = 0;
9673 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9674 if (TREE_CODE (field) != FIELD_DECL
9675 || DECL_ARTIFICIAL (field)
9676 || DECL_UNNAMED_BIT_FIELD (field))
9677 continue;
9678 else
9680 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9681 NULL_TREE);
9682 if (REFERENCE_REF_P (tt))
9683 tt = TREE_OPERAND (tt, 0);
9684 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9685 layout_decl (v[i], 0);
9686 if (!processing_template_decl)
9688 SET_DECL_VALUE_EXPR (v[i], tt);
9689 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9691 i++;
9694 if (processing_template_decl)
9696 for (unsigned int i = 0; i < count; i++)
9697 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9699 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9700 NULL_TREE, NULL_TREE);
9701 SET_DECL_VALUE_EXPR (v[i], a);
9702 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9707 /* Returns a declaration for a VAR_DECL as if:
9709 extern "C" TYPE NAME;
9711 had been seen. Used to create compiler-generated global
9712 variables. */
9714 static tree
9715 declare_global_var (tree name, tree type)
9717 auto cookie = push_abi_namespace (global_namespace);
9718 tree decl = build_decl (input_location, VAR_DECL, name, type);
9719 TREE_PUBLIC (decl) = 1;
9720 DECL_EXTERNAL (decl) = 1;
9721 DECL_ARTIFICIAL (decl) = 1;
9722 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9723 /* If the user has explicitly declared this variable (perhaps
9724 because the code we are compiling is part of a low-level runtime
9725 library), then it is possible that our declaration will be merged
9726 with theirs by pushdecl. */
9727 decl = pushdecl (decl);
9728 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9729 pop_abi_namespace (cookie, global_namespace);
9731 return decl;
9734 /* Returns the type for the argument to "atexit" corresponding to the function
9735 to be called when the program exits. */
9737 static tree
9738 get_atexit_fn_ptr_type ()
9740 if (!atexit_fn_ptr_type_node)
9742 tree fn_type = build_function_type_list (void_type_node, NULL_TREE);
9743 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9746 return atexit_fn_ptr_type_node;
9749 /* Returns the type for the argument to "__cxa_atexit", "__cxa_thread_atexit"
9750 or "__cxa_throw" corresponding to the destructor to be called when the
9751 program exits. */
9753 tree
9754 get_cxa_atexit_fn_ptr_type ()
9756 if (!cleanup_type)
9758 tree fntype = build_function_type_list (void_type_node,
9759 ptr_type_node, NULL_TREE);
9760 fntype = targetm.cxx.adjust_cdtor_callabi_fntype (fntype);
9761 cleanup_type = build_pointer_type (fntype);
9764 return cleanup_type;
9767 /* Returns a pointer to the `atexit' function. Note that if
9768 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9769 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9771 static tree
9772 get_atexit_node (void)
9774 tree atexit_fndecl;
9775 tree fn_type;
9776 tree fn_ptr_type;
9777 const char *name;
9778 bool use_aeabi_atexit;
9779 tree ctx = global_namespace;
9781 if (atexit_node)
9782 return atexit_node;
9784 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9786 /* The declaration for `__cxa_atexit' is:
9788 int __cxa_atexit (void (*)(void *), void *, void *)
9790 We build up the argument types and then the function type
9791 itself. */
9792 tree argtype0, argtype1, argtype2;
9794 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9795 /* First, build the pointer-to-function type for the first
9796 argument. */
9797 fn_ptr_type = get_cxa_atexit_fn_ptr_type ();
9798 /* Then, build the rest of the argument types. */
9799 argtype2 = ptr_type_node;
9800 if (use_aeabi_atexit)
9802 argtype1 = fn_ptr_type;
9803 argtype0 = ptr_type_node;
9805 else
9807 argtype1 = ptr_type_node;
9808 argtype0 = fn_ptr_type;
9810 /* And the final __cxa_atexit type. */
9811 fn_type = build_function_type_list (integer_type_node,
9812 argtype0, argtype1, argtype2,
9813 NULL_TREE);
9814 /* ... which needs noexcept. */
9815 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9816 if (use_aeabi_atexit)
9818 name = "__aeabi_atexit";
9819 push_to_top_level ();
9820 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9821 ctx = current_namespace;
9822 while (n--)
9823 pop_namespace ();
9824 pop_from_top_level ();
9826 else
9828 name = "__cxa_atexit";
9829 ctx = abi_node;
9832 else
9834 /* The declaration for `atexit' is:
9836 int atexit (void (*)());
9838 We build up the argument types and then the function type
9839 itself. */
9840 fn_ptr_type = get_atexit_fn_ptr_type ();
9841 /* Build the final atexit type. */
9842 fn_type = build_function_type_list (integer_type_node,
9843 fn_ptr_type, NULL_TREE);
9844 /* ... which needs noexcept. */
9845 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9846 name = "atexit";
9849 /* Now, build the function declaration. */
9850 push_lang_context (lang_name_c);
9851 auto cookie = push_abi_namespace (ctx);
9852 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9853 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9854 /* Install as hidden builtin so we're (a) more relaxed about
9855 exception spec matching and (b) will not give a confusing location
9856 in diagnostic and (c) won't magically appear in user-visible name
9857 lookups. */
9858 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9859 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9860 pop_abi_namespace (cookie, ctx);
9861 mark_used (atexit_fndecl);
9862 pop_lang_context ();
9863 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9865 return atexit_node;
9868 /* Like get_atexit_node, but for thread-local cleanups. */
9870 static tree
9871 get_thread_atexit_node (void)
9873 if (thread_atexit_node)
9874 return thread_atexit_node;
9876 /* The declaration for `__cxa_thread_atexit' is:
9878 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9879 tree fn_type = build_function_type_list (integer_type_node,
9880 get_cxa_atexit_fn_ptr_type (),
9881 ptr_type_node, ptr_type_node,
9882 NULL_TREE);
9884 /* Now, build the function declaration, as with __cxa_atexit. */
9885 unsigned flags = push_abi_namespace ();
9886 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9887 ECF_LEAF | ECF_NOTHROW);
9888 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9889 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9890 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9891 pop_abi_namespace (flags);
9892 mark_used (atexit_fndecl);
9893 thread_atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9895 return thread_atexit_node;
9898 /* Returns the __dso_handle VAR_DECL. */
9900 static tree
9901 get_dso_handle_node (void)
9903 if (dso_handle_node)
9904 return dso_handle_node;
9906 /* Declare the variable. */
9907 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9908 ptr_type_node);
9910 #ifdef HAVE_GAS_HIDDEN
9911 if (dso_handle_node != error_mark_node)
9913 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9914 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9916 #endif
9918 return dso_handle_node;
9921 /* Begin a new function with internal linkage whose job will be simply
9922 to destroy some particular variable. OB_PARM is true if object pointer
9923 is passed to the cleanup function, otherwise no argument is passed. */
9925 static GTY(()) int start_cleanup_cnt;
9927 static tree
9928 start_cleanup_fn (bool ob_parm)
9930 char name[32];
9932 push_to_top_level ();
9934 /* No need to mangle this. */
9935 push_lang_context (lang_name_c);
9937 /* Build the name of the function. */
9938 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9939 tree fntype = TREE_TYPE (ob_parm ? get_cxa_atexit_fn_ptr_type ()
9940 : get_atexit_fn_ptr_type ());
9941 /* Build the function declaration. */
9942 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9943 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9944 /* It's a function with internal linkage, generated by the
9945 compiler. */
9946 TREE_PUBLIC (fndecl) = 0;
9947 DECL_ARTIFICIAL (fndecl) = 1;
9948 /* Make the function `inline' so that it is only emitted if it is
9949 actually needed. It is unlikely that it will be inlined, since
9950 it is only called via a function pointer, but we avoid unnecessary
9951 emissions this way. */
9952 DECL_DECLARED_INLINE_P (fndecl) = 1;
9953 DECL_INTERFACE_KNOWN (fndecl) = 1;
9954 if (ob_parm)
9956 /* Build the parameter. */
9957 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9958 TREE_USED (parmdecl) = 1;
9959 DECL_READ_P (parmdecl) = 1;
9960 DECL_ARGUMENTS (fndecl) = parmdecl;
9963 fndecl = pushdecl (fndecl, /*hidden=*/true);
9964 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9966 pop_lang_context ();
9968 return current_function_decl;
9971 /* Finish the cleanup function begun by start_cleanup_fn. */
9973 static void
9974 end_cleanup_fn (void)
9976 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9978 pop_from_top_level ();
9981 /* Generate code to handle the destruction of DECL, an object with
9982 static storage duration. */
9984 tree
9985 register_dtor_fn (tree decl)
9987 tree cleanup;
9988 tree addr;
9989 tree compound_stmt;
9990 tree fcall;
9991 tree type;
9992 bool ob_parm, dso_parm, use_dtor;
9993 tree arg0, arg1, arg2;
9994 tree atex_node;
9996 type = TREE_TYPE (decl);
9997 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9998 return void_node;
10000 if (decl_maybe_constant_destruction (decl, type)
10001 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
10003 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
10004 return void_node;
10007 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
10008 "__aeabi_atexit"), and DECL is a class object, we can just pass the
10009 destructor to "__cxa_atexit"; we don't have to build a temporary
10010 function to do the cleanup. */
10011 dso_parm = (flag_use_cxa_atexit
10012 && !targetm.cxx.use_atexit_for_cxa_atexit ());
10013 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
10014 use_dtor = ob_parm && CLASS_TYPE_P (type);
10015 if (use_dtor)
10017 cleanup = get_class_binding (type, complete_dtor_identifier);
10019 /* Make sure it is accessible. */
10020 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
10021 tf_warning_or_error);
10023 else
10025 /* Call build_cleanup before we enter the anonymous function so
10026 that any access checks will be done relative to the current
10027 scope, rather than the scope of the anonymous function. */
10028 build_cleanup (decl);
10030 /* Now start the function. */
10031 cleanup = start_cleanup_fn (ob_parm);
10033 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
10034 to the original function, rather than the anonymous one. That
10035 will make the back end think that nested functions are in use,
10036 which causes confusion. */
10037 push_deferring_access_checks (dk_no_check);
10038 fcall = build_cleanup (decl);
10039 pop_deferring_access_checks ();
10041 /* Create the body of the anonymous function. */
10042 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
10043 finish_expr_stmt (fcall);
10044 finish_compound_stmt (compound_stmt);
10045 end_cleanup_fn ();
10048 /* Call atexit with the cleanup function. */
10049 mark_used (cleanup);
10050 cleanup = build_address (cleanup);
10052 if (CP_DECL_THREAD_LOCAL_P (decl))
10053 atex_node = get_thread_atexit_node ();
10054 else
10055 atex_node = get_atexit_node ();
10057 if (use_dtor)
10059 /* We must convert CLEANUP to the type that "__cxa_atexit"
10060 expects. */
10061 cleanup = build_nop (get_cxa_atexit_fn_ptr_type (), cleanup);
10062 /* "__cxa_atexit" will pass the address of DECL to the
10063 cleanup function. */
10064 mark_used (decl);
10065 addr = build_address (decl);
10066 /* The declared type of the parameter to "__cxa_atexit" is
10067 "void *". For plain "T*", we could just let the
10068 machinery in cp_build_function_call convert it -- but if the
10069 type is "cv-qualified T *", then we need to convert it
10070 before passing it in, to avoid spurious errors. */
10071 addr = build_nop (ptr_type_node, addr);
10073 else
10074 /* Since the cleanup functions we build ignore the address
10075 they're given, there's no reason to pass the actual address
10076 in, and, in general, it's cheaper to pass NULL than any
10077 other value. */
10078 addr = null_pointer_node;
10080 if (dso_parm)
10081 arg2 = cp_build_addr_expr (get_dso_handle_node (),
10082 tf_warning_or_error);
10083 else if (ob_parm)
10084 /* Just pass NULL to the dso handle parm if we don't actually
10085 have a DSO handle on this target. */
10086 arg2 = null_pointer_node;
10087 else
10088 arg2 = NULL_TREE;
10090 if (ob_parm)
10092 if (!CP_DECL_THREAD_LOCAL_P (decl)
10093 && targetm.cxx.use_aeabi_atexit ())
10095 arg1 = cleanup;
10096 arg0 = addr;
10098 else
10100 arg1 = addr;
10101 arg0 = cleanup;
10104 else
10106 arg0 = cleanup;
10107 arg1 = NULL_TREE;
10109 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
10110 arg0, arg1, arg2, NULL_TREE);
10113 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
10114 is its initializer. Generate code to handle the construction
10115 and destruction of DECL. */
10117 static void
10118 expand_static_init (tree decl, tree init)
10120 gcc_assert (VAR_P (decl));
10121 gcc_assert (TREE_STATIC (decl));
10123 /* Some variables require no dynamic initialization. */
10124 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
10126 /* Make sure the destructor is callable. */
10127 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
10128 if (!init)
10129 return;
10132 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
10133 && !DECL_FUNCTION_SCOPE_P (decl))
10135 location_t dloc = DECL_SOURCE_LOCATION (decl);
10136 if (init)
10137 error_at (dloc, "non-local variable %qD declared %<__thread%> "
10138 "needs dynamic initialization", decl);
10139 else
10140 error_at (dloc, "non-local variable %qD declared %<__thread%> "
10141 "has a non-trivial destructor", decl);
10142 static bool informed;
10143 if (!informed)
10145 inform (dloc, "C++11 %<thread_local%> allows dynamic "
10146 "initialization and destruction");
10147 informed = true;
10149 return;
10152 if (DECL_FUNCTION_SCOPE_P (decl))
10154 /* Emit code to perform this initialization but once. */
10155 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
10156 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
10157 tree guard, guard_addr;
10158 tree flag, begin;
10159 /* We don't need thread-safety code for thread-local vars. */
10160 bool thread_guard = (flag_threadsafe_statics
10161 && !CP_DECL_THREAD_LOCAL_P (decl));
10163 /* Emit code to perform this initialization but once. This code
10164 looks like:
10166 static <type> guard;
10167 if (!__atomic_load (guard.first_byte)) {
10168 if (__cxa_guard_acquire (&guard)) {
10169 bool flag = false;
10170 try {
10171 // Do initialization.
10172 flag = true; __cxa_guard_release (&guard);
10173 // Register variable for destruction at end of program.
10174 } catch {
10175 if (!flag) __cxa_guard_abort (&guard);
10180 Note that the `flag' variable is only set to 1 *after* the
10181 initialization is complete. This ensures that an exception,
10182 thrown during the construction, will cause the variable to
10183 reinitialized when we pass through this code again, as per:
10185 [stmt.dcl]
10187 If the initialization exits by throwing an exception, the
10188 initialization is not complete, so it will be tried again
10189 the next time control enters the declaration.
10191 This process should be thread-safe, too; multiple threads
10192 should not be able to initialize the variable more than
10193 once. */
10195 /* Create the guard variable. */
10196 guard = get_guard (decl);
10198 /* Begin the conditional initialization. */
10199 if_stmt = begin_if_stmt ();
10201 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
10202 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
10204 if (thread_guard)
10206 tree vfntype = NULL_TREE;
10207 tree acquire_name, release_name, abort_name;
10208 tree acquire_fn, release_fn, abort_fn;
10209 guard_addr = build_address (guard);
10211 acquire_name = get_identifier ("__cxa_guard_acquire");
10212 release_name = get_identifier ("__cxa_guard_release");
10213 abort_name = get_identifier ("__cxa_guard_abort");
10214 acquire_fn = get_global_binding (acquire_name);
10215 release_fn = get_global_binding (release_name);
10216 abort_fn = get_global_binding (abort_name);
10217 if (!acquire_fn)
10218 acquire_fn = push_library_fn
10219 (acquire_name, build_function_type_list (integer_type_node,
10220 TREE_TYPE (guard_addr),
10221 NULL_TREE),
10222 NULL_TREE, ECF_NOTHROW);
10223 if (!release_fn || !abort_fn)
10224 vfntype = build_function_type_list (void_type_node,
10225 TREE_TYPE (guard_addr),
10226 NULL_TREE);
10227 if (!release_fn)
10228 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
10229 ECF_NOTHROW);
10230 if (!abort_fn)
10231 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
10232 ECF_NOTHROW | ECF_LEAF);
10234 inner_if_stmt = begin_if_stmt ();
10235 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
10236 inner_if_stmt);
10238 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
10239 begin = get_target_expr (boolean_false_node);
10240 flag = TARGET_EXPR_SLOT (begin);
10242 TARGET_EXPR_CLEANUP (begin)
10243 = build3 (COND_EXPR, void_type_node, flag,
10244 void_node,
10245 build_call_n (abort_fn, 1, guard_addr));
10246 CLEANUP_EH_ONLY (begin) = 1;
10248 /* Do the initialization itself. */
10249 init = add_stmt_to_compound (begin, init);
10250 init = add_stmt_to_compound (init,
10251 build2 (MODIFY_EXPR, void_type_node,
10252 flag, boolean_true_node));
10254 /* Use atexit to register a function for destroying this static
10255 variable. Do this before calling __cxa_guard_release. */
10256 init = add_stmt_to_compound (init, register_dtor_fn (decl));
10258 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
10259 guard_addr));
10261 else
10263 init = add_stmt_to_compound (init, set_guard (guard));
10265 /* Use atexit to register a function for destroying this static
10266 variable. */
10267 init = add_stmt_to_compound (init, register_dtor_fn (decl));
10270 finish_expr_stmt (init);
10272 if (thread_guard)
10274 finish_compound_stmt (inner_then_clause);
10275 finish_then_clause (inner_if_stmt);
10276 finish_if_stmt (inner_if_stmt);
10279 finish_compound_stmt (then_clause);
10280 finish_then_clause (if_stmt);
10281 finish_if_stmt (if_stmt);
10283 else if (CP_DECL_THREAD_LOCAL_P (decl))
10284 tls_aggregates = tree_cons (init, decl, tls_aggregates);
10285 else
10286 static_aggregates = tree_cons (init, decl, static_aggregates);
10290 /* Make TYPE a complete type based on INITIAL_VALUE.
10291 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
10292 2 if there was no information (in which case assume 0 if DO_DEFAULT),
10293 3 if the initializer list is empty (in pedantic mode). */
10296 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
10298 int failure;
10299 tree type, elt_type;
10301 /* Don't get confused by a CONSTRUCTOR for some other type. */
10302 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
10303 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
10304 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
10305 return 1;
10307 if (initial_value)
10309 /* An array of character type can be initialized from a
10310 brace-enclosed string constant so call reshape_init to
10311 remove the optional braces from a braced string literal. */
10312 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
10313 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
10314 initial_value = reshape_init (*ptype, initial_value,
10315 tf_warning_or_error);
10317 /* If any of the elements are parameter packs, we can't actually
10318 complete this type now because the array size is dependent. */
10319 if (TREE_CODE (initial_value) == CONSTRUCTOR)
10320 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
10321 if (PACK_EXPANSION_P (e.value))
10322 return 0;
10325 failure = complete_array_type (ptype, initial_value, do_default);
10327 /* We can create the array before the element type is complete, which
10328 means that we didn't have these two bits set in the original type
10329 either. In completing the type, we are expected to propagate these
10330 bits. See also complete_type which does the same thing for arrays
10331 of fixed size. */
10332 type = *ptype;
10333 if (type != error_mark_node && TYPE_DOMAIN (type))
10335 elt_type = TREE_TYPE (type);
10336 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
10337 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
10338 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
10341 return failure;
10344 /* As above, but either give an error or reject zero-size arrays, depending
10345 on COMPLAIN. */
10348 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
10349 bool do_default, tsubst_flags_t complain)
10351 int failure;
10352 bool sfinae = !(complain & tf_error);
10353 /* In SFINAE context we can't be lenient about zero-size arrays. */
10354 if (sfinae)
10355 ++pedantic;
10356 failure = cp_complete_array_type (ptype, initial_value, do_default);
10357 if (sfinae)
10358 --pedantic;
10359 if (failure)
10361 if (sfinae)
10362 /* Not an error. */;
10363 else if (failure == 1)
10364 error ("initializer fails to determine size of %qT", *ptype);
10365 else if (failure == 2)
10367 if (do_default)
10368 error ("array size missing in %qT", *ptype);
10370 else if (failure == 3)
10371 error ("zero-size array %qT", *ptype);
10372 *ptype = error_mark_node;
10374 return failure;
10377 /* Return zero if something is declared to be a member of type
10378 CTYPE when in the context of CUR_TYPE. STRING is the error
10379 message to print in that case. Otherwise, quietly return 1. */
10381 static int
10382 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
10384 if (ctype && ctype != cur_type)
10386 if (flags == DTOR_FLAG)
10387 error ("destructor for alien class %qT cannot be a member", ctype);
10388 else
10389 error ("constructor for alien class %qT cannot be a member", ctype);
10390 return 0;
10392 return 1;
10395 /* Subroutine of `grokdeclarator'. */
10397 /* Generate errors possibly applicable for a given set of specifiers.
10398 This is for ARM $7.1.2. */
10400 static void
10401 bad_specifiers (tree object,
10402 enum bad_spec_place type,
10403 int virtualp,
10404 int quals,
10405 int inlinep,
10406 int friendp,
10407 int raises,
10408 const location_t* locations)
10410 switch (type)
10412 case BSP_VAR:
10413 if (virtualp)
10414 error_at (locations[ds_virtual],
10415 "%qD declared as a %<virtual%> variable", object);
10416 if (quals)
10417 error ("%<const%> and %<volatile%> function specifiers on "
10418 "%qD invalid in variable declaration", object);
10419 break;
10420 case BSP_PARM:
10421 if (virtualp)
10422 error_at (locations[ds_virtual],
10423 "%qD declared as a %<virtual%> parameter", object);
10424 if (inlinep)
10425 error_at (locations[ds_inline],
10426 "%qD declared as an %<inline%> parameter", object);
10427 if (quals)
10428 error ("%<const%> and %<volatile%> function specifiers on "
10429 "%qD invalid in parameter declaration", object);
10430 break;
10431 case BSP_TYPE:
10432 if (virtualp)
10433 error_at (locations[ds_virtual],
10434 "%qD declared as a %<virtual%> type", object);
10435 if (inlinep)
10436 error_at (locations[ds_inline],
10437 "%qD declared as an %<inline%> type", object);
10438 if (quals)
10439 error ("%<const%> and %<volatile%> function specifiers on "
10440 "%qD invalid in type declaration", object);
10441 break;
10442 case BSP_FIELD:
10443 if (virtualp)
10444 error_at (locations[ds_virtual],
10445 "%qD declared as a %<virtual%> field", object);
10446 if (inlinep)
10447 error_at (locations[ds_inline],
10448 "%qD declared as an %<inline%> field", object);
10449 if (quals)
10450 error ("%<const%> and %<volatile%> function specifiers on "
10451 "%qD invalid in field declaration", object);
10452 break;
10453 default:
10454 gcc_unreachable();
10456 if (friendp)
10457 error ("%q+D declared as a friend", object);
10458 if (raises
10459 && !flag_noexcept_type
10460 && (TREE_CODE (object) == TYPE_DECL
10461 || (!TYPE_PTRFN_P (TREE_TYPE (object))
10462 && !TYPE_REFFN_P (TREE_TYPE (object))
10463 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
10464 error ("%q+D declared with an exception specification", object);
10467 /* DECL is a member function or static data member and is presently
10468 being defined. Check that the definition is taking place in a
10469 valid namespace. */
10471 static void
10472 check_class_member_definition_namespace (tree decl)
10474 /* These checks only apply to member functions and static data
10475 members. */
10476 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
10477 /* We check for problems with specializations in pt.cc in
10478 check_specialization_namespace, where we can issue better
10479 diagnostics. */
10480 if (processing_specialization)
10481 return;
10482 /* We check this in check_explicit_instantiation_namespace. */
10483 if (processing_explicit_instantiation)
10484 return;
10485 /* [class.mfct]
10487 A member function definition that appears outside of the
10488 class definition shall appear in a namespace scope enclosing
10489 the class definition.
10491 [class.static.data]
10493 The definition for a static data member shall appear in a
10494 namespace scope enclosing the member's class definition. */
10495 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
10496 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
10497 decl, DECL_CONTEXT (decl));
10500 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
10501 METHOD_TYPE for a non-static member function; QUALS are the
10502 cv-qualifiers that apply to the function. */
10504 tree
10505 build_this_parm (tree fn, tree type, cp_cv_quals quals)
10507 tree this_type;
10508 tree qual_type;
10509 tree parm;
10510 cp_cv_quals this_quals;
10512 if (CLASS_TYPE_P (type))
10514 this_type
10515 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
10516 this_type = build_pointer_type (this_type);
10518 else
10519 this_type = type_of_this_parm (type);
10520 /* The `this' parameter is implicitly `const'; it cannot be
10521 assigned to. */
10522 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
10523 qual_type = cp_build_qualified_type (this_type, this_quals);
10524 parm = build_artificial_parm (fn, this_identifier, qual_type);
10525 cp_apply_type_quals_to_decl (this_quals, parm);
10526 return parm;
10529 /* DECL is a static member function. Complain if it was declared
10530 with function-cv-quals. */
10532 static void
10533 check_static_quals (tree decl, cp_cv_quals quals)
10535 if (quals != TYPE_UNQUALIFIED)
10536 error ("static member function %q#D declared with type qualifiers",
10537 decl);
10540 // Check that FN takes no arguments and returns bool.
10541 static void
10542 check_concept_fn (tree fn)
10544 // A constraint is nullary.
10545 if (DECL_ARGUMENTS (fn))
10546 error_at (DECL_SOURCE_LOCATION (fn),
10547 "concept %q#D declared with function parameters", fn);
10549 // The declared return type of the concept shall be bool, and
10550 // it shall not be deduced from it definition.
10551 tree type = TREE_TYPE (TREE_TYPE (fn));
10552 if (is_auto (type))
10553 error_at (DECL_SOURCE_LOCATION (fn),
10554 "concept %q#D declared with a deduced return type", fn);
10555 else if (type != boolean_type_node)
10556 error_at (DECL_SOURCE_LOCATION (fn),
10557 "concept %q#D with non-%<bool%> return type %qT", fn, type);
10560 /* Helper function. Replace the temporary this parameter injected
10561 during cp_finish_omp_declare_simd with the real this parameter. */
10563 static tree
10564 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10566 tree this_parm = (tree) data;
10567 if (TREE_CODE (*tp) == PARM_DECL
10568 && DECL_NAME (*tp) == this_identifier
10569 && *tp != this_parm)
10570 *tp = this_parm;
10571 else if (TYPE_P (*tp))
10572 *walk_subtrees = 0;
10573 return NULL_TREE;
10576 /* CTYPE is class type, or null if non-class.
10577 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10578 or METHOD_TYPE.
10579 DECLARATOR is the function's name.
10580 PARMS is a chain of PARM_DECLs for the function.
10581 VIRTUALP is truthvalue of whether the function is virtual or not.
10582 FLAGS are to be passed through to `grokclassfn'.
10583 QUALS are qualifiers indicating whether the function is `const'
10584 or `volatile'.
10585 RAISES is a list of exceptions that this function can raise.
10586 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10587 not look, and -1 if we should not call `grokclassfn' at all.
10589 SFK is the kind of special function (if any) for the new function.
10591 Returns `NULL_TREE' if something goes wrong, after issuing
10592 applicable error messages. */
10594 static tree
10595 grokfndecl (tree ctype,
10596 tree type,
10597 tree declarator,
10598 tree parms,
10599 tree orig_declarator,
10600 const cp_decl_specifier_seq *declspecs,
10601 tree decl_reqs,
10602 int virtualp,
10603 enum overload_flags flags,
10604 cp_cv_quals quals,
10605 cp_ref_qualifier rqual,
10606 tree raises,
10607 int check,
10608 int friendp,
10609 int publicp,
10610 int inlinep,
10611 bool deletedp,
10612 bool xobj_func_p,
10613 special_function_kind sfk,
10614 bool funcdef_flag,
10615 bool late_return_type_p,
10616 int template_count,
10617 tree in_namespace,
10618 tree* attrlist,
10619 location_t location)
10621 tree decl;
10622 tree t;
10624 if (location == UNKNOWN_LOCATION)
10625 location = input_location;
10627 /* Was the concept specifier present? */
10628 bool concept_p = inlinep & 4;
10630 /* Concept declarations must have a corresponding definition. */
10631 if (concept_p && !funcdef_flag)
10633 error_at (location, "concept %qD has no definition", declarator);
10634 return NULL_TREE;
10637 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10639 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10641 /* Set the constraints on the declaration. */
10642 if (flag_concepts)
10644 tree tmpl_reqs = NULL_TREE;
10645 tree ctx = friendp ? current_class_type : ctype;
10646 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10647 bool memtmpl = (!block_local
10648 && (current_template_depth
10649 > template_class_depth (ctx)));
10650 if (memtmpl)
10652 if (!current_template_parms)
10653 /* If there are no template parameters, something must have
10654 gone wrong. */
10655 gcc_assert (seen_error ());
10656 else
10657 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10659 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10660 if (concept_p && ci)
10662 error_at (location, "a function concept cannot be constrained");
10663 ci = NULL_TREE;
10665 /* C++20 CA378: Remove non-templated constrained functions. */
10666 /* [temp.friend]/9 A non-template friend declaration with a
10667 requires-clause shall be a definition. A friend function template with
10668 a constraint that depends on a template parameter from an enclosing
10669 template shall be a definition. */
10670 if (ci
10671 && (block_local
10672 || !processing_template_decl
10673 || (friendp && !memtmpl && !funcdef_flag)))
10675 if (!friendp || !processing_template_decl)
10676 error_at (location, "constraints on a non-templated function");
10677 else
10678 error_at (location, "constrained non-template friend declaration"
10679 " must be a definition");
10680 ci = NULL_TREE;
10682 set_constraints (decl, ci);
10683 if (ci && friendp && memtmpl && !funcdef_flag
10684 && uses_outer_template_parms_in_constraints (decl, ctx))
10685 error_at (location, "friend function template with constraints that "
10686 "depend on outer template parameters must be a definition");
10689 if (TREE_CODE (type) == METHOD_TYPE)
10691 tree parm = build_this_parm (decl, type, quals);
10692 DECL_CHAIN (parm) = parms;
10693 parms = parm;
10695 /* Allocate space to hold the vptr bit if needed. */
10696 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10699 DECL_ARGUMENTS (decl) = parms;
10700 for (t = parms; t; t = DECL_CHAIN (t))
10701 DECL_CONTEXT (t) = decl;
10703 /* Propagate volatile out from type to decl. */
10704 if (TYPE_VOLATILE (type))
10705 TREE_THIS_VOLATILE (decl) = 1;
10707 /* Setup decl according to sfk. */
10708 switch (sfk)
10710 case sfk_constructor:
10711 case sfk_copy_constructor:
10712 case sfk_move_constructor:
10713 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10714 DECL_NAME (decl) = ctor_identifier;
10715 break;
10716 case sfk_destructor:
10717 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10718 DECL_NAME (decl) = dtor_identifier;
10719 break;
10720 case sfk_deduction_guide:
10721 /* Give deduction guides a definition even though they don't really
10722 have one: the restriction that you can't repeat a deduction guide
10723 makes them more like a definition anyway. */
10724 DECL_INITIAL (decl) = void_node;
10725 break;
10726 default:
10727 break;
10730 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10732 if (funcdef_flag)
10733 error_at (location,
10734 "defining explicit specialization %qD in friend declaration",
10735 orig_declarator);
10736 else
10738 tree fns = TREE_OPERAND (orig_declarator, 0);
10739 tree args = TREE_OPERAND (orig_declarator, 1);
10741 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10743 /* Something like `template <class T> friend void f<T>()'. */
10744 error_at (location,
10745 "invalid use of template-id %qD in declaration "
10746 "of primary template",
10747 orig_declarator);
10748 return NULL_TREE;
10751 /* A friend declaration of the form friend void f<>(). Record
10752 the information in the TEMPLATE_ID_EXPR. */
10753 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10755 gcc_assert (identifier_p (fns) || OVL_P (fns));
10756 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10758 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10759 if (TREE_PURPOSE (t)
10760 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10762 error_at (defparse_location (TREE_PURPOSE (t)),
10763 "default arguments are not allowed in declaration "
10764 "of friend template specialization %qD",
10765 decl);
10766 return NULL_TREE;
10769 if (inlinep & 1)
10771 error_at (declspecs->locations[ds_inline],
10772 "%<inline%> is not allowed in declaration of friend "
10773 "template specialization %qD",
10774 decl);
10775 return NULL_TREE;
10780 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10781 expression, that declaration shall be a definition..." */
10782 if (friendp && !funcdef_flag)
10784 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10785 t && t != void_list_node; t = TREE_CHAIN (t))
10786 if (TREE_PURPOSE (t))
10788 permerror (DECL_SOURCE_LOCATION (decl),
10789 "friend declaration of %qD specifies default "
10790 "arguments and isn%'t a definition", decl);
10791 break;
10795 /* If this decl has namespace scope, set that up. */
10796 if (in_namespace)
10797 set_decl_namespace (decl, in_namespace, friendp);
10798 else if (ctype)
10799 DECL_CONTEXT (decl) = ctype;
10800 else
10801 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10803 /* `main' and builtins have implicit 'C' linkage. */
10804 if (ctype == NULL_TREE
10805 && DECL_FILE_SCOPE_P (decl)
10806 && current_lang_name == lang_name_cplusplus
10807 && (MAIN_NAME_P (declarator)
10808 || (IDENTIFIER_LENGTH (declarator) > 10
10809 && IDENTIFIER_POINTER (declarator)[0] == '_'
10810 && IDENTIFIER_POINTER (declarator)[1] == '_'
10811 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10812 "builtin_"))
10813 || (targetcm.cxx_implicit_extern_c
10814 && (targetcm.cxx_implicit_extern_c
10815 (IDENTIFIER_POINTER (declarator))))))
10816 SET_DECL_LANGUAGE (decl, lang_c);
10818 DECL_STATIC_FUNCTION_P (decl)
10819 = !xobj_func_p && ctype && TREE_CODE (type) == FUNCTION_TYPE;
10820 DECL_FUNCTION_XOBJ_FLAG (decl) = xobj_func_p;
10822 if (deletedp)
10823 DECL_DELETED_FN (decl) = 1;
10825 if (ctype && funcdef_flag)
10826 check_class_member_definition_namespace (decl);
10828 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10830 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10831 error_at (location, "cannot declare %<::main%> to be a template");
10832 if (inlinep & 1)
10833 error_at (declspecs->locations[ds_inline],
10834 "cannot declare %<::main%> to be inline");
10835 if (inlinep & 2)
10836 error_at (declspecs->locations[ds_constexpr],
10837 "cannot declare %<::main%> to be %qs", "constexpr");
10838 if (inlinep & 8)
10839 error_at (declspecs->locations[ds_consteval],
10840 "cannot declare %<::main%> to be %qs", "consteval");
10841 if (!publicp)
10842 error_at (location, "cannot declare %<::main%> to be static");
10843 if (current_lang_depth () != 0)
10844 pedwarn (location, OPT_Wpedantic, "cannot declare %<::main%> with a"
10845 " linkage specification");
10846 if (module_attach_p ())
10847 error_at (location, "cannot attach %<::main%> to a named module");
10848 inlinep = 0;
10849 publicp = 1;
10852 /* Members of anonymous types and local classes have no linkage; make
10853 them internal. If a typedef is made later, this will be changed. */
10854 if (ctype && !TREE_PUBLIC (TYPE_MAIN_DECL (ctype)))
10855 publicp = 0;
10856 else if (ctype && decl_function_context (TYPE_MAIN_DECL (ctype)))
10857 /* But members of local classes in a module CMI should have their
10858 definitions exported, in case they are (directly or indirectly)
10859 used by an importer. We don't just use module_has_cmi_p here
10860 because for entities in the GMF we don't yet know whether this
10861 module will have a CMI, so we'll conservatively assume it might. */
10862 publicp = module_maybe_has_cmi_p ();
10864 if (publicp && cxx_dialect == cxx98)
10866 /* [basic.link]: A name with no linkage (notably, the name of a class
10867 or enumeration declared in a local scope) shall not be used to
10868 declare an entity with linkage.
10870 DR 757 relaxes this restriction for C++0x. */
10871 no_linkage_error (decl);
10874 TREE_PUBLIC (decl) = publicp;
10875 if (! publicp)
10877 DECL_INTERFACE_KNOWN (decl) = 1;
10878 DECL_NOT_REALLY_EXTERN (decl) = 1;
10881 /* If the declaration was declared inline, mark it as such. */
10882 if (inlinep)
10884 DECL_DECLARED_INLINE_P (decl) = 1;
10885 if (publicp)
10886 DECL_COMDAT (decl) = 1;
10888 if (inlinep & 2)
10889 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10890 else if (inlinep & 8)
10892 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10893 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10896 // If the concept declaration specifier was found, check
10897 // that the declaration satisfies the necessary requirements.
10898 if (concept_p)
10900 DECL_DECLARED_CONCEPT_P (decl) = true;
10901 check_concept_fn (decl);
10904 DECL_EXTERNAL (decl) = 1;
10905 if (TREE_CODE (type) == FUNCTION_TYPE)
10907 if (quals || rqual)
10908 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10909 TYPE_UNQUALIFIED,
10910 REF_QUAL_NONE);
10911 auto_diagnostic_group d;
10912 if (quals)
10913 error (!ctype
10914 ? G_("non-member function %qD cannot have cv-qualifier")
10915 : !xobj_func_p
10916 ? G_("static member function %qD cannot have cv-qualifier")
10917 : G_("explicit object member function "
10918 "%qD cannot have cv-qualifier"),
10919 decl);
10920 if (rqual)
10921 error (!ctype
10922 ? G_("non-member function %qD cannot have ref-qualifier")
10923 : !xobj_func_p
10924 ? G_("static member function %qD cannot have ref-qualifier")
10925 : G_("explicit object member function "
10926 "%qD cannot have ref-qualifier"),
10927 decl);
10929 if (xobj_func_p && (quals || rqual))
10930 inform (DECL_SOURCE_LOCATION (DECL_ARGUMENTS (decl)),
10931 "explicit object parameter declared here");
10932 quals = TYPE_UNQUALIFIED;
10933 rqual = REF_QUAL_NONE;
10937 if (deduction_guide_p (decl))
10939 tree type = TREE_TYPE (DECL_NAME (decl));
10940 if (in_namespace == NULL_TREE
10941 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10943 error_at (location, "deduction guide %qD must be declared in the "
10944 "same scope as %qT", decl, type);
10945 inform (location_of (type), " declared here");
10946 return NULL_TREE;
10948 if (DECL_CLASS_SCOPE_P (decl)
10949 && current_access_specifier != declared_access (TYPE_NAME (type)))
10951 error_at (location, "deduction guide %qD must have the same access "
10952 "as %qT", decl, type);
10953 inform (location_of (type), " declared here");
10955 if (funcdef_flag)
10956 error_at (location,
10957 "deduction guide %qD must not have a function body", decl);
10959 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10960 && !grok_op_properties (decl, /*complain=*/true))
10961 return NULL_TREE;
10962 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10964 bool long_long_unsigned_p;
10965 bool long_double_p;
10966 const char *suffix = NULL;
10967 /* [over.literal]/6: Literal operators shall not have C linkage. */
10968 if (DECL_LANGUAGE (decl) == lang_c)
10970 error_at (location, "literal operator with C linkage");
10971 maybe_show_extern_c_location ();
10972 return NULL_TREE;
10975 if (DECL_NAMESPACE_SCOPE_P (decl))
10977 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10978 &long_double_p))
10980 error_at (location, "%qD has invalid argument list", decl);
10981 return NULL_TREE;
10984 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10985 if (long_long_unsigned_p)
10987 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10988 warning_at (location, 0, "integer suffix %qs"
10989 " shadowed by implementation", suffix);
10991 else if (long_double_p)
10993 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10994 warning_at (location, 0, "floating-point suffix %qs"
10995 " shadowed by implementation", suffix);
10997 /* 17.6.3.3.5 */
10998 if (suffix[0] != '_'
10999 && !current_function_decl && !(friendp && !funcdef_flag))
11000 warning_at (location, OPT_Wliteral_suffix,
11001 "literal operator suffixes not preceded by %<_%>"
11002 " are reserved for future standardization");
11004 else
11006 error_at (location, "%qD must be a non-member function", decl);
11007 return NULL_TREE;
11011 if (funcdef_flag)
11012 /* Make the init_value nonzero so pushdecl knows this is not
11013 tentative. error_mark_node is replaced later with the BLOCK. */
11014 DECL_INITIAL (decl) = error_mark_node;
11016 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
11017 TREE_NOTHROW (decl) = 1;
11019 if (flag_openmp || flag_openmp_simd)
11021 /* Adjust "omp declare simd" attributes. */
11022 tree ods = lookup_attribute ("omp declare simd", *attrlist);
11023 if (ods)
11025 tree attr;
11026 for (attr = ods; attr;
11027 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
11029 if (TREE_CODE (type) == METHOD_TYPE)
11030 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
11031 DECL_ARGUMENTS (decl), NULL);
11032 if (TREE_VALUE (attr) != NULL_TREE)
11034 tree cl = TREE_VALUE (TREE_VALUE (attr));
11035 cl = c_omp_declare_simd_clauses_to_numbers
11036 (DECL_ARGUMENTS (decl), cl);
11037 if (cl)
11038 TREE_VALUE (TREE_VALUE (attr)) = cl;
11039 else
11040 TREE_VALUE (attr) = NULL_TREE;
11046 /* Caller will do the rest of this. */
11047 if (check < 0)
11048 return decl;
11050 if (ctype != NULL_TREE)
11051 grokclassfn (ctype, decl, flags);
11053 /* 12.4/3 */
11054 if (cxx_dialect >= cxx11
11055 && DECL_DESTRUCTOR_P (decl)
11056 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
11057 && !processing_template_decl)
11058 deduce_noexcept_on_destructor (decl);
11060 set_originating_module (decl);
11062 decl = check_explicit_specialization (orig_declarator, decl,
11063 template_count,
11064 2 * funcdef_flag +
11065 4 * (friendp != 0) +
11066 8 * concept_p,
11067 *attrlist);
11068 if (decl == error_mark_node)
11069 return NULL_TREE;
11071 if (DECL_STATIC_FUNCTION_P (decl))
11072 check_static_quals (decl, quals);
11074 if (attrlist)
11076 cplus_decl_attributes (&decl, *attrlist, 0);
11077 *attrlist = NULL_TREE;
11080 if (DECL_HAS_CONTRACTS_P (decl))
11081 rebuild_postconditions (decl);
11083 /* Check main's type after attributes have been applied. */
11084 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
11086 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
11087 integer_type_node))
11089 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
11090 tree newtype;
11091 error_at (declspecs->locations[ds_type_spec],
11092 "%<::main%> must return %<int%>");
11093 newtype = build_function_type (integer_type_node, oldtypeargs);
11094 TREE_TYPE (decl) = newtype;
11096 if (warn_main)
11097 check_main_parameter_types (decl);
11100 if (ctype != NULL_TREE && check)
11102 tree old_decl = check_classfn (ctype, decl,
11103 (current_template_depth
11104 > template_class_depth (ctype))
11105 ? current_template_parms
11106 : NULL_TREE);
11108 if (old_decl == error_mark_node)
11109 return NULL_TREE;
11111 if (old_decl)
11113 tree ok;
11114 tree pushed_scope;
11116 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
11117 /* Because grokfndecl is always supposed to return a
11118 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
11119 here. We depend on our callers to figure out that its
11120 really a template that's being returned. */
11121 old_decl = DECL_TEMPLATE_RESULT (old_decl);
11123 if (DECL_STATIC_FUNCTION_P (old_decl)
11124 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
11126 /* Remove the `this' parm added by grokclassfn. */
11127 revert_static_member_fn (decl);
11128 check_static_quals (decl, quals);
11130 if (DECL_ARTIFICIAL (old_decl))
11132 error ("definition of implicitly-declared %qD", old_decl);
11133 return NULL_TREE;
11135 else if (DECL_DEFAULTED_FN (old_decl))
11137 error ("definition of explicitly-defaulted %q+D", decl);
11138 inform (DECL_SOURCE_LOCATION (old_decl),
11139 "%q#D explicitly defaulted here", old_decl);
11140 return NULL_TREE;
11143 /* Since we've smashed OLD_DECL to its
11144 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
11145 if (TREE_CODE (decl) == TEMPLATE_DECL)
11146 decl = DECL_TEMPLATE_RESULT (decl);
11148 /* Attempt to merge the declarations. This can fail, in
11149 the case of some invalid specialization declarations. */
11150 pushed_scope = push_scope (ctype);
11151 ok = duplicate_decls (decl, old_decl);
11152 if (pushed_scope)
11153 pop_scope (pushed_scope);
11154 if (!ok)
11156 error ("no %q#D member function declared in class %qT",
11157 decl, ctype);
11158 return NULL_TREE;
11160 if (ok == error_mark_node)
11161 return NULL_TREE;
11162 return old_decl;
11166 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
11167 return NULL_TREE;
11169 if (ctype == NULL_TREE || check)
11170 return decl;
11172 if (virtualp)
11173 DECL_VIRTUAL_P (decl) = 1;
11175 return decl;
11178 /* decl is a FUNCTION_DECL.
11179 specifiers are the parsed virt-specifiers.
11181 Set flags to reflect the virt-specifiers.
11183 Returns decl. */
11185 static tree
11186 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
11188 if (decl == NULL_TREE)
11189 return decl;
11190 if (specifiers & VIRT_SPEC_OVERRIDE)
11191 DECL_OVERRIDE_P (decl) = 1;
11192 if (specifiers & VIRT_SPEC_FINAL)
11193 DECL_FINAL_P (decl) = 1;
11194 return decl;
11197 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
11198 the linkage that DECL will receive in the object file. */
11200 static void
11201 set_linkage_for_static_data_member (tree decl)
11203 /* A static data member always has static storage duration and
11204 external linkage. Note that static data members are forbidden in
11205 local classes -- the only situation in which a class has
11206 non-external linkage. */
11207 TREE_PUBLIC (decl) = 1;
11208 TREE_STATIC (decl) = 1;
11209 /* For non-template classes, static data members are always put
11210 out in exactly those files where they are defined, just as
11211 with ordinary namespace-scope variables. */
11212 if (!processing_template_decl)
11213 DECL_INTERFACE_KNOWN (decl) = 1;
11216 /* Create a VAR_DECL named NAME with the indicated TYPE.
11218 If SCOPE is non-NULL, it is the class type or namespace containing
11219 the variable. If SCOPE is NULL, the variable should is created in
11220 the innermost enclosing scope. */
11222 static tree
11223 grokvardecl (tree type,
11224 tree name,
11225 tree orig_declarator,
11226 const cp_decl_specifier_seq *declspecs,
11227 int initialized,
11228 int type_quals,
11229 int inlinep,
11230 bool conceptp,
11231 int template_count,
11232 tree scope,
11233 location_t location)
11235 tree decl;
11236 tree explicit_scope;
11238 gcc_assert (!name || identifier_p (name));
11240 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
11241 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
11243 /* Compute the scope in which to place the variable, but remember
11244 whether or not that scope was explicitly specified by the user. */
11245 explicit_scope = scope;
11246 if (!scope)
11248 /* An explicit "extern" specifier indicates a namespace-scope
11249 variable. */
11250 if (declspecs->storage_class == sc_extern)
11251 scope = current_decl_namespace ();
11252 else if (!at_function_scope_p ())
11253 scope = current_scope ();
11256 if (scope
11257 && (/* If the variable is a namespace-scope variable declared in a
11258 template, we need DECL_LANG_SPECIFIC. */
11259 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
11260 /* Similarly for namespace-scope variables with language linkage
11261 other than C++. */
11262 || (TREE_CODE (scope) == NAMESPACE_DECL
11263 && current_lang_name != lang_name_cplusplus)
11264 /* Similarly for static data members. */
11265 || TYPE_P (scope)
11266 /* Similarly for explicit specializations. */
11267 || (orig_declarator
11268 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
11269 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
11270 else
11271 decl = build_decl (location, VAR_DECL, name, type);
11273 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
11274 set_decl_namespace (decl, explicit_scope, 0);
11275 else
11276 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
11278 if (declspecs->storage_class == sc_extern)
11280 DECL_THIS_EXTERN (decl) = 1;
11281 DECL_EXTERNAL (decl) = !initialized;
11284 if (DECL_CLASS_SCOPE_P (decl))
11286 set_linkage_for_static_data_member (decl);
11287 /* This function is only called with out-of-class definitions. */
11288 DECL_EXTERNAL (decl) = 0;
11289 check_class_member_definition_namespace (decl);
11291 /* At top level, either `static' or no s.c. makes a definition
11292 (perhaps tentative), and absence of `static' makes it public. */
11293 else if (toplevel_bindings_p ())
11295 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
11296 && (DECL_THIS_EXTERN (decl)
11297 || ! constp
11298 || volatilep
11299 || inlinep
11300 || module_attach_p ()));
11301 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
11303 /* Not at top level, only `static' makes a static definition. */
11304 else
11306 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
11307 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
11310 set_originating_module (decl);
11312 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
11314 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
11316 CP_DECL_THREAD_LOCAL_P (decl) = true;
11317 if (!processing_template_decl)
11318 set_decl_tls_model (decl, decl_default_tls_model (decl));
11320 if (declspecs->gnu_thread_keyword_p)
11321 SET_DECL_GNU_TLS_P (decl);
11324 /* If the type of the decl has no linkage, make sure that we'll
11325 notice that in mark_used. */
11326 if (cxx_dialect > cxx98
11327 && decl_linkage (decl) != lk_none
11328 && DECL_LANG_SPECIFIC (decl) == NULL
11329 && !DECL_EXTERN_C_P (decl)
11330 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
11331 retrofit_lang_decl (decl);
11333 if (TREE_PUBLIC (decl))
11335 /* [basic.link]: A name with no linkage (notably, the name of a class
11336 or enumeration declared in a local scope) shall not be used to
11337 declare an entity with linkage.
11339 DR 757 relaxes this restriction for C++0x. */
11340 if (cxx_dialect < cxx11)
11341 no_linkage_error (decl);
11343 else
11344 DECL_INTERFACE_KNOWN (decl) = 1;
11346 if (DECL_NAME (decl)
11347 && MAIN_NAME_P (DECL_NAME (decl)))
11349 if (scope == global_namespace)
11350 error_at (DECL_SOURCE_LOCATION (decl),
11351 "cannot declare %<::main%> to be a global variable");
11352 else if (DECL_EXTERN_C_P (decl))
11353 error_at (DECL_SOURCE_LOCATION (decl),
11354 "an entity named %<main%> cannot be declared with "
11355 "C language linkage");
11358 /* Check that the variable can be safely declared as a concept.
11359 Note that this also forbids explicit specializations. */
11360 if (conceptp)
11362 if (!processing_template_decl)
11364 error_at (declspecs->locations[ds_concept],
11365 "a non-template variable cannot be %<concept%>");
11366 return NULL_TREE;
11368 else if (!at_namespace_scope_p ())
11370 error_at (declspecs->locations[ds_concept],
11371 "concept must be defined at namespace scope");
11372 return NULL_TREE;
11374 else
11375 DECL_DECLARED_CONCEPT_P (decl) = true;
11376 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
11378 error_at (location, "a variable concept cannot be constrained");
11379 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
11382 else if (flag_concepts
11383 && current_template_depth > template_class_depth (scope))
11385 tree ci = current_template_constraints ();
11386 set_constraints (decl, ci);
11389 // Handle explicit specializations and instantiations of variable templates.
11390 if (orig_declarator)
11391 decl = check_explicit_specialization (orig_declarator, decl,
11392 template_count, conceptp * 8);
11394 return decl != error_mark_node ? decl : NULL_TREE;
11397 /* Create and return a canonical pointer to member function type, for
11398 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
11400 tree
11401 build_ptrmemfunc_type (tree type)
11403 tree field, fields;
11404 tree t;
11406 if (type == error_mark_node)
11407 return type;
11409 /* Make sure that we always have the unqualified pointer-to-member
11410 type first. */
11411 if (cp_cv_quals quals = cp_type_quals (type))
11413 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
11414 return cp_build_qualified_type (unqual, quals);
11417 /* If a canonical type already exists for this type, use it. We use
11418 this method instead of type_hash_canon, because it only does a
11419 simple equality check on the list of field members. */
11421 t = TYPE_PTRMEMFUNC_TYPE (type);
11422 if (t)
11423 return t;
11425 t = make_node (RECORD_TYPE);
11427 /* Let the front end know this is a pointer to member function. */
11428 TYPE_PTRMEMFUNC_FLAG (t) = 1;
11430 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
11431 DECL_NONADDRESSABLE_P (field) = 1;
11432 fields = field;
11434 field = build_decl (input_location, FIELD_DECL, delta_identifier,
11435 delta_type_node);
11436 DECL_NONADDRESSABLE_P (field) = 1;
11437 DECL_CHAIN (field) = fields;
11438 fields = field;
11440 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
11442 /* Zap out the name so that the back end will give us the debugging
11443 information for this anonymous RECORD_TYPE. */
11444 TYPE_NAME (t) = NULL_TREE;
11446 /* Cache this pointer-to-member type so that we can find it again
11447 later. */
11448 TYPE_PTRMEMFUNC_TYPE (type) = t;
11450 if (TYPE_STRUCTURAL_EQUALITY_P (type))
11451 SET_TYPE_STRUCTURAL_EQUALITY (t);
11452 else if (TYPE_CANONICAL (type) != type)
11453 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
11455 return t;
11458 /* Create and return a pointer to data member type. */
11460 tree
11461 build_ptrmem_type (tree class_type, tree member_type)
11463 if (TREE_CODE (member_type) == METHOD_TYPE)
11465 cp_cv_quals quals = type_memfn_quals (member_type);
11466 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
11467 member_type = build_memfn_type (member_type, class_type, quals, rqual);
11468 return build_ptrmemfunc_type (build_pointer_type (member_type));
11470 else
11472 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
11473 return build_offset_type (class_type, member_type);
11477 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
11478 Check to see that the definition is valid. Issue appropriate error
11479 messages. */
11481 static void
11482 check_static_variable_definition (tree decl, tree type)
11484 /* Avoid redundant diagnostics on out-of-class definitions. */
11485 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
11487 /* Can't check yet if we don't know the type. */
11488 else if (dependent_type_p (type))
11490 /* If DECL is declared constexpr, we'll do the appropriate checks
11491 in check_initializer. Similarly for inline static data members. */
11492 else if (DECL_P (decl)
11493 && (DECL_DECLARED_CONSTEXPR_P (decl)
11494 || DECL_VAR_DECLARED_INLINE_P (decl)))
11496 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11498 if (!COMPLETE_TYPE_P (type))
11499 error_at (DECL_SOURCE_LOCATION (decl),
11500 "in-class initialization of static data member %q#D of "
11501 "incomplete type", decl);
11502 else if (literal_type_p (type))
11503 permerror (DECL_SOURCE_LOCATION (decl),
11504 "%<constexpr%> needed for in-class initialization of "
11505 "static data member %q#D of non-integral type", decl);
11506 else
11507 error_at (DECL_SOURCE_LOCATION (decl),
11508 "in-class initialization of static data member %q#D of "
11509 "non-literal type", decl);
11511 /* Motion 10 at San Diego: If a static const integral data member is
11512 initialized with an integral constant expression, the initializer
11513 may appear either in the declaration (within the class), or in
11514 the definition, but not both. If it appears in the class, the
11515 member is a member constant. The file-scope definition is always
11516 required. */
11517 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
11518 error_at (DECL_SOURCE_LOCATION (decl),
11519 "invalid in-class initialization of static data member "
11520 "of non-integral type %qT",
11521 type);
11522 else if (!CP_TYPE_CONST_P (type))
11523 error_at (DECL_SOURCE_LOCATION (decl),
11524 "ISO C++ forbids in-class initialization of non-const "
11525 "static member %qD",
11526 decl);
11527 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11528 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
11529 "ISO C++ forbids initialization of member constant "
11530 "%qD of non-integral type %qT", decl, type);
11533 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
11534 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
11535 expressions out into temporary variables so that walk_tree doesn't
11536 step into them (c++/15764). */
11538 static tree
11539 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
11541 hash_set<tree> *pset = (hash_set<tree> *)data;
11542 tree expr = *expr_p;
11543 if (TREE_CODE (expr) == SAVE_EXPR)
11545 tree op = TREE_OPERAND (expr, 0);
11546 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
11547 if (TREE_SIDE_EFFECTS (op))
11548 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
11549 *walk_subtrees = 0;
11551 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
11552 *walk_subtrees = 0;
11553 return NULL;
11556 /* Entry point for the above. */
11558 static void
11559 stabilize_vla_size (tree size)
11561 hash_set<tree> pset;
11562 /* Break out any function calls into temporary variables. */
11563 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
11566 /* Reduce a SIZEOF_EXPR to its value. */
11568 tree
11569 fold_sizeof_expr (tree t)
11571 tree r;
11572 if (SIZEOF_EXPR_TYPE_P (t))
11573 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11574 TREE_TYPE (TREE_OPERAND (t, 0)),
11575 SIZEOF_EXPR, false, false);
11576 else if (TYPE_P (TREE_OPERAND (t, 0)))
11577 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11578 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11579 false, false);
11580 else
11581 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
11582 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11583 false, false);
11584 if (r == error_mark_node)
11585 r = size_one_node;
11586 return r;
11589 /* Given the SIZE (i.e., number of elements) in an array, compute
11590 an appropriate index type for the array. If non-NULL, NAME is
11591 the name of the entity being declared. */
11593 static tree
11594 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11595 tsubst_flags_t complain)
11597 if (error_operand_p (size))
11598 return error_mark_node;
11600 /* The type of the index being computed. */
11601 tree itype;
11603 /* The original numeric size as seen in the source code before
11604 conversion to size_t. */
11605 tree origsize = size;
11607 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11609 if (!type_dependent_expression_p (size))
11611 origsize = size = mark_rvalue_use (size);
11613 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11614 && TREE_SIDE_EFFECTS (size))
11615 /* In C++98, we mark a non-constant array bound with a magic
11616 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11617 else
11619 size = build_converted_constant_expr (size_type_node, size, complain);
11620 /* Pedantically a constant expression is required here and so
11621 __builtin_is_constant_evaluated () should fold to true if it
11622 is successfully folded into a constant. */
11623 size = fold_non_dependent_expr (size, complain,
11624 /*manifestly_const_eval=*/true);
11626 if (!TREE_CONSTANT (size))
11627 size = origsize;
11630 if (error_operand_p (size))
11631 return error_mark_node;
11633 /* The array bound must be an integer type. */
11634 tree type = TREE_TYPE (size);
11635 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11637 if (!(complain & tf_error))
11638 return error_mark_node;
11639 if (name)
11640 error_at (loc, "size of array %qD has non-integral type %qT",
11641 name, type);
11642 else
11643 error_at (loc, "size of array has non-integral type %qT", type);
11644 size = integer_one_node;
11648 /* A type is dependent if it is...an array type constructed from any
11649 dependent type or whose size is specified by a constant expression
11650 that is value-dependent. */
11651 /* We can only call value_dependent_expression_p on integral constant
11652 expressions. */
11653 if (processing_template_decl
11654 && potential_constant_expression (size)
11655 && value_dependent_expression_p (size))
11657 /* Just build the index type and mark that it requires
11658 structural equality checks. */
11659 in_template:
11660 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11661 size, size_one_node));
11662 TYPE_DEPENDENT_P (itype) = 1;
11663 TYPE_DEPENDENT_P_VALID (itype) = 1;
11664 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11665 return itype;
11668 if (TREE_CODE (size) != INTEGER_CST)
11670 tree folded = cp_fully_fold (size);
11671 if (TREE_CODE (folded) == INTEGER_CST)
11673 if (name)
11674 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11675 "integral constant-expression", name);
11676 else
11677 pedwarn (loc, OPT_Wpedantic,
11678 "size of array is not an integral constant-expression");
11680 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11681 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11682 folding a conversion from a pointer to integral type. In that
11683 case issue an error below and don't treat this as a VLA. */;
11684 else
11685 /* Use the folded result for VLAs, too; it will have resolved
11686 SIZEOF_EXPR. */
11687 size = folded;
11690 /* Normally, the array-bound will be a constant. */
11691 if (TREE_CODE (size) == INTEGER_CST)
11693 /* The size to use in diagnostics that reflects the constant
11694 size used in the source, rather than SIZE massaged above. */
11695 tree diagsize = size;
11697 /* If the original size before conversion to size_t was signed
11698 and negative, convert it to ssizetype to restore the sign. */
11699 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11700 && TREE_CODE (size) == INTEGER_CST
11701 && tree_int_cst_sign_bit (size))
11703 diagsize = fold_convert (ssizetype, size);
11705 /* Clear the overflow bit that may have been set as a result
11706 of the conversion from the sizetype of the new size to
11707 ssizetype. */
11708 TREE_OVERFLOW (diagsize) = false;
11711 /* Verify that the array has a positive number of elements
11712 and issue the appropriate diagnostic if it doesn't. */
11713 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11715 if (!(complain & tf_error))
11716 return error_mark_node;
11717 size = integer_one_node;
11719 /* As an extension we allow zero-sized arrays. */
11720 else if (integer_zerop (size))
11722 if (!(complain & tf_error))
11723 /* We must fail if performing argument deduction (as
11724 indicated by the state of complain), so that
11725 another substitution can be found. */
11726 return error_mark_node;
11727 else if (name)
11728 pedwarn (loc, OPT_Wpedantic,
11729 "ISO C++ forbids zero-size array %qD", name);
11730 else
11731 pedwarn (loc, OPT_Wpedantic,
11732 "ISO C++ forbids zero-size array");
11735 else if (TREE_CONSTANT (size)
11736 /* We don't allow VLAs at non-function scopes, or during
11737 tentative template substitution. */
11738 || !at_function_scope_p ()
11739 || !(complain & tf_error))
11741 if (!(complain & tf_error))
11742 return error_mark_node;
11743 /* `(int) &fn' is not a valid array bound. */
11744 if (name)
11745 error_at (loc,
11746 "size of array %qD is not an integral constant-expression",
11747 name);
11748 else
11749 error_at (loc, "size of array is not an integral constant-expression");
11750 size = integer_one_node;
11752 else if (pedantic && warn_vla != 0)
11754 if (name)
11755 pedwarn (name_loc, OPT_Wvla,
11756 "ISO C++ forbids variable length array %qD", name);
11757 else
11758 pedwarn (input_location, OPT_Wvla,
11759 "ISO C++ forbids variable length array");
11761 else if (warn_vla > 0)
11763 if (name)
11764 warning_at (name_loc, OPT_Wvla,
11765 "variable length array %qD is used", name);
11766 else
11767 warning (OPT_Wvla,
11768 "variable length array is used");
11771 if (processing_template_decl && !TREE_CONSTANT (size))
11772 goto in_template;
11773 else
11775 if (!TREE_CONSTANT (size))
11777 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11778 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11779 that happens when building TYPE_SIZE. */
11780 size = variable_size (size);
11781 stabilize_vla_size (size);
11784 /* Compute the index of the largest element in the array. It is
11785 one less than the number of elements in the array. We save
11786 and restore PROCESSING_TEMPLATE_DECL so that computations in
11787 cp_build_binary_op will be appropriately folded. */
11789 processing_template_decl_sentinel s;
11790 itype = cp_build_binary_op (input_location,
11791 MINUS_EXPR,
11792 cp_convert (ssizetype, size, complain),
11793 cp_convert (ssizetype, integer_one_node,
11794 complain),
11795 complain);
11796 itype = maybe_constant_value (itype, NULL_TREE, mce_true);
11799 if (!TREE_CONSTANT (itype))
11801 if (sanitize_flags_p (SANITIZE_VLA)
11802 && current_function_decl != NULL_TREE)
11804 /* We have to add 1 -- in the ubsan routine we generate
11805 LE_EXPR rather than LT_EXPR. */
11806 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11807 build_one_cst (TREE_TYPE (itype)));
11808 t = ubsan_instrument_vla (input_location, t);
11809 finish_expr_stmt (t);
11812 /* Make sure that there was no overflow when creating to a signed
11813 index type. (For example, on a 32-bit machine, an array with
11814 size 2^32 - 1 is too big.) */
11815 else if (TREE_CODE (itype) == INTEGER_CST
11816 && TREE_OVERFLOW (itype))
11818 if (!(complain & tf_error))
11819 return error_mark_node;
11820 error ("overflow in array dimension");
11821 TREE_OVERFLOW (itype) = 0;
11825 /* Create and return the appropriate index type. */
11826 itype = build_index_type (itype);
11828 /* If the index type were dependent, we would have returned early, so
11829 remember that it isn't. */
11830 TYPE_DEPENDENT_P (itype) = 0;
11831 TYPE_DEPENDENT_P_VALID (itype) = 1;
11832 return itype;
11835 tree
11836 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11838 return compute_array_index_type_loc (input_location, name, size, complain);
11841 /* Returns the scope (if any) in which the entity declared by
11842 DECLARATOR will be located. If the entity was declared with an
11843 unqualified name, NULL_TREE is returned. */
11845 tree
11846 get_scope_of_declarator (const cp_declarator *declarator)
11848 while (declarator && declarator->kind != cdk_id)
11849 declarator = declarator->declarator;
11851 /* If the declarator-id is a SCOPE_REF, the scope in which the
11852 declaration occurs is the first operand. */
11853 if (declarator
11854 && declarator->u.id.qualifying_scope)
11855 return declarator->u.id.qualifying_scope;
11857 /* Otherwise, the declarator is not a qualified name; the entity will
11858 be declared in the current scope. */
11859 return NULL_TREE;
11862 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11863 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11864 with this type. */
11866 static tree
11867 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11869 tree itype = NULL_TREE;
11871 /* If things have already gone awry, bail now. */
11872 if (type == error_mark_node || size == error_mark_node)
11873 return error_mark_node;
11875 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11876 for a deduced class type. */
11877 if (template_placeholder_p (type))
11879 if (name)
11880 error_at (loc, "%qD declared as array of template placeholder "
11881 "type %qT", name, type);
11882 else
11883 error ("creating array of template placeholder type %qT", type);
11884 return error_mark_node;
11887 /* If there are some types which cannot be array elements,
11888 issue an error-message and return. */
11889 switch (TREE_CODE (type))
11891 case VOID_TYPE:
11892 if (name)
11893 error_at (loc, "declaration of %qD as array of void", name);
11894 else
11895 error ("creating array of void");
11896 return error_mark_node;
11898 case FUNCTION_TYPE:
11899 if (name)
11900 error_at (loc, "declaration of %qD as array of functions", name);
11901 else
11902 error ("creating array of functions");
11903 return error_mark_node;
11905 case REFERENCE_TYPE:
11906 if (name)
11907 error_at (loc, "declaration of %qD as array of references", name);
11908 else
11909 error ("creating array of references");
11910 return error_mark_node;
11912 case METHOD_TYPE:
11913 if (name)
11914 error_at (loc, "declaration of %qD as array of function members",
11915 name);
11916 else
11917 error ("creating array of function members");
11918 return error_mark_node;
11920 default:
11921 break;
11924 if (!verify_type_context (name ? loc : input_location,
11925 TCTX_ARRAY_ELEMENT, type))
11926 return error_mark_node;
11928 /* [dcl.array]
11930 The constant expressions that specify the bounds of the arrays
11931 can be omitted only for the first member of the sequence. */
11932 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11934 if (name)
11935 error_at (loc, "declaration of %qD as multidimensional array must "
11936 "have bounds for all dimensions except the first",
11937 name);
11938 else
11939 error ("multidimensional array must have bounds for all "
11940 "dimensions except the first");
11942 return error_mark_node;
11945 /* Figure out the index type for the array. */
11946 if (size)
11948 itype = compute_array_index_type_loc (loc, name, size,
11949 tf_warning_or_error);
11950 if (type_uses_auto (type)
11951 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11953 sorry_at (loc, "variable-length array of %<auto%>");
11954 return error_mark_node;
11958 return build_cplus_array_type (type, itype);
11961 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11963 static location_t
11964 min_location (location_t loca, location_t locb)
11966 if (loca == UNKNOWN_LOCATION
11967 || (locb != UNKNOWN_LOCATION
11968 && linemap_location_before_p (line_table, locb, loca)))
11969 return locb;
11970 return loca;
11973 /* Returns the smallest location != UNKNOWN_LOCATION among the
11974 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11975 and LOCATIONS[ds_restrict]. */
11977 static location_t
11978 smallest_type_quals_location (int type_quals, const location_t* locations)
11980 location_t loc = UNKNOWN_LOCATION;
11982 if (type_quals & TYPE_QUAL_CONST)
11983 loc = locations[ds_const];
11985 if (type_quals & TYPE_QUAL_VOLATILE)
11986 loc = min_location (loc, locations[ds_volatile]);
11988 if (type_quals & TYPE_QUAL_RESTRICT)
11989 loc = min_location (loc, locations[ds_restrict]);
11991 return loc;
11994 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11996 static location_t
11997 smallest_type_location (int type_quals, const location_t* locations)
11999 location_t loc = smallest_type_quals_location (type_quals, locations);
12000 return min_location (loc, locations[ds_type_spec]);
12003 static location_t
12004 smallest_type_location (const cp_decl_specifier_seq *declspecs)
12006 int type_quals = get_type_quals (declspecs);
12007 return smallest_type_location (type_quals, declspecs->locations);
12010 /* Check that it's OK to declare a function with the indicated TYPE
12011 and TYPE_QUALS. SFK indicates the kind of special function (if any)
12012 that this function is. OPTYPE is the type given in a conversion
12013 operator declaration, or the class type for a constructor/destructor.
12014 Returns the actual return type of the function; that may be different
12015 than TYPE if an error occurs, or for certain special functions. */
12017 static tree
12018 check_special_function_return_type (special_function_kind sfk,
12019 tree type,
12020 tree optype,
12021 int type_quals,
12022 const location_t* locations)
12024 switch (sfk)
12026 case sfk_constructor:
12027 if (type)
12028 error_at (smallest_type_location (type_quals, locations),
12029 "return type specification for constructor invalid");
12030 else if (type_quals != TYPE_UNQUALIFIED)
12031 error_at (smallest_type_quals_location (type_quals, locations),
12032 "qualifiers are not allowed on constructor declaration");
12034 if (targetm.cxx.cdtor_returns_this ())
12035 type = build_pointer_type (optype);
12036 else
12037 type = void_type_node;
12038 break;
12040 case sfk_destructor:
12041 if (type)
12042 error_at (smallest_type_location (type_quals, locations),
12043 "return type specification for destructor invalid");
12044 else if (type_quals != TYPE_UNQUALIFIED)
12045 error_at (smallest_type_quals_location (type_quals, locations),
12046 "qualifiers are not allowed on destructor declaration");
12048 /* We can't use the proper return type here because we run into
12049 problems with ambiguous bases and covariant returns. */
12050 if (targetm.cxx.cdtor_returns_this ())
12051 type = build_pointer_type (void_type_node);
12052 else
12053 type = void_type_node;
12054 break;
12056 case sfk_conversion:
12057 if (type)
12058 error_at (smallest_type_location (type_quals, locations),
12059 "return type specified for %<operator %T%>", optype);
12060 else if (type_quals != TYPE_UNQUALIFIED)
12061 error_at (smallest_type_quals_location (type_quals, locations),
12062 "qualifiers are not allowed on declaration of "
12063 "%<operator %T%>", optype);
12065 type = optype;
12066 break;
12068 case sfk_deduction_guide:
12069 if (type)
12070 error_at (smallest_type_location (type_quals, locations),
12071 "return type specified for deduction guide");
12072 else if (type_quals != TYPE_UNQUALIFIED)
12073 error_at (smallest_type_quals_location (type_quals, locations),
12074 "qualifiers are not allowed on declaration of "
12075 "deduction guide");
12076 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
12078 error ("template template parameter %qT in declaration of "
12079 "deduction guide", optype);
12080 type = error_mark_node;
12082 else
12083 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
12084 for (int i = 0; i < ds_last; ++i)
12085 if (i != ds_explicit && locations[i])
12086 error_at (locations[i],
12087 "%<decl-specifier%> in declaration of deduction guide");
12088 break;
12090 default:
12091 gcc_unreachable ();
12094 return type;
12097 /* A variable or data member (whose unqualified name is IDENTIFIER)
12098 has been declared with the indicated TYPE. If the TYPE is not
12099 acceptable, issue an error message and return a type to use for
12100 error-recovery purposes. */
12102 tree
12103 check_var_type (tree identifier, tree type, location_t loc)
12105 if (VOID_TYPE_P (type))
12107 if (!identifier)
12108 error_at (loc, "unnamed variable or field declared void");
12109 else if (identifier_p (identifier))
12111 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
12112 error_at (loc, "variable or field %qE declared void",
12113 identifier);
12115 else
12116 error_at (loc, "variable or field declared void");
12117 type = error_mark_node;
12120 return type;
12123 /* Handle declaring DECL as an inline variable. */
12125 static void
12126 mark_inline_variable (tree decl, location_t loc)
12128 bool inlinep = true;
12129 if (! toplevel_bindings_p ())
12131 error_at (loc, "%<inline%> specifier invalid for variable "
12132 "%qD declared at block scope", decl);
12133 inlinep = false;
12135 else if (cxx_dialect < cxx17)
12136 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
12137 "with %<-std=c++17%> or %<-std=gnu++17%>");
12138 if (inlinep)
12140 retrofit_lang_decl (decl);
12141 SET_DECL_VAR_DECLARED_INLINE_P (decl);
12146 /* Assign a typedef-given name to a class or enumeration type declared
12147 as anonymous at first. This was split out of grokdeclarator
12148 because it is also used in libcc1. */
12150 void
12151 name_unnamed_type (tree type, tree decl)
12153 gcc_assert (TYPE_UNNAMED_P (type));
12155 /* Replace the anonymous decl with the real decl. Be careful not to
12156 rename other typedefs (such as the self-reference) of type. */
12157 tree orig = TYPE_NAME (type);
12158 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
12159 if (TYPE_NAME (t) == orig)
12160 TYPE_NAME (t) = decl;
12162 /* If this is a typedef within a template class, the nested
12163 type is a (non-primary) template. The name for the
12164 template needs updating as well. */
12165 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
12166 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
12168 /* Adjust linkage now that we aren't unnamed anymore. */
12169 reset_type_linkage (type);
12171 /* FIXME remangle member functions; member functions of a
12172 type with external linkage have external linkage. */
12174 /* Check that our job is done, and that it would fail if we
12175 attempted to do it again. */
12176 gcc_assert (!TYPE_UNNAMED_P (type));
12179 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
12180 is allowed. TYPE might contain a decltype(auto). Returns true if
12181 there was a problem, false otherwise. */
12183 static bool
12184 check_decltype_auto (location_t loc, tree type)
12186 if (tree a = type_uses_auto (type))
12188 if (AUTO_IS_DECLTYPE (a))
12190 if (a != type)
12192 error_at (loc, "%qT as type rather than plain "
12193 "%<decltype(auto)%>", type);
12194 return true;
12196 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
12198 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
12199 return true;
12203 return false;
12206 /* Given declspecs and a declarator (abstract or otherwise), determine
12207 the name and type of the object declared and construct a DECL node
12208 for it.
12210 DECLSPECS points to the representation of declaration-specifier
12211 sequence that precedes declarator.
12213 DECL_CONTEXT says which syntactic context this declaration is in:
12214 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
12215 FUNCDEF for a function definition. Like NORMAL but a few different
12216 error messages in each case. Return value may be zero meaning
12217 this definition is too screwy to try to parse.
12218 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
12219 handle member functions (which have FIELD context).
12220 Return value may be zero meaning this definition is too screwy to
12221 try to parse.
12222 PARM for a parameter declaration (either within a function prototype
12223 or before a function body). Make a PARM_DECL, or return void_type_node.
12224 TPARM for a template parameter declaration.
12225 CATCHPARM for a parameter declaration before a catch clause.
12226 TYPENAME if for a typename (in a cast or sizeof).
12227 Don't make a DECL node; just return the ..._TYPE node.
12228 FIELD for a struct or union field; make a FIELD_DECL.
12229 BITFIELD for a field with specified width.
12231 INITIALIZED is as for start_decl.
12233 ATTRLIST is a pointer to the list of attributes, which may be NULL
12234 if there are none; *ATTRLIST may be modified if attributes from inside
12235 the declarator should be applied to the declaration.
12237 When this function is called, scoping variables (such as
12238 CURRENT_CLASS_TYPE) should reflect the scope in which the
12239 declaration occurs, not the scope in which the new declaration will
12240 be placed. For example, on:
12242 void S::f() { ... }
12244 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
12245 should not be `S'.
12247 Returns a DECL (if a declarator is present), a TYPE (if there is no
12248 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
12249 error occurs. */
12251 tree
12252 grokdeclarator (const cp_declarator *declarator,
12253 cp_decl_specifier_seq *declspecs,
12254 enum decl_context decl_context,
12255 int initialized,
12256 tree* attrlist)
12258 tree type = NULL_TREE;
12259 int longlong = 0;
12260 int explicit_intN = 0;
12261 int int_n_alt = 0;
12262 int virtualp, explicitp, friendp, inlinep, staticp;
12263 int explicit_int = 0;
12264 int explicit_char = 0;
12265 int defaulted_int = 0;
12267 tree typedef_decl = NULL_TREE;
12268 const char *name = NULL;
12269 tree typedef_type = NULL_TREE;
12270 /* True if this declarator is a function definition. */
12271 bool funcdef_flag = false;
12272 cp_declarator_kind innermost_code = cdk_error;
12273 int bitfield = 0;
12274 #if 0
12275 /* See the code below that used this. */
12276 tree decl_attr = NULL_TREE;
12277 #endif
12279 /* Keep track of what sort of function is being processed
12280 so that we can warn about default return values, or explicit
12281 return values which do not match prescribed defaults. */
12282 special_function_kind sfk = sfk_none;
12284 tree dname = NULL_TREE;
12285 tree ctor_return_type = NULL_TREE;
12286 enum overload_flags flags = NO_SPECIAL;
12287 /* cv-qualifiers that apply to the declarator, for a declaration of
12288 a member function. */
12289 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
12290 /* virt-specifiers that apply to the declarator, for a declaration of
12291 a member function. */
12292 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
12293 /* ref-qualifier that applies to the declarator, for a declaration of
12294 a member function. */
12295 cp_ref_qualifier rqual = REF_QUAL_NONE;
12296 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
12297 int type_quals = get_type_quals (declspecs);
12298 tree raises = NULL_TREE;
12299 int template_count = 0;
12300 tree returned_attrs = NULL_TREE;
12301 tree parms = NULL_TREE;
12302 const cp_declarator *id_declarator;
12303 /* The unqualified name of the declarator; either an
12304 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
12305 tree unqualified_id;
12306 /* The class type, if any, in which this entity is located,
12307 or NULL_TREE if none. Note that this value may be different from
12308 the current class type; for example if an attempt is made to declare
12309 "A::f" inside "B", this value will be "A". */
12310 tree ctype = current_class_type;
12311 /* The NAMESPACE_DECL for the namespace in which this entity is
12312 located. If an unqualified name is used to declare the entity,
12313 this value will be NULL_TREE, even if the entity is located at
12314 namespace scope. */
12315 tree in_namespace = NULL_TREE;
12316 cp_storage_class storage_class;
12317 bool unsigned_p, signed_p, short_p, long_p, thread_p;
12318 bool type_was_error_mark_node = false;
12319 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
12320 bool template_type_arg = false;
12321 bool template_parm_flag = false;
12322 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
12323 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
12324 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
12325 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
12326 bool late_return_type_p = false;
12327 bool array_parameter_p = false;
12328 tree reqs = NULL_TREE;
12330 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
12331 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
12332 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
12333 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
12334 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
12335 explicit_intN = declspecs->explicit_intN_p;
12336 int_n_alt = declspecs->int_n_alt;
12337 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
12339 // Was concept_p specified? Note that ds_concept
12340 // implies ds_constexpr!
12341 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
12342 if (concept_p)
12343 constexpr_p = true;
12345 if (decl_context == FUNCDEF)
12346 funcdef_flag = true, decl_context = NORMAL;
12347 else if (decl_context == MEMFUNCDEF)
12348 funcdef_flag = true, decl_context = FIELD;
12349 else if (decl_context == BITFIELD)
12350 bitfield = 1, decl_context = FIELD;
12351 else if (decl_context == TEMPLATE_TYPE_ARG)
12352 template_type_arg = true, decl_context = TYPENAME;
12353 else if (decl_context == TPARM)
12354 template_parm_flag = true, decl_context = PARM;
12356 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
12357 funcdef_flag = true;
12359 location_t typespec_loc = loc_or_input_loc (smallest_type_location
12360 (type_quals,
12361 declspecs->locations));
12362 location_t id_loc;
12363 location_t init_loc;
12364 if (declarator)
12366 id_loc = loc_or_input_loc (declarator->id_loc);
12367 init_loc = loc_or_input_loc (declarator->init_loc);
12369 else
12370 init_loc = id_loc = input_location;
12372 /* Look inside a declarator for the name being declared
12373 and get it as a string, for an error message. */
12374 for (id_declarator = declarator;
12375 id_declarator;
12376 id_declarator = id_declarator->declarator)
12378 if (id_declarator->kind != cdk_id)
12379 innermost_code = id_declarator->kind;
12381 switch (id_declarator->kind)
12383 case cdk_function:
12384 if (id_declarator->declarator
12385 && id_declarator->declarator->kind == cdk_id)
12387 sfk = id_declarator->declarator->u.id.sfk;
12388 if (sfk == sfk_destructor)
12389 flags = DTOR_FLAG;
12391 break;
12393 case cdk_id:
12395 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
12396 tree decl = id_declarator->u.id.unqualified_name;
12397 if (!decl)
12398 break;
12399 if (qualifying_scope)
12401 if (check_for_bare_parameter_packs (qualifying_scope,
12402 id_declarator->id_loc))
12403 return error_mark_node;
12404 if (at_function_scope_p ())
12406 /* [dcl.meaning]
12408 A declarator-id shall not be qualified except
12409 for ...
12411 None of the cases are permitted in block
12412 scope. */
12413 if (qualifying_scope == global_namespace)
12414 error ("invalid use of qualified-name %<::%D%>",
12415 decl);
12416 else if (TYPE_P (qualifying_scope))
12417 error ("invalid use of qualified-name %<%T::%D%>",
12418 qualifying_scope, decl);
12419 else
12420 error ("invalid use of qualified-name %<%D::%D%>",
12421 qualifying_scope, decl);
12422 return error_mark_node;
12424 else if (TYPE_P (qualifying_scope))
12426 ctype = qualifying_scope;
12427 if (!MAYBE_CLASS_TYPE_P (ctype))
12429 error_at (id_declarator->id_loc,
12430 "%q#T is not a class or namespace", ctype);
12431 ctype = NULL_TREE;
12433 else if (innermost_code != cdk_function
12434 && current_class_type
12435 && !uniquely_derived_from_p (ctype,
12436 current_class_type))
12438 error_at (id_declarator->id_loc,
12439 "invalid use of qualified-name %<%T::%D%>",
12440 qualifying_scope, decl);
12441 return error_mark_node;
12444 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
12445 in_namespace = qualifying_scope;
12447 switch (TREE_CODE (decl))
12449 case BIT_NOT_EXPR:
12451 if (innermost_code != cdk_function)
12453 error_at (EXPR_LOCATION (decl),
12454 "declaration of %qE as non-function", decl);
12455 return error_mark_node;
12457 else if (!qualifying_scope
12458 && !(current_class_type && at_class_scope_p ()))
12460 error_at (EXPR_LOCATION (decl),
12461 "declaration of %qE as non-member", decl);
12462 return error_mark_node;
12465 tree type = TREE_OPERAND (decl, 0);
12466 if (TYPE_P (type))
12467 type = constructor_name (type);
12468 name = identifier_to_locale (IDENTIFIER_POINTER (type));
12469 dname = decl;
12471 break;
12473 case TEMPLATE_ID_EXPR:
12475 tree fns = TREE_OPERAND (decl, 0);
12477 dname = fns;
12478 if (!identifier_p (dname))
12479 dname = OVL_NAME (dname);
12481 /* Fall through. */
12483 case IDENTIFIER_NODE:
12484 if (identifier_p (decl))
12485 dname = decl;
12487 if (IDENTIFIER_KEYWORD_P (dname))
12489 error ("declarator-id missing; using reserved word %qD",
12490 dname);
12491 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12493 else if (!IDENTIFIER_CONV_OP_P (dname))
12494 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12495 else
12497 gcc_assert (flags == NO_SPECIAL);
12498 flags = TYPENAME_FLAG;
12499 sfk = sfk_conversion;
12500 tree glob = get_global_binding (dname);
12501 if (glob && TREE_CODE (glob) == TYPE_DECL)
12502 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12503 else
12504 name = "<invalid operator>";
12506 break;
12508 default:
12509 gcc_unreachable ();
12511 break;
12514 case cdk_array:
12515 case cdk_pointer:
12516 case cdk_reference:
12517 case cdk_ptrmem:
12518 break;
12520 case cdk_decomp:
12521 name = "structured binding";
12522 break;
12524 case cdk_error:
12525 return error_mark_node;
12527 default:
12528 gcc_unreachable ();
12530 if (id_declarator->kind == cdk_id)
12531 break;
12534 /* [dcl.fct.edf]
12536 The declarator in a function-definition shall have the form
12537 D1 ( parameter-declaration-clause) ... */
12538 if (funcdef_flag && innermost_code != cdk_function)
12540 error_at (id_loc, "function definition does not declare parameters");
12541 return error_mark_node;
12544 if (flags == TYPENAME_FLAG
12545 && innermost_code != cdk_function
12546 && ! (ctype && !declspecs->any_specifiers_p))
12548 error_at (id_loc, "declaration of %qD as non-function", dname);
12549 return error_mark_node;
12552 if (dname && identifier_p (dname))
12554 if (UDLIT_OPER_P (dname)
12555 && innermost_code != cdk_function)
12557 error_at (id_loc, "declaration of %qD as non-function", dname);
12558 return error_mark_node;
12561 if (IDENTIFIER_ANY_OP_P (dname))
12563 if (typedef_p)
12565 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
12566 return error_mark_node;
12568 else if (decl_context == PARM || decl_context == CATCHPARM)
12570 error_at (id_loc, "declaration of %qD as parameter", dname);
12571 return error_mark_node;
12576 /* Anything declared one level down from the top level
12577 must be one of the parameters of a function
12578 (because the body is at least two levels down). */
12580 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
12581 by not allowing C++ class definitions to specify their parameters
12582 with xdecls (must be spec.d in the parmlist).
12584 Since we now wait to push a class scope until we are sure that
12585 we are in a legitimate method context, we must set oldcname
12586 explicitly (since current_class_name is not yet alive).
12588 We also want to avoid calling this a PARM if it is in a namespace. */
12590 if (decl_context == NORMAL && !toplevel_bindings_p ())
12592 cp_binding_level *b = current_binding_level;
12593 current_binding_level = b->level_chain;
12594 if (current_binding_level != 0 && toplevel_bindings_p ())
12595 decl_context = PARM;
12596 current_binding_level = b;
12599 if (name == NULL)
12600 name = decl_context == PARM ? "parameter" : "type name";
12602 if (consteval_p && constexpr_p)
12604 error_at (declspecs->locations[ds_consteval],
12605 "both %qs and %qs specified", "constexpr", "consteval");
12606 return error_mark_node;
12609 if (concept_p && typedef_p)
12611 error_at (declspecs->locations[ds_concept],
12612 "%qs cannot appear in a typedef declaration", "concept");
12613 return error_mark_node;
12616 if (constexpr_p && typedef_p)
12618 error_at (declspecs->locations[ds_constexpr],
12619 "%qs cannot appear in a typedef declaration", "constexpr");
12620 return error_mark_node;
12623 if (consteval_p && typedef_p)
12625 error_at (declspecs->locations[ds_consteval],
12626 "%qs cannot appear in a typedef declaration", "consteval");
12627 return error_mark_node;
12630 if (constinit_p && typedef_p)
12632 error_at (declspecs->locations[ds_constinit],
12633 "%qs cannot appear in a typedef declaration", "constinit");
12634 return error_mark_node;
12637 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12638 keywords shall appear in a decl-specifier-seq." */
12639 if (constinit_p && constexpr_p)
12641 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12642 richloc.add_range (declspecs->locations[ds_constexpr]);
12643 error_at (&richloc,
12644 "can use at most one of the %<constinit%> and %<constexpr%> "
12645 "specifiers");
12646 return error_mark_node;
12649 /* If there were multiple types specified in the decl-specifier-seq,
12650 issue an error message. */
12651 if (declspecs->multiple_types_p)
12653 error_at (typespec_loc,
12654 "two or more data types in declaration of %qs", name);
12655 return error_mark_node;
12658 if (declspecs->conflicting_specifiers_p)
12659 return error_mark_node;
12661 /* Extract the basic type from the decl-specifier-seq. */
12662 type = declspecs->type;
12663 if (type == error_mark_node)
12665 type = NULL_TREE;
12666 type_was_error_mark_node = true;
12669 /* Ignore erroneous attributes. */
12670 if (attrlist && *attrlist == error_mark_node)
12671 *attrlist = NULL_TREE;
12673 /* An object declared as __attribute__((unavailable)) suppresses
12674 any reports of being declared with unavailable or deprecated
12675 items. An object declared as __attribute__((deprecated))
12676 suppresses warnings of uses of other deprecated items. */
12677 auto ds = make_temp_override (deprecated_state);
12678 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12679 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12680 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12681 deprecated_state = DEPRECATED_SUPPRESS;
12683 cp_handle_deprecated_or_unavailable (type);
12684 if (type && TREE_CODE (type) == TYPE_DECL)
12686 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12687 typedef_decl = type;
12688 type = TREE_TYPE (typedef_decl);
12689 if (DECL_ARTIFICIAL (typedef_decl))
12690 cp_handle_deprecated_or_unavailable (type);
12692 /* No type at all: default to `int', and set DEFAULTED_INT
12693 because it was not a user-defined typedef. */
12694 if (type == NULL_TREE)
12696 if (signed_p || unsigned_p || long_p || short_p)
12698 /* These imply 'int'. */
12699 type = integer_type_node;
12700 defaulted_int = 1;
12702 /* If we just have "complex", it is equivalent to "complex double". */
12703 else if (!longlong && !explicit_intN
12704 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12706 type = double_type_node;
12707 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12708 "ISO C++ does not support plain %<complex%> meaning "
12709 "%<double complex%>");
12712 /* Gather flags. */
12713 explicit_int = declspecs->explicit_int_p;
12714 explicit_char = declspecs->explicit_char_p;
12716 #if 0
12717 /* See the code below that used this. */
12718 if (typedef_decl)
12719 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12720 #endif
12721 typedef_type = type;
12723 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12724 ctor_return_type = TREE_TYPE (dname);
12725 else
12726 ctor_return_type = ctype;
12728 if (sfk != sfk_none)
12730 type = check_special_function_return_type (sfk, type,
12731 ctor_return_type,
12732 type_quals,
12733 declspecs->locations);
12734 type_quals = TYPE_UNQUALIFIED;
12736 else if (type == NULL_TREE)
12738 int is_main;
12740 explicit_int = -1;
12742 /* We handle `main' specially here, because 'main () { }' is so
12743 common. With no options, it is allowed. With -Wreturn-type,
12744 it is a warning. It is only an error with -pedantic-errors. */
12745 is_main = (funcdef_flag
12746 && dname && identifier_p (dname)
12747 && MAIN_NAME_P (dname)
12748 && ctype == NULL_TREE
12749 && in_namespace == NULL_TREE
12750 && current_namespace == global_namespace);
12752 if (type_was_error_mark_node)
12753 /* We've already issued an error, don't complain more. */;
12754 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12755 /* Allow it, sigh. */;
12756 else if (! is_main)
12757 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12758 name);
12759 else if (pedantic)
12760 pedwarn (id_loc, OPT_Wpedantic,
12761 "ISO C++ forbids declaration of %qs with no type", name);
12762 else
12763 warning_at (id_loc, OPT_Wreturn_type,
12764 "ISO C++ forbids declaration of %qs with no type", name);
12766 if (type_was_error_mark_node && template_parm_flag)
12767 /* FIXME we should be able to propagate the error_mark_node as is
12768 for other contexts too. */
12769 type = error_mark_node;
12770 else
12771 type = integer_type_node;
12774 ctype = NULL_TREE;
12776 if (explicit_intN)
12778 if (! int_n_enabled_p[declspecs->int_n_idx])
12780 error_at (declspecs->locations[ds_type_spec],
12781 "%<__int%d%> is not supported by this target",
12782 int_n_data[declspecs->int_n_idx].bitsize);
12783 explicit_intN = false;
12785 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12786 of "__intN". */
12787 else if (!int_n_alt && pedantic)
12788 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12789 "ISO C++ does not support %<__int%d%> for %qs",
12790 int_n_data[declspecs->int_n_idx].bitsize, name);
12793 /* Now process the modifiers that were specified
12794 and check for invalid combinations. */
12796 /* Long double is a special combination. */
12797 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12799 long_p = false;
12800 type = cp_build_qualified_type (long_double_type_node,
12801 cp_type_quals (type));
12804 /* Check all other uses of type modifiers. */
12806 if (unsigned_p || signed_p || long_p || short_p)
12808 location_t loc;
12809 const char *key;
12810 if (unsigned_p)
12812 key = "unsigned";
12813 loc = declspecs->locations[ds_unsigned];
12815 else if (signed_p)
12817 key = "signed";
12818 loc = declspecs->locations[ds_signed];
12820 else if (longlong)
12822 key = "long long";
12823 loc = declspecs->locations[ds_long_long];
12825 else if (long_p)
12827 key = "long";
12828 loc = declspecs->locations[ds_long];
12830 else /* if (short_p) */
12832 key = "short";
12833 loc = declspecs->locations[ds_short];
12836 int ok = 0;
12838 if (signed_p && unsigned_p)
12840 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12841 richloc.add_range (declspecs->locations[ds_unsigned]);
12842 error_at (&richloc,
12843 "%<signed%> and %<unsigned%> specified together");
12845 else if (long_p && short_p)
12847 gcc_rich_location richloc (declspecs->locations[ds_long]);
12848 richloc.add_range (declspecs->locations[ds_short]);
12849 error_at (&richloc, "%<long%> and %<short%> specified together");
12851 else if (TREE_CODE (type) != INTEGER_TYPE
12852 || type == char8_type_node
12853 || type == char16_type_node
12854 || type == char32_type_node
12855 || ((long_p || short_p)
12856 && (explicit_char || explicit_intN)))
12857 error_at (loc, "%qs specified with %qT", key, type);
12858 else if (!explicit_int && !defaulted_int
12859 && !explicit_char && !explicit_intN)
12861 if (typedef_decl)
12863 pedwarn (loc, OPT_Wpedantic,
12864 "%qs specified with typedef-name %qD",
12865 key, typedef_decl);
12866 ok = !flag_pedantic_errors;
12867 /* PR108099: __int128_t comes from c_common_nodes_and_builtins,
12868 and is not built as a typedef. */
12869 if (is_typedef_decl (typedef_decl))
12870 type = DECL_ORIGINAL_TYPE (typedef_decl);
12872 else if (declspecs->decltype_p)
12873 error_at (loc, "%qs specified with %<decltype%>", key);
12874 else
12875 error_at (loc, "%qs specified with %<typeof%>", key);
12877 else
12878 ok = 1;
12880 /* Discard the type modifiers if they are invalid. */
12881 if (! ok)
12883 unsigned_p = false;
12884 signed_p = false;
12885 long_p = false;
12886 short_p = false;
12887 longlong = 0;
12891 /* Decide whether an integer type is signed or not.
12892 Optionally treat bitfields as signed by default. */
12893 if (unsigned_p
12894 /* [class.bit]
12896 It is implementation-defined whether a plain (neither
12897 explicitly signed or unsigned) char, short, int, or long
12898 bit-field is signed or unsigned.
12900 Naturally, we extend this to long long as well. Note that
12901 this does not include wchar_t. */
12902 || (bitfield && !flag_signed_bitfields
12903 && !signed_p
12904 /* A typedef for plain `int' without `signed' can be
12905 controlled just like plain `int', but a typedef for
12906 `signed int' cannot be so controlled. */
12907 && !(typedef_decl
12908 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12909 && TREE_CODE (type) == INTEGER_TYPE
12910 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12912 if (explicit_intN)
12913 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12914 else if (longlong)
12915 type = long_long_unsigned_type_node;
12916 else if (long_p)
12917 type = long_unsigned_type_node;
12918 else if (short_p)
12919 type = short_unsigned_type_node;
12920 else if (type == char_type_node)
12921 type = unsigned_char_type_node;
12922 else if (typedef_decl)
12923 type = c_common_unsigned_type (type);
12924 else
12925 type = unsigned_type_node;
12927 else if (signed_p && type == char_type_node)
12928 type = signed_char_type_node;
12929 else if (explicit_intN)
12930 type = int_n_trees[declspecs->int_n_idx].signed_type;
12931 else if (longlong)
12932 type = long_long_integer_type_node;
12933 else if (long_p)
12934 type = long_integer_type_node;
12935 else if (short_p)
12936 type = short_integer_type_node;
12937 else if (signed_p && typedef_decl)
12938 type = c_common_signed_type (type);
12940 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12942 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12943 error_at (declspecs->locations[ds_complex],
12944 "complex invalid for %qs", name);
12945 /* If a modifier is specified, the resulting complex is the complex
12946 form of TYPE. E.g, "complex short" is "complex short int". */
12947 else if (type == integer_type_node)
12948 type = complex_integer_type_node;
12949 else if (type == float_type_node)
12950 type = complex_float_type_node;
12951 else if (type == double_type_node)
12952 type = complex_double_type_node;
12953 else if (type == long_double_type_node)
12954 type = complex_long_double_type_node;
12955 else
12956 type = build_complex_type (type);
12959 /* If we're using the injected-class-name to form a compound type or a
12960 declaration, replace it with the underlying class so we don't get
12961 redundant typedefs in the debug output. But if we are returning the
12962 type unchanged, leave it alone so that it's available to
12963 maybe_get_template_decl_from_type_decl. */
12964 if (CLASS_TYPE_P (type)
12965 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12966 && type == TREE_TYPE (TYPE_NAME (type))
12967 && (declarator || type_quals))
12968 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12970 type_quals |= cp_type_quals (type);
12971 type = cp_build_qualified_type
12972 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12973 || declspecs->decltype_p)
12974 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12975 /* We might have ignored or rejected some of the qualifiers. */
12976 type_quals = cp_type_quals (type);
12978 if (cxx_dialect >= cxx17 && type && is_auto (type)
12979 && innermost_code != cdk_function
12980 /* Placeholder in parm gets a better error below. */
12981 && !(decl_context == PARM || decl_context == CATCHPARM)
12982 && id_declarator && declarator != id_declarator)
12983 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12985 auto_diagnostic_group g;
12986 gcc_rich_location richloc (typespec_loc);
12987 richloc.add_fixit_insert_after ("<>");
12988 error_at (&richloc, "missing template argument list after %qE; "
12989 "for deduction, template placeholder must be followed "
12990 "by a simple declarator-id", tmpl);
12991 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12992 type = error_mark_node;
12995 staticp = 0;
12996 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12997 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12998 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
13000 storage_class = declspecs->storage_class;
13001 if (storage_class == sc_static)
13002 staticp = 1 + (decl_context == FIELD);
13003 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
13004 /* Treat class-scope deduction guides as static member functions
13005 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
13006 staticp = 2;
13008 if (virtualp)
13010 if (staticp == 2)
13012 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13013 richloc.add_range (declspecs->locations[ds_storage_class]);
13014 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
13015 "and %<static%>", dname);
13016 storage_class = sc_none;
13017 staticp = 0;
13019 if (constexpr_p && pedantic && cxx_dialect < cxx20)
13021 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13022 richloc.add_range (declspecs->locations[ds_constexpr]);
13023 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
13024 "declared both %<virtual%> and %<constexpr%> only in "
13025 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
13028 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
13030 /* Issue errors about use of storage classes for parameters. */
13031 if (decl_context == PARM)
13033 if (typedef_p)
13035 error_at (declspecs->locations[ds_typedef],
13036 "typedef declaration invalid in parameter declaration");
13037 return error_mark_node;
13039 else if (template_parm_flag && storage_class != sc_none)
13041 error_at (min_location (declspecs->locations[ds_thread],
13042 declspecs->locations[ds_storage_class]),
13043 "storage class specified for template parameter %qs",
13044 name);
13045 return error_mark_node;
13047 else if (storage_class == sc_static
13048 || storage_class == sc_extern
13049 || thread_p)
13051 error_at (min_location (declspecs->locations[ds_thread],
13052 declspecs->locations[ds_storage_class]),
13053 "storage class specified for parameter %qs", name);
13054 return error_mark_node;
13057 /* Function parameters cannot be concept. */
13058 if (concept_p)
13060 error_at (declspecs->locations[ds_concept],
13061 "a parameter cannot be declared %qs", "concept");
13062 concept_p = 0;
13063 constexpr_p = 0;
13065 /* Function parameters cannot be constexpr. If we saw one, moan
13066 and pretend it wasn't there. */
13067 else if (constexpr_p)
13069 error_at (declspecs->locations[ds_constexpr],
13070 "a parameter cannot be declared %qs", "constexpr");
13071 constexpr_p = 0;
13073 if (constinit_p)
13075 error_at (declspecs->locations[ds_constinit],
13076 "a parameter cannot be declared %qs", "constinit");
13077 constinit_p = 0;
13079 if (consteval_p)
13081 error_at (declspecs->locations[ds_consteval],
13082 "a parameter cannot be declared %qs", "consteval");
13083 consteval_p = 0;
13087 /* Give error if `virtual' is used outside of class declaration. */
13088 if (virtualp
13089 && (current_class_name == NULL_TREE || decl_context != FIELD))
13091 error_at (declspecs->locations[ds_virtual],
13092 "%<virtual%> outside class declaration");
13093 virtualp = 0;
13096 if (innermost_code == cdk_decomp)
13098 location_t loc = (declarator->kind == cdk_reference
13099 ? declarator->declarator->id_loc : declarator->id_loc);
13100 if (inlinep)
13101 error_at (declspecs->locations[ds_inline],
13102 "structured binding declaration cannot be %qs", "inline");
13103 if (typedef_p)
13104 error_at (declspecs->locations[ds_typedef],
13105 "structured binding declaration cannot be %qs", "typedef");
13106 if (constexpr_p && !concept_p)
13107 error_at (declspecs->locations[ds_constexpr], "structured "
13108 "binding declaration cannot be %qs", "constexpr");
13109 if (consteval_p)
13110 error_at (declspecs->locations[ds_consteval], "structured "
13111 "binding declaration cannot be %qs", "consteval");
13112 if (thread_p && cxx_dialect < cxx20)
13113 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
13114 "structured binding declaration can be %qs only in "
13115 "%<-std=c++20%> or %<-std=gnu++20%>",
13116 declspecs->gnu_thread_keyword_p
13117 ? "__thread" : "thread_local");
13118 if (concept_p)
13119 error_at (declspecs->locations[ds_concept],
13120 "structured binding declaration cannot be %qs", "concept");
13121 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
13122 if (type_quals & TYPE_QUAL_VOLATILE)
13123 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
13124 "%<volatile%>-qualified structured binding is deprecated");
13125 switch (storage_class)
13127 case sc_none:
13128 break;
13129 case sc_register:
13130 error_at (loc, "structured binding declaration cannot be %qs",
13131 "register");
13132 break;
13133 case sc_static:
13134 if (cxx_dialect < cxx20)
13135 pedwarn (loc, OPT_Wc__20_extensions,
13136 "structured binding declaration can be %qs only in "
13137 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
13138 break;
13139 case sc_extern:
13140 error_at (loc, "structured binding declaration cannot be %qs",
13141 "extern");
13142 break;
13143 case sc_mutable:
13144 error_at (loc, "structured binding declaration cannot be %qs",
13145 "mutable");
13146 break;
13147 case sc_auto:
13148 error_at (loc, "structured binding declaration cannot be "
13149 "C++98 %<auto%>");
13150 break;
13151 default:
13152 gcc_unreachable ();
13154 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
13155 || TYPE_IDENTIFIER (type) != auto_identifier)
13157 if (type != error_mark_node)
13159 auto_diagnostic_group d;
13160 error_at (loc, "structured binding declaration cannot have "
13161 "type %qT", type);
13162 inform (loc,
13163 "type must be cv-qualified %<auto%> or reference to "
13164 "cv-qualified %<auto%>");
13166 type = build_qualified_type (make_auto (), type_quals);
13167 declspecs->type = type;
13169 else if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type))
13170 pedwarn (loc, OPT_Wpedantic,
13171 "structured binding declaration cannot have constrained "
13172 "%<auto%> type %qT", type);
13173 inlinep = 0;
13174 typedef_p = 0;
13175 constexpr_p = 0;
13176 consteval_p = 0;
13177 concept_p = 0;
13178 if (storage_class != sc_static)
13180 storage_class = sc_none;
13181 declspecs->storage_class = sc_none;
13185 /* Static anonymous unions are dealt with here. */
13186 if (staticp && decl_context == TYPENAME
13187 && declspecs->type
13188 && ANON_AGGR_TYPE_P (declspecs->type))
13189 decl_context = FIELD;
13191 /* Warn about storage classes that are invalid for certain
13192 kinds of declarations (parameters, typenames, etc.). */
13193 if (thread_p
13194 && ((storage_class
13195 && storage_class != sc_extern
13196 && storage_class != sc_static)
13197 || typedef_p))
13199 location_t loc
13200 = min_location (declspecs->locations[ds_thread],
13201 declspecs->locations[ds_storage_class]);
13202 error_at (loc, "multiple storage classes in declaration of %qs", name);
13203 thread_p = false;
13205 if (decl_context != NORMAL
13206 && ((storage_class != sc_none
13207 && storage_class != sc_mutable)
13208 || thread_p))
13210 if ((decl_context == PARM || decl_context == CATCHPARM)
13211 && (storage_class == sc_register
13212 || storage_class == sc_auto))
13214 else if (typedef_p)
13216 else if (decl_context == FIELD
13217 /* C++ allows static class elements. */
13218 && storage_class == sc_static)
13219 /* C++ also allows inlines and signed and unsigned elements,
13220 but in those cases we don't come in here. */
13222 else
13224 location_t loc
13225 = min_location (declspecs->locations[ds_thread],
13226 declspecs->locations[ds_storage_class]);
13227 if (decl_context == FIELD)
13228 error_at (loc, "storage class specified for %qs", name);
13229 else if (decl_context == PARM || decl_context == CATCHPARM)
13230 error_at (loc, "storage class specified for parameter %qs", name);
13231 else
13232 error_at (loc, "storage class specified for typename");
13233 if (storage_class == sc_register
13234 || storage_class == sc_auto
13235 || storage_class == sc_extern
13236 || thread_p)
13237 storage_class = sc_none;
13240 else if (storage_class == sc_extern && funcdef_flag
13241 && ! toplevel_bindings_p ())
13242 error ("nested function %qs declared %<extern%>", name);
13243 else if (toplevel_bindings_p ())
13245 if (storage_class == sc_auto)
13246 error_at (declspecs->locations[ds_storage_class],
13247 "top-level declaration of %qs specifies %<auto%>", name);
13249 else if (thread_p
13250 && storage_class != sc_extern
13251 && storage_class != sc_static)
13253 if (declspecs->gnu_thread_keyword_p)
13254 pedwarn (declspecs->locations[ds_thread],
13255 0, "function-scope %qs implicitly auto and "
13256 "declared %<__thread%>", name);
13258 /* When thread_local is applied to a variable of block scope the
13259 storage-class-specifier static is implied if it does not appear
13260 explicitly. */
13261 storage_class = declspecs->storage_class = sc_static;
13262 staticp = 1;
13265 if (storage_class && friendp)
13267 error_at (min_location (declspecs->locations[ds_thread],
13268 declspecs->locations[ds_storage_class]),
13269 "storage class specifiers invalid in friend function "
13270 "declarations");
13271 storage_class = sc_none;
13272 staticp = 0;
13275 if (!id_declarator)
13276 unqualified_id = NULL_TREE;
13277 else
13279 unqualified_id = id_declarator->u.id.unqualified_name;
13280 switch (TREE_CODE (unqualified_id))
13282 case BIT_NOT_EXPR:
13283 unqualified_id = TREE_OPERAND (unqualified_id, 0);
13284 if (TYPE_P (unqualified_id))
13285 unqualified_id = constructor_name (unqualified_id);
13286 break;
13288 case IDENTIFIER_NODE:
13289 case TEMPLATE_ID_EXPR:
13290 break;
13292 default:
13293 gcc_unreachable ();
13297 if (declspecs->std_attributes
13298 && !diagnose_misapplied_contracts (declspecs->std_attributes))
13300 location_t attr_loc = declspecs->locations[ds_std_attribute];
13301 if (any_nonignored_attribute_p (declspecs->std_attributes)
13302 && warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
13303 inform (attr_loc, "an attribute that appertains to a type-specifier "
13304 "is ignored");
13307 if (attrlist)
13308 diagnose_misapplied_contracts (*attrlist);
13310 /* Skip over build_memfn_type when a FUNCTION_DECL is an xobj memfn. */
13311 bool is_xobj_member_function = false;
13312 /* Determine the type of the entity declared by recurring on the
13313 declarator. */
13314 for (; declarator; declarator = declarator->declarator)
13316 const cp_declarator *inner_declarator;
13317 tree attrs;
13319 if (type == error_mark_node)
13320 return error_mark_node;
13322 attrs = declarator->attributes;
13323 if (attrs)
13325 int attr_flags;
13327 attr_flags = 0;
13328 if (declarator->kind == cdk_id)
13329 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
13330 if (declarator->kind == cdk_function)
13331 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
13332 if (declarator->kind == cdk_array)
13333 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
13334 tree late_attrs = NULL_TREE;
13335 if (decl_context != PARM && decl_context != TYPENAME)
13336 /* Assume that any attributes that get applied late to
13337 templates will DTRT when applied to the declaration
13338 as a whole. */
13339 late_attrs = splice_template_attributes (&attrs, type);
13340 returned_attrs = decl_attributes (&type,
13341 attr_chainon (returned_attrs,
13342 attrs),
13343 attr_flags);
13344 returned_attrs = attr_chainon (late_attrs, returned_attrs);
13347 inner_declarator = declarator->declarator;
13349 /* Check that contracts aren't misapplied. */
13350 if (tree contract_attr = find_contract (declarator->std_attributes))
13351 if (declarator->kind != cdk_function
13352 || innermost_code != cdk_function)
13353 diagnose_misapplied_contracts (contract_attr);
13355 /* We don't want to warn in parameter context because we don't
13356 yet know if the parse will succeed, and this might turn out
13357 to be a constructor call. */
13358 if (decl_context != PARM
13359 && decl_context != TYPENAME
13360 && !typedef_p
13361 && declarator->parenthesized != UNKNOWN_LOCATION
13362 /* If the type is class-like and the inner name used a
13363 global namespace qualifier, we need the parens.
13364 Unfortunately all we can tell is whether a qualified name
13365 was used or not. */
13366 && !(inner_declarator
13367 && inner_declarator->kind == cdk_id
13368 && inner_declarator->u.id.qualifying_scope
13369 && (MAYBE_CLASS_TYPE_P (type)
13370 || TREE_CODE (type) == ENUMERAL_TYPE)))
13372 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
13373 "unnecessary parentheses in declaration of %qs",
13374 name))
13376 gcc_rich_location iloc (declarator->parenthesized);
13377 iloc.add_fixit_remove (get_start (declarator->parenthesized));
13378 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
13379 inform (&iloc, "remove parentheses");
13382 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
13383 break;
13385 switch (declarator->kind)
13387 case cdk_array:
13388 type = create_array_type_for_decl (dname, type,
13389 declarator->u.array.bounds,
13390 declarator->id_loc);
13391 if (!valid_array_size_p (dname
13392 ? declarator->id_loc : input_location,
13393 type, dname))
13394 type = error_mark_node;
13396 if (declarator->std_attributes)
13397 /* [dcl.array]/1:
13399 The optional attribute-specifier-seq appertains to the
13400 array. */
13401 returned_attrs = attr_chainon (returned_attrs,
13402 declarator->std_attributes);
13403 break;
13405 case cdk_function:
13407 tree arg_types;
13408 int funcdecl_p;
13410 /* Declaring a function type. */
13412 /* Pick up type qualifiers which should be applied to `this'. */
13413 memfn_quals = declarator->u.function.qualifiers;
13414 /* Pick up virt-specifiers. */
13415 virt_specifiers = declarator->u.function.virt_specifiers;
13416 /* And ref-qualifier, too */
13417 rqual = declarator->u.function.ref_qualifier;
13418 /* And tx-qualifier. */
13419 tree tx_qual = declarator->u.function.tx_qualifier;
13420 /* Pick up the exception specifications. */
13421 raises = declarator->u.function.exception_specification;
13422 /* If the exception-specification is ill-formed, let's pretend
13423 there wasn't one. */
13424 if (raises == error_mark_node)
13425 raises = NULL_TREE;
13427 auto find_xobj_parm = [](tree parm_list)
13429 /* There is no need to iterate over the list,
13430 only the first parm can be a valid xobj parm. */
13431 if (!parm_list || TREE_PURPOSE (parm_list) != this_identifier)
13432 return NULL_TREE;
13433 /* If we make it here, we are looking at an xobj parm.
13435 Non-null 'purpose' usually means the parm has a default
13436 argument, we don't want to violate this assumption. */
13437 TREE_PURPOSE (parm_list) = NULL_TREE;
13438 return TREE_VALUE (parm_list);
13441 tree xobj_parm
13442 = find_xobj_parm (declarator->u.function.parameters);
13443 is_xobj_member_function = xobj_parm;
13445 if (xobj_parm && cxx_dialect < cxx23)
13446 pedwarn (DECL_SOURCE_LOCATION (xobj_parm), OPT_Wc__23_extensions,
13447 "explicit object member function only available "
13448 "with %<-std=c++23%> or %<-std=gnu++23%>");
13450 if (xobj_parm && decl_context == TYPENAME)
13452 /* We inform in every case, just differently depending on what
13453 case it is. */
13454 auto_diagnostic_group d;
13455 bool ptr_type = true;
13456 /* If declarator->kind is cdk_function and we are at the end of
13457 the declarator chain, we are looking at a function type. */
13458 if (!declarator->declarator)
13460 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13461 "a function type cannot "
13462 "have an explicit object parameter");
13463 ptr_type = false;
13465 else if (declarator->declarator->kind == cdk_pointer)
13466 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13467 "a pointer to function type cannot "
13468 "have an explicit object parameter");
13469 else if (declarator->declarator->kind == cdk_ptrmem)
13470 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13471 "a pointer to member function type "
13472 "cannot have an explicit object parameter");
13473 else
13474 gcc_unreachable ();
13476 /* The locations being used here are probably not correct. */
13477 if (ptr_type)
13478 inform (DECL_SOURCE_LOCATION (xobj_parm),
13479 "the type of a pointer to explicit object member "
13480 "function is a regular pointer to function type");
13481 else
13482 inform (DECL_SOURCE_LOCATION (xobj_parm),
13483 "the type of an explicit object "
13484 "member function is a regular function type");
13485 /* Ideally we should synthesize the correct syntax
13486 for the user, perhaps this could be added later. */
13488 /* Since a valid xobj parm has its purpose cleared in find_xobj_parm
13489 the first parm node will never erroneously be detected here. */
13491 auto_diagnostic_group d;
13492 bool bad_xobj_parm_encountered = false;
13493 for (tree parm = declarator->u.function.parameters;
13494 parm && parm != void_list_node;
13495 parm = TREE_CHAIN (parm))
13497 if (TREE_PURPOSE (parm) != this_identifier)
13498 continue;
13499 bad_xobj_parm_encountered = true;
13500 TREE_PURPOSE (parm) = NULL_TREE;
13501 gcc_rich_location bad_xobj_parm
13502 (DECL_SOURCE_LOCATION (TREE_VALUE (parm)));
13503 error_at (&bad_xobj_parm,
13504 "only the first parameter of a member function "
13505 "can be declared as an explicit object parameter");
13507 if (bad_xobj_parm_encountered && xobj_parm)
13508 inform (DECL_SOURCE_LOCATION (xobj_parm),
13509 "valid explicit object parameter declared here");
13512 if (reqs)
13513 error_at (location_of (reqs), "requires-clause on return type");
13514 reqs = declarator->u.function.requires_clause;
13516 /* Say it's a definition only for the CALL_EXPR
13517 closest to the identifier. */
13518 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13520 /* Handle a late-specified return type. */
13521 tree late_return_type = declarator->u.function.late_return_type;
13522 if (tree auto_node = type_uses_auto (type))
13524 if (!late_return_type)
13526 if (!funcdecl_p)
13527 /* auto (*fp)() = f; is OK. */;
13528 else if (current_class_type
13529 && LAMBDA_TYPE_P (current_class_type))
13530 /* OK for C++11 lambdas. */;
13531 else if (cxx_dialect < cxx14)
13533 error_at (typespec_loc, "%qs function uses "
13534 "%<auto%> type specifier without "
13535 "trailing return type", name);
13536 inform (typespec_loc,
13537 "deduced return type only available "
13538 "with %<-std=c++14%> or %<-std=gnu++14%>");
13540 else if (virtualp)
13542 error_at (typespec_loc, "virtual function "
13543 "cannot have deduced return type");
13544 virtualp = false;
13547 else if (!is_auto (type) && sfk != sfk_conversion)
13549 error_at (typespec_loc, "%qs function with trailing "
13550 "return type has %qT as its type rather "
13551 "than plain %<auto%>", name, type);
13552 return error_mark_node;
13554 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13556 if (funcdecl_p)
13557 error_at (typespec_loc,
13558 "%qs function with trailing return type "
13559 "has %<decltype(auto)%> as its type "
13560 "rather than plain %<auto%>", name);
13561 else
13562 error_at (typespec_loc,
13563 "invalid use of %<decltype(auto)%>");
13564 return error_mark_node;
13566 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13567 if (!tmpl)
13568 if (tree late_auto = type_uses_auto (late_return_type))
13569 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13570 if (tmpl)
13572 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13574 auto_diagnostic_group g;
13575 error_at (typespec_loc, "deduced class "
13576 "type %qD in function return type",
13577 DECL_NAME (tmpl));
13578 inform (DECL_SOURCE_LOCATION (tmpl),
13579 "%qD declared here", tmpl);
13580 return error_mark_node;
13582 else if (!late_return_type)
13584 error_at (declarator->id_loc, "deduction guide "
13585 "for %qT must have trailing return "
13586 "type", TREE_TYPE (tmpl));
13587 inform (DECL_SOURCE_LOCATION (tmpl),
13588 "%qD declared here", tmpl);
13589 return error_mark_node;
13591 else if (CLASS_TYPE_P (late_return_type)
13592 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13593 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13594 == tmpl))
13595 /* OK */;
13596 else
13597 error ("trailing return type %qT of deduction guide "
13598 "is not a specialization of %qT",
13599 late_return_type, TREE_TYPE (tmpl));
13602 else if (late_return_type
13603 && sfk != sfk_conversion)
13605 if (late_return_type == error_mark_node)
13606 return error_mark_node;
13607 if (cxx_dialect < cxx11)
13608 /* Not using maybe_warn_cpp0x because this should
13609 always be an error. */
13610 error_at (typespec_loc,
13611 "trailing return type only available "
13612 "with %<-std=c++11%> or %<-std=gnu++11%>");
13613 else
13614 error_at (typespec_loc, "%qs function with trailing "
13615 "return type not declared with %<auto%> "
13616 "type specifier", name);
13617 return error_mark_node;
13619 if (late_return_type && sfk == sfk_conversion)
13621 error ("a conversion function cannot have a trailing return type");
13622 return error_mark_node;
13624 type = splice_late_return_type (type, late_return_type);
13625 if (type == error_mark_node)
13626 return error_mark_node;
13628 if (late_return_type)
13630 late_return_type_p = true;
13631 type_quals = cp_type_quals (type);
13634 if (type_quals != TYPE_UNQUALIFIED)
13636 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13637 warning for
13638 static_assert(!is_same_v<void(*)(), const void(*)()>);
13639 because there the qualifier matters. */
13640 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13641 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13642 "qualifiers ignored on function return type");
13643 /* [dcl.fct] "A volatile-qualified return type is
13644 deprecated." */
13645 if (type_quals & TYPE_QUAL_VOLATILE)
13646 warning_at (typespec_loc, OPT_Wvolatile,
13647 "%<volatile%>-qualified return type is "
13648 "deprecated");
13650 /* We now know that the TYPE_QUALS don't apply to the
13651 decl, but to its return type. */
13652 type_quals = TYPE_UNQUALIFIED;
13655 /* Error about some types functions can't return. */
13657 if (TREE_CODE (type) == FUNCTION_TYPE)
13659 error_at (typespec_loc, "%qs declared as function returning "
13660 "a function", name);
13661 return error_mark_node;
13663 if (TREE_CODE (type) == ARRAY_TYPE)
13665 error_at (typespec_loc, "%qs declared as function returning "
13666 "an array", name);
13667 return error_mark_node;
13669 if (constinit_p && funcdecl_p)
13671 error_at (declspecs->locations[ds_constinit],
13672 "%<constinit%> on function return type is not "
13673 "allowed");
13674 return error_mark_node;
13677 if (check_decltype_auto (typespec_loc, type))
13678 return error_mark_node;
13680 if (ctype == NULL_TREE
13681 && decl_context == FIELD
13682 && funcdecl_p
13683 && friendp == 0)
13684 ctype = current_class_type;
13686 if (ctype && (sfk == sfk_constructor
13687 || sfk == sfk_destructor))
13689 /* We are within a class's scope. If our declarator name
13690 is the same as the class name, and we are defining
13691 a function, then it is a constructor/destructor, and
13692 therefore returns a void type. */
13694 /* ISO C++ 12.4/2. A destructor may not be declared
13695 const or volatile. A destructor may not be static.
13696 A destructor may not be declared with ref-qualifier.
13698 ISO C++ 12.1. A constructor may not be declared
13699 const or volatile. A constructor may not be
13700 virtual. A constructor may not be static.
13701 A constructor may not be declared with ref-qualifier. */
13702 if (staticp == 2)
13703 error_at (declspecs->locations[ds_storage_class],
13704 (flags == DTOR_FLAG)
13705 ? G_("destructor cannot be static member "
13706 "function")
13707 : G_("constructor cannot be static member "
13708 "function"));
13709 if (memfn_quals)
13711 error ((flags == DTOR_FLAG)
13712 ? G_("destructors may not be cv-qualified")
13713 : G_("constructors may not be cv-qualified"));
13714 memfn_quals = TYPE_UNQUALIFIED;
13717 if (rqual)
13719 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13720 error ((flags == DTOR_FLAG)
13721 ? G_("destructors may not be ref-qualified")
13722 : G_("constructors may not be ref-qualified"));
13723 rqual = REF_QUAL_NONE;
13726 if (decl_context == FIELD
13727 && !member_function_or_else (ctype,
13728 current_class_type,
13729 flags))
13730 return error_mark_node;
13732 if (flags != DTOR_FLAG)
13734 /* It's a constructor. */
13735 if (explicitp == 1)
13736 explicitp = 2;
13737 if (virtualp)
13739 permerror (declspecs->locations[ds_virtual],
13740 "constructors cannot be declared %<virtual%>");
13741 virtualp = 0;
13743 if (decl_context == FIELD
13744 && sfk != sfk_constructor)
13745 return error_mark_node;
13747 if (decl_context == FIELD)
13748 staticp = 0;
13750 else if (friendp)
13752 if (virtualp)
13754 /* Cannot be both friend and virtual. */
13755 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13756 richloc.add_range (declspecs->locations[ds_friend]);
13757 error_at (&richloc, "virtual functions cannot be friends");
13758 friendp = 0;
13760 if (decl_context == NORMAL)
13761 error_at (declarator->id_loc,
13762 "friend declaration not in class definition");
13763 if (current_function_decl && funcdef_flag)
13765 error_at (declarator->id_loc,
13766 "cannot define friend function %qs in a local "
13767 "class definition", name);
13768 friendp = 0;
13770 /* [class.friend]/6: A function can be defined in a friend
13771 declaration if the function name is unqualified. */
13772 if (funcdef_flag && in_namespace)
13774 if (in_namespace == global_namespace)
13775 error_at (declarator->id_loc,
13776 "friend function definition %qs cannot have "
13777 "a name qualified with %<::%>", name);
13778 else
13779 error_at (declarator->id_loc,
13780 "friend function definition %qs cannot have "
13781 "a name qualified with %<%D::%>", name,
13782 in_namespace);
13785 else if (ctype && sfk == sfk_conversion)
13787 if (explicitp == 1)
13789 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13790 explicitp = 2;
13793 else if (sfk == sfk_deduction_guide)
13795 if (explicitp == 1)
13796 explicitp = 2;
13799 if (xobj_parm)
13801 if (!ctype
13802 && decl_context == NORMAL
13803 && (in_namespace
13804 || !declarator->declarator->u.id.qualifying_scope))
13805 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13806 "a non-member function cannot have "
13807 "an explicit object parameter");
13808 else
13810 if (virtualp)
13812 auto_diagnostic_group d;
13813 error_at (declspecs->locations[ds_virtual],
13814 "an explicit object member function cannot "
13815 "be %<virtual%>");
13816 inform (DECL_SOURCE_LOCATION (xobj_parm),
13817 "explicit object parameter declared here");
13818 virtualp = false;
13820 if (staticp >= 2)
13822 auto_diagnostic_group d;
13823 error_at (declspecs->locations[ds_storage_class],
13824 "an explicit object member function cannot "
13825 "be %<static%>");
13826 inform (DECL_SOURCE_LOCATION (xobj_parm),
13827 "explicit object parameter declared here");
13829 if (unqualified_id
13830 && identifier_p (unqualified_id)
13831 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13832 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13833 "%qD cannot be an explicit object member "
13834 "function", unqualified_id);
13837 tree pushed_scope = NULL_TREE;
13838 if (funcdecl_p
13839 && decl_context != FIELD
13840 && inner_declarator->u.id.qualifying_scope
13841 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13842 pushed_scope
13843 = push_scope (inner_declarator->u.id.qualifying_scope);
13845 arg_types = grokparms (declarator->u.function.parameters, &parms);
13847 if (pushed_scope)
13848 pop_scope (pushed_scope);
13850 if (inner_declarator
13851 && inner_declarator->kind == cdk_id
13852 && inner_declarator->u.id.sfk == sfk_destructor
13853 && arg_types != void_list_node)
13855 error_at (declarator->id_loc,
13856 "destructors may not have parameters");
13857 arg_types = void_list_node;
13858 parms = NULL_TREE;
13859 is_xobj_member_function = false;
13862 type = build_function_type (type, arg_types);
13864 tree attrs = declarator->std_attributes;
13865 if (tx_qual)
13867 tree att = build_tree_list (tx_qual, NULL_TREE);
13868 /* transaction_safe applies to the type, but
13869 transaction_safe_dynamic applies to the function. */
13870 if (is_attribute_p ("transaction_safe", tx_qual))
13871 attrs = attr_chainon (attrs, att);
13872 else
13873 returned_attrs = attr_chainon (returned_attrs, att);
13876 /* Actually apply the contract attributes to the declaration. */
13877 for (tree *p = &attrs; *p;)
13879 tree l = *p;
13880 if (cxx_contract_attribute_p (l))
13882 *p = TREE_CHAIN (l);
13883 /* Intentionally reverse order of contracts so they're
13884 reversed back into their lexical order. */
13885 TREE_CHAIN (l) = NULL_TREE;
13886 returned_attrs = chainon (l, returned_attrs);
13888 else
13889 p = &TREE_CHAIN (l);
13892 if (attrs)
13893 /* [dcl.fct]/2:
13895 The optional attribute-specifier-seq appertains to
13896 the function type. */
13897 cplus_decl_attributes (&type, attrs, 0);
13899 if (raises)
13900 type = build_exception_variant (type, raises);
13902 break;
13904 case cdk_pointer:
13905 case cdk_reference:
13906 case cdk_ptrmem:
13907 /* Filter out pointers-to-references and references-to-references.
13908 We can get these if a TYPE_DECL is used. */
13910 if (TYPE_REF_P (type))
13912 if (declarator->kind != cdk_reference)
13914 error ("cannot declare pointer to %q#T", type);
13915 type = TREE_TYPE (type);
13918 /* In C++0x, we allow reference to reference declarations
13919 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13920 and template type arguments [14.3.1/4 temp.arg.type]. The
13921 check for direct reference to reference declarations, which
13922 are still forbidden, occurs below. Reasoning behind the change
13923 can be found in DR106, DR540, and the rvalue reference
13924 proposals. */
13925 else if (cxx_dialect == cxx98)
13927 error ("cannot declare reference to %q#T", type);
13928 type = TREE_TYPE (type);
13931 else if (VOID_TYPE_P (type))
13933 if (declarator->kind == cdk_reference)
13934 error ("cannot declare reference to %q#T", type);
13935 else if (declarator->kind == cdk_ptrmem)
13936 error ("cannot declare pointer to %q#T member", type);
13939 /* We now know that the TYPE_QUALS don't apply to the decl,
13940 but to the target of the pointer. */
13941 type_quals = TYPE_UNQUALIFIED;
13943 /* This code used to handle METHOD_TYPE, but I don't think it's
13944 possible to get it here anymore. */
13945 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13946 if (declarator->kind == cdk_ptrmem
13947 && TREE_CODE (type) == FUNCTION_TYPE)
13949 memfn_quals |= type_memfn_quals (type);
13950 type = build_memfn_type (type,
13951 declarator->u.pointer.class_type,
13952 memfn_quals,
13953 rqual);
13954 if (type == error_mark_node)
13955 return error_mark_node;
13957 rqual = REF_QUAL_NONE;
13958 memfn_quals = TYPE_UNQUALIFIED;
13961 if (TREE_CODE (type) == FUNCTION_TYPE
13962 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13963 || type_memfn_rqual (type) != REF_QUAL_NONE))
13964 error (declarator->kind == cdk_reference
13965 ? G_("cannot declare reference to qualified function type %qT")
13966 : G_("cannot declare pointer to qualified function type %qT"),
13967 type);
13969 /* When the pointed-to type involves components of variable size,
13970 care must be taken to ensure that the size evaluation code is
13971 emitted early enough to dominate all the possible later uses
13972 and late enough for the variables on which it depends to have
13973 been assigned.
13975 This is expected to happen automatically when the pointed-to
13976 type has a name/declaration of it's own, but special attention
13977 is required if the type is anonymous.
13979 We handle the NORMAL and FIELD contexts here by inserting a
13980 dummy statement that just evaluates the size at a safe point
13981 and ensures it is not deferred until e.g. within a deeper
13982 conditional context (c++/43555).
13984 We expect nothing to be needed here for PARM or TYPENAME.
13985 Evaluating the size at this point for TYPENAME would
13986 actually be incorrect, as we might be in the middle of an
13987 expression with side effects on the pointed-to type size
13988 "arguments" prior to the pointer declaration point and the
13989 size evaluation could end up prior to the side effects. */
13991 if (!TYPE_NAME (type)
13992 && (decl_context == NORMAL || decl_context == FIELD)
13993 && at_function_scope_p ()
13994 && variably_modified_type_p (type, NULL_TREE))
13996 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13997 NULL_TREE, type);
13998 add_decl_expr (TYPE_NAME (type));
14001 if (declarator->kind == cdk_reference)
14003 /* In C++0x, the type we are creating a reference to might be
14004 a typedef which is itself a reference type. In that case,
14005 we follow the reference collapsing rules in
14006 [7.1.3/8 dcl.typedef] to create the final reference type:
14008 "If a typedef TD names a type that is a reference to a type
14009 T, an attempt to create the type 'lvalue reference to cv TD'
14010 creates the type 'lvalue reference to T,' while an attempt
14011 to create the type "rvalue reference to cv TD' creates the
14012 type TD."
14014 if (VOID_TYPE_P (type))
14015 /* We already gave an error. */;
14016 else if (TYPE_REF_P (type))
14018 if (declarator->u.reference.rvalue_ref)
14019 /* Leave type alone. */;
14020 else
14021 type = cp_build_reference_type (TREE_TYPE (type), false);
14023 else
14024 type = cp_build_reference_type
14025 (type, declarator->u.reference.rvalue_ref);
14027 /* In C++0x, we need this check for direct reference to
14028 reference declarations, which are forbidden by
14029 [8.3.2/5 dcl.ref]. Reference to reference declarations
14030 are only allowed indirectly through typedefs and template
14031 type arguments. Example:
14033 void foo(int & &); // invalid ref-to-ref decl
14035 typedef int & int_ref;
14036 void foo(int_ref &); // valid ref-to-ref decl
14038 if (inner_declarator && inner_declarator->kind == cdk_reference)
14039 error ("cannot declare reference to %q#T, which is not "
14040 "a typedef or a template type argument", type);
14042 else if (TREE_CODE (type) == METHOD_TYPE)
14043 type = build_ptrmemfunc_type (build_pointer_type (type));
14044 else if (declarator->kind == cdk_ptrmem)
14046 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
14047 != NAMESPACE_DECL);
14048 if (declarator->u.pointer.class_type == error_mark_node)
14049 /* We will already have complained. */
14050 type = error_mark_node;
14051 else
14052 type = build_ptrmem_type (declarator->u.pointer.class_type,
14053 type);
14055 else
14056 type = build_pointer_type (type);
14058 /* Process a list of type modifier keywords (such as
14059 const or volatile) that were given inside the `*' or `&'. */
14061 if (declarator->u.pointer.qualifiers)
14063 type
14064 = cp_build_qualified_type (type,
14065 declarator->u.pointer.qualifiers);
14066 type_quals = cp_type_quals (type);
14069 /* Apply C++11 attributes to the pointer, and not to the
14070 type pointed to. This is unlike what is done for GNU
14071 attributes above. It is to comply with [dcl.ptr]/1:
14073 [the optional attribute-specifier-seq (7.6.1) appertains
14074 to the pointer and not to the object pointed to]. */
14075 if (declarator->std_attributes)
14076 decl_attributes (&type, declarator->std_attributes,
14079 ctype = NULL_TREE;
14080 break;
14082 case cdk_error:
14083 break;
14085 default:
14086 gcc_unreachable ();
14090 id_loc = declarator ? declarator->id_loc : input_location;
14092 if (innermost_code != cdk_function
14093 /* Don't check this if it can be the artifical decltype(auto)
14094 we created when building a constraint in a compound-requirement:
14095 that the type-constraint is plain is going to be checked in
14096 cp_parser_compound_requirement. */
14097 && decl_context != TYPENAME
14098 && check_decltype_auto (id_loc, type))
14099 return error_mark_node;
14101 /* A `constexpr' specifier used in an object declaration declares
14102 the object as `const'. */
14103 if (constexpr_p && innermost_code != cdk_function)
14105 /* DR1688 says that a `constexpr' specifier in combination with
14106 `volatile' is valid. */
14108 if (!TYPE_REF_P (type))
14110 type_quals |= TYPE_QUAL_CONST;
14111 type = cp_build_qualified_type (type, type_quals);
14115 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
14116 && !FUNC_OR_METHOD_TYPE_P (type)
14117 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
14119 error ("template-id %qD used as a declarator",
14120 unqualified_id);
14121 unqualified_id = dname;
14124 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
14125 qualified with a class-name, turn it into a METHOD_TYPE, unless
14126 we know that the function is static. We take advantage of this
14127 opportunity to do other processing that pertains to entities
14128 explicitly declared to be class members. Note that if DECLARATOR
14129 is non-NULL, we know it is a cdk_id declarator; otherwise, we
14130 would not have exited the loop above. */
14131 if (declarator
14132 && declarator->kind == cdk_id
14133 && declarator->u.id.qualifying_scope
14134 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
14136 ctype = declarator->u.id.qualifying_scope;
14137 ctype = TYPE_MAIN_VARIANT (ctype);
14138 template_count = num_template_headers_for_class (ctype);
14140 if (ctype == current_class_type)
14142 if (friendp)
14144 permerror (declspecs->locations[ds_friend],
14145 "member functions are implicitly "
14146 "friends of their class");
14147 friendp = 0;
14149 else
14150 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
14151 ctype, name);
14153 else if (/* If the qualifying type is already complete, then we
14154 can skip the following checks. */
14155 !COMPLETE_TYPE_P (ctype)
14156 && (/* If the function is being defined, then
14157 qualifying type must certainly be complete. */
14158 funcdef_flag
14159 /* A friend declaration of "T::f" is OK, even if
14160 "T" is a template parameter. But, if this
14161 function is not a friend, the qualifying type
14162 must be a class. */
14163 || (!friendp && !CLASS_TYPE_P (ctype))
14164 /* For a declaration, the type need not be
14165 complete, if either it is dependent (since there
14166 is no meaningful definition of complete in that
14167 case) or the qualifying class is currently being
14168 defined. */
14169 || !(dependent_type_p (ctype)
14170 || currently_open_class (ctype)))
14171 /* Check that the qualifying type is complete. */
14172 && !complete_type_or_else (ctype, NULL_TREE))
14173 return error_mark_node;
14174 else if (TREE_CODE (type) == FUNCTION_TYPE)
14176 if (current_class_type
14177 && (!friendp || funcdef_flag || initialized))
14179 error_at (id_loc, funcdef_flag || initialized
14180 ? G_("cannot define member function %<%T::%s%> "
14181 "within %qT")
14182 : G_("cannot declare member function %<%T::%s%> "
14183 "within %qT"),
14184 ctype, name, current_class_type);
14185 return error_mark_node;
14188 else if (typedef_p && current_class_type)
14190 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
14191 ctype, name, current_class_type);
14192 return error_mark_node;
14196 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
14197 ctype = current_class_type;
14199 /* Now TYPE has the actual type. */
14201 if (returned_attrs)
14203 if (attrlist)
14204 *attrlist = attr_chainon (returned_attrs, *attrlist);
14205 else
14206 attrlist = &returned_attrs;
14209 if (declarator
14210 && declarator->kind == cdk_id
14211 && declarator->std_attributes
14212 && attrlist != NULL)
14214 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
14215 a declarator-id appertains to the entity that is declared. */
14216 if (declarator->std_attributes != error_mark_node)
14217 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
14218 else
14219 /* We should have already diagnosed the issue (c++/78344). */
14220 gcc_assert (seen_error ());
14223 /* Handle parameter packs. */
14224 if (parameter_pack_p)
14226 if (decl_context == PARM)
14227 /* Turn the type into a pack expansion.*/
14228 type = make_pack_expansion (type);
14229 else
14230 error ("non-parameter %qs cannot be a parameter pack", name);
14233 if ((decl_context == FIELD || decl_context == PARM)
14234 && !processing_template_decl
14235 && variably_modified_type_p (type, NULL_TREE))
14237 if (decl_context == FIELD)
14238 error_at (id_loc,
14239 "data member may not have variably modified type %qT", type);
14240 else
14241 error_at (id_loc,
14242 "parameter may not have variably modified type %qT", type);
14243 type = error_mark_node;
14246 if (explicitp == 1 || (explicitp && friendp))
14248 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
14249 in the declaration of a constructor or conversion function within
14250 a class definition. */
14251 if (!current_class_type)
14252 error_at (declspecs->locations[ds_explicit],
14253 "%<explicit%> outside class declaration");
14254 else if (friendp)
14255 error_at (declspecs->locations[ds_explicit],
14256 "%<explicit%> in friend declaration");
14257 else
14258 error_at (declspecs->locations[ds_explicit],
14259 "only declarations of constructors and conversion operators "
14260 "can be %<explicit%>");
14261 explicitp = 0;
14264 if (storage_class == sc_mutable)
14266 location_t sloc = declspecs->locations[ds_storage_class];
14267 if (decl_context != FIELD || friendp)
14269 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
14270 name);
14271 storage_class = sc_none;
14273 else if (decl_context == TYPENAME || typedef_p)
14275 error_at (sloc,
14276 "non-object member %qs cannot be declared %<mutable%>",
14277 name);
14278 storage_class = sc_none;
14280 else if (FUNC_OR_METHOD_TYPE_P (type))
14282 error_at (sloc, "function %qs cannot be declared %<mutable%>",
14283 name);
14284 storage_class = sc_none;
14286 else if (staticp)
14288 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
14289 name);
14290 storage_class = sc_none;
14292 else if (type_quals & TYPE_QUAL_CONST)
14294 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
14295 name);
14296 storage_class = sc_none;
14298 else if (TYPE_REF_P (type))
14300 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
14301 name);
14302 storage_class = sc_none;
14306 /* If this is declaring a typedef name, return a TYPE_DECL. */
14307 if (typedef_p && decl_context != TYPENAME)
14309 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
14310 tree decl;
14312 if (funcdef_flag)
14314 if (decl_context == NORMAL)
14315 error_at (id_loc,
14316 "typedef may not be a function definition");
14317 else
14318 error_at (id_loc,
14319 "typedef may not be a member function definition");
14320 return error_mark_node;
14323 /* This declaration:
14325 typedef void f(int) const;
14327 declares a function type which is not a member of any
14328 particular class, but which is cv-qualified; for
14329 example "f S::*" declares a pointer to a const-qualified
14330 member function of S. We record the cv-qualification in the
14331 function type. */
14332 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
14334 type = apply_memfn_quals (type, memfn_quals, rqual);
14336 /* We have now dealt with these qualifiers. */
14337 memfn_quals = TYPE_UNQUALIFIED;
14338 rqual = REF_QUAL_NONE;
14341 if (type_uses_auto (type))
14343 if (alias_p)
14344 error_at (declspecs->locations[ds_type_spec],
14345 "%<auto%> not allowed in alias declaration");
14346 else
14347 error_at (declspecs->locations[ds_type_spec],
14348 "typedef declared %<auto%>");
14349 type = error_mark_node;
14352 if (reqs)
14353 error_at (location_of (reqs), "requires-clause on typedef");
14355 if (id_declarator && declarator->u.id.qualifying_scope)
14357 error_at (id_loc, "typedef name may not be a nested-name-specifier");
14358 type = error_mark_node;
14361 if (decl_context == FIELD)
14362 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
14363 else
14364 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
14366 if (decl_context != FIELD)
14368 if (!current_function_decl)
14369 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
14370 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
14371 /* The TYPE_DECL is "abstract" because there will be
14372 clones of this constructor/destructor, and there will
14373 be copies of this TYPE_DECL generated in those
14374 clones. The decloning optimization (for space) may
14375 revert this subsequently if it determines that
14376 the clones should share a common implementation. */
14377 DECL_ABSTRACT_P (decl) = true;
14379 set_originating_module (decl);
14381 else if (current_class_type
14382 && constructor_name_p (unqualified_id, current_class_type))
14383 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
14384 "as enclosing class",
14385 unqualified_id);
14387 /* If the user declares "typedef struct {...} foo" then the
14388 struct will have an anonymous name. Fill that name in now.
14389 Nothing can refer to it, so nothing needs know about the name
14390 change. */
14391 if (type != error_mark_node
14392 && unqualified_id
14393 && TYPE_NAME (type)
14394 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
14395 && TYPE_UNNAMED_P (type)
14396 && declspecs->type_definition_p
14397 && attributes_naming_typedef_ok (*attrlist)
14398 && cp_type_quals (type) == TYPE_UNQUALIFIED)
14399 name_unnamed_type (type, decl);
14401 if (signed_p
14402 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
14403 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
14405 bad_specifiers (decl, BSP_TYPE, virtualp,
14406 memfn_quals != TYPE_UNQUALIFIED,
14407 inlinep, friendp, raises != NULL_TREE,
14408 declspecs->locations);
14410 if (alias_p)
14411 /* Acknowledge that this was written:
14412 `using analias = atype;'. */
14413 TYPE_DECL_ALIAS_P (decl) = 1;
14415 return decl;
14418 /* Detect the case of an array type of unspecified size
14419 which came, as such, direct from a typedef name.
14420 We must copy the type, so that the array's domain can be
14421 individually set by the object's initializer. */
14423 if (type && typedef_type
14424 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
14425 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
14426 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14428 /* Detect where we're using a typedef of function type to declare a
14429 function. PARMS will not be set, so we must create it now. */
14431 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
14433 tree decls = NULL_TREE;
14434 tree args;
14436 for (args = TYPE_ARG_TYPES (type);
14437 args && args != void_list_node;
14438 args = TREE_CHAIN (args))
14440 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
14441 TREE_VALUE (args));
14443 DECL_CHAIN (decl) = decls;
14444 decls = decl;
14447 parms = nreverse (decls);
14449 if (decl_context != TYPENAME)
14451 /* The qualifiers on the function type become the qualifiers on
14452 the non-static member function. */
14453 memfn_quals |= type_memfn_quals (type);
14454 rqual = type_memfn_rqual (type);
14455 type_quals = TYPE_UNQUALIFIED;
14456 raises = TYPE_RAISES_EXCEPTIONS (type);
14460 /* If this is a type name (such as, in a cast or sizeof),
14461 compute the type and return it now. */
14463 if (decl_context == TYPENAME)
14465 /* Note that here we don't care about type_quals. */
14467 /* Special case: "friend class foo" looks like a TYPENAME context. */
14468 if (friendp)
14470 if (inlinep)
14472 error ("%<inline%> specified for friend class declaration");
14473 inlinep = 0;
14476 if (!current_aggr)
14478 /* Don't allow friend declaration without a class-key. */
14479 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14480 permerror (input_location, "template parameters cannot be friends");
14481 else if (TREE_CODE (type) == TYPENAME_TYPE)
14482 permerror (input_location, "friend declaration requires class-key, "
14483 "i.e. %<friend class %T::%D%>",
14484 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
14485 else
14486 permerror (input_location, "friend declaration requires class-key, "
14487 "i.e. %<friend %#T%>",
14488 type);
14491 /* Only try to do this stuff if we didn't already give up. */
14492 if (type != integer_type_node)
14494 /* A friendly class? */
14495 if (current_class_type)
14496 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
14497 /*complain=*/true);
14498 else
14499 error ("trying to make class %qT a friend of global scope",
14500 type);
14502 type = void_type_node;
14505 else if (memfn_quals || rqual)
14507 if (ctype == NULL_TREE
14508 && TREE_CODE (type) == METHOD_TYPE)
14509 ctype = TYPE_METHOD_BASETYPE (type);
14511 if (ctype)
14512 type = build_memfn_type (type, ctype, memfn_quals, rqual);
14513 /* Core issue #547: need to allow this in template type args.
14514 Allow it in general in C++11 for alias-declarations. */
14515 else if ((template_type_arg || cxx_dialect >= cxx11)
14516 && TREE_CODE (type) == FUNCTION_TYPE)
14517 type = apply_memfn_quals (type, memfn_quals, rqual);
14518 else
14519 error ("invalid qualifiers on non-member function type");
14522 if (reqs)
14523 error_at (location_of (reqs), "requires-clause on type-id");
14525 return type;
14527 else if (unqualified_id == NULL_TREE && decl_context != PARM
14528 && decl_context != CATCHPARM
14529 && TREE_CODE (type) != UNION_TYPE
14530 && ! bitfield
14531 && innermost_code != cdk_decomp)
14533 error ("abstract declarator %qT used as declaration", type);
14534 return error_mark_node;
14537 if (!FUNC_OR_METHOD_TYPE_P (type))
14539 /* Only functions may be declared using an operator-function-id. */
14540 if (dname && IDENTIFIER_ANY_OP_P (dname))
14542 error_at (id_loc, "declaration of %qD as non-function", dname);
14543 return error_mark_node;
14546 if (reqs)
14547 error_at (location_of (reqs),
14548 "requires-clause on declaration of non-function type %qT",
14549 type);
14552 /* We don't check parameter types here because we can emit a better
14553 error message later. */
14554 if (decl_context != PARM)
14556 type = check_var_type (unqualified_id, type, id_loc);
14557 if (type == error_mark_node)
14558 return error_mark_node;
14561 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14562 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14564 if (decl_context == PARM || decl_context == CATCHPARM)
14566 if (ctype || in_namespace)
14567 error ("cannot use %<::%> in parameter declaration");
14569 tree auto_node = type_uses_auto (type);
14570 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14572 bool err_p = true;
14573 if (cxx_dialect >= cxx14)
14575 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14576 error_at (typespec_loc,
14577 "cannot declare a parameter with %<decltype(auto)%>");
14578 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14580 auto_diagnostic_group g;
14581 gcc_rich_location richloc (typespec_loc);
14582 richloc.add_fixit_insert_after ("<>");
14583 error_at (&richloc,
14584 "missing template argument list after %qE; template "
14585 "placeholder not permitted in parameter", c);
14586 if (decl_context == PARM && cxx_dialect >= cxx20)
14587 inform (typespec_loc, "or use %<auto%> for an "
14588 "abbreviated function template");
14589 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14591 else if (decl_context == CATCHPARM || template_parm_flag)
14592 error_at (typespec_loc,
14593 "%<auto%> parameter not permitted in this context");
14594 else
14595 /* Do not issue an error while tentatively parsing a function
14596 parameter: for T t(auto(a), 42);, when we just saw the 1st
14597 parameter, we don't know yet that this construct won't be
14598 a function declaration. Defer the checking to
14599 cp_parser_parameter_declaration_clause. */
14600 err_p = false;
14602 else
14603 error_at (typespec_loc, "parameter declared %<auto%>");
14604 if (err_p)
14605 type = error_mark_node;
14608 /* A parameter declared as an array of T is really a pointer to T.
14609 One declared as a function is really a pointer to a function.
14610 One declared as a member is really a pointer to member. */
14612 if (TREE_CODE (type) == ARRAY_TYPE)
14614 /* Transfer const-ness of array into that of type pointed to. */
14615 type = build_pointer_type (TREE_TYPE (type));
14616 type_quals = TYPE_UNQUALIFIED;
14617 array_parameter_p = true;
14619 else if (TREE_CODE (type) == FUNCTION_TYPE)
14620 type = build_pointer_type (type);
14623 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14624 /* Don't convert xobj member functions to METHOD_TYPE. */
14625 && !is_xobj_member_function
14626 && !(unqualified_id
14627 && identifier_p (unqualified_id)
14628 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14630 cp_cv_quals real_quals = memfn_quals;
14631 if (cxx_dialect < cxx14 && constexpr_p
14632 && sfk != sfk_constructor && sfk != sfk_destructor)
14633 real_quals |= TYPE_QUAL_CONST;
14634 type = build_memfn_type (type, ctype, real_quals, rqual);
14638 tree decl = NULL_TREE;
14640 if (decl_context == PARM)
14642 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14643 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14645 bad_specifiers (decl, BSP_PARM, virtualp,
14646 memfn_quals != TYPE_UNQUALIFIED,
14647 inlinep, friendp, raises != NULL_TREE,
14648 declspecs->locations);
14650 else if (decl_context == FIELD)
14652 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14653 if (tree auto_node = type_uses_auto (type))
14655 location_t tloc = declspecs->locations[ds_type_spec];
14656 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14657 error_at (tloc, "invalid use of template-name %qE without an "
14658 "argument list",
14659 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14660 else
14661 error_at (tloc, "non-static data member declared with "
14662 "placeholder %qT", auto_node);
14663 type = error_mark_node;
14666 /* The C99 flexible array extension. */
14667 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14668 && TYPE_DOMAIN (type) == NULL_TREE)
14670 if (ctype
14671 && (TREE_CODE (ctype) == UNION_TYPE
14672 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14673 pedwarn (id_loc, OPT_Wpedantic,
14674 "flexible array member in union is a GCC extension");
14676 else
14678 /* Array is a flexible member. */
14679 if (name)
14680 pedwarn (id_loc, OPT_Wpedantic,
14681 "ISO C++ forbids flexible array member %qs", name);
14682 else
14683 pedwarn (input_location, OPT_Wpedantic,
14684 "ISO C++ forbids flexible array members");
14686 /* Flexible array member has a null domain. */
14687 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14691 if (type == error_mark_node)
14693 /* Happens when declaring arrays of sizes which
14694 are error_mark_node, for example. */
14695 decl = NULL_TREE;
14697 else if (in_namespace && !friendp)
14699 /* Something like struct S { int N::j; }; */
14700 error_at (id_loc, "invalid use of %<::%>");
14701 return error_mark_node;
14703 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14705 int publicp = 0;
14706 tree function_context;
14708 if (friendp == 0)
14710 /* This should never happen in pure C++ (the check
14711 could be an assert). It could happen in
14712 Objective-C++ if someone writes invalid code that
14713 uses a function declaration for an instance
14714 variable or property (instance variables and
14715 properties are parsed as FIELD_DECLs, but they are
14716 part of an Objective-C class, not a C++ class).
14717 That code is invalid and is caught by this
14718 check. */
14719 if (!ctype)
14721 error ("declaration of function %qD in invalid context",
14722 unqualified_id);
14723 return error_mark_node;
14726 /* ``A union may [ ... ] not [ have ] virtual functions.''
14727 ARM 9.5 */
14728 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14730 error_at (declspecs->locations[ds_virtual],
14731 "function %qD declared %<virtual%> inside a union",
14732 unqualified_id);
14733 return error_mark_node;
14736 if (virtualp
14737 && identifier_p (unqualified_id)
14738 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14740 error_at (declspecs->locations[ds_virtual],
14741 "%qD cannot be declared %<virtual%>, since it "
14742 "is always static", unqualified_id);
14743 virtualp = 0;
14747 /* Check that the name used for a destructor makes sense. */
14748 if (sfk == sfk_destructor)
14750 tree uqname = id_declarator->u.id.unqualified_name;
14752 if (!ctype)
14754 gcc_assert (friendp);
14755 error_at (id_loc, "expected qualified name in friend "
14756 "declaration for destructor %qD", uqname);
14757 return error_mark_node;
14760 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14762 error_at (id_loc, "declaration of %qD as member of %qT",
14763 uqname, ctype);
14764 return error_mark_node;
14766 if (concept_p)
14768 error_at (declspecs->locations[ds_concept],
14769 "a destructor cannot be %qs", "concept");
14770 return error_mark_node;
14772 if (constexpr_p && cxx_dialect < cxx20)
14774 error_at (declspecs->locations[ds_constexpr],
14775 "%<constexpr%> destructors only available"
14776 " with %<-std=c++20%> or %<-std=gnu++20%>");
14777 return error_mark_node;
14779 if (consteval_p)
14781 error_at (declspecs->locations[ds_consteval],
14782 "a destructor cannot be %qs", "consteval");
14783 return error_mark_node;
14786 else if (sfk == sfk_constructor && friendp && !ctype)
14788 error ("expected qualified name in friend declaration "
14789 "for constructor %qD",
14790 id_declarator->u.id.unqualified_name);
14791 return error_mark_node;
14793 if (sfk == sfk_constructor)
14794 if (concept_p)
14796 error_at (declspecs->locations[ds_concept],
14797 "a constructor cannot be %<concept%>");
14798 return error_mark_node;
14800 if (concept_p)
14802 error_at (declspecs->locations[ds_concept],
14803 "a concept cannot be a member function");
14804 concept_p = false;
14806 else if (consteval_p
14807 && identifier_p (unqualified_id)
14808 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14810 error_at (declspecs->locations[ds_consteval],
14811 "%qD cannot be %qs", unqualified_id, "consteval");
14812 consteval_p = false;
14815 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14817 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14818 if (variable_template_p (tmpl))
14820 error_at (id_loc, "specialization of variable template "
14821 "%qD declared as function", tmpl);
14822 inform (DECL_SOURCE_LOCATION (tmpl),
14823 "variable template declared here");
14824 return error_mark_node;
14828 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14829 function_context
14830 = (ctype != NULL_TREE
14831 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14832 publicp = ((! friendp || ! staticp)
14833 && function_context == NULL_TREE);
14835 decl = grokfndecl (ctype, type,
14836 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14837 ? unqualified_id : dname,
14838 parms,
14839 unqualified_id,
14840 declspecs,
14841 reqs,
14842 virtualp, flags, memfn_quals, rqual, raises,
14843 friendp ? -1 : 0, friendp, publicp,
14844 inlinep | (2 * constexpr_p) | (4 * concept_p)
14845 | (8 * consteval_p),
14846 initialized == SD_DELETED,
14847 is_xobj_member_function, sfk,
14848 funcdef_flag, late_return_type_p,
14849 template_count, in_namespace,
14850 attrlist, id_loc);
14851 decl = set_virt_specifiers (decl, virt_specifiers);
14852 if (decl == NULL_TREE)
14853 return error_mark_node;
14854 #if 0
14855 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14856 /* The decl and setting of decl_attr is also turned off. */
14857 decl = build_decl_attribute_variant (decl, decl_attr);
14858 #endif
14860 /* [class.conv.ctor]
14862 A constructor declared without the function-specifier
14863 explicit that can be called with a single parameter
14864 specifies a conversion from the type of its first
14865 parameter to the type of its class. Such a constructor
14866 is called a converting constructor. */
14867 if (explicitp == 2)
14868 DECL_NONCONVERTING_P (decl) = 1;
14870 if (declspecs->explicit_specifier)
14871 store_explicit_specifier (decl, declspecs->explicit_specifier);
14873 else if (!staticp
14874 && ((current_class_type
14875 && same_type_p (type, current_class_type))
14876 || (!dependent_type_p (type)
14877 && !COMPLETE_TYPE_P (complete_type (type))
14878 && (!complete_or_array_type_p (type)
14879 || initialized == SD_UNINITIALIZED))))
14881 if (TREE_CODE (type) != ARRAY_TYPE
14882 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14884 if (unqualified_id)
14886 error_at (id_loc, "field %qD has incomplete type %qT",
14887 unqualified_id, type);
14888 cxx_incomplete_type_inform (strip_array_types (type));
14890 else
14891 error ("name %qT has incomplete type", type);
14893 type = error_mark_node;
14894 decl = NULL_TREE;
14897 else if (!verify_type_context (input_location,
14898 staticp
14899 ? TCTX_STATIC_STORAGE
14900 : TCTX_FIELD, type))
14902 type = error_mark_node;
14903 decl = NULL_TREE;
14905 else
14907 if (friendp)
14909 if (unqualified_id)
14910 error_at (id_loc,
14911 "%qE is neither function nor member function; "
14912 "cannot be declared friend", unqualified_id);
14913 else
14914 error ("unnamed field is neither function nor member "
14915 "function; cannot be declared friend");
14916 return error_mark_node;
14918 decl = NULL_TREE;
14921 if (friendp)
14923 /* Packages tend to use GNU attributes on friends, so we only
14924 warn for standard attributes. */
14925 if (attrlist
14926 && !funcdef_flag
14927 && cxx11_attribute_p (*attrlist)
14928 && !all_attributes_are_contracts_p (*attrlist))
14930 *attrlist = NULL_TREE;
14931 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14932 inform (id_loc, "an attribute that appertains to a friend "
14933 "declaration that is not a definition is ignored");
14935 /* Friends are treated specially. */
14936 if (ctype == current_class_type)
14937 ; /* We already issued a permerror. */
14938 else if (decl && DECL_NAME (decl))
14940 set_originating_module (decl, true);
14942 if (initialized)
14943 /* Kludge: We need funcdef_flag to be true in do_friend for
14944 in-class defaulted functions, but that breaks grokfndecl.
14945 So set it here. */
14946 funcdef_flag = true;
14948 cplus_decl_attributes (&decl, *attrlist, 0);
14949 *attrlist = NULL_TREE;
14951 tree scope = ctype ? ctype : in_namespace;
14952 decl = do_friend (scope, unqualified_id, decl,
14953 flags, funcdef_flag);
14954 return decl;
14956 else
14957 return error_mark_node;
14960 /* Structure field. It may not be a function, except for C++. */
14962 if (decl == NULL_TREE)
14964 if (staticp)
14966 /* C++ allows static class members. All other work
14967 for this is done by grokfield. */
14968 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14969 dname, type);
14970 if (unqualified_id
14971 && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14973 decl = check_explicit_specialization (unqualified_id, decl,
14974 template_count,
14975 concept_p * 8);
14976 if (decl == error_mark_node)
14977 return error_mark_node;
14979 set_linkage_for_static_data_member (decl);
14980 if (concept_p)
14981 error_at (declspecs->locations[ds_concept],
14982 "static data member %qE declared %qs",
14983 unqualified_id, "concept");
14984 else if (constexpr_p && !initialized)
14986 error_at (DECL_SOURCE_LOCATION (decl),
14987 "%<constexpr%> static data member %qD must "
14988 "have an initializer", decl);
14989 constexpr_p = false;
14991 if (consteval_p)
14992 error_at (declspecs->locations[ds_consteval],
14993 "static data member %qE declared %qs",
14994 unqualified_id, "consteval");
14996 if (inlinep)
14997 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14999 if (!DECL_VAR_DECLARED_INLINE_P (decl)
15000 && !(cxx_dialect >= cxx17 && constexpr_p))
15001 /* Even if there is an in-class initialization, DECL
15002 is considered undefined until an out-of-class
15003 definition is provided, unless this is an inline
15004 variable. */
15005 DECL_EXTERNAL (decl) = 1;
15007 if (thread_p)
15009 CP_DECL_THREAD_LOCAL_P (decl) = true;
15010 if (!processing_template_decl)
15011 set_decl_tls_model (decl, decl_default_tls_model (decl));
15012 if (declspecs->gnu_thread_keyword_p)
15013 SET_DECL_GNU_TLS_P (decl);
15016 /* Set the constraints on the declaration. */
15017 bool memtmpl = (current_template_depth
15018 > template_class_depth (current_class_type));
15019 if (memtmpl)
15021 tree ci = current_template_constraints ();
15022 set_constraints (decl, ci);
15025 else
15027 if (concept_p)
15029 error_at (declspecs->locations[ds_concept],
15030 "non-static data member %qE declared %qs",
15031 unqualified_id, "concept");
15032 concept_p = false;
15033 constexpr_p = false;
15035 else if (constexpr_p)
15037 error_at (declspecs->locations[ds_constexpr],
15038 "non-static data member %qE declared %qs",
15039 unqualified_id, "constexpr");
15040 constexpr_p = false;
15042 if (constinit_p)
15044 error_at (declspecs->locations[ds_constinit],
15045 "non-static data member %qE declared %qs",
15046 unqualified_id, "constinit");
15047 constinit_p = false;
15049 if (consteval_p)
15051 error_at (declspecs->locations[ds_consteval],
15052 "non-static data member %qE declared %qs",
15053 unqualified_id, "consteval");
15054 consteval_p = false;
15056 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
15057 DECL_NONADDRESSABLE_P (decl) = bitfield;
15058 if (bitfield && !unqualified_id)
15059 DECL_PADDING_P (decl) = 1;
15061 if (storage_class == sc_mutable)
15063 DECL_MUTABLE_P (decl) = 1;
15064 storage_class = sc_none;
15067 if (initialized)
15069 /* An attempt is being made to initialize a non-static
15070 member. This is new in C++11. */
15071 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
15073 /* If this has been parsed with static storage class, but
15074 errors forced staticp to be cleared, ensure NSDMI is
15075 not present. */
15076 if (declspecs->storage_class == sc_static)
15077 DECL_INITIAL (decl) = error_mark_node;
15081 bad_specifiers (decl, BSP_FIELD, virtualp,
15082 memfn_quals != TYPE_UNQUALIFIED,
15083 staticp ? false : inlinep, friendp,
15084 raises != NULL_TREE,
15085 declspecs->locations);
15088 else if (FUNC_OR_METHOD_TYPE_P (type))
15090 tree original_name;
15091 int publicp = 0;
15093 if (!unqualified_id)
15094 return error_mark_node;
15096 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
15097 original_name = dname;
15098 else
15099 original_name = unqualified_id;
15100 // FIXME:gcc_assert (original_name == dname);
15102 if (storage_class == sc_auto)
15103 error_at (declspecs->locations[ds_storage_class],
15104 "storage class %<auto%> invalid for function %qs", name);
15105 else if (storage_class == sc_register)
15106 error_at (declspecs->locations[ds_storage_class],
15107 "storage class %<register%> invalid for function %qs",
15108 name);
15109 else if (thread_p)
15111 if (declspecs->gnu_thread_keyword_p)
15112 error_at (declspecs->locations[ds_thread],
15113 "storage class %<__thread%> invalid for function %qs",
15114 name);
15115 else
15116 error_at (declspecs->locations[ds_thread],
15117 "storage class %<thread_local%> invalid for "
15118 "function %qs", name);
15120 else if (constinit_p)
15121 error_at (declspecs->locations[ds_constinit],
15122 "%<constinit%> specifier invalid for function %qs", name);
15124 if (virt_specifiers)
15125 error ("virt-specifiers in %qs not allowed outside a class "
15126 "definition", name);
15127 /* Function declaration not at top level.
15128 Storage classes other than `extern' are not allowed
15129 and `extern' makes no difference. */
15130 if (! toplevel_bindings_p ()
15131 && (storage_class == sc_static
15132 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
15133 && pedantic)
15135 if (storage_class == sc_static)
15136 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
15137 "%<static%> specifier invalid for function %qs "
15138 "declared out of global scope", name);
15139 else
15140 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
15141 "%<inline%> specifier invalid for function %qs "
15142 "declared out of global scope", name);
15145 if (ctype == NULL_TREE)
15147 if (virtualp)
15149 error ("virtual non-class function %qs", name);
15150 virtualp = 0;
15152 else if (sfk == sfk_constructor
15153 || sfk == sfk_destructor)
15155 error (funcdef_flag
15156 ? G_("%qs defined in a non-class scope")
15157 : G_("%qs declared in a non-class scope"), name);
15158 sfk = sfk_none;
15161 if (consteval_p
15162 && identifier_p (unqualified_id)
15163 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
15165 error_at (declspecs->locations[ds_consteval],
15166 "%qD cannot be %qs", unqualified_id, "consteval");
15167 consteval_p = false;
15170 /* Record whether the function is public. */
15171 publicp = (ctype != NULL_TREE
15172 || storage_class != sc_static);
15174 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
15175 declspecs,
15176 reqs, virtualp, flags, memfn_quals, rqual, raises,
15177 1, friendp,
15178 publicp,
15179 inlinep | (2 * constexpr_p) | (4 * concept_p)
15180 | (8 * consteval_p),
15181 initialized == SD_DELETED,
15182 is_xobj_member_function, sfk,
15183 funcdef_flag,
15184 late_return_type_p,
15185 template_count, in_namespace, attrlist,
15186 id_loc);
15187 if (decl == NULL_TREE)
15188 return error_mark_node;
15190 if (explicitp == 2)
15191 DECL_NONCONVERTING_P (decl) = 1;
15192 if (staticp == 1)
15194 int invalid_static = 0;
15196 /* Don't allow a static member function in a class, and forbid
15197 declaring main to be static. */
15198 if (TREE_CODE (type) == METHOD_TYPE)
15200 permerror (input_location, "cannot declare member function %qD to have "
15201 "static linkage", decl);
15202 invalid_static = 1;
15204 else if (current_function_decl)
15206 /* 7.1.1: There can be no static function declarations within a
15207 block. */
15208 error_at (declspecs->locations[ds_storage_class],
15209 "cannot declare static function inside another function");
15210 invalid_static = 1;
15213 if (invalid_static)
15215 staticp = 0;
15216 storage_class = sc_none;
15219 if (declspecs->explicit_specifier)
15220 store_explicit_specifier (decl, declspecs->explicit_specifier);
15222 else
15224 /* It's a variable. */
15226 /* An uninitialized decl with `extern' is a reference. */
15227 decl = grokvardecl (type, dname, unqualified_id,
15228 declspecs,
15229 initialized,
15230 type_quals,
15231 inlinep,
15232 concept_p,
15233 template_count,
15234 ctype ? ctype : in_namespace,
15235 id_loc);
15236 if (decl == NULL_TREE)
15237 return error_mark_node;
15239 bad_specifiers (decl, BSP_VAR, virtualp,
15240 memfn_quals != TYPE_UNQUALIFIED,
15241 inlinep, friendp, raises != NULL_TREE,
15242 declspecs->locations);
15244 if (ctype)
15246 DECL_CONTEXT (decl) = ctype;
15247 if (staticp == 1)
15249 permerror (declspecs->locations[ds_storage_class],
15250 "%<static%> may not be used when defining "
15251 "(as opposed to declaring) a static data member");
15252 staticp = 0;
15253 storage_class = sc_none;
15255 if (storage_class == sc_register && TREE_STATIC (decl))
15257 error ("static member %qD declared %<register%>", decl);
15258 storage_class = sc_none;
15260 if (storage_class == sc_extern && pedantic)
15262 pedwarn (input_location, OPT_Wpedantic,
15263 "cannot explicitly declare member %q#D to have "
15264 "extern linkage", decl);
15265 storage_class = sc_none;
15268 else if (constexpr_p && DECL_EXTERNAL (decl))
15270 error_at (DECL_SOURCE_LOCATION (decl),
15271 "declaration of %<constexpr%> variable %qD "
15272 "is not a definition", decl);
15273 constexpr_p = false;
15275 if (consteval_p)
15277 error_at (DECL_SOURCE_LOCATION (decl),
15278 "a variable cannot be declared %<consteval%>");
15279 consteval_p = false;
15282 if (inlinep)
15283 mark_inline_variable (decl, declspecs->locations[ds_inline]);
15284 if (innermost_code == cdk_decomp)
15286 gcc_assert (declarator && declarator->kind == cdk_decomp);
15287 DECL_SOURCE_LOCATION (decl) = id_loc;
15288 DECL_ARTIFICIAL (decl) = 1;
15289 fit_decomposition_lang_decl (decl, NULL_TREE);
15293 if (VAR_P (decl) && !initialized)
15294 if (tree auto_node = type_uses_auto (type))
15295 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
15297 location_t loc = declspecs->locations[ds_type_spec];
15298 error_at (loc, "declaration of %q#D has no initializer", decl);
15299 TREE_TYPE (decl) = error_mark_node;
15302 if (storage_class == sc_extern && initialized && !funcdef_flag)
15304 if (toplevel_bindings_p ())
15306 /* It's common practice (and completely valid) to have a const
15307 be initialized and declared extern. */
15308 if (!(type_quals & TYPE_QUAL_CONST))
15309 warning_at (DECL_SOURCE_LOCATION (decl), 0,
15310 "%qs initialized and declared %<extern%>", name);
15312 else
15314 error_at (DECL_SOURCE_LOCATION (decl),
15315 "%qs has both %<extern%> and initializer", name);
15316 return error_mark_node;
15320 /* Record `register' declaration for warnings on &
15321 and in case doing stupid register allocation. */
15323 if (storage_class == sc_register)
15325 DECL_REGISTER (decl) = 1;
15326 /* Warn about register storage specifiers on PARM_DECLs. */
15327 if (TREE_CODE (decl) == PARM_DECL)
15329 if (cxx_dialect >= cxx17)
15330 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15331 "ISO C++17 does not allow %<register%> storage "
15332 "class specifier");
15333 else
15334 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15335 "%<register%> storage class specifier used");
15338 else if (storage_class == sc_extern)
15339 DECL_THIS_EXTERN (decl) = 1;
15340 else if (storage_class == sc_static)
15341 DECL_THIS_STATIC (decl) = 1;
15343 if (VAR_P (decl))
15345 /* Set constexpr flag on vars (functions got it in grokfndecl). */
15346 if (constexpr_p)
15347 DECL_DECLARED_CONSTEXPR_P (decl) = true;
15348 /* And the constinit flag (which only applies to variables). */
15349 else if (constinit_p)
15350 DECL_DECLARED_CONSTINIT_P (decl) = true;
15352 else if (TREE_CODE (decl) == FUNCTION_DECL)
15354 /* If we saw a return type, record its location. */
15355 location_t loc = declspecs->locations[ds_type_spec];
15356 if (loc == UNKNOWN_LOCATION)
15357 /* Build DECL_RESULT in start_preparsed_function. */;
15358 else if (!DECL_RESULT (decl))
15360 tree restype = TREE_TYPE (TREE_TYPE (decl));
15361 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
15362 DECL_ARTIFICIAL (resdecl) = 1;
15363 DECL_IGNORED_P (resdecl) = 1;
15364 DECL_RESULT (decl) = resdecl;
15366 else if (funcdef_flag)
15367 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
15370 /* Record constancy and volatility on the DECL itself . There's
15371 no need to do this when processing a template; we'll do this
15372 for the instantiated declaration based on the type of DECL. */
15373 if (!processing_template_decl
15374 /* Don't do it for instantiated variable templates either,
15375 cp_apply_type_quals_to_decl should have been called on it
15376 already and might have been overridden in cp_finish_decl
15377 if initializer needs runtime initialization. */
15378 && (!VAR_P (decl) || !DECL_TEMPLATE_INSTANTIATED (decl)))
15379 cp_apply_type_quals_to_decl (type_quals, decl);
15381 return decl;
15385 /* Subroutine of start_function. Ensure that each of the parameter
15386 types (as listed in PARMS) is complete, as is required for a
15387 function definition. */
15389 static void
15390 require_complete_types_for_parms (tree parms)
15392 for (; parms; parms = DECL_CHAIN (parms))
15394 if (dependent_type_p (TREE_TYPE (parms)))
15395 continue;
15396 if (!VOID_TYPE_P (TREE_TYPE (parms))
15397 && complete_type_or_else (TREE_TYPE (parms), parms))
15399 relayout_decl (parms);
15400 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
15402 abstract_virtuals_error (parms, TREE_TYPE (parms));
15403 maybe_warn_parm_abi (TREE_TYPE (parms),
15404 DECL_SOURCE_LOCATION (parms));
15406 else
15407 /* grokparms or complete_type_or_else will have already issued
15408 an error. */
15409 TREE_TYPE (parms) = error_mark_node;
15413 /* Returns nonzero if T is a local variable. */
15416 local_variable_p (const_tree t)
15418 if ((VAR_P (t)
15419 && (DECL_LOCAL_DECL_P (t)
15420 || !DECL_CONTEXT (t)
15421 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
15422 || (TREE_CODE (t) == PARM_DECL))
15423 return 1;
15425 return 0;
15428 /* Like local_variable_p, but suitable for use as a tree-walking
15429 function. */
15431 static tree
15432 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
15433 void * /*data*/)
15435 if (unevaluated_p (TREE_CODE (*tp)))
15437 /* DR 2082 permits local variables in unevaluated contexts
15438 within a default argument. */
15439 *walk_subtrees = 0;
15440 return NULL_TREE;
15443 if (local_variable_p (*tp)
15444 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
15445 return *tp;
15446 else if (TYPE_P (*tp))
15447 *walk_subtrees = 0;
15449 return NULL_TREE;
15452 /* Check that ARG, which is a default-argument expression for a
15453 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
15454 something goes wrong. DECL may also be a _TYPE node, rather than a
15455 DECL, if there is no DECL available. */
15457 tree
15458 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
15460 tree var;
15461 tree decl_type;
15463 if (TREE_CODE (arg) == DEFERRED_PARSE)
15464 /* We get a DEFERRED_PARSE when looking at an in-class declaration
15465 with a default argument. Ignore the argument for now; we'll
15466 deal with it after the class is complete. */
15467 return arg;
15469 if (TYPE_P (decl))
15471 decl_type = decl;
15472 decl = NULL_TREE;
15474 else
15475 decl_type = TREE_TYPE (decl);
15477 if (arg == error_mark_node
15478 || decl == error_mark_node
15479 || TREE_TYPE (arg) == error_mark_node
15480 || decl_type == error_mark_node)
15481 /* Something already went wrong. There's no need to check
15482 further. */
15483 return error_mark_node;
15485 /* [dcl.fct.default]
15487 A default argument expression is implicitly converted to the
15488 parameter type. */
15489 ++cp_unevaluated_operand;
15490 /* Avoid digest_init clobbering the initializer. */
15491 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
15492 perform_implicit_conversion_flags (decl_type, carg, complain,
15493 LOOKUP_IMPLICIT);
15494 --cp_unevaluated_operand;
15496 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
15497 the call sites. */
15498 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
15499 && null_ptr_cst_p (arg)
15500 /* Don't lose side-effects as in PR90473. */
15501 && !TREE_SIDE_EFFECTS (arg))
15502 return nullptr_node;
15504 /* [dcl.fct.default]
15506 Local variables shall not be used in default argument
15507 expressions.
15509 The keyword `this' shall not be used in a default argument of a
15510 member function. */
15511 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
15512 if (var)
15514 if (complain & tf_warning_or_error)
15516 if (DECL_NAME (var) == this_identifier)
15517 permerror (input_location, "default argument %qE uses %qD",
15518 arg, var);
15519 else
15520 error ("default argument %qE uses local variable %qD", arg, var);
15522 return error_mark_node;
15525 /* All is well. */
15526 return arg;
15529 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
15531 static tree
15532 type_is_deprecated (tree type)
15534 enum tree_code code;
15535 if (TREE_DEPRECATED (type))
15536 return type;
15537 if (TYPE_NAME (type))
15539 if (TREE_DEPRECATED (TYPE_NAME (type)))
15540 return type;
15541 else
15543 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15544 return NULL_TREE;
15548 /* Do warn about using typedefs to a deprecated class. */
15549 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15550 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15552 code = TREE_CODE (type);
15554 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15555 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15556 || code == METHOD_TYPE || code == ARRAY_TYPE)
15557 return type_is_deprecated (TREE_TYPE (type));
15559 if (TYPE_PTRMEMFUNC_P (type))
15560 return type_is_deprecated
15561 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15563 return NULL_TREE;
15566 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
15568 static tree
15569 type_is_unavailable (tree type)
15571 enum tree_code code;
15572 if (TREE_UNAVAILABLE (type))
15573 return type;
15574 if (TYPE_NAME (type))
15576 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
15577 return type;
15578 else
15580 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15581 return NULL_TREE;
15585 /* Do warn about using typedefs to a deprecated class. */
15586 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15587 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15589 code = TREE_CODE (type);
15591 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15592 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15593 || code == METHOD_TYPE || code == ARRAY_TYPE)
15594 return type_is_unavailable (TREE_TYPE (type));
15596 if (TYPE_PTRMEMFUNC_P (type))
15597 return type_is_unavailable
15598 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15600 return NULL_TREE;
15603 /* Decode the list of parameter types for a function type.
15604 Given the list of things declared inside the parens,
15605 return a list of types.
15607 If this parameter does not end with an ellipsis, we append
15608 void_list_node.
15610 *PARMS is set to the chain of PARM_DECLs created. */
15612 tree
15613 grokparms (tree parmlist, tree *parms)
15615 tree result = NULL_TREE;
15616 tree decls = NULL_TREE;
15617 tree parm;
15618 int any_error = 0;
15620 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15622 tree type = NULL_TREE;
15623 tree init = TREE_PURPOSE (parm);
15624 tree decl = TREE_VALUE (parm);
15626 if (parm == void_list_node || parm == explicit_void_list_node)
15627 break;
15629 if (! decl || TREE_TYPE (decl) == error_mark_node)
15631 any_error = 1;
15632 continue;
15635 type = TREE_TYPE (decl);
15636 if (VOID_TYPE_P (type))
15638 if (same_type_p (type, void_type_node)
15639 && !init
15640 && !DECL_NAME (decl) && !result
15641 && TREE_CHAIN (parm) == void_list_node)
15642 /* DR 577: A parameter list consisting of a single
15643 unnamed parameter of non-dependent type 'void'. */
15644 break;
15645 else if (cv_qualified_p (type))
15646 error_at (DECL_SOURCE_LOCATION (decl),
15647 "invalid use of cv-qualified type %qT in "
15648 "parameter declaration", type);
15649 else
15650 error_at (DECL_SOURCE_LOCATION (decl),
15651 "invalid use of type %<void%> in parameter "
15652 "declaration");
15653 /* It's not a good idea to actually create parameters of
15654 type `void'; other parts of the compiler assume that a
15655 void type terminates the parameter list. */
15656 type = error_mark_node;
15657 TREE_TYPE (decl) = error_mark_node;
15660 if (type != error_mark_node)
15662 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15664 tree unavailtype = type_is_unavailable (type);
15665 if (unavailtype)
15666 cp_handle_deprecated_or_unavailable (unavailtype);
15668 if (deprecated_state != DEPRECATED_SUPPRESS
15669 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15671 tree deptype = type_is_deprecated (type);
15672 if (deptype)
15673 cp_handle_deprecated_or_unavailable (deptype);
15676 /* [dcl.fct] "A parameter with volatile-qualified type is
15677 deprecated." */
15678 if (CP_TYPE_VOLATILE_P (type))
15679 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15680 "%<volatile%>-qualified parameter is "
15681 "deprecated");
15683 /* Top-level qualifiers on the parameters are
15684 ignored for function types. */
15685 type = cp_build_qualified_type (type, 0);
15686 if (TREE_CODE (type) == METHOD_TYPE)
15688 error ("parameter %qD invalidly declared method type", decl);
15689 type = build_pointer_type (type);
15690 TREE_TYPE (decl) = type;
15692 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15694 /* Before C++17 DR 393:
15695 [dcl.fct]/6, parameter types cannot contain pointers
15696 (references) to arrays of unknown bound. */
15697 tree t = TREE_TYPE (type);
15698 int ptr = TYPE_PTR_P (type);
15700 while (1)
15702 if (TYPE_PTR_P (t))
15703 ptr = 1;
15704 else if (TREE_CODE (t) != ARRAY_TYPE)
15705 break;
15706 else if (!TYPE_DOMAIN (t))
15707 break;
15708 t = TREE_TYPE (t);
15710 if (TREE_CODE (t) == ARRAY_TYPE)
15711 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15713 ? G_("parameter %qD includes pointer to array of "
15714 "unknown bound %qT")
15715 : G_("parameter %qD includes reference to array of "
15716 "unknown bound %qT"),
15717 decl, t);
15720 if (init && !processing_template_decl)
15721 init = check_default_argument (decl, init, tf_warning_or_error);
15724 DECL_CHAIN (decl) = decls;
15725 decls = decl;
15726 result = tree_cons (init, type, result);
15728 decls = nreverse (decls);
15729 result = nreverse (result);
15730 if (parm)
15731 result = chainon (result, void_list_node);
15732 *parms = decls;
15733 if (any_error)
15734 result = NULL_TREE;
15736 if (any_error)
15737 /* We had parm errors, recover by giving the function (...) type. */
15738 result = NULL_TREE;
15740 return result;
15744 /* D is a constructor or overloaded `operator='.
15746 Let T be the class in which D is declared. Then, this function
15747 returns:
15749 -1 if D's is an ill-formed constructor or copy assignment operator
15750 whose first parameter is of type `T'.
15751 0 if D is not a copy constructor or copy assignment
15752 operator.
15753 1 if D is a copy constructor or copy assignment operator whose
15754 first parameter is a reference to non-const qualified T.
15755 2 if D is a copy constructor or copy assignment operator whose
15756 first parameter is a reference to const qualified T.
15758 This function can be used as a predicate. Positive values indicate
15759 a copy constructor and nonzero values indicate a copy assignment
15760 operator. */
15763 copy_fn_p (const_tree d)
15765 tree args;
15766 tree arg_type;
15767 int result = 1;
15769 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15771 if (TREE_CODE (d) == TEMPLATE_DECL
15772 || (DECL_TEMPLATE_INFO (d)
15773 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15774 /* Instantiations of template member functions are never copy
15775 functions. Note that member functions of templated classes are
15776 represented as template functions internally, and we must
15777 accept those as copy functions. */
15778 return 0;
15780 if (!DECL_CONSTRUCTOR_P (d)
15781 && DECL_NAME (d) != assign_op_identifier)
15782 return 0;
15784 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15786 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15787 if (!TYPE_REF_P (object_param)
15788 || TYPE_REF_IS_RVALUE (object_param)
15789 /* Reject unrelated object parameters. */
15790 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15791 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15792 return 0;
15793 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15795 else
15796 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15797 if (!args)
15798 return 0;
15800 arg_type = TREE_VALUE (args);
15801 if (arg_type == error_mark_node)
15802 return 0;
15804 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15806 /* Pass by value copy assignment operator. */
15807 result = -1;
15809 else if (TYPE_REF_P (arg_type)
15810 && !TYPE_REF_IS_RVALUE (arg_type)
15811 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15813 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15814 result = 2;
15816 else
15817 return 0;
15819 args = TREE_CHAIN (args);
15821 if (args && args != void_list_node && !TREE_PURPOSE (args))
15822 /* There are more non-optional args. */
15823 return 0;
15825 return result;
15828 /* D is a constructor or overloaded `operator='.
15830 Let T be the class in which D is declared. Then, this function
15831 returns true when D is a move constructor or move assignment
15832 operator, false otherwise. */
15834 bool
15835 move_fn_p (const_tree d)
15837 if (cxx_dialect == cxx98)
15838 /* There are no move constructors if we are in C++98 mode. */
15839 return false;
15841 if (TREE_CODE (d) == TEMPLATE_DECL
15842 || (DECL_TEMPLATE_INFO (d)
15843 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15844 /* Instantiations of template member functions are never move
15845 functions. Note that member functions of templated classes are
15846 represented as template functions internally, and we must
15847 accept those as move functions. */
15848 return 0;
15850 return move_signature_fn_p (d);
15853 /* D is a constructor or overloaded `operator='.
15855 Then, this function returns true when D has the same signature as a move
15856 constructor or move assignment operator (because either it is such a
15857 ctor/op= or it is a template specialization with the same signature),
15858 false otherwise. */
15860 bool
15861 move_signature_fn_p (const_tree d)
15863 tree args;
15864 tree arg_type;
15865 bool result = false;
15867 if (!DECL_CONSTRUCTOR_P (d)
15868 && DECL_NAME (d) != assign_op_identifier)
15869 return 0;
15871 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15873 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15874 if (!TYPE_REF_P (object_param)
15875 || TYPE_REF_IS_RVALUE (object_param)
15876 /* Reject unrelated object parameters. */
15877 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15878 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15879 return 0;
15880 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15882 else
15883 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15884 if (!args)
15885 return 0;
15887 arg_type = TREE_VALUE (args);
15888 if (arg_type == error_mark_node)
15889 return 0;
15891 if (TYPE_REF_P (arg_type)
15892 && TYPE_REF_IS_RVALUE (arg_type)
15893 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15894 DECL_CONTEXT (d)))
15895 result = true;
15897 args = TREE_CHAIN (args);
15899 if (args && args != void_list_node && !TREE_PURPOSE (args))
15900 /* There are more non-optional args. */
15901 return false;
15903 return result;
15906 /* Remember any special properties of member function DECL. */
15908 void
15909 grok_special_member_properties (tree decl)
15911 tree class_type;
15913 if (TREE_CODE (decl) == USING_DECL
15914 || !DECL_OBJECT_MEMBER_FUNCTION_P (decl))
15915 return;
15917 class_type = DECL_CONTEXT (decl);
15918 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15920 int ctor = copy_fn_p (decl);
15922 if (!DECL_ARTIFICIAL (decl))
15923 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15925 if (ctor > 0)
15927 /* [class.copy]
15929 A non-template constructor for class X is a copy
15930 constructor if its first parameter is of type X&, const
15931 X&, volatile X& or const volatile X&, and either there
15932 are no other parameters or else all other parameters have
15933 default arguments. */
15934 TYPE_HAS_COPY_CTOR (class_type) = 1;
15935 if (ctor > 1)
15936 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15939 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15940 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15942 if (is_list_ctor (decl))
15943 TYPE_HAS_LIST_CTOR (class_type) = 1;
15945 if (maybe_constexpr_fn (decl)
15946 && !ctor && !move_fn_p (decl))
15947 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15949 else if (DECL_NAME (decl) == assign_op_identifier)
15951 /* [class.copy]
15953 A non-template assignment operator for class X is a copy
15954 assignment operator if its parameter is of type X, X&, const
15955 X&, volatile X& or const volatile X&. */
15957 int assop = copy_fn_p (decl);
15959 if (assop)
15961 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15962 if (assop != 1)
15963 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15966 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15967 TYPE_HAS_CONVERSION (class_type) = true;
15969 /* Destructors are handled in check_methods. */
15972 /* Check a constructor DECL has the correct form. Complains
15973 if the class has a constructor of the form X(X). */
15975 bool
15976 grok_ctor_properties (const_tree ctype, const_tree decl)
15978 int ctor_parm = copy_fn_p (decl);
15980 if (ctor_parm < 0)
15982 /* [class.copy]
15984 A declaration of a constructor for a class X is ill-formed if
15985 its first parameter is of type (optionally cv-qualified) X
15986 and either there are no other parameters or else all other
15987 parameters have default arguments.
15989 We *don't* complain about member template instantiations that
15990 have this form, though; they can occur as we try to decide
15991 what constructor to use during overload resolution. Since
15992 overload resolution will never prefer such a constructor to
15993 the non-template copy constructor (which is either explicitly
15994 or implicitly defined), there's no need to worry about their
15995 existence. Theoretically, they should never even be
15996 instantiated, but that's hard to forestall. */
15997 error_at (DECL_SOURCE_LOCATION (decl),
15998 "invalid constructor; you probably meant %<%T (const %T&)%>",
15999 ctype, ctype);
16000 return false;
16003 return true;
16006 /* DECL is a declaration for an overloaded or conversion operator. If
16007 COMPLAIN is true, errors are issued for invalid declarations. */
16009 bool
16010 grok_op_properties (tree decl, bool complain)
16012 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
16013 bool const methodp = DECL_IOBJ_MEMBER_FUNCTION_P (decl);
16014 tree name = DECL_NAME (decl);
16015 location_t loc = DECL_SOURCE_LOCATION (decl);
16017 tree class_type = DECL_CONTEXT (decl);
16018 if (class_type && !CLASS_TYPE_P (class_type))
16019 class_type = NULL_TREE;
16021 tree_code operator_code;
16022 unsigned op_flags;
16023 if (IDENTIFIER_CONV_OP_P (name))
16025 /* Conversion operators are TYPE_EXPR for the purposes of this
16026 function. */
16027 operator_code = TYPE_EXPR;
16028 op_flags = OVL_OP_FLAG_UNARY;
16030 else
16032 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
16034 operator_code = ovl_op->tree_code;
16035 op_flags = ovl_op->flags;
16036 gcc_checking_assert (operator_code != ERROR_MARK);
16037 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
16040 if (op_flags & OVL_OP_FLAG_ALLOC)
16042 /* operator new and operator delete are quite special. */
16043 if (class_type)
16044 switch (op_flags)
16046 case OVL_OP_FLAG_ALLOC:
16047 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
16048 break;
16050 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
16051 TYPE_GETS_DELETE (class_type) |= 1;
16052 break;
16054 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
16055 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
16056 break;
16058 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
16059 TYPE_GETS_DELETE (class_type) |= 2;
16060 break;
16062 default:
16063 gcc_unreachable ();
16066 /* [basic.std.dynamic.allocation]/1:
16068 A program is ill-formed if an allocation function is declared
16069 in a namespace scope other than global scope or declared
16070 static in global scope.
16072 The same also holds true for deallocation functions. */
16073 if (DECL_NAMESPACE_SCOPE_P (decl))
16075 if (CP_DECL_CONTEXT (decl) != global_namespace)
16077 error_at (loc, "%qD may not be declared within a namespace",
16078 decl);
16079 return false;
16082 if (!TREE_PUBLIC (decl))
16084 error_at (loc, "%qD may not be declared as static", decl);
16085 return false;
16089 if (op_flags & OVL_OP_FLAG_DELETE)
16091 DECL_SET_IS_OPERATOR_DELETE (decl, true);
16092 coerce_delete_type (decl, loc);
16094 else
16096 DECL_SET_IS_OPERATOR_NEW (decl, true);
16097 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
16100 return true;
16103 /* An operator function must either be a non-static member function
16104 or have at least one parameter of a class, a reference to a class,
16105 an enumeration, or a reference to an enumeration. 13.4.0.6 */
16106 if (!DECL_OBJECT_MEMBER_FUNCTION_P (decl))
16108 if (operator_code == TYPE_EXPR
16109 || operator_code == COMPONENT_REF
16110 || operator_code == NOP_EXPR)
16112 error_at (loc, "%qD must be a non-static member function", decl);
16113 return false;
16116 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
16118 if (! DECL_STATIC_FUNCTION_P (decl))
16120 error_at (loc, "%qD must be a member function", decl);
16121 return false;
16123 if (cxx_dialect < cxx23
16124 /* For lambdas we diagnose static lambda specifier elsewhere. */
16125 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
16126 /* For instantiations, we have diagnosed this already. */
16127 && ! DECL_USE_TEMPLATE (decl))
16128 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
16129 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
16130 decl);
16131 if (operator_code == ARRAY_REF)
16132 /* static operator[] should have exactly one argument
16133 for C++20 and earlier, so that it isn't multidimensional. */
16134 op_flags = OVL_OP_FLAG_UNARY;
16136 else if (DECL_STATIC_FUNCTION_P (decl))
16138 error_at (loc, "%qD must be either a non-static member "
16139 "function or a non-member function", decl);
16140 return false;
16142 else
16143 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
16145 if (!arg || arg == void_list_node)
16147 if (complain)
16148 error_at (loc, "%qD must have an argument of class or "
16149 "enumerated type", decl);
16150 return false;
16153 tree type = non_reference (TREE_VALUE (arg));
16154 if (type == error_mark_node)
16155 return false;
16157 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
16158 because these checks are performed even on template
16159 functions. */
16160 if (MAYBE_CLASS_TYPE_P (type)
16161 || TREE_CODE (type) == ENUMERAL_TYPE)
16162 break;
16166 if (operator_code == CALL_EXPR)
16167 /* There are no further restrictions on the arguments to an overloaded
16168 "operator ()". */
16169 return true;
16171 /* C++23 allows an arbitrary number of parameters and default arguments for
16172 operator[], and none of the other checks below apply. */
16173 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
16174 return true;
16176 if (operator_code == COND_EXPR)
16178 /* 13.4.0.3 */
16179 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
16180 return false;
16183 /* Count the number of arguments and check for ellipsis. */
16184 int arity = 0;
16185 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
16187 if (!arg)
16189 error_at (loc, "%qD must not have variable number of arguments",
16190 decl);
16191 return false;
16193 ++arity;
16195 /* FIXME: We need tests for these errors with xobj member functions. */
16196 /* Verify correct number of arguments. */
16197 switch (op_flags)
16199 case OVL_OP_FLAG_AMBIARY:
16200 if (arity == 1)
16202 /* We have a unary instance of an ambi-ary op. Remap to the
16203 unary one. */
16204 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
16205 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
16206 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
16207 operator_code = ovl_op->tree_code;
16208 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
16210 else if (arity != 2)
16212 /* This was an ambiguous operator but is invalid. */
16213 error_at (loc,
16214 methodp
16215 ? G_("%qD must have either zero or one argument")
16216 : G_("%qD must have either one or two arguments"), decl);
16217 return false;
16219 else if ((operator_code == POSTINCREMENT_EXPR
16220 || operator_code == POSTDECREMENT_EXPR)
16221 && ! processing_template_decl
16222 /* x++ and x--'s second argument must be an int. */
16223 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
16224 integer_type_node))
16226 error_at (loc,
16227 methodp
16228 ? G_("postfix %qD must have %<int%> as its argument")
16229 : G_("postfix %qD must have %<int%> as its second argument"),
16230 decl);
16231 return false;
16233 break;
16235 case OVL_OP_FLAG_UNARY:
16236 if (arity != 1)
16238 error_at (loc,
16239 methodp
16240 ? G_("%qD must have no arguments")
16241 : G_("%qD must have exactly one argument"), decl);
16242 return false;
16244 break;
16246 case OVL_OP_FLAG_BINARY:
16247 if (arity != 2)
16249 error_at (loc,
16250 methodp
16251 ? G_("%qD must have exactly one argument")
16252 : G_("%qD must have exactly two arguments"), decl);
16253 return false;
16255 break;
16257 default:
16258 gcc_unreachable ();
16261 /* There can be no default arguments. */
16262 for (tree arg = argtypes; arg && arg != void_list_node;
16263 arg = TREE_CHAIN (arg))
16264 if (TREE_PURPOSE (arg))
16266 TREE_PURPOSE (arg) = NULL_TREE;
16267 error_at (loc, "%qD cannot have default arguments", decl);
16268 return false;
16271 /* At this point the declaration is well-formed. It may not be
16272 sensible though. */
16274 /* Check member function warnings only on the in-class declaration.
16275 There's no point warning on an out-of-class definition. */
16276 if (class_type && class_type != current_class_type)
16277 return true;
16279 /* Warn about conversion operators that will never be used. */
16280 if (IDENTIFIER_CONV_OP_P (name)
16281 && ! DECL_TEMPLATE_INFO (decl)
16282 && warn_class_conversion)
16284 tree t = TREE_TYPE (name);
16285 int ref = TYPE_REF_P (t);
16287 if (ref)
16288 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
16290 if (VOID_TYPE_P (t))
16291 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
16292 "will never use a type conversion operator", class_type);
16293 else if (class_type)
16295 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
16296 warning_at (loc, OPT_Wclass_conversion,
16298 ? G_("converting %qT to a reference to the same type "
16299 "will never use a type conversion operator")
16300 : G_("converting %qT to the same type "
16301 "will never use a type conversion operator"),
16302 class_type);
16303 /* Don't force t to be complete here. */
16304 else if (MAYBE_CLASS_TYPE_P (t)
16305 && COMPLETE_TYPE_P (t)
16306 && DERIVED_FROM_P (t, class_type))
16307 warning_at (loc, OPT_Wclass_conversion,
16309 ? G_("converting %qT to a reference to a base class "
16310 "%qT will never use a type conversion operator")
16311 : G_("converting %qT to a base class %qT "
16312 "will never use a type conversion operator"),
16313 class_type, t);
16317 if (!warn_ecpp)
16318 return true;
16320 /* Effective C++ rules below. */
16322 /* More Effective C++ rule 7. */
16323 if (operator_code == TRUTH_ANDIF_EXPR
16324 || operator_code == TRUTH_ORIF_EXPR
16325 || operator_code == COMPOUND_EXPR)
16326 warning_at (loc, OPT_Weffc__,
16327 "user-defined %qD always evaluates both arguments", decl);
16329 /* More Effective C++ rule 6. */
16330 if (operator_code == POSTINCREMENT_EXPR
16331 || operator_code == POSTDECREMENT_EXPR
16332 || operator_code == PREINCREMENT_EXPR
16333 || operator_code == PREDECREMENT_EXPR)
16335 tree arg = TREE_VALUE (argtypes);
16336 tree ret = TREE_TYPE (TREE_TYPE (decl));
16337 if (methodp || TYPE_REF_P (arg))
16338 arg = TREE_TYPE (arg);
16339 arg = TYPE_MAIN_VARIANT (arg);
16341 if (operator_code == PREINCREMENT_EXPR
16342 || operator_code == PREDECREMENT_EXPR)
16344 if (!TYPE_REF_P (ret)
16345 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
16346 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
16347 build_reference_type (arg));
16349 else
16351 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
16352 warning_at (loc, OPT_Weffc__,
16353 "postfix %qD should return %qT", decl, arg);
16357 /* Effective C++ rule 23. */
16358 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
16359 && (operator_code == PLUS_EXPR
16360 || operator_code == MINUS_EXPR
16361 || operator_code == TRUNC_DIV_EXPR
16362 || operator_code == MULT_EXPR
16363 || operator_code == TRUNC_MOD_EXPR)
16364 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
16365 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
16367 return true;
16370 /* Return a string giving the keyword associate with CODE. */
16372 static const char *
16373 tag_name (enum tag_types code)
16375 switch (code)
16377 case record_type:
16378 return "struct";
16379 case class_type:
16380 return "class";
16381 case union_type:
16382 return "union";
16383 case enum_type:
16384 return "enum";
16385 case typename_type:
16386 return "typename";
16387 default:
16388 gcc_unreachable ();
16392 /* Name lookup in an elaborated-type-specifier (after the keyword
16393 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
16394 elaborated-type-specifier is invalid, issue a diagnostic and return
16395 error_mark_node; otherwise, return the *_TYPE to which it referred.
16396 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
16398 tree
16399 check_elaborated_type_specifier (enum tag_types tag_code,
16400 tree decl,
16401 bool allow_template_p)
16403 tree type;
16405 /* In the case of:
16407 struct S { struct S *p; };
16409 name lookup will find the TYPE_DECL for the implicit "S::S"
16410 typedef. Adjust for that here. */
16411 if (DECL_SELF_REFERENCE_P (decl))
16412 decl = TYPE_NAME (TREE_TYPE (decl));
16414 type = TREE_TYPE (decl);
16416 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
16417 is false for this case as well. */
16418 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16420 error ("using template type parameter %qT after %qs",
16421 type, tag_name (tag_code));
16422 return error_mark_node;
16424 /* Accept template template parameters. */
16425 else if (allow_template_p
16426 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
16427 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
16429 /* [dcl.type.elab]
16431 If the identifier resolves to a typedef-name or the
16432 simple-template-id resolves to an alias template
16433 specialization, the elaborated-type-specifier is ill-formed.
16435 In other words, the only legitimate declaration to use in the
16436 elaborated type specifier is the implicit typedef created when
16437 the type is declared. */
16438 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
16439 && !DECL_SELF_REFERENCE_P (decl)
16440 && tag_code != typename_type)
16442 if (alias_template_specialization_p (type, nt_opaque))
16443 error ("using alias template specialization %qT after %qs",
16444 type, tag_name (tag_code));
16445 else
16446 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
16447 inform (DECL_SOURCE_LOCATION (decl),
16448 "%qD has a previous declaration here", decl);
16449 return error_mark_node;
16451 else if (TREE_CODE (type) != RECORD_TYPE
16452 && TREE_CODE (type) != UNION_TYPE
16453 && tag_code != enum_type
16454 && tag_code != typename_type)
16456 error ("%qT referred to as %qs", type, tag_name (tag_code));
16457 inform (location_of (type), "%qT has a previous declaration here", type);
16458 return error_mark_node;
16460 else if (TREE_CODE (type) != ENUMERAL_TYPE
16461 && tag_code == enum_type)
16463 error ("%qT referred to as enum", type);
16464 inform (location_of (type), "%qT has a previous declaration here", type);
16465 return error_mark_node;
16467 else if (!allow_template_p
16468 && TREE_CODE (type) == RECORD_TYPE
16469 && CLASSTYPE_IS_TEMPLATE (type))
16471 /* If a class template appears as elaborated type specifier
16472 without a template header such as:
16474 template <class T> class C {};
16475 void f(class C); // No template header here
16477 then the required template argument is missing. */
16478 error ("template argument required for %<%s %T%>",
16479 tag_name (tag_code),
16480 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
16481 return error_mark_node;
16484 return type;
16487 /* Lookup NAME of an elaborated type specifier according to SCOPE and
16488 issue diagnostics if necessary. Return *_TYPE node upon success,
16489 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
16490 error. */
16492 static tree
16493 lookup_and_check_tag (enum tag_types tag_code, tree name,
16494 TAG_how how, bool template_header_p)
16496 tree decl;
16497 if (how == TAG_how::GLOBAL)
16499 /* First try ordinary name lookup, ignoring hidden class name
16500 injected via friend declaration. */
16501 decl = lookup_name (name, LOOK_want::TYPE);
16502 /* If that fails, the name will be placed in the smallest
16503 non-class, non-function-prototype scope according to 3.3.1/5.
16504 We may already have a hidden name declared as friend in this
16505 scope. So lookup again but not ignoring hidden names.
16506 If we find one, that name will be made visible rather than
16507 creating a new tag. */
16508 if (!decl)
16509 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
16511 else
16512 decl = lookup_elaborated_type (name, how);
16514 if (!decl)
16515 /* We found nothing. */
16516 return NULL_TREE;
16518 if (TREE_CODE (decl) == TREE_LIST)
16520 error ("reference to %qD is ambiguous", name);
16521 print_candidates (decl);
16522 return error_mark_node;
16525 if (DECL_CLASS_TEMPLATE_P (decl)
16526 && !template_header_p
16527 && how == TAG_how::CURRENT_ONLY)
16529 error ("class template %qD redeclared as non-template", name);
16530 inform (location_of (decl), "previous declaration here");
16531 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
16532 return error_mark_node;
16535 if (DECL_CLASS_TEMPLATE_P (decl)
16536 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
16537 so ignore a template template parameter. */
16538 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
16539 decl = DECL_TEMPLATE_RESULT (decl);
16541 if (TREE_CODE (decl) != TYPE_DECL)
16542 /* Found not-a-type. */
16543 return NULL_TREE;
16545 /* Look for invalid nested type:
16546 class C {
16547 class C {};
16548 }; */
16549 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
16551 error ("%qD has the same name as the class in which it is "
16552 "declared", decl);
16553 return error_mark_node;
16556 /* Two cases we need to consider when deciding if a class
16557 template is allowed as an elaborated type specifier:
16558 1. It is a self reference to its own class.
16559 2. It comes with a template header.
16561 For example:
16563 template <class T> class C {
16564 class C *c1; // DECL_SELF_REFERENCE_P is true
16565 class D;
16567 template <class U> class C; // template_header_p is true
16568 template <class T> class C<T>::D {
16569 class C *c2; // DECL_SELF_REFERENCE_P is true
16570 }; */
16572 tree t = check_elaborated_type_specifier (tag_code, decl,
16573 template_header_p
16574 | DECL_SELF_REFERENCE_P (decl));
16575 if (template_header_p && t && CLASS_TYPE_P (t)
16576 && (!CLASSTYPE_TEMPLATE_INFO (t)
16577 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
16579 error ("%qT is not a template", t);
16580 inform (location_of (t), "previous declaration here");
16581 if (TYPE_CLASS_SCOPE_P (t)
16582 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
16583 inform (input_location,
16584 "perhaps you want to explicitly add %<%T::%>",
16585 TYPE_CONTEXT (t));
16586 return error_mark_node;
16589 return t;
16592 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
16593 Define the tag as a forward-reference if it is not defined.
16595 If a declaration is given, process it here, and report an error if
16596 multiple declarations are not identical.
16598 SCOPE is TS_CURRENT when this is also a definition. Only look in
16599 the current frame for the name (since C++ allows new names in any
16600 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
16601 declaration. Only look beginning from the current scope outward up
16602 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
16604 TEMPLATE_HEADER_P is true when this declaration is preceded by
16605 a set of template parameters. */
16607 tree
16608 xref_tag (enum tag_types tag_code, tree name,
16609 TAG_how how, bool template_header_p)
16611 enum tree_code code;
16612 tree context = NULL_TREE;
16614 auto_cond_timevar tv (TV_NAME_LOOKUP);
16616 gcc_assert (identifier_p (name));
16618 switch (tag_code)
16620 case record_type:
16621 case class_type:
16622 code = RECORD_TYPE;
16623 break;
16624 case union_type:
16625 code = UNION_TYPE;
16626 break;
16627 case enum_type:
16628 code = ENUMERAL_TYPE;
16629 break;
16630 default:
16631 gcc_unreachable ();
16634 /* In case of anonymous name, xref_tag is only called to
16635 make type node and push name. Name lookup is not required. */
16636 tree t = NULL_TREE;
16637 if (!IDENTIFIER_ANON_P (name))
16638 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16640 if (t == error_mark_node)
16641 return error_mark_node;
16643 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16644 && template_class_depth (current_class_type)
16645 && template_header_p)
16647 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16648 return t;
16650 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16651 a definition of this tag. Since, in addition, we are
16652 currently processing a (member) template declaration of a
16653 template class, we must be very careful; consider:
16655 template <class X> struct S1
16657 template <class U> struct S2
16659 template <class V> friend struct S1;
16662 Here, the S2::S1 declaration should not be confused with the
16663 outer declaration. In particular, the inner version should
16664 have a template parameter of level 2, not level 1.
16666 On the other hand, when presented with:
16668 template <class T> struct S1
16670 template <class U> struct S2 {};
16671 template <class U> friend struct S2;
16674 the friend must find S1::S2 eventually. We accomplish this
16675 by making sure that the new type we create to represent this
16676 declaration has the right TYPE_CONTEXT. */
16677 context = TYPE_CONTEXT (t);
16678 t = NULL_TREE;
16681 if (! t)
16683 /* If no such tag is yet defined, create a forward-reference node
16684 and record it as the "definition".
16685 When a real declaration of this type is found,
16686 the forward-reference will be altered into a real type. */
16687 if (code == ENUMERAL_TYPE)
16689 error ("use of enum %q#D without previous declaration", name);
16690 return error_mark_node;
16693 t = make_class_type (code);
16694 TYPE_CONTEXT (t) = context;
16695 if (IDENTIFIER_LAMBDA_P (name))
16696 /* Mark it as a lambda type right now. Our caller will
16697 correct the value. */
16698 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16699 t = pushtag (name, t, how);
16701 else
16703 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16705 /* Check that we aren't trying to overload a class with different
16706 constraints. */
16707 if (!redeclare_class_template (t, current_template_parms,
16708 current_template_constraints ()))
16709 return error_mark_node;
16711 else if (!processing_template_decl
16712 && CLASS_TYPE_P (t)
16713 && CLASSTYPE_IS_TEMPLATE (t))
16715 error ("redeclaration of %qT as a non-template", t);
16716 inform (location_of (t), "previous declaration %qD", t);
16717 return error_mark_node;
16720 if (modules_p ()
16721 && how == TAG_how::CURRENT_ONLY)
16723 tree decl = TYPE_NAME (t);
16724 if (!module_may_redeclare (decl))
16725 return error_mark_node;
16727 tree not_tmpl = STRIP_TEMPLATE (decl);
16728 if (DECL_LANG_SPECIFIC (not_tmpl)
16729 && DECL_MODULE_ATTACH_P (not_tmpl)
16730 && !DECL_MODULE_EXPORT_P (not_tmpl)
16731 && module_exporting_p ())
16733 auto_diagnostic_group d;
16734 error ("conflicting exporting for declaration %qD", decl);
16735 inform (DECL_SOURCE_LOCATION (decl),
16736 "previously declared here without exporting");
16739 tree maybe_tmpl = decl;
16740 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16741 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16743 /* FIXME: we should do a more precise check for redefinitions
16744 of a conflicting using-declaration here, as these diagnostics
16745 are not ideal. */
16746 if (DECL_LANG_SPECIFIC (decl)
16747 && DECL_MODULE_IMPORT_P (decl)
16748 && CP_DECL_CONTEXT (decl) == current_namespace)
16750 /* Push it into this TU's symbol slot. */
16751 if (maybe_tmpl != decl)
16752 /* We're in the template parm binding level.
16753 Pushtag has logic to slide under that, but we're
16754 not pushing a *new* type. */
16755 push_nested_namespace (CP_DECL_CONTEXT (decl));
16757 pushdecl (maybe_tmpl);
16758 if (maybe_tmpl != decl)
16759 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16762 set_instantiating_module (maybe_tmpl);
16766 return t;
16769 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16770 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16771 access_* node, and the TREE_VALUE is the type of the base-class.
16772 Non-NULL TREE_TYPE indicates virtual inheritance. */
16774 void
16775 xref_basetypes (tree ref, tree base_list)
16777 tree *basep;
16778 tree binfo, base_binfo;
16779 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16780 unsigned max_bases = 0; /* Maximum direct bases. */
16781 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16782 int i;
16783 tree default_access;
16784 tree igo_prev; /* Track Inheritance Graph Order. */
16786 if (ref == error_mark_node)
16787 return;
16789 /* The base of a derived class is private by default, all others are
16790 public. */
16791 default_access = (TREE_CODE (ref) == RECORD_TYPE
16792 && CLASSTYPE_DECLARED_CLASS (ref)
16793 ? access_private_node : access_public_node);
16795 /* First, make sure that any templates in base-classes are
16796 instantiated. This ensures that if we call ourselves recursively
16797 we do not get confused about which classes are marked and which
16798 are not. */
16799 basep = &base_list;
16800 while (*basep)
16802 tree basetype = TREE_VALUE (*basep);
16804 /* The dependent_type_p call below should really be dependent_scope_p
16805 so that we give a hard error about using an incomplete type as a
16806 base, but we allow it with a pedwarn for backward
16807 compatibility. */
16808 if (processing_template_decl
16809 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16810 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16811 if (!dependent_type_p (basetype)
16812 && !complete_type_or_else (basetype, NULL))
16813 /* An incomplete type. Remove it from the list. */
16814 *basep = TREE_CHAIN (*basep);
16815 else
16817 max_bases++;
16818 if (TREE_TYPE (*basep))
16819 max_dvbases++;
16820 if (CLASS_TYPE_P (basetype))
16821 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16822 basep = &TREE_CHAIN (*basep);
16825 max_vbases += max_dvbases;
16827 TYPE_MARKED_P (ref) = 1;
16829 /* The binfo slot should be empty, unless this is an (ill-formed)
16830 redefinition. */
16831 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16833 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16835 binfo = make_tree_binfo (max_bases);
16837 TYPE_BINFO (ref) = binfo;
16838 BINFO_OFFSET (binfo) = size_zero_node;
16839 BINFO_TYPE (binfo) = ref;
16841 /* Apply base-class info set up to the variants of this type. */
16842 fixup_type_variants (ref);
16844 if (max_bases)
16846 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16847 /* A C++98 POD cannot have base classes. */
16848 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16850 if (TREE_CODE (ref) == UNION_TYPE)
16852 error ("derived union %qT invalid", ref);
16853 return;
16857 if (max_bases > 1)
16858 warning (OPT_Wmultiple_inheritance,
16859 "%qT defined with multiple direct bases", ref);
16861 if (max_vbases)
16863 /* An aggregate can't have virtual base classes. */
16864 CLASSTYPE_NON_AGGREGATE (ref) = true;
16866 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16868 if (max_dvbases)
16869 warning (OPT_Wvirtual_inheritance,
16870 "%qT defined with direct virtual base", ref);
16873 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16875 tree access = TREE_PURPOSE (base_list);
16876 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16877 tree basetype = TREE_VALUE (base_list);
16879 if (access == access_default_node)
16880 access = default_access;
16882 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16883 aggregate can't have virtual, private, or protected base classes. */
16884 if (cxx_dialect < cxx17
16885 || access != access_public_node
16886 || via_virtual)
16887 CLASSTYPE_NON_AGGREGATE (ref) = true;
16889 if (PACK_EXPANSION_P (basetype))
16890 basetype = PACK_EXPANSION_PATTERN (basetype);
16891 if (TREE_CODE (basetype) == TYPE_DECL)
16892 basetype = TREE_TYPE (basetype);
16893 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16895 error ("base type %qT fails to be a struct or class type",
16896 basetype);
16897 goto dropped_base;
16900 base_binfo = NULL_TREE;
16901 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16903 base_binfo = TYPE_BINFO (basetype);
16904 /* The original basetype could have been a typedef'd type. */
16905 basetype = BINFO_TYPE (base_binfo);
16907 /* Inherit flags from the base. */
16908 TYPE_HAS_NEW_OPERATOR (ref)
16909 |= TYPE_HAS_NEW_OPERATOR (basetype);
16910 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16911 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16912 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16913 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16914 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16915 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16916 CLASSTYPE_REPEATED_BASE_P (ref)
16917 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16920 /* We must do this test after we've seen through a typedef
16921 type. */
16922 if (TYPE_MARKED_P (basetype))
16924 if (basetype == ref)
16925 error ("recursive type %qT undefined", basetype);
16926 else
16927 error ("duplicate base type %qT invalid", basetype);
16928 goto dropped_base;
16931 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16932 /* Regenerate the pack expansion for the bases. */
16933 basetype = make_pack_expansion (basetype);
16935 TYPE_MARKED_P (basetype) = 1;
16937 base_binfo = copy_binfo (base_binfo, basetype, ref,
16938 &igo_prev, via_virtual);
16939 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16940 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16942 BINFO_BASE_APPEND (binfo, base_binfo);
16943 BINFO_BASE_ACCESS_APPEND (binfo, access);
16944 continue;
16946 dropped_base:
16947 /* Update max_vbases to reflect the reality that we are dropping
16948 this base: if it reaches zero we want to undo the vec_alloc
16949 above to avoid inconsistencies during error-recovery: eg, in
16950 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16951 and vtt null (c++/27952). */
16952 if (via_virtual)
16953 max_vbases--;
16954 if (CLASS_TYPE_P (basetype))
16955 max_vbases
16956 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16959 if (CLASSTYPE_VBASECLASSES (ref)
16960 && max_vbases == 0)
16961 vec_free (CLASSTYPE_VBASECLASSES (ref));
16963 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16964 /* If we didn't get max_vbases vbases, we must have shared at
16965 least one of them, and are therefore diamond shaped. */
16966 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16968 /* Unmark all the types. */
16969 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16970 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16971 TYPE_MARKED_P (ref) = 0;
16973 /* Now see if we have a repeated base type. */
16974 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16976 for (base_binfo = binfo; base_binfo;
16977 base_binfo = TREE_CHAIN (base_binfo))
16979 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16981 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16982 break;
16984 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16986 for (base_binfo = binfo; base_binfo;
16987 base_binfo = TREE_CHAIN (base_binfo))
16988 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16989 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16990 else
16991 break;
16996 /* Copies the enum-related properties from type SRC to type DST.
16997 Used with the underlying type of an enum and the enum itself. */
16998 static void
16999 copy_type_enum (tree dst, tree src)
17001 tree t;
17002 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
17004 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
17005 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
17006 TYPE_SIZE (t) = TYPE_SIZE (src);
17007 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
17008 SET_TYPE_MODE (dst, TYPE_MODE (src));
17009 TYPE_PRECISION (t) = TYPE_PRECISION (src);
17010 unsigned valign = TYPE_ALIGN (src);
17011 if (TYPE_USER_ALIGN (t))
17012 valign = MAX (valign, TYPE_ALIGN (t));
17013 else
17014 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
17015 SET_TYPE_ALIGN (t, valign);
17016 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
17020 /* Begin compiling the definition of an enumeration type.
17021 NAME is its name,
17023 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
17025 UNDERLYING_TYPE is the type that will be used as the storage for
17026 the enumeration type. This should be NULL_TREE if no storage type
17027 was specified.
17029 ATTRIBUTES are any attributes specified after the enum-key.
17031 SCOPED_ENUM_P is true if this is a scoped enumeration type.
17033 if IS_NEW is not NULL, gets TRUE iff a new type is created.
17035 Returns the type object, as yet incomplete.
17036 Also records info about it so that build_enumerator
17037 may be used to declare the individual values as they are read. */
17039 tree
17040 start_enum (tree name, tree enumtype, tree underlying_type,
17041 tree attributes, bool scoped_enum_p, bool *is_new)
17043 tree prevtype = NULL_TREE;
17044 gcc_assert (identifier_p (name));
17046 if (is_new)
17047 *is_new = false;
17048 /* [C++0x dcl.enum]p5:
17050 If not explicitly specified, the underlying type of a scoped
17051 enumeration type is int. */
17052 if (!underlying_type && scoped_enum_p)
17053 underlying_type = integer_type_node;
17055 if (underlying_type)
17056 underlying_type = cv_unqualified (underlying_type);
17058 /* If this is the real definition for a previous forward reference,
17059 fill in the contents in the same object that used to be the
17060 forward reference. */
17061 if (!enumtype)
17062 enumtype = lookup_and_check_tag (enum_type, name,
17063 /*tag_scope=*/TAG_how::CURRENT_ONLY,
17064 /*template_header_p=*/false);
17066 /* In case of a template_decl, the only check that should be deferred
17067 to instantiation time is the comparison of underlying types. */
17068 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
17070 /* Attempt to set the declaring module. */
17071 if (modules_p ())
17073 tree decl = TYPE_NAME (enumtype);
17074 if (!module_may_redeclare (decl))
17075 enumtype = error_mark_node;
17076 else
17077 set_instantiating_module (decl);
17080 if (enumtype == error_mark_node)
17082 else if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
17084 auto_diagnostic_group d;
17085 error_at (input_location, "scoped/unscoped mismatch "
17086 "in enum %q#T", enumtype);
17087 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17088 "previous definition here");
17089 enumtype = error_mark_node;
17091 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
17093 auto_diagnostic_group d;
17094 error_at (input_location, "underlying type mismatch "
17095 "in enum %q#T", enumtype);
17096 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17097 "previous definition here");
17098 enumtype = error_mark_node;
17100 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
17101 && !same_type_p (underlying_type,
17102 ENUM_UNDERLYING_TYPE (enumtype)))
17104 auto_diagnostic_group d;
17105 error_at (input_location, "different underlying type "
17106 "in enum %q#T", enumtype);
17107 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17108 "previous definition here");
17109 underlying_type = NULL_TREE;
17113 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
17114 || processing_template_decl)
17116 /* In case of error, make a dummy enum to allow parsing to
17117 continue. */
17118 if (enumtype == error_mark_node)
17120 name = make_anon_name ();
17121 enumtype = NULL_TREE;
17124 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
17125 of an opaque enum, or an opaque enum of an already defined
17126 enumeration (C++11).
17127 In any other case, it'll be NULL_TREE. */
17128 if (!enumtype)
17130 if (is_new)
17131 *is_new = true;
17133 prevtype = enumtype;
17135 /* Do not push the decl more than once. */
17136 if (!enumtype
17137 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
17139 enumtype = cxx_make_type (ENUMERAL_TYPE);
17140 enumtype = pushtag (name, enumtype);
17142 /* std::byte aliases anything. */
17143 if (enumtype != error_mark_node
17144 && TYPE_CONTEXT (enumtype) == std_node
17145 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
17146 TYPE_ALIAS_SET (enumtype) = 0;
17148 else
17149 enumtype = xref_tag (enum_type, name);
17151 if (enumtype == error_mark_node)
17152 return error_mark_node;
17154 /* The enum is considered opaque until the opening '{' of the
17155 enumerator list. */
17156 SET_OPAQUE_ENUM_P (enumtype, true);
17157 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
17160 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
17162 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
17164 if (underlying_type)
17166 if (ENUM_UNDERLYING_TYPE (enumtype))
17167 /* We already checked that it matches, don't change it to a different
17168 typedef variant. */;
17169 else if (CP_INTEGRAL_TYPE_P (underlying_type))
17171 copy_type_enum (enumtype, underlying_type);
17172 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17174 else if (dependent_type_p (underlying_type))
17175 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17176 else
17178 error ("underlying type %qT of %qT must be an integral type",
17179 underlying_type, enumtype);
17180 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
17184 /* If into a template class, the returned enum is always the first
17185 declaration (opaque or not) seen. This way all the references to
17186 this type will be to the same declaration. The following ones are used
17187 only to check for definition errors. */
17188 if (prevtype && processing_template_decl)
17189 return prevtype;
17190 else
17191 return enumtype;
17194 /* After processing and defining all the values of an enumeration type,
17195 install their decls in the enumeration type.
17196 ENUMTYPE is the type object. */
17198 void
17199 finish_enum_value_list (tree enumtype)
17201 tree values;
17202 tree underlying_type;
17203 tree decl;
17204 tree value;
17205 tree minnode, maxnode;
17206 tree t;
17208 bool fixed_underlying_type_p
17209 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
17211 /* We built up the VALUES in reverse order. */
17212 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
17214 /* For an enum defined in a template, just set the type of the values;
17215 all further processing is postponed until the template is
17216 instantiated. We need to set the type so that tsubst of a CONST_DECL
17217 works. */
17218 if (processing_template_decl)
17220 for (values = TYPE_VALUES (enumtype);
17221 values;
17222 values = TREE_CHAIN (values))
17223 TREE_TYPE (TREE_VALUE (values)) = enumtype;
17224 return;
17227 /* Determine the minimum and maximum values of the enumerators. */
17228 if (TYPE_VALUES (enumtype))
17230 minnode = maxnode = NULL_TREE;
17232 for (values = TYPE_VALUES (enumtype);
17233 values;
17234 values = TREE_CHAIN (values))
17236 decl = TREE_VALUE (values);
17238 /* [dcl.enum]: Following the closing brace of an enum-specifier,
17239 each enumerator has the type of its enumeration. Prior to the
17240 closing brace, the type of each enumerator is the type of its
17241 initializing value. */
17242 TREE_TYPE (decl) = enumtype;
17244 /* Update the minimum and maximum values, if appropriate. */
17245 value = DECL_INITIAL (decl);
17246 if (TREE_CODE (value) != INTEGER_CST)
17247 value = integer_zero_node;
17248 /* Figure out what the minimum and maximum values of the
17249 enumerators are. */
17250 if (!minnode)
17251 minnode = maxnode = value;
17252 else if (tree_int_cst_lt (maxnode, value))
17253 maxnode = value;
17254 else if (tree_int_cst_lt (value, minnode))
17255 minnode = value;
17258 else
17259 /* [dcl.enum]
17261 If the enumerator-list is empty, the underlying type is as if
17262 the enumeration had a single enumerator with value 0. */
17263 minnode = maxnode = integer_zero_node;
17265 if (!fixed_underlying_type_p)
17267 /* Compute the number of bits require to represent all values of the
17268 enumeration. We must do this before the type of MINNODE and
17269 MAXNODE are transformed, since tree_int_cst_min_precision relies
17270 on the TREE_TYPE of the value it is passed. */
17271 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
17272 int lowprec = tree_int_cst_min_precision (minnode, sgn);
17273 int highprec = tree_int_cst_min_precision (maxnode, sgn);
17274 int precision = MAX (lowprec, highprec);
17275 unsigned int itk;
17276 bool use_short_enum;
17278 /* Determine the underlying type of the enumeration.
17280 [dcl.enum]
17282 The underlying type of an enumeration is an integral type that
17283 can represent all the enumerator values defined in the
17284 enumeration. It is implementation-defined which integral type is
17285 used as the underlying type for an enumeration except that the
17286 underlying type shall not be larger than int unless the value of
17287 an enumerator cannot fit in an int or unsigned int.
17289 We use "int" or an "unsigned int" as the underlying type, even if
17290 a smaller integral type would work, unless the user has
17291 explicitly requested that we use the smallest possible type. The
17292 user can request that for all enumerations with a command line
17293 flag, or for just one enumeration with an attribute. */
17295 use_short_enum = flag_short_enums
17296 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
17298 /* If the precision of the type was specified with an attribute and it
17299 was too small, give an error. Otherwise, use it. */
17300 if (TYPE_PRECISION (enumtype))
17302 if (precision > TYPE_PRECISION (enumtype))
17303 error ("specified mode too small for enumerated values");
17304 else
17306 use_short_enum = true;
17307 precision = TYPE_PRECISION (enumtype);
17311 for (itk = (use_short_enum ? itk_char : itk_int);
17312 itk != itk_none;
17313 itk++)
17315 underlying_type = integer_types[itk];
17316 if (underlying_type != NULL_TREE
17317 && TYPE_PRECISION (underlying_type) >= precision
17318 && TYPE_SIGN (underlying_type) == sgn)
17319 break;
17321 if (itk == itk_none)
17323 /* DR 377
17325 IF no integral type can represent all the enumerator values, the
17326 enumeration is ill-formed. */
17327 error ("no integral type can represent all of the enumerator values "
17328 "for %qT", enumtype);
17329 precision = TYPE_PRECISION (long_long_integer_type_node);
17330 underlying_type = integer_types[itk_unsigned_long_long];
17333 /* [dcl.enum]
17335 The value of sizeof() applied to an enumeration type, an object
17336 of an enumeration type, or an enumerator, is the value of sizeof()
17337 applied to the underlying type. */
17338 copy_type_enum (enumtype, underlying_type);
17340 /* Compute the minimum and maximum values for the type.
17342 [dcl.enum]
17344 For an enumeration where emin is the smallest enumerator and emax
17345 is the largest, the values of the enumeration are the values of the
17346 underlying type in the range bmin to bmax, where bmin and bmax are,
17347 respectively, the smallest and largest values of the smallest bit-
17348 field that can store emin and emax. */
17350 /* The middle-end currently assumes that types with TYPE_PRECISION
17351 narrower than their underlying type are suitably zero or sign
17352 extended to fill their mode. Similarly, it assumes that the front
17353 end assures that a value of a particular type must be within
17354 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
17356 We used to set these fields based on bmin and bmax, but that led
17357 to invalid assumptions like optimizing away bounds checking. So
17358 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
17359 TYPE_MAX_VALUE to the values for the mode above and only restrict
17360 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
17361 ENUM_UNDERLYING_TYPE (enumtype)
17362 = build_distinct_type_copy (underlying_type);
17363 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
17364 set_min_and_max_values_for_integral_type
17365 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
17367 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
17368 if (flag_strict_enums)
17369 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
17371 if (use_short_enum)
17373 TYPE_PACKED (enumtype) = use_short_enum;
17374 fixup_attribute_variants (enumtype);
17377 else
17378 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
17380 /* If the enum is exported, mark the consts too. */
17381 bool export_p = (UNSCOPED_ENUM_P (enumtype)
17382 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
17383 && at_namespace_scope_p ());
17385 /* Convert each of the enumerators to the type of the underlying
17386 type of the enumeration. */
17387 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
17389 decl = TREE_VALUE (values);
17390 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
17391 if (fixed_underlying_type_p)
17392 /* If the enumeration type has a fixed underlying type, we
17393 already checked all of the enumerator values. */
17394 value = DECL_INITIAL (decl);
17395 else
17396 value = perform_implicit_conversion (underlying_type,
17397 DECL_INITIAL (decl),
17398 tf_warning_or_error);
17399 /* Do not clobber shared ints. */
17400 if (value != error_mark_node)
17402 value = copy_node (value);
17404 TREE_TYPE (value) = enumtype;
17406 DECL_INITIAL (decl) = value;
17407 if (export_p)
17408 DECL_MODULE_EXPORT_P (decl) = true;
17411 /* Fix up all variant types of this enum type. */
17412 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
17413 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
17415 if (at_class_scope_p ()
17416 && COMPLETE_TYPE_P (current_class_type)
17417 && UNSCOPED_ENUM_P (enumtype))
17419 insert_late_enum_def_bindings (current_class_type, enumtype);
17420 /* TYPE_FIELDS needs fixup. */
17421 fixup_type_variants (current_class_type);
17424 /* Finish debugging output for this type. */
17425 rest_of_type_compilation (enumtype, namespace_bindings_p ());
17427 /* Each enumerator now has the type of its enumeration. Clear the cache
17428 so that this change in types doesn't confuse us later on. */
17429 clear_cv_and_fold_caches ();
17432 /* Finishes the enum type. This is called only the first time an
17433 enumeration is seen, be it opaque or odinary.
17434 ENUMTYPE is the type object. */
17436 void
17437 finish_enum (tree enumtype)
17439 if (processing_template_decl)
17441 if (at_function_scope_p ())
17442 add_stmt (build_min (TAG_DEFN, enumtype));
17443 return;
17446 /* If this is a forward declaration, there should not be any variants,
17447 though we can get a variant in the middle of an enum-specifier with
17448 wacky code like 'enum E { e = sizeof(const E*) };' */
17449 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
17450 && (TYPE_VALUES (enumtype)
17451 || !TYPE_NEXT_VARIANT (enumtype)));
17454 /* Build and install a CONST_DECL for an enumeration constant of the
17455 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
17456 Apply ATTRIBUTES if available. LOC is the location of NAME.
17457 Assignment of sequential values by default is handled here. */
17459 tree
17460 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
17461 location_t loc)
17463 tree decl;
17464 tree context;
17465 tree type;
17467 /* scalar_constant_value will pull out this expression, so make sure
17468 it's folded as appropriate. */
17469 if (processing_template_decl)
17470 value = fold_non_dependent_expr (value);
17472 /* If the VALUE was erroneous, pretend it wasn't there; that will
17473 result in the enum being assigned the next value in sequence. */
17474 if (value == error_mark_node)
17475 value = NULL_TREE;
17477 /* Remove no-op casts from the value. */
17478 if (value)
17479 STRIP_TYPE_NOPS (value);
17481 if (! processing_template_decl)
17483 /* Validate and default VALUE. */
17484 if (value != NULL_TREE)
17486 if (!ENUM_UNDERLYING_TYPE (enumtype))
17488 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
17489 value, true);
17490 if (tmp_value)
17491 value = tmp_value;
17493 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17494 (TREE_TYPE (value)))
17495 value = perform_implicit_conversion_flags
17496 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
17497 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
17499 if (value == error_mark_node)
17500 value = NULL_TREE;
17502 if (value != NULL_TREE)
17504 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17505 (TREE_TYPE (value)))
17507 error_at (cp_expr_loc_or_input_loc (value),
17508 "enumerator value for %qD must have integral or "
17509 "unscoped enumeration type", name);
17510 value = NULL_TREE;
17512 else
17514 value = cxx_constant_value (value);
17516 if (TREE_CODE (value) != INTEGER_CST)
17518 error ("enumerator value for %qD is not an integer "
17519 "constant", name);
17520 value = NULL_TREE;
17526 /* Default based on previous value. */
17527 if (value == NULL_TREE)
17529 if (TYPE_VALUES (enumtype))
17531 tree prev_value;
17533 /* C++03 7.2/4: If no initializer is specified for the first
17534 enumerator, the type is an unspecified integral
17535 type. Otherwise the type is the same as the type of the
17536 initializing value of the preceding enumerator unless the
17537 incremented value is not representable in that type, in
17538 which case the type is an unspecified integral type
17539 sufficient to contain the incremented value. */
17540 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
17541 if (TREE_CODE (prev_value) != INTEGER_CST)
17542 value = error_mark_node;
17543 else
17545 wi::overflow_type overflowed;
17546 tree type = TREE_TYPE (prev_value);
17547 signop sgn = TYPE_SIGN (type);
17548 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
17549 &overflowed);
17550 if (!overflowed)
17552 bool pos = !wi::neg_p (wi, sgn);
17553 if (!wi::fits_to_tree_p (wi, type))
17555 unsigned int itk;
17556 for (itk = itk_int; itk != itk_none; itk++)
17558 type = integer_types[itk];
17559 if (type != NULL_TREE
17560 && (pos || !TYPE_UNSIGNED (type))
17561 && wi::fits_to_tree_p (wi, type))
17562 break;
17564 if (type && cxx_dialect < cxx11
17565 && itk > itk_unsigned_long)
17566 pedwarn (input_location, OPT_Wlong_long,
17567 pos ? G_("\
17568 incremented enumerator value is too large for %<unsigned long%>") : G_("\
17569 incremented enumerator value is too large for %<long%>"));
17571 if (type == NULL_TREE)
17572 overflowed = wi::OVF_UNKNOWN;
17573 else
17574 value = wide_int_to_tree (type, wi);
17577 if (overflowed)
17579 error ("overflow in enumeration values at %qD", name);
17580 value = error_mark_node;
17584 else
17585 value = integer_zero_node;
17588 /* Remove no-op casts from the value. */
17589 STRIP_TYPE_NOPS (value);
17591 /* If the underlying type of the enum is fixed, check whether
17592 the enumerator values fits in the underlying type. If it
17593 does not fit, the program is ill-formed [C++0x dcl.enum]. */
17594 if (ENUM_UNDERLYING_TYPE (enumtype)
17595 && value
17596 && TREE_CODE (value) == INTEGER_CST)
17598 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
17599 error ("enumerator value %qE is outside the range of underlying "
17600 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
17602 /* Convert the value to the appropriate type. */
17603 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
17607 /* C++ associates enums with global, function, or class declarations. */
17608 context = current_scope ();
17610 /* Build the actual enumeration constant. Note that the enumeration
17611 constants have the underlying type of the enum (if it is fixed)
17612 or the type of their initializer (if the underlying type of the
17613 enum is not fixed):
17615 [ C++0x dcl.enum ]
17617 If the underlying type is fixed, the type of each enumerator
17618 prior to the closing brace is the underlying type; if the
17619 initializing value of an enumerator cannot be represented by
17620 the underlying type, the program is ill-formed. If the
17621 underlying type is not fixed, the type of each enumerator is
17622 the type of its initializing value.
17624 If the underlying type is not fixed, it will be computed by
17625 finish_enum and we will reset the type of this enumerator. Of
17626 course, if we're processing a template, there may be no value. */
17627 type = value ? TREE_TYPE (value) : NULL_TREE;
17629 decl = build_decl (loc, CONST_DECL, name, type);
17631 DECL_CONTEXT (decl) = enumtype;
17632 TREE_CONSTANT (decl) = 1;
17633 TREE_READONLY (decl) = 1;
17634 DECL_INITIAL (decl) = value;
17636 if (attributes)
17637 cplus_decl_attributes (&decl, attributes, 0);
17639 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17641 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17642 on the TYPE_FIELDS list for `S'. (That's so that you can say
17643 things like `S::i' later.) */
17645 /* The enumerator may be getting declared outside of its enclosing
17646 class, like so:
17648 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17650 For which case we need to make sure that the access of `S::i'
17651 matches the access of `S::E'. */
17652 auto cas = make_temp_override (current_access_specifier);
17653 set_current_access_from_decl (TYPE_NAME (enumtype));
17654 finish_member_declaration (decl);
17656 else
17657 pushdecl (decl);
17659 /* Add this enumeration constant to the list for this type. */
17660 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17662 return decl;
17665 /* Look for an enumerator with the given NAME within the enumeration
17666 type ENUMTYPE. This routine is used primarily for qualified name
17667 lookup into an enumerator in C++0x, e.g.,
17669 enum class Color { Red, Green, Blue };
17671 Color color = Color::Red;
17673 Returns the value corresponding to the enumerator, or
17674 NULL_TREE if no such enumerator was found. */
17675 tree
17676 lookup_enumerator (tree enumtype, tree name)
17678 tree e;
17679 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17681 e = purpose_member (name, TYPE_VALUES (enumtype));
17682 return e? TREE_VALUE (e) : NULL_TREE;
17685 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17687 tree
17688 cxx_simulate_enum_decl (location_t loc, const char *name,
17689 vec<string_int_pair> *values)
17691 location_t saved_loc = input_location;
17692 input_location = loc;
17694 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17695 NULL_TREE, false, NULL);
17696 if (!OPAQUE_ENUM_P (enumtype))
17698 error_at (loc, "multiple definition of %q#T", enumtype);
17699 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17700 "previous definition here");
17701 return enumtype;
17703 SET_OPAQUE_ENUM_P (enumtype, false);
17704 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17706 for (const string_int_pair &value : values)
17707 build_enumerator (get_identifier (value.first),
17708 build_int_cst (integer_type_node, value.second),
17709 enumtype, NULL_TREE, loc);
17711 finish_enum_value_list (enumtype);
17712 finish_enum (enumtype);
17714 input_location = saved_loc;
17715 return enumtype;
17718 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17720 tree
17721 cxx_simulate_record_decl (location_t loc, const char *name,
17722 array_slice<const tree> fields)
17724 iloc_sentinel ils (loc);
17726 tree ident = get_identifier (name);
17727 tree type = xref_tag (/*tag_code=*/record_type, ident);
17728 if (type != error_mark_node
17729 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17731 error ("redefinition of %q#T", type);
17732 type = error_mark_node;
17734 if (type == error_mark_node)
17735 return lhd_simulate_record_decl (loc, name, fields);
17737 xref_basetypes (type, NULL_TREE);
17738 type = begin_class_definition (type);
17739 if (type == error_mark_node)
17740 return lhd_simulate_record_decl (loc, name, fields);
17742 for (tree field : fields)
17743 finish_member_declaration (field);
17745 type = finish_struct (type, NULL_TREE);
17747 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17748 set_underlying_type (decl);
17749 lang_hooks.decls.pushdecl (decl);
17751 return type;
17754 /* We're defining DECL. Make sure that its type is OK. */
17756 static void
17757 check_function_type (tree decl, tree current_function_parms)
17759 tree fntype = TREE_TYPE (decl);
17760 tree return_type = complete_type (TREE_TYPE (fntype));
17762 /* In a function definition, arg types must be complete. */
17763 require_complete_types_for_parms (current_function_parms);
17765 if (dependent_type_p (return_type)
17766 || type_uses_auto (return_type))
17767 return;
17768 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17770 tree args = TYPE_ARG_TYPES (fntype);
17772 error ("return type %q#T is incomplete", return_type);
17774 /* Make it return void instead. */
17775 if (TREE_CODE (fntype) == METHOD_TYPE)
17776 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17777 void_type_node,
17778 TREE_CHAIN (args));
17779 else
17780 fntype = build_function_type (void_type_node, args);
17781 fntype = (cp_build_type_attribute_variant
17782 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17783 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17784 TREE_TYPE (decl) = fntype;
17786 else
17788 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17789 maybe_warn_parm_abi (TREE_TYPE (fntype),
17790 DECL_SOURCE_LOCATION (decl));
17794 /* True iff FN is an implicitly-defined default constructor. */
17796 static bool
17797 implicit_default_ctor_p (tree fn)
17799 return (DECL_CONSTRUCTOR_P (fn)
17800 && !user_provided_p (fn)
17801 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17804 /* Clobber the contents of *this to let the back end know that the object
17805 storage is dead when we enter the constructor or leave the destructor. */
17807 static tree
17808 build_clobber_this (clobber_kind kind)
17810 /* Clobbering an empty base is pointless, and harmful if its one byte
17811 TYPE_SIZE overlays real data. */
17812 if (is_empty_class (current_class_type))
17813 return void_node;
17815 /* If we have virtual bases, clobber the whole object, but only if we're in
17816 charge. If we don't have virtual bases, clobber the as-base type so we
17817 don't mess with tail padding. */
17818 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17820 tree ctype = current_class_type;
17821 if (!vbases)
17822 ctype = CLASSTYPE_AS_BASE (ctype);
17824 tree clobber = build_clobber (ctype, kind);
17826 tree thisref = current_class_ref;
17827 if (ctype != current_class_type)
17829 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17830 thisref = convert_from_reference (thisref);
17833 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17834 if (vbases)
17835 exprstmt = build_if_in_charge (exprstmt);
17837 return exprstmt;
17840 /* Create the FUNCTION_DECL for a function definition.
17841 DECLSPECS and DECLARATOR are the parts of the declaration;
17842 they describe the function's name and the type it returns,
17843 but twisted together in a fashion that parallels the syntax of C.
17845 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17846 DECLARATOR is really the DECL for the function we are about to
17847 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17848 indicating that the function is an inline defined in-class.
17850 This function creates a binding context for the function body
17851 as well as setting up the FUNCTION_DECL in current_function_decl.
17853 For C++, we must first check whether that datum makes any sense.
17854 For example, "class A local_a(1,2);" means that variable local_a
17855 is an aggregate of type A, which should have a constructor
17856 applied to it with the argument list [1, 2].
17858 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17859 or may be a BLOCK if the function has been defined previously
17860 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17861 error_mark_node if the function has never been defined, or
17862 a BLOCK if the function has been defined somewhere. */
17864 bool
17865 start_preparsed_function (tree decl1, tree attrs, int flags)
17867 tree ctype = NULL_TREE;
17868 bool doing_friend = false;
17870 /* Sanity check. */
17871 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17872 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17874 tree fntype = TREE_TYPE (decl1);
17875 if (DECL_CLASS_SCOPE_P (decl1))
17876 ctype = DECL_CONTEXT (decl1);
17877 else
17879 ctype = DECL_FRIEND_CONTEXT (decl1);
17881 if (ctype)
17882 doing_friend = true;
17885 /* Adjust for #pragma target/optimize. */
17886 decl_attributes (&decl1, NULL_TREE, 0);
17888 if (DECL_DECLARED_INLINE_P (decl1)
17889 && lookup_attribute ("noinline", attrs))
17890 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17891 "inline function %qD given attribute %qs", decl1, "noinline");
17893 /* Handle gnu_inline attribute. */
17894 if (GNU_INLINE_P (decl1))
17896 DECL_EXTERNAL (decl1) = 1;
17897 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17898 DECL_INTERFACE_KNOWN (decl1) = 1;
17899 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17902 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17903 /* This is a constructor, we must ensure that any default args
17904 introduced by this definition are propagated to the clones
17905 now. The clones are used directly in overload resolution. */
17906 adjust_clone_args (decl1);
17908 /* Sometimes we don't notice that a function is a static member, and
17909 build a METHOD_TYPE for it. Fix that up now. */
17910 gcc_assert (!(DECL_STATIC_FUNCTION_P (decl1)
17911 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17913 /* Set up current_class_type, and enter the scope of the class, if
17914 appropriate. */
17915 if (ctype)
17916 push_nested_class (ctype);
17918 /* Now that we have entered the scope of the class, we must restore
17919 the bindings for any template parameters surrounding DECL1, if it
17920 is an inline member template. (Order is important; consider the
17921 case where a template parameter has the same name as a field of
17922 the class.) It is not until after this point that
17923 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17924 if (flags & SF_INCLASS_INLINE)
17925 maybe_begin_member_template_processing (decl1);
17927 /* Effective C++ rule 15. */
17928 if (warn_ecpp
17929 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17930 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17931 && VOID_TYPE_P (TREE_TYPE (fntype)))
17932 warning (OPT_Weffc__,
17933 "%<operator=%> should return a reference to %<*this%>");
17935 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17936 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17937 if (!DECL_INITIAL (decl1))
17938 DECL_INITIAL (decl1) = error_mark_node;
17940 /* This function exists in static storage.
17941 (This does not mean `static' in the C sense!) */
17942 TREE_STATIC (decl1) = 1;
17944 /* We must call push_template_decl after current_class_type is set
17945 up. (If we are processing inline definitions after exiting a
17946 class scope, current_class_type will be NULL_TREE until set above
17947 by push_nested_class.) */
17948 if (processing_template_decl)
17950 tree newdecl1 = push_template_decl (decl1, doing_friend);
17951 if (newdecl1 == error_mark_node)
17953 if (ctype)
17954 pop_nested_class ();
17955 return false;
17957 decl1 = newdecl1;
17960 /* Make sure the parameter and return types are reasonable. When
17961 you declare a function, these types can be incomplete, but they
17962 must be complete when you define the function. */
17963 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17965 /* Build the return declaration for the function. */
17966 tree restype = TREE_TYPE (fntype);
17968 if (DECL_RESULT (decl1) == NULL_TREE)
17970 /* In a template instantiation, copy the return type location. When
17971 parsing, the location will be set in grokdeclarator. */
17972 location_t loc = input_location;
17973 if (DECL_TEMPLATE_INSTANTIATION (decl1))
17975 tree tmpl = template_for_substitution (decl1);
17976 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
17977 loc = DECL_SOURCE_LOCATION (res);
17980 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
17981 DECL_ARTIFICIAL (resdecl) = 1;
17982 DECL_IGNORED_P (resdecl) = 1;
17983 DECL_RESULT (decl1) = resdecl;
17985 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17988 /* Record the decl so that the function name is defined.
17989 If we already have a decl for this name, and it is a FUNCTION_DECL,
17990 use the old decl. */
17991 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17993 /* A specialization is not used to guide overload resolution. */
17994 if (!DECL_FUNCTION_MEMBER_P (decl1)
17995 && !(DECL_USE_TEMPLATE (decl1) &&
17996 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17998 tree olddecl = pushdecl (decl1);
18000 if (olddecl == error_mark_node)
18001 /* If something went wrong when registering the declaration,
18002 use DECL1; we have to have a FUNCTION_DECL to use when
18003 parsing the body of the function. */
18005 else
18007 /* Otherwise, OLDDECL is either a previous declaration
18008 of the same function or DECL1 itself. */
18010 if (warn_missing_declarations
18011 && olddecl == decl1
18012 && !DECL_MAIN_P (decl1)
18013 && TREE_PUBLIC (decl1)
18014 && !DECL_DECLARED_INLINE_P (decl1))
18016 tree context;
18018 /* Check whether DECL1 is in an anonymous
18019 namespace. */
18020 for (context = DECL_CONTEXT (decl1);
18021 context;
18022 context = DECL_CONTEXT (context))
18024 if (TREE_CODE (context) == NAMESPACE_DECL
18025 && DECL_NAME (context) == NULL_TREE)
18026 break;
18029 if (context == NULL)
18030 warning_at (DECL_SOURCE_LOCATION (decl1),
18031 OPT_Wmissing_declarations,
18032 "no previous declaration for %qD", decl1);
18035 decl1 = olddecl;
18038 else
18040 /* We need to set the DECL_CONTEXT. */
18041 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
18042 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
18044 fntype = TREE_TYPE (decl1);
18045 restype = TREE_TYPE (fntype);
18047 /* If #pragma weak applies, mark the decl appropriately now.
18048 The pragma only applies to global functions. Because
18049 determining whether or not the #pragma applies involves
18050 computing the mangled name for the declaration, we cannot
18051 apply the pragma until after we have merged this declaration
18052 with any previous declarations; if the original declaration
18053 has a linkage specification, that specification applies to
18054 the definition as well, and may affect the mangled name. */
18055 if (DECL_FILE_SCOPE_P (decl1))
18056 maybe_apply_pragma_weak (decl1);
18059 /* We are now in the scope of the function being defined. */
18060 current_function_decl = decl1;
18062 /* Save the parm names or decls from this function's declarator
18063 where store_parm_decls will find them. */
18064 tree current_function_parms = DECL_ARGUMENTS (decl1);
18066 /* Let the user know we're compiling this function. */
18067 announce_function (decl1);
18069 gcc_assert (DECL_INITIAL (decl1));
18071 /* This function may already have been parsed, in which case just
18072 return; our caller will skip over the body without parsing. */
18073 if (DECL_INITIAL (decl1) != error_mark_node)
18074 return true;
18076 /* Initialize RTL machinery. We cannot do this until
18077 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
18078 even when processing a template; this is how we get
18079 CFUN set up, and our per-function variables initialized.
18080 FIXME factor out the non-RTL stuff. */
18081 cp_binding_level *bl = current_binding_level;
18082 allocate_struct_function (decl1, processing_template_decl);
18084 /* Initialize the language data structures. Whenever we start
18085 a new function, we destroy temporaries in the usual way. */
18086 cfun->language = ggc_cleared_alloc<language_function> ();
18087 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
18088 current_binding_level = bl;
18090 /* If we are (erroneously) defining a function that we have already
18091 defined before, wipe out what we knew before. */
18092 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
18093 FNDECL_USED_AUTO (decl1) = false;
18094 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
18096 if (!processing_template_decl && type_uses_auto (restype))
18098 FNDECL_USED_AUTO (decl1) = true;
18099 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
18102 /* Start the statement-tree, start the tree now. */
18103 DECL_SAVED_TREE (decl1) = push_stmt_list ();
18105 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1))
18107 /* We know that this was set up by `grokclassfn'. We do not
18108 wait until `store_parm_decls', since evil parse errors may
18109 never get us to that point. Here we keep the consistency
18110 between `current_class_type' and `current_class_ptr'. */
18111 tree t = DECL_ARGUMENTS (decl1);
18113 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
18114 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
18116 cp_function_chain->x_current_class_ref
18117 = cp_build_fold_indirect_ref (t);
18118 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
18119 cp_function_chain->x_current_class_ptr = t;
18121 /* Constructors and destructors need to know whether they're "in
18122 charge" of initializing virtual base classes. */
18123 t = DECL_CHAIN (t);
18124 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
18126 current_in_charge_parm = t;
18127 t = DECL_CHAIN (t);
18129 if (DECL_HAS_VTT_PARM_P (decl1))
18131 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
18132 current_vtt_parm = t;
18136 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
18137 /* Implicitly-defined methods (like the
18138 destructor for a class in which no destructor
18139 is explicitly declared) must not be defined
18140 until their definition is needed. So, we
18141 ignore interface specifications for
18142 compiler-generated functions. */
18143 && !DECL_ARTIFICIAL (decl1));
18144 struct c_fileinfo *finfo
18145 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
18147 if (processing_template_decl)
18148 /* Don't mess with interface flags. */;
18149 else if (DECL_INTERFACE_KNOWN (decl1))
18151 tree ctx = decl_function_context (decl1);
18153 if (DECL_NOT_REALLY_EXTERN (decl1))
18154 DECL_EXTERNAL (decl1) = 0;
18156 if (ctx != NULL_TREE && vague_linkage_p (ctx))
18157 /* This is a function in a local class in an extern inline
18158 or template function. */
18159 comdat_linkage (decl1);
18161 /* If this function belongs to an interface, it is public.
18162 If it belongs to someone else's interface, it is also external.
18163 This only affects inlines and template instantiations. */
18164 else if (!finfo->interface_unknown && honor_interface)
18166 if (DECL_DECLARED_INLINE_P (decl1)
18167 || DECL_TEMPLATE_INSTANTIATION (decl1))
18169 DECL_EXTERNAL (decl1)
18170 = (finfo->interface_only
18171 || (DECL_DECLARED_INLINE_P (decl1)
18172 && ! flag_implement_inlines
18173 && !DECL_VINDEX (decl1)));
18175 /* For WIN32 we also want to put these in linkonce sections. */
18176 maybe_make_one_only (decl1);
18178 else
18179 DECL_EXTERNAL (decl1) = 0;
18180 DECL_INTERFACE_KNOWN (decl1) = 1;
18181 /* If this function is in an interface implemented in this file,
18182 make sure that the back end knows to emit this function
18183 here. */
18184 if (!DECL_EXTERNAL (decl1))
18185 mark_needed (decl1);
18187 else if (finfo->interface_unknown && finfo->interface_only
18188 && honor_interface)
18190 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
18191 interface, we will have both finfo->interface_unknown and
18192 finfo->interface_only set. In that case, we don't want to
18193 use the normal heuristics because someone will supply a
18194 #pragma implementation elsewhere, and deducing it here would
18195 produce a conflict. */
18196 comdat_linkage (decl1);
18197 DECL_EXTERNAL (decl1) = 0;
18198 DECL_INTERFACE_KNOWN (decl1) = 1;
18199 DECL_DEFER_OUTPUT (decl1) = 1;
18201 else
18203 /* This is a definition, not a reference.
18204 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
18205 if (!GNU_INLINE_P (decl1))
18206 DECL_EXTERNAL (decl1) = 0;
18208 if ((DECL_DECLARED_INLINE_P (decl1)
18209 || DECL_TEMPLATE_INSTANTIATION (decl1))
18210 && ! DECL_INTERFACE_KNOWN (decl1))
18211 DECL_DEFER_OUTPUT (decl1) = 1;
18212 else
18213 DECL_INTERFACE_KNOWN (decl1) = 1;
18216 /* Determine the ELF visibility attribute for the function. We must not
18217 do this before calling "pushdecl", as we must allow "duplicate_decls"
18218 to merge any attributes appropriately. We also need to wait until
18219 linkage is set. */
18220 if (!DECL_CLONED_FUNCTION_P (decl1))
18221 determine_visibility (decl1);
18223 if (!processing_template_decl)
18224 maybe_instantiate_noexcept (decl1);
18226 begin_scope (sk_function_parms, decl1);
18228 ++function_depth;
18230 start_fname_decls ();
18232 store_parm_decls (current_function_parms);
18234 start_function_contracts (decl1);
18236 if (!processing_template_decl
18237 && (flag_lifetime_dse > 1)
18238 && DECL_CONSTRUCTOR_P (decl1)
18239 && !DECL_CLONED_FUNCTION_P (decl1)
18240 /* Clobbering an empty base is harmful if it overlays real data. */
18241 && !is_empty_class (current_class_type)
18242 /* We can't clobber safely for an implicitly-defined default constructor
18243 because part of the initialization might happen before we enter the
18244 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
18245 && !implicit_default_ctor_p (decl1))
18246 finish_expr_stmt (build_clobber_this (CLOBBER_OBJECT_BEGIN));
18248 if (!processing_template_decl
18249 && DECL_CONSTRUCTOR_P (decl1)
18250 && sanitize_flags_p (SANITIZE_VPTR)
18251 && !DECL_CLONED_FUNCTION_P (decl1)
18252 && !implicit_default_ctor_p (decl1))
18253 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
18255 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
18256 start_lambda_scope (decl1);
18258 return true;
18262 /* Like start_preparsed_function, except that instead of a
18263 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
18265 Returns true on success. If the DECLARATOR is not suitable
18266 for a function, we return false, which tells the parser to
18267 skip the entire function. */
18269 bool
18270 start_function (cp_decl_specifier_seq *declspecs,
18271 const cp_declarator *declarator,
18272 tree attrs)
18274 tree decl1;
18276 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
18277 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
18278 if (decl1 == error_mark_node)
18279 return false;
18281 if (DECL_MAIN_P (decl1))
18282 /* main must return int. grokfndecl should have corrected it
18283 (and issued a diagnostic) if the user got it wrong. */
18284 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
18285 integer_type_node));
18287 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
18290 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
18291 FN. */
18293 static bool
18294 use_eh_spec_block (tree fn)
18296 return (flag_exceptions && flag_enforce_eh_specs
18297 && !processing_template_decl
18298 /* We insert the EH_SPEC_BLOCK only in the original
18299 function; then, it is copied automatically to the
18300 clones. */
18301 && !DECL_CLONED_FUNCTION_P (fn)
18302 /* Implicitly-generated constructors and destructors have
18303 exception specifications. However, those specifications
18304 are the union of the possible exceptions specified by the
18305 constructors/destructors for bases and members, so no
18306 unallowed exception will ever reach this function. By
18307 not creating the EH_SPEC_BLOCK we save a little memory,
18308 and we avoid spurious warnings about unreachable
18309 code. */
18310 && !DECL_DEFAULTED_FN (fn)
18311 && !type_throw_all_p (TREE_TYPE (fn)));
18314 /* Helper function to push ARGS into the current lexical scope. DECL
18315 is the function declaration. NONPARMS is used to handle enum
18316 constants. */
18318 void
18319 do_push_parm_decls (tree decl, tree args, tree *nonparms)
18321 /* If we're doing semantic analysis, then we'll call pushdecl
18322 for each of these. We must do them in reverse order so that
18323 they end in the correct forward order. */
18324 args = nreverse (args);
18326 tree next;
18327 for (tree parm = args; parm; parm = next)
18329 next = DECL_CHAIN (parm);
18330 if (TREE_CODE (parm) == PARM_DECL)
18331 pushdecl (parm);
18332 else if (nonparms)
18334 /* If we find an enum constant or a type tag, put it aside for
18335 the moment. */
18336 TREE_CHAIN (parm) = NULL_TREE;
18337 *nonparms = chainon (*nonparms, parm);
18341 /* Get the decls in their original chain order and record in the
18342 function. This is all and only the PARM_DECLs that were
18343 pushed into scope by the loop above. */
18344 DECL_ARGUMENTS (decl) = get_local_decls ();
18347 /* Store the parameter declarations into the current function declaration.
18348 This is called after parsing the parameter declarations, before
18349 digesting the body of the function.
18351 Also install to binding contour return value identifier, if any. */
18353 static void
18354 store_parm_decls (tree current_function_parms)
18356 tree fndecl = current_function_decl;
18358 /* This is a chain of any other decls that came in among the parm
18359 declarations. If a parm is declared with enum {foo, bar} x;
18360 then CONST_DECLs for foo and bar are put here. */
18361 tree nonparms = NULL_TREE;
18363 if (current_function_parms)
18365 /* This case is when the function was defined with an ANSI prototype.
18366 The parms already have decls, so we need not do anything here
18367 except record them as in effect
18368 and complain if any redundant old-style parm decls were written. */
18370 tree specparms = current_function_parms;
18372 /* Must clear this because it might contain TYPE_DECLs declared
18373 at class level. */
18374 current_binding_level->names = NULL;
18376 do_push_parm_decls (fndecl, specparms, &nonparms);
18378 else
18379 DECL_ARGUMENTS (fndecl) = NULL_TREE;
18381 /* Now store the final chain of decls for the arguments
18382 as the decl-chain of the current lexical scope.
18383 Put the enumerators in as well, at the front so that
18384 DECL_ARGUMENTS is not modified. */
18385 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
18387 if (use_eh_spec_block (current_function_decl))
18388 current_eh_spec_block = begin_eh_spec_block ();
18392 /* Mark CDTOR's implicit THIS argument for returning, if required by
18393 the ABI.. Return the decl for THIS, if it is to be returned, and
18394 NULL otherwise. */
18396 tree
18397 maybe_prepare_return_this (tree cdtor)
18399 if (targetm.cxx.cdtor_returns_this ())
18400 if (tree val = DECL_ARGUMENTS (cdtor))
18402 suppress_warning (val, OPT_Wuse_after_free);
18403 return val;
18406 return NULL_TREE;
18409 /* Set the return value of the [cd]tor if the ABI wants that. */
18411 void
18412 maybe_return_this ()
18414 if (tree val = maybe_prepare_return_this (current_function_decl))
18416 /* Return the address of the object. */
18417 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
18418 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
18419 DECL_RESULT (current_function_decl), val);
18420 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
18421 add_stmt (exprstmt);
18425 /* Do all the processing for the beginning of a destructor; set up the
18426 vtable pointers and cleanups for bases and members. */
18428 static void
18429 begin_destructor_body (void)
18431 tree compound_stmt;
18433 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
18434 issued an error message. We still want to try to process the
18435 body of the function, but initialize_vtbl_ptrs will crash if
18436 TYPE_BINFO is NULL. */
18437 if (COMPLETE_TYPE_P (current_class_type))
18439 compound_stmt = begin_compound_stmt (0);
18440 /* Make all virtual function table pointers in non-virtual base
18441 classes point to CURRENT_CLASS_TYPE's virtual function
18442 tables. */
18443 initialize_vtbl_ptrs (current_class_ptr);
18444 finish_compound_stmt (compound_stmt);
18446 if (flag_lifetime_dse
18447 /* Clobbering an empty base is harmful if it overlays real data. */
18448 && !is_empty_class (current_class_type))
18450 if (sanitize_flags_p (SANITIZE_VPTR)
18451 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
18452 && TYPE_CONTAINS_VPTR_P (current_class_type))
18454 tree binfo = TYPE_BINFO (current_class_type);
18455 tree ref
18456 = cp_build_fold_indirect_ref (current_class_ptr);
18458 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
18459 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
18460 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
18461 NOP_EXPR, vtbl,
18462 tf_warning_or_error);
18463 /* If the vptr is shared with some virtual nearly empty base,
18464 don't clear it if not in charge, the dtor of the virtual
18465 nearly empty base will do that later. */
18466 if (CLASSTYPE_VBASECLASSES (current_class_type))
18468 tree c = current_class_type;
18469 while (CLASSTYPE_PRIMARY_BINFO (c))
18471 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
18473 stmt = convert_to_void (stmt, ICV_STATEMENT,
18474 tf_warning_or_error);
18475 stmt = build_if_in_charge (stmt);
18476 break;
18478 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
18481 finish_decl_cleanup (NULL_TREE, stmt);
18483 else
18484 finish_decl_cleanup (NULL_TREE,
18485 build_clobber_this (CLOBBER_OBJECT_END));
18488 /* And insert cleanups for our bases and members so that they
18489 will be properly destroyed if we throw. */
18490 push_base_cleanups ();
18494 /* Do the necessary processing for the beginning of a function body, which
18495 in this case includes member-initializers, but not the catch clauses of
18496 a function-try-block. Currently, this means opening a binding level
18497 for the member-initializers (in a ctor), member cleanups (in a dtor),
18498 and capture proxies (in a lambda operator()). */
18500 tree
18501 begin_function_body (void)
18503 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
18504 return NULL_TREE;
18506 if (processing_template_decl)
18507 /* Do nothing now. */;
18508 else
18509 /* Always keep the BLOCK node associated with the outermost pair of
18510 curly braces of a function. These are needed for correct
18511 operation of dwarfout.c. */
18512 keep_next_level (true);
18514 tree stmt = begin_compound_stmt (BCS_FN_BODY);
18515 current_binding_level->artificial = 1;
18517 if (processing_template_decl)
18518 /* Do nothing now. */;
18519 else if (DECL_DESTRUCTOR_P (current_function_decl))
18520 begin_destructor_body ();
18522 return stmt;
18525 /* Do the processing for the end of a function body. Currently, this means
18526 closing out the cleanups for fully-constructed bases and members, and in
18527 the case of the destructor, deleting the object if desired. Again, this
18528 is only meaningful for [cd]tors, since they are the only functions where
18529 there is a significant distinction between the main body and any
18530 function catch clauses. Handling, say, main() return semantics here
18531 would be wrong, as flowing off the end of a function catch clause for
18532 main() would also need to return 0. */
18534 void
18535 finish_function_body (tree compstmt)
18537 if (compstmt == NULL_TREE)
18538 return;
18540 /* Close the block. */
18541 finish_compound_stmt (compstmt);
18543 if (processing_template_decl)
18544 /* Do nothing now. */;
18545 else if (DECL_CONSTRUCTOR_P (current_function_decl)
18546 || DECL_DESTRUCTOR_P (current_function_decl))
18547 maybe_return_this ();
18550 /* Given a function, returns the BLOCK corresponding to the outermost level
18551 of curly braces, skipping the artificial block created for constructor
18552 initializers. */
18554 tree
18555 outer_curly_brace_block (tree fndecl)
18557 tree block = DECL_INITIAL (fndecl);
18558 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18559 return block;
18560 block = BLOCK_SUBBLOCKS (block);
18561 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18562 return block;
18563 block = BLOCK_SUBBLOCKS (block);
18564 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
18565 return block;
18568 /* If FNDECL is a class's key method, add the class to the list of
18569 keyed classes that should be emitted. */
18571 static void
18572 record_key_method_defined (tree fndecl)
18574 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
18575 && DECL_VIRTUAL_P (fndecl)
18576 && !processing_template_decl)
18578 tree fnclass = DECL_CONTEXT (fndecl);
18579 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
18581 tree classdecl = TYPE_NAME (fnclass);
18582 /* Classes attached to a named module are already handled. */
18583 if (!DECL_LANG_SPECIFIC (classdecl)
18584 || !DECL_MODULE_ATTACH_P (classdecl))
18585 vec_safe_push (keyed_classes, fnclass);
18590 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
18591 of "return *this;" immediately before its location, using FNDECL's
18592 first statement (if any) to give the indentation, if appropriate. */
18594 static void
18595 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
18597 location_t indent = UNKNOWN_LOCATION;
18598 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
18599 if (stmts)
18600 indent = EXPR_LOCATION (stmts);
18601 richloc->add_fixit_insert_formatted ("return *this;",
18602 richloc->get_loc (),
18603 indent);
18606 /* This function carries out the subset of finish_function operations needed
18607 to emit the compiler-generated outlined helper functions used by the
18608 coroutines implementation. */
18610 static void
18611 emit_coro_helper (tree helper)
18613 /* This is a partial set of the operations done by finish_function()
18614 plus emitting the result. */
18615 set_cfun (NULL);
18616 current_function_decl = helper;
18617 begin_scope (sk_function_parms, NULL);
18618 store_parm_decls (DECL_ARGUMENTS (helper));
18619 announce_function (helper);
18620 allocate_struct_function (helper, false);
18621 cfun->language = ggc_cleared_alloc<language_function> ();
18622 poplevel (1, 0, 1);
18623 maybe_save_constexpr_fundef (helper);
18624 /* We must start each function with a clear fold cache. */
18625 clear_fold_cache ();
18626 cp_fold_function (helper);
18627 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
18628 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
18629 /* This function has coroutine IFNs that we should handle in middle
18630 end lowering. */
18631 cfun->coroutine_component = true;
18632 cp_genericize (helper);
18633 expand_or_defer_fn (helper);
18636 /* Finish up a function declaration and compile that function
18637 all the way to assembler language output. The free the storage
18638 for the function definition. INLINE_P is TRUE if we just
18639 finished processing the body of an in-class inline function
18640 definition. (This processing will have taken place after the
18641 class definition is complete.) */
18643 tree
18644 finish_function (bool inline_p)
18646 tree fndecl = current_function_decl;
18647 tree fntype, ctype = NULL_TREE;
18648 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18650 /* When we get some parse errors, we can end up without a
18651 current_function_decl, so cope. */
18652 if (fndecl == NULL_TREE || fndecl == error_mark_node)
18653 return error_mark_node;
18655 bool coro_p = (flag_coroutines
18656 && !processing_template_decl
18657 && DECL_COROUTINE_P (fndecl));
18658 bool coro_emit_helpers = false;
18659 bool do_contracts = (DECL_HAS_CONTRACTS_P (fndecl)
18660 && !processing_template_decl);
18662 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18663 finish_lambda_scope ();
18665 if (c_dialect_objc ())
18666 objc_finish_function ();
18668 record_key_method_defined (fndecl);
18670 fntype = TREE_TYPE (fndecl);
18672 /* TREE_READONLY (fndecl) = 1;
18673 This caused &foo to be of type ptr-to-const-function
18674 which then got a warning when stored in a ptr-to-function variable. */
18676 gcc_assert (building_stmt_list_p ());
18677 /* The current function is being defined, so its DECL_INITIAL should
18678 be set, and unless there's a multiple definition, it should be
18679 error_mark_node. */
18680 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18682 if (coro_p)
18684 /* Only try to emit the coroutine outlined helper functions if the
18685 transforms succeeded. Otherwise, treat errors in the same way as
18686 a regular function. */
18687 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
18689 /* We should handle coroutine IFNs in middle end lowering. */
18690 cfun->coroutine_component = true;
18692 /* Do not try to process the ramp's EH unless outlining succeeded. */
18693 if (coro_emit_helpers && use_eh_spec_block (fndecl))
18694 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18695 (TREE_TYPE (fndecl)),
18696 current_eh_spec_block);
18698 /* If outlining succeeded, then add contracts handling if needed. */
18699 if (coro_emit_helpers && do_contracts)
18700 maybe_apply_function_contracts (fndecl);
18702 else
18703 /* For a cloned function, we've already got all the code we need;
18704 there's no need to add any extra bits. */
18705 if (!DECL_CLONED_FUNCTION_P (fndecl))
18707 /* Make it so that `main' always returns 0 by default. */
18708 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18709 && !TREE_THIS_VOLATILE (current_function_decl))
18710 finish_return_stmt (integer_zero_node);
18712 if (use_eh_spec_block (current_function_decl))
18713 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18714 (TREE_TYPE (current_function_decl)),
18715 current_eh_spec_block);
18717 if (do_contracts)
18718 maybe_apply_function_contracts (current_function_decl);
18722 /* If we're saving up tree structure, tie off the function now. */
18723 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18725 finish_fname_decls ();
18727 /* This must come after expand_function_end because cleanups might
18728 have declarations (from inline functions) that need to go into
18729 this function's blocks. */
18731 /* If the current binding level isn't the outermost binding level
18732 for this function, either there is a bug, or we have experienced
18733 syntax errors and the statement tree is malformed. */
18734 if (current_binding_level->kind != sk_function_parms)
18736 /* Make sure we have already experienced errors. */
18737 gcc_assert (errorcount);
18739 /* Throw away the broken statement tree and extra binding
18740 levels. */
18741 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18743 while (current_binding_level->kind != sk_function_parms)
18745 if (current_binding_level->kind == sk_class)
18746 pop_nested_class ();
18747 else
18748 poplevel (0, 0, 0);
18751 poplevel (1, 0, 1);
18753 /* Statements should always be full-expressions at the outermost set
18754 of curly braces for a function. */
18755 gcc_assert (stmts_are_full_exprs_p ());
18757 /* If there are no return statements in a function with auto return type,
18758 the return type is void. But if the declared type is something like
18759 auto*, this is an error. */
18760 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18761 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18763 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18764 && !current_function_returns_value
18765 && !current_function_returns_null)
18767 /* We haven't applied return type deduction because we haven't
18768 seen any return statements. Do that now. */
18769 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18770 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18771 void_node, node, tf_warning_or_error,
18772 adc_return_type);
18774 apply_deduced_return_type (fndecl, void_type_node);
18775 fntype = TREE_TYPE (fndecl);
18777 else if (!current_function_returns_value
18778 && !current_function_returns_null)
18780 error ("no return statements in function returning %qT",
18781 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18782 inform (input_location, "only plain %<auto%> return type can be "
18783 "deduced to %<void%>");
18787 /* Remember that we were in class scope. */
18788 if (current_class_name)
18789 ctype = current_class_type;
18791 if (DECL_DELETED_FN (fndecl))
18793 DECL_INITIAL (fndecl) = error_mark_node;
18794 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18795 goto cleanup;
18798 // If this is a concept, check that the definition is reasonable.
18799 if (DECL_DECLARED_CONCEPT_P (fndecl))
18800 check_function_concept (fndecl);
18802 if (flag_openmp)
18803 if (tree attr = lookup_attribute ("omp declare variant base",
18804 DECL_ATTRIBUTES (fndecl)))
18805 omp_declare_variant_finalize (fndecl, attr);
18807 /* Complain if there's just no return statement. */
18808 if ((warn_return_type
18809 || (cxx_dialect >= cxx14
18810 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18811 && !VOID_TYPE_P (TREE_TYPE (fntype))
18812 && !dependent_type_p (TREE_TYPE (fntype))
18813 && !current_function_returns_value && !current_function_returns_null
18814 /* Don't complain if we abort or throw. */
18815 && !current_function_returns_abnormally
18816 /* Don't complain if there's an infinite loop. */
18817 && !current_function_infinite_loop
18818 /* Don't complain if we are declared noreturn. */
18819 && !TREE_THIS_VOLATILE (fndecl)
18820 && !DECL_NAME (DECL_RESULT (fndecl))
18821 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18822 /* Structor return values (if any) are set by the compiler. */
18823 && !DECL_CONSTRUCTOR_P (fndecl)
18824 && !DECL_DESTRUCTOR_P (fndecl)
18825 && targetm.warn_func_return (fndecl))
18827 gcc_rich_location richloc (input_location);
18828 /* Potentially add a "return *this;" fix-it hint for
18829 assignment operators. */
18830 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18832 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18833 if (TREE_CODE (valtype) == REFERENCE_TYPE
18834 && current_class_ref
18835 && same_type_ignoring_top_level_qualifiers_p
18836 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18837 && global_dc->option_enabled_p (OPT_Wreturn_type))
18838 add_return_star_this_fixit (&richloc, fndecl);
18840 if (cxx_dialect >= cxx14
18841 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18842 error_at (&richloc, "no return statement in %<constexpr%> function "
18843 "returning non-void");
18844 else if (warning_at (&richloc, OPT_Wreturn_type,
18845 "no return statement in function returning "
18846 "non-void"))
18847 suppress_warning (fndecl, OPT_Wreturn_type);
18850 /* Lambda closure members are implicitly constexpr if possible. */
18851 if (cxx_dialect >= cxx17
18852 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18853 DECL_DECLARED_CONSTEXPR_P (fndecl)
18854 = ((processing_template_decl
18855 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18856 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18858 /* Save constexpr function body before it gets munged by
18859 the NRV transformation. */
18860 maybe_save_constexpr_fundef (fndecl);
18862 /* Invoke the pre-genericize plugin before we start munging things. */
18863 if (!processing_template_decl)
18864 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18866 /* Perform delayed folding before NRV transformation. */
18867 if (!processing_template_decl
18868 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18869 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18870 cp_fold_function (fndecl);
18872 /* Set up the named return value optimization, if we can. Candidate
18873 variables are selected in check_return_expr. */
18874 if (tree r = current_function_return_value)
18876 if (r != error_mark_node)
18877 finalize_nrv (fndecl, r);
18878 current_function_return_value = NULL_TREE;
18881 /* Must mark the RESULT_DECL as being in this function. */
18882 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18884 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18885 to the FUNCTION_DECL node itself. */
18886 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18888 /* Store the end of the function, so that we get good line number
18889 info for the epilogue. */
18890 cfun->function_end_locus = input_location;
18892 /* Complain about parameters that are only set, but never otherwise used. */
18893 if (warn_unused_but_set_parameter
18894 && !processing_template_decl
18895 && errorcount == unused_but_set_errorcount
18896 && !DECL_CLONED_FUNCTION_P (fndecl))
18898 tree decl;
18900 for (decl = DECL_ARGUMENTS (fndecl);
18901 decl;
18902 decl = DECL_CHAIN (decl))
18903 if (TREE_USED (decl)
18904 && TREE_CODE (decl) == PARM_DECL
18905 && !DECL_READ_P (decl)
18906 && DECL_NAME (decl)
18907 && !DECL_ARTIFICIAL (decl)
18908 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18909 && !DECL_IN_SYSTEM_HEADER (decl)
18910 && TREE_TYPE (decl) != error_mark_node
18911 && !TYPE_REF_P (TREE_TYPE (decl))
18912 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18913 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18914 warning_at (DECL_SOURCE_LOCATION (decl),
18915 OPT_Wunused_but_set_parameter,
18916 "parameter %qD set but not used", decl);
18917 unused_but_set_errorcount = errorcount;
18920 /* Complain about locally defined typedefs that are not used in this
18921 function. */
18922 maybe_warn_unused_local_typedefs ();
18924 /* Possibly warn about unused parameters. */
18925 if (warn_unused_parameter
18926 && !processing_template_decl
18927 && !DECL_CLONED_FUNCTION_P (fndecl))
18928 do_warn_unused_parameter (fndecl);
18930 /* Genericize before inlining. */
18931 if (!processing_template_decl
18932 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18933 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18934 cp_genericize (fndecl);
18936 /* If this function can't throw any exceptions, remember that. */
18937 if (!processing_template_decl
18938 && !cp_function_chain->can_throw
18939 && !flag_non_call_exceptions
18940 && !decl_replaceable_p (fndecl,
18941 opt_for_fn (fndecl, flag_semantic_interposition)))
18942 TREE_NOTHROW (fndecl) = 1;
18944 /* Emit the resumer and destroyer functions now, providing that we have
18945 not encountered some fatal error. */
18946 if (coro_emit_helpers)
18948 emit_coro_helper (resumer);
18949 emit_coro_helper (destroyer);
18952 cleanup:
18953 /* We're leaving the context of this function, so zap cfun. It's still in
18954 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18955 set_cfun (NULL);
18956 current_function_decl = NULL;
18958 /* If this is an in-class inline definition, we may have to pop the
18959 bindings for the template parameters that we added in
18960 maybe_begin_member_template_processing when start_function was
18961 called. */
18962 if (inline_p)
18963 maybe_end_member_template_processing ();
18965 /* Leave the scope of the class. */
18966 if (ctype)
18967 pop_nested_class ();
18969 --function_depth;
18971 /* Clean up. */
18972 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18974 /* If we have used outlined contracts checking functions, build and emit
18975 them here. */
18976 finish_function_contracts (fndecl);
18978 return fndecl;
18981 /* Create the FUNCTION_DECL for a function definition.
18982 DECLSPECS and DECLARATOR are the parts of the declaration;
18983 they describe the return type and the name of the function,
18984 but twisted together in a fashion that parallels the syntax of C.
18986 This function creates a binding context for the function body
18987 as well as setting up the FUNCTION_DECL in current_function_decl.
18989 Returns a FUNCTION_DECL on success.
18991 If the DECLARATOR is not suitable for a function (it defines a datum
18992 instead), we return 0, which tells yyparse to report a parse error.
18994 May return void_type_node indicating that this method is actually
18995 a friend. See grokfield for more details.
18997 Came here with a `.pushlevel' .
18999 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
19000 CHANGES TO CODE IN `grokfield'. */
19002 tree
19003 grokmethod (cp_decl_specifier_seq *declspecs,
19004 const cp_declarator *declarator, tree attrlist)
19006 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
19007 &attrlist);
19009 if (fndecl == error_mark_node)
19010 return error_mark_node;
19012 if (attrlist)
19013 cplus_decl_attributes (&fndecl, attrlist, 0);
19015 /* Pass friends other than inline friend functions back. */
19016 if (fndecl == void_type_node)
19017 return fndecl;
19019 if (DECL_IN_AGGR_P (fndecl))
19021 if (DECL_CLASS_SCOPE_P (fndecl))
19022 error ("%qD is already defined in class %qT", fndecl,
19023 DECL_CONTEXT (fndecl));
19024 return error_mark_node;
19027 check_template_shadow (fndecl);
19029 /* p1779 ABI-Isolation makes inline not a default for in-class
19030 definitions attached to a named module. If the user explicitly
19031 made it inline, grokdeclarator will already have done the right
19032 things. */
19033 if ((!named_module_attach_p ()
19034 || flag_module_implicit_inline
19035 /* Lambda's operator function remains inline. */
19036 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
19037 /* If the user explicitly asked for this to be inline, we don't
19038 need to do more, but more importantly we want to warn if we
19039 can't inline it. */
19040 && !DECL_DECLARED_INLINE_P (fndecl))
19042 if (TREE_PUBLIC (fndecl))
19043 DECL_COMDAT (fndecl) = 1;
19044 DECL_DECLARED_INLINE_P (fndecl) = 1;
19045 /* It's ok if we can't inline this. */
19046 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
19049 /* We process method specializations in finish_struct_1. */
19050 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
19052 /* Avoid calling decl_spec_seq... until we have to. */
19053 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
19054 fndecl = push_template_decl (fndecl, friendp);
19055 if (fndecl == error_mark_node)
19056 return fndecl;
19059 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
19061 fndecl = copy_node (fndecl);
19062 TREE_CHAIN (fndecl) = NULL_TREE;
19065 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
19067 DECL_IN_AGGR_P (fndecl) = 1;
19068 return fndecl;
19072 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
19073 we can lay it out later, when and if its type becomes complete.
19075 Also handle constexpr variables where the initializer involves
19076 an unlowered PTRMEM_CST because the class isn't complete yet. */
19078 void
19079 maybe_register_incomplete_var (tree var)
19081 gcc_assert (VAR_P (var));
19083 /* Keep track of variables with incomplete types. */
19084 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
19085 && DECL_EXTERNAL (var))
19087 tree inner_type = TREE_TYPE (var);
19089 while (TREE_CODE (inner_type) == ARRAY_TYPE)
19090 inner_type = TREE_TYPE (inner_type);
19091 inner_type = TYPE_MAIN_VARIANT (inner_type);
19093 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
19094 /* RTTI TD entries are created while defining the type_info. */
19095 || (TYPE_LANG_SPECIFIC (inner_type)
19096 && TYPE_BEING_DEFINED (inner_type)))
19098 incomplete_var iv = {var, inner_type};
19099 vec_safe_push (incomplete_vars, iv);
19101 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
19102 && DECL_CLASS_SCOPE_P (var)
19103 && TYPE_BEING_DEFINED (DECL_CONTEXT (var))
19104 && decl_constant_var_p (var)
19105 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
19107 /* When the outermost open class is complete we can resolve any
19108 pointers-to-members. */
19109 tree context = outermost_open_class ();
19110 incomplete_var iv = {var, context};
19111 vec_safe_push (incomplete_vars, iv);
19116 /* Called when a class type (given by TYPE) is defined. If there are
19117 any existing VAR_DECLs whose type has been completed by this
19118 declaration, update them now. */
19120 void
19121 complete_vars (tree type)
19123 unsigned ix;
19124 incomplete_var *iv;
19126 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
19128 if (same_type_p (type, iv->incomplete_type))
19130 tree var = iv->decl;
19131 tree type = TREE_TYPE (var);
19133 if (type != error_mark_node
19134 && (TYPE_MAIN_VARIANT (strip_array_types (type))
19135 == iv->incomplete_type))
19137 /* Complete the type of the variable. */
19138 complete_type (type);
19139 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
19140 if (COMPLETE_TYPE_P (type))
19141 layout_var_decl (var);
19144 /* Remove this entry from the list. */
19145 incomplete_vars->unordered_remove (ix);
19147 else
19148 ix++;
19152 /* If DECL is of a type which needs a cleanup, build and return an
19153 expression to perform that cleanup here. Return NULL_TREE if no
19154 cleanup need be done. DECL can also be a _REF when called from
19155 split_nonconstant_init_1. */
19157 tree
19158 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
19160 tree type;
19161 tree attr;
19162 tree cleanup;
19164 /* Assume no cleanup is required. */
19165 cleanup = NULL_TREE;
19167 if (error_operand_p (decl))
19168 return cleanup;
19170 /* Handle "__attribute__((cleanup))". We run the cleanup function
19171 before the destructor since the destructor is what actually
19172 terminates the lifetime of the object. */
19173 if (DECL_P (decl))
19174 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
19175 else
19176 attr = NULL_TREE;
19177 if (attr)
19179 tree id;
19180 tree fn;
19181 tree arg;
19183 /* Get the name specified by the user for the cleanup function. */
19184 id = TREE_VALUE (TREE_VALUE (attr));
19185 /* Look up the name to find the cleanup function to call. It is
19186 important to use lookup_name here because that is what is
19187 used in c-common.cc:handle_cleanup_attribute when performing
19188 initial checks on the attribute. Note that those checks
19189 include ensuring that the function found is not an overloaded
19190 function, or an object with an overloaded call operator,
19191 etc.; we can rely on the fact that the function found is an
19192 ordinary FUNCTION_DECL. */
19193 fn = lookup_name (id);
19194 arg = build_address (decl);
19195 if (!mark_used (decl, complain) && !(complain & tf_error))
19196 return error_mark_node;
19197 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
19198 if (cleanup == error_mark_node)
19199 return error_mark_node;
19201 /* Handle ordinary C++ destructors. */
19202 type = TREE_TYPE (decl);
19203 if (type_build_dtor_call (type))
19205 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
19206 tree addr;
19207 tree call;
19209 if (TREE_CODE (type) == ARRAY_TYPE)
19210 addr = decl;
19211 else
19212 addr = build_address (decl);
19214 call = build_delete (input_location, TREE_TYPE (addr), addr,
19215 sfk_complete_destructor, flags, 0, complain);
19216 if (call == error_mark_node)
19217 cleanup = error_mark_node;
19218 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
19219 /* Discard the call. */;
19220 else if (decl_maybe_constant_destruction (decl, type)
19221 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
19222 cxx_constant_dtor (call, decl);
19223 else if (cleanup)
19224 cleanup = cp_build_compound_expr (cleanup, call, complain);
19225 else
19226 cleanup = call;
19229 /* build_delete sets the location of the destructor call to the
19230 current location, even though the destructor is going to be
19231 called later, at the end of the current scope. This can lead to
19232 a "jumpy" behavior for users of debuggers when they step around
19233 the end of the block. So let's unset the location of the
19234 destructor call instead. */
19235 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
19236 if (cleanup && CONVERT_EXPR_P (cleanup))
19237 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
19239 if (cleanup
19240 && DECL_P (decl)
19241 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
19242 /* Treat objects with destructors as used; the destructor may do
19243 something substantive. */
19244 && !mark_used (decl, complain) && !(complain & tf_error))
19245 return error_mark_node;
19247 if (cleanup && cfun && !processing_template_decl
19248 && !expr_noexcept_p (cleanup, tf_none))
19249 cp_function_chain->throwing_cleanup = true;
19251 return cleanup;
19255 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
19256 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
19257 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
19259 tree
19260 static_fn_type (tree memfntype)
19262 tree fntype;
19263 tree args;
19265 if (TYPE_PTRMEMFUNC_P (memfntype))
19266 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
19267 if (INDIRECT_TYPE_P (memfntype)
19268 || TREE_CODE (memfntype) == FUNCTION_DECL)
19269 memfntype = TREE_TYPE (memfntype);
19270 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
19271 return memfntype;
19272 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
19273 args = TYPE_ARG_TYPES (memfntype);
19274 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
19275 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
19276 fntype = (cp_build_type_attribute_variant
19277 (fntype, TYPE_ATTRIBUTES (memfntype)));
19278 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
19279 return fntype;
19282 /* DECL was originally constructed as a non-static member function,
19283 but turned out to be static. Update it accordingly. */
19285 void
19286 revert_static_member_fn (tree decl)
19288 tree stype = static_fn_type (decl);
19289 cp_cv_quals quals = type_memfn_quals (stype);
19290 cp_ref_qualifier rqual = type_memfn_rqual (stype);
19292 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
19293 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
19295 TREE_TYPE (decl) = stype;
19297 if (DECL_ARGUMENTS (decl))
19298 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
19299 DECL_STATIC_FUNCTION_P (decl) = 1;
19302 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
19303 one of the language-independent trees. */
19305 enum cp_tree_node_structure_enum
19306 cp_tree_node_structure (union lang_tree_node * t)
19308 switch (TREE_CODE (&t->generic))
19310 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
19311 case BASELINK: return TS_CP_BASELINK;
19312 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
19313 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
19314 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
19315 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
19316 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
19317 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
19318 case OVERLOAD: return TS_CP_OVERLOAD;
19319 case PTRMEM_CST: return TS_CP_PTRMEM;
19320 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
19321 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
19322 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
19323 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
19324 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
19325 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
19326 default: return TS_CP_GENERIC;
19330 bool
19331 cp_missing_noreturn_ok_p (tree decl)
19333 /* A missing noreturn is ok for the `main' function. */
19334 return DECL_MAIN_P (decl);
19337 /* Return the decl used to identify the COMDAT group into which DECL should
19338 be placed. */
19340 tree
19341 cxx_comdat_group (tree decl)
19343 /* Virtual tables, construction virtual tables, and virtual table
19344 tables all go in a single COMDAT group, named after the primary
19345 virtual table. */
19346 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
19347 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
19348 /* For all other DECLs, the COMDAT group is the mangled name of the
19349 declaration itself. */
19350 else
19352 while (DECL_THUNK_P (decl))
19354 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
19355 into the same section as the target function. In that case
19356 we must return target's name. */
19357 tree target = THUNK_TARGET (decl);
19358 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
19359 && DECL_SECTION_NAME (target) != NULL
19360 && DECL_ONE_ONLY (target))
19361 decl = target;
19362 else
19363 break;
19365 /* If a ctor/dtor has already set the comdat group by
19366 maybe_clone_body, don't override it. */
19367 if (SUPPORTS_ONE_ONLY
19368 && TREE_CODE (decl) == FUNCTION_DECL
19369 && DECL_CLONED_FUNCTION_P (decl))
19370 if (tree comdat = DECL_COMDAT_GROUP (decl))
19371 return comdat;
19374 return decl;
19377 /* Returns the return type for FN as written by the user, which may include
19378 a placeholder for a deduced return type. */
19380 tree
19381 fndecl_declared_return_type (tree fn)
19383 fn = STRIP_TEMPLATE (fn);
19384 if (FNDECL_USED_AUTO (fn))
19385 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
19387 return TREE_TYPE (TREE_TYPE (fn));
19390 /* Returns true iff DECL is a variable or function declared with an auto type
19391 that has not yet been deduced to a real type. */
19393 bool
19394 undeduced_auto_decl (tree decl)
19396 if (cxx_dialect < cxx11)
19397 return false;
19398 STRIP_ANY_LOCATION_WRAPPER (decl);
19399 return ((VAR_OR_FUNCTION_DECL_P (decl)
19400 || TREE_CODE (decl) == TEMPLATE_DECL)
19401 && type_uses_auto (TREE_TYPE (decl)));
19404 /* Complain if DECL has an undeduced return type. */
19406 bool
19407 require_deduced_type (tree decl, tsubst_flags_t complain)
19409 if (undeduced_auto_decl (decl))
19411 if (TREE_CODE (decl) == FUNCTION_DECL
19412 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
19413 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
19415 /* Set the return type of __builtin_source_location. */
19416 tree type = get_source_location_impl_type ();
19417 if (type == error_mark_node)
19419 inform (input_location, "using %qs", "__builtin_source_location");
19420 return false;
19422 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
19423 type = build_pointer_type (type);
19424 apply_deduced_return_type (decl, type);
19425 return true;
19428 if (warning_suppressed_p (decl) && seen_error ())
19429 /* We probably already complained about deduction failure. */;
19430 else if (complain & tf_error)
19431 error ("use of %qD before deduction of %<auto%>", decl);
19432 note_failed_type_completion_for_satisfaction (decl);
19433 return false;
19435 return true;
19438 /* Create a representation of the explicit-specifier with
19439 constant-expression of EXPR. COMPLAIN is as for tsubst. */
19441 tree
19442 build_explicit_specifier (tree expr, tsubst_flags_t complain)
19444 if (check_for_bare_parameter_packs (expr))
19445 return error_mark_node;
19447 if (instantiation_dependent_expression_p (expr))
19448 /* Wait for instantiation, tsubst_function_decl will handle it. */
19449 return expr;
19451 expr = build_converted_constant_bool_expr (expr, complain);
19452 expr = instantiate_non_dependent_expr (expr, complain);
19453 expr = cxx_constant_value (expr, complain);
19454 return expr;
19457 #include "gt-cp-decl.h"