ada: Fix infinite loop with multiple limited with clauses
[official-gcc.git] / gcc / cp / decl.cc
blob255c4026bdbdf565ca5ecab1bc2f9df114ceb103
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2023 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 (void);
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*);
109 /* The following symbols are subsumed in the cp_global_trees array, and
110 listed here individually for documentation purposes.
112 C++ extensions
113 tree wchar_decl_node;
115 tree vtable_entry_type;
116 tree delta_type_node;
117 tree __t_desc_type_node;
119 tree class_type_node;
120 tree unknown_type_node;
122 Array type `vtable_entry_type[]'
124 tree vtbl_type_node;
125 tree vtbl_ptr_type_node;
127 Namespaces,
129 tree std_node;
130 tree abi_node;
132 A FUNCTION_DECL which can call `abort'. Not necessarily the
133 one that the user will declare, but sufficient to be called
134 by routines that want to abort the program.
136 tree abort_fndecl;
138 Used by RTTI
139 tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
140 tree tinfo_var_id; */
142 tree cp_global_trees[CPTI_MAX];
144 /* A list of objects which have constructors or destructors
145 which reside in namespace scope. The decl is stored in
146 the TREE_VALUE slot and the initializer is stored
147 in the TREE_PURPOSE slot. */
148 tree static_aggregates;
150 /* Like static_aggregates, but for thread_local variables. */
151 tree tls_aggregates;
153 /* A hash-map mapping from variable decls to the dynamic initializer for
154 the decl. This is currently only used by OpenMP. */
155 decl_tree_map *dynamic_initializers;
157 /* -- end of C++ */
159 /* A node for the integer constant 2. */
161 tree integer_two_node;
163 /* vector of static decls. */
164 vec<tree, va_gc> *static_decls;
166 /* vector of keyed classes. */
167 vec<tree, va_gc> *keyed_classes;
169 /* Used only for jumps to as-yet undefined labels, since jumps to
170 defined labels can have their validity checked immediately. */
172 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
173 struct named_label_use_entry *next;
174 /* The binding level to which this entry is *currently* attached.
175 This is initially the binding level in which the goto appeared,
176 but is modified as scopes are closed. */
177 cp_binding_level *binding_level;
178 /* The head of the names list that was current when the goto appeared,
179 or the inner scope popped. These are the decls that will *not* be
180 skipped when jumping to the label. */
181 tree names_in_scope;
182 /* The location of the goto, for error reporting. */
183 location_t o_goto_locus;
184 /* True if an OpenMP structured block scope has been closed since
185 the goto appeared. This means that the branch from the label will
186 illegally exit an OpenMP scope. */
187 bool in_omp_scope;
190 /* A list of all LABEL_DECLs in the function that have names. Here so
191 we can clear out their names' definitions at the end of the
192 function, and so we can check the validity of jumps to these labels. */
194 struct GTY((for_user)) named_label_entry {
196 tree name; /* Name of decl. */
198 tree label_decl; /* LABEL_DECL, unless deleted local label. */
200 named_label_entry *outer; /* Outer shadowed chain. */
202 /* The binding level to which the label is *currently* attached.
203 This is initially set to the binding level in which the label
204 is defined, but is modified as scopes are closed. */
205 cp_binding_level *binding_level;
207 /* The head of the names list that was current when the label was
208 defined, or the inner scope popped. These are the decls that will
209 be skipped when jumping to the label. */
210 tree names_in_scope;
212 /* A vector of all decls from all binding levels that would be
213 crossed by a backward branch to the label. */
214 vec<tree, va_gc> *bad_decls;
216 /* A list of uses of the label, before the label is defined. */
217 named_label_use_entry *uses;
219 /* The following bits are set after the label is defined, and are
220 updated as scopes are popped. They indicate that a jump to the
221 label will illegally enter a scope of the given flavor. */
222 bool in_try_scope;
223 bool in_catch_scope;
224 bool in_omp_scope;
225 bool in_transaction_scope;
226 bool in_constexpr_if;
227 bool in_consteval_if;
228 bool in_stmt_expr;
231 #define named_labels cp_function_chain->x_named_labels
233 /* The number of function bodies which we are currently processing.
234 (Zero if we are at namespace scope, one inside the body of a
235 function, two inside the body of a function in a local class, etc.) */
236 int function_depth;
238 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
239 bool flag_noexcept_type;
241 /* States indicating how grokdeclarator() should handle declspecs marked
242 with __attribute__((deprecated)). An object declared as
243 __attribute__((deprecated)) suppresses warnings of uses of other
244 deprecated items. */
245 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
248 /* A list of VAR_DECLs whose type was incomplete at the time the
249 variable was declared. */
251 struct GTY(()) incomplete_var {
252 tree decl;
253 tree incomplete_type;
257 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
259 /* Returns the kind of template specialization we are currently
260 processing, given that it's declaration contained N_CLASS_SCOPES
261 explicit scope qualifications. */
263 tmpl_spec_kind
264 current_tmpl_spec_kind (int n_class_scopes)
266 int n_template_parm_scopes = 0;
267 int seen_specialization_p = 0;
268 int innermost_specialization_p = 0;
269 cp_binding_level *b;
271 /* Scan through the template parameter scopes. */
272 for (b = current_binding_level;
273 b->kind == sk_template_parms;
274 b = b->level_chain)
276 /* If we see a specialization scope inside a parameter scope,
277 then something is wrong. That corresponds to a declaration
278 like:
280 template <class T> template <> ...
282 which is always invalid since [temp.expl.spec] forbids the
283 specialization of a class member template if the enclosing
284 class templates are not explicitly specialized as well. */
285 if (b->explicit_spec_p)
287 if (n_template_parm_scopes == 0)
288 innermost_specialization_p = 1;
289 else
290 seen_specialization_p = 1;
292 else if (seen_specialization_p == 1)
293 return tsk_invalid_member_spec;
295 ++n_template_parm_scopes;
298 /* Handle explicit instantiations. */
299 if (processing_explicit_instantiation)
301 if (n_template_parm_scopes != 0)
302 /* We've seen a template parameter list during an explicit
303 instantiation. For example:
305 template <class T> template void f(int);
307 This is erroneous. */
308 return tsk_invalid_expl_inst;
309 else
310 return tsk_expl_inst;
313 if (n_template_parm_scopes < n_class_scopes)
314 /* We've not seen enough template headers to match all the
315 specialized classes present. For example:
317 template <class T> void R<T>::S<T>::f(int);
319 This is invalid; there needs to be one set of template
320 parameters for each class. */
321 return tsk_insufficient_parms;
322 else if (n_template_parm_scopes == n_class_scopes)
323 /* We're processing a non-template declaration (even though it may
324 be a member of a template class.) For example:
326 template <class T> void S<T>::f(int);
328 The `class T' matches the `S<T>', leaving no template headers
329 corresponding to the `f'. */
330 return tsk_none;
331 else if (n_template_parm_scopes > n_class_scopes + 1)
332 /* We've got too many template headers. For example:
334 template <> template <class T> void f (T);
336 There need to be more enclosing classes. */
337 return tsk_excessive_parms;
338 else
339 /* This must be a template. It's of the form:
341 template <class T> template <class U> void S<T>::f(U);
343 This is a specialization if the innermost level was a
344 specialization; otherwise it's just a definition of the
345 template. */
346 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
349 /* Exit the current scope. */
351 void
352 finish_scope (void)
354 poplevel (0, 0, 0);
357 /* When a label goes out of scope, check to see if that label was used
358 in a valid manner, and issue any appropriate warnings or errors. */
360 static void
361 check_label_used (tree label)
363 if (!processing_template_decl)
365 if (DECL_INITIAL (label) == NULL_TREE)
367 location_t location;
369 error ("label %q+D used but not defined", label);
370 location = input_location;
371 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
372 /* Avoid crashing later. */
373 define_label (location, DECL_NAME (label));
375 else
376 warn_for_unused_label (label);
380 /* Helper function to sort named label entries in a vector by DECL_UID. */
382 static int
383 sort_labels (const void *a, const void *b)
385 tree label1 = *(tree const *) a;
386 tree label2 = *(tree const *) b;
388 /* DECL_UIDs can never be equal. */
389 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
392 /* At the end of a function, all labels declared within the function
393 go out of scope. BLOCK is the top-level block for the
394 function. */
396 static void
397 pop_labels (tree block)
399 if (!named_labels)
400 return;
402 /* We need to add the labels to the block chain, so debug
403 information is emitted. But, we want the order to be stable so
404 need to sort them first. Otherwise the debug output could be
405 randomly ordered. I guess it's mostly stable, unless the hash
406 table implementation changes. */
407 auto_vec<tree, 32> labels (named_labels->elements ());
408 hash_table<named_label_hash>::iterator end (named_labels->end ());
409 for (hash_table<named_label_hash>::iterator iter
410 (named_labels->begin ()); iter != end; ++iter)
412 named_label_entry *ent = *iter;
414 gcc_checking_assert (!ent->outer);
415 if (ent->label_decl)
416 labels.quick_push (ent->label_decl);
417 ggc_free (ent);
419 named_labels = NULL;
420 labels.qsort (sort_labels);
422 while (labels.length ())
424 tree label = labels.pop ();
426 DECL_CHAIN (label) = BLOCK_VARS (block);
427 BLOCK_VARS (block) = label;
429 check_label_used (label);
433 /* At the end of a block with local labels, restore the outer definition. */
435 static void
436 pop_local_label (tree id, tree label)
438 check_label_used (label);
439 named_label_entry **slot = named_labels->find_slot_with_hash
440 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
441 named_label_entry *ent = *slot;
443 if (ent->outer)
444 ent = ent->outer;
445 else
447 ent = ggc_cleared_alloc<named_label_entry> ();
448 ent->name = id;
450 *slot = ent;
453 /* The following two routines are used to interface to Objective-C++.
454 The binding level is purposely treated as an opaque type. */
456 void *
457 objc_get_current_scope (void)
459 return current_binding_level;
462 /* The following routine is used by the NeXT-style SJLJ exceptions;
463 variables get marked 'volatile' so as to not be clobbered by
464 _setjmp()/_longjmp() calls. All variables in the current scope,
465 as well as parent scopes up to (but not including) ENCLOSING_BLK
466 shall be thusly marked. */
468 void
469 objc_mark_locals_volatile (void *enclosing_blk)
471 cp_binding_level *scope;
473 for (scope = current_binding_level;
474 scope && scope != enclosing_blk;
475 scope = scope->level_chain)
477 tree decl;
479 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
480 objc_volatilize_decl (decl);
482 /* Do not climb up past the current function. */
483 if (scope->kind == sk_function_parms)
484 break;
488 /* True if B is the level for the condition of a constexpr if. */
490 static bool
491 level_for_constexpr_if (cp_binding_level *b)
493 return (b->kind == sk_cond && b->this_entity
494 && TREE_CODE (b->this_entity) == IF_STMT
495 && IF_STMT_CONSTEXPR_P (b->this_entity));
498 /* True if B is the level for the condition of a consteval if. */
500 static bool
501 level_for_consteval_if (cp_binding_level *b)
503 return (b->kind == sk_cond && b->this_entity
504 && TREE_CODE (b->this_entity) == IF_STMT
505 && IF_STMT_CONSTEVAL_P (b->this_entity));
508 /* Update data for defined and undefined labels when leaving a scope. */
511 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
513 named_label_entry *ent = *slot;
514 cp_binding_level *obl = bl->level_chain;
516 if (ent->binding_level == bl)
518 tree decl;
520 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
521 TREE_LISTs representing OVERLOADs, so be careful. */
522 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
523 ? DECL_CHAIN (decl)
524 : TREE_CHAIN (decl)))
525 if (decl_jump_unsafe (decl))
526 vec_safe_push (ent->bad_decls, decl);
528 ent->binding_level = obl;
529 ent->names_in_scope = obl->names;
530 switch (bl->kind)
532 case sk_try:
533 ent->in_try_scope = true;
534 break;
535 case sk_catch:
536 ent->in_catch_scope = true;
537 break;
538 case sk_omp:
539 ent->in_omp_scope = true;
540 break;
541 case sk_transaction:
542 ent->in_transaction_scope = true;
543 break;
544 case sk_stmt_expr:
545 ent->in_stmt_expr = true;
546 break;
547 case sk_block:
548 if (level_for_constexpr_if (bl->level_chain))
549 ent->in_constexpr_if = true;
550 else if (level_for_consteval_if (bl->level_chain))
551 ent->in_consteval_if = true;
552 break;
553 default:
554 break;
557 else if (ent->uses)
559 struct named_label_use_entry *use;
561 for (use = ent->uses; use ; use = use->next)
562 if (use->binding_level == bl)
564 use->binding_level = obl;
565 use->names_in_scope = obl->names;
566 if (bl->kind == sk_omp)
567 use->in_omp_scope = true;
571 return 1;
574 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
575 when errors were reported, except for -Werror-unused-but-set-*. */
576 static int unused_but_set_errorcount;
578 /* Exit a binding level.
579 Pop the level off, and restore the state of the identifier-decl mappings
580 that were in effect when this level was entered.
582 If KEEP == 1, this level had explicit declarations, so
583 and create a "block" (a BLOCK node) for the level
584 to record its declarations and subblocks for symbol table output.
586 If FUNCTIONBODY is nonzero, this level is the body of a function,
587 so create a block as if KEEP were set and also clear out all
588 label names.
590 If REVERSE is nonzero, reverse the order of decls before putting
591 them into the BLOCK. */
593 tree
594 poplevel (int keep, int reverse, int functionbody)
596 tree link;
597 /* The chain of decls was accumulated in reverse order.
598 Put it into forward order, just for cleanliness. */
599 tree decls;
600 tree subblocks;
601 tree block;
602 tree decl;
603 scope_kind kind;
605 auto_cond_timevar tv (TV_NAME_LOOKUP);
606 restart:
608 block = NULL_TREE;
610 gcc_assert (current_binding_level->kind != sk_class
611 && current_binding_level->kind != sk_namespace);
613 if (current_binding_level->kind == sk_cleanup)
614 functionbody = 0;
615 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
617 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
619 /* We used to use KEEP == 2 to indicate that the new block should go
620 at the beginning of the list of blocks at this binding level,
621 rather than the end. This hack is no longer used. */
622 gcc_assert (keep == 0 || keep == 1);
624 if (current_binding_level->keep)
625 keep = 1;
627 /* Any uses of undefined labels, and any defined labels, now operate
628 under constraints of next binding contour. */
629 if (cfun && !functionbody && named_labels)
630 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
631 (current_binding_level);
633 /* Get the decls in the order they were written.
634 Usually current_binding_level->names is in reverse order.
635 But parameter decls were previously put in forward order. */
637 decls = current_binding_level->names;
638 if (reverse)
640 decls = nreverse (decls);
641 current_binding_level->names = decls;
644 /* If there were any declarations or structure tags in that level,
645 or if this level is a function body,
646 create a BLOCK to record them for the life of this function. */
647 block = NULL_TREE;
648 /* Avoid function body block if possible. */
649 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
650 keep = 0;
651 else if (keep == 1 || functionbody)
652 block = make_node (BLOCK);
653 if (block != NULL_TREE)
655 BLOCK_VARS (block) = decls;
656 BLOCK_SUBBLOCKS (block) = subblocks;
659 /* In each subblock, record that this is its superior. */
660 if (keep >= 0)
661 for (link = subblocks; link; link = BLOCK_CHAIN (link))
662 BLOCK_SUPERCONTEXT (link) = block;
664 /* Before we remove the declarations first check for unused variables. */
665 if ((warn_unused_variable || warn_unused_but_set_variable)
666 && current_binding_level->kind != sk_template_parms
667 && !processing_template_decl)
668 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
670 /* There are cases where D itself is a TREE_LIST. See in
671 push_local_binding where the list of decls returned by
672 getdecls is built. */
673 decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
675 tree type = TREE_TYPE (decl);
676 if (VAR_P (decl)
677 && (! TREE_USED (decl) || !DECL_READ_P (decl))
678 && ! DECL_IN_SYSTEM_HEADER (decl)
679 /* For structured bindings, consider only real variables, not
680 subobjects. */
681 && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
682 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
683 && type != error_mark_node
684 && (!CLASS_TYPE_P (type)
685 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
686 || lookup_attribute ("warn_unused",
687 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
689 if (! TREE_USED (decl))
691 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
692 warning_at (DECL_SOURCE_LOCATION (decl),
693 OPT_Wunused_variable,
694 "unused structured binding declaration");
695 else
696 warning_at (DECL_SOURCE_LOCATION (decl),
697 OPT_Wunused_variable, "unused variable %qD", decl);
698 suppress_warning (decl, OPT_Wunused_variable);
700 else if (DECL_CONTEXT (decl) == current_function_decl
701 // For -Wunused-but-set-variable leave references alone.
702 && !TYPE_REF_P (TREE_TYPE (decl))
703 && errorcount == unused_but_set_errorcount)
705 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
706 warning_at (DECL_SOURCE_LOCATION (decl),
707 OPT_Wunused_but_set_variable, "structured "
708 "binding declaration set but not used");
709 else
710 warning_at (DECL_SOURCE_LOCATION (decl),
711 OPT_Wunused_but_set_variable,
712 "variable %qD set but not used", decl);
713 unused_but_set_errorcount = errorcount;
718 /* Remove declarations for all the DECLs in this level. */
719 for (link = decls; link; link = TREE_CHAIN (link))
721 tree name;
722 if (TREE_CODE (link) == TREE_LIST)
724 decl = TREE_VALUE (link);
725 name = TREE_PURPOSE (link);
726 gcc_checking_assert (name);
728 else
730 decl = link;
731 name = DECL_NAME (decl);
734 /* Remove the binding. */
735 if (TREE_CODE (decl) == LABEL_DECL)
736 pop_local_label (name, decl);
737 else
738 pop_local_binding (name, decl);
741 /* Restore the IDENTIFIER_TYPE_VALUEs. */
742 for (link = current_binding_level->type_shadowed;
743 link; link = TREE_CHAIN (link))
744 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
746 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
747 list if a `using' declaration put them there. The debugging
748 back ends won't understand OVERLOAD, so we remove them here.
749 Because the BLOCK_VARS are (temporarily) shared with
750 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
751 popped all the bindings. Also remove undeduced 'auto' decls,
752 which LTO doesn't understand, and can't have been used by anything. */
753 if (block)
755 tree* d;
757 for (d = &BLOCK_VARS (block); *d; )
759 if (TREE_CODE (*d) == TREE_LIST
760 || (!processing_template_decl
761 && undeduced_auto_decl (*d)))
762 *d = TREE_CHAIN (*d);
763 else
764 d = &DECL_CHAIN (*d);
768 /* If the level being exited is the top level of a function,
769 check over all the labels. */
770 if (functionbody)
772 if (block)
774 /* Since this is the top level block of a function, the vars are
775 the function's parameters. Don't leave them in the BLOCK
776 because they are found in the FUNCTION_DECL instead. */
777 BLOCK_VARS (block) = 0;
778 pop_labels (block);
780 else
781 pop_labels (subblocks);
784 kind = current_binding_level->kind;
785 if (kind == sk_cleanup)
787 tree stmt;
789 /* If this is a temporary binding created for a cleanup, then we'll
790 have pushed a statement list level. Pop that, create a new
791 BIND_EXPR for the block, and insert it into the stream. */
792 stmt = pop_stmt_list (current_binding_level->statement_list);
793 stmt = c_build_bind_expr (input_location, block, stmt);
794 add_stmt (stmt);
797 leave_scope ();
798 if (functionbody)
800 /* The current function is being defined, so its DECL_INITIAL
801 should be error_mark_node. */
802 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
803 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
804 if (subblocks)
806 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
808 if (BLOCK_SUBBLOCKS (subblocks))
809 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
811 else
812 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
815 else if (block)
816 current_binding_level->blocks
817 = block_chainon (current_binding_level->blocks, block);
819 /* If we did not make a block for the level just exited,
820 any blocks made for inner levels
821 (since they cannot be recorded as subblocks in that level)
822 must be carried forward so they will later become subblocks
823 of something else. */
824 else if (subblocks)
825 current_binding_level->blocks
826 = block_chainon (current_binding_level->blocks, subblocks);
828 /* Each and every BLOCK node created here in `poplevel' is important
829 (e.g. for proper debugging information) so if we created one
830 earlier, mark it as "used". */
831 if (block)
832 TREE_USED (block) = 1;
834 /* All temporary bindings created for cleanups are popped silently. */
835 if (kind == sk_cleanup)
836 goto restart;
838 return block;
841 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
842 /* Diagnose odr-used extern inline variables without definitions
843 in the current TU. */
846 wrapup_namespace_globals ()
848 if (vec<tree, va_gc> *statics = static_decls)
850 for (tree decl : *statics)
852 if (warn_unused_function
853 && TREE_CODE (decl) == FUNCTION_DECL
854 && DECL_INITIAL (decl) == 0
855 && DECL_EXTERNAL (decl)
856 && !TREE_PUBLIC (decl)
857 && !DECL_ARTIFICIAL (decl)
858 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
859 && !warning_suppressed_p (decl, OPT_Wunused_function))
860 warning_at (DECL_SOURCE_LOCATION (decl),
861 OPT_Wunused_function,
862 "%qF declared %<static%> but never defined", decl);
864 if (VAR_P (decl)
865 && DECL_EXTERNAL (decl)
866 && DECL_INLINE_VAR_P (decl)
867 && DECL_ODR_USED (decl))
868 error_at (DECL_SOURCE_LOCATION (decl),
869 "odr-used inline variable %qD is not defined", decl);
872 /* Clear out the list, so we don't rescan next time. */
873 static_decls = NULL;
875 /* Write out any globals that need to be output. */
876 return wrapup_global_declarations (statics->address (),
877 statics->length ());
879 return 0;
882 /* In C++, you don't have to write `struct S' to refer to `S'; you
883 can just use `S'. We accomplish this by creating a TYPE_DECL as
884 if the user had written `typedef struct S S'. Create and return
885 the TYPE_DECL for TYPE. */
887 tree
888 create_implicit_typedef (tree name, tree type)
890 tree decl;
892 decl = build_decl (input_location, TYPE_DECL, name, type);
893 DECL_ARTIFICIAL (decl) = 1;
894 /* There are other implicit type declarations, like the one *within*
895 a class that allows you to write `S::S'. We must distinguish
896 amongst these. */
897 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
898 TYPE_NAME (type) = decl;
899 TYPE_STUB_DECL (type) = decl;
901 return decl;
904 /* Function-scope local entities that need discriminators. Each entry
905 is a {decl,name} pair. VAR_DECLs for anon unions get their name
906 smashed, so we cannot rely on DECL_NAME. */
908 static GTY((deletable)) vec<tree, va_gc> *local_entities;
910 /* Determine the mangling discriminator of local DECL. There are
911 generally very few of these in any particular function. */
913 void
914 determine_local_discriminator (tree decl, tree name)
916 auto_cond_timevar tv (TV_NAME_LOOKUP);
917 retrofit_lang_decl (decl);
918 tree ctx = DECL_CONTEXT (decl);
919 size_t nelts = vec_safe_length (local_entities);
920 if (name == NULL_TREE)
921 name = (TREE_CODE (decl) == TYPE_DECL
922 && TYPE_UNNAMED_P (TREE_TYPE (decl))
923 ? NULL_TREE : DECL_NAME (decl));
924 for (size_t i = 0; i < nelts; i += 2)
926 tree *pair = &(*local_entities)[i];
927 tree d = pair[0];
928 tree n = pair[1];
929 gcc_checking_assert (d != decl);
930 if (name == n
931 && TREE_CODE (decl) == TREE_CODE (d)
932 && ctx == DECL_CONTEXT (d))
934 tree disc = integer_one_node;
935 if (DECL_DISCRIMINATOR (d))
936 disc = build_int_cst (TREE_TYPE (disc),
937 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
938 DECL_DISCRIMINATOR (decl) = disc;
939 /* Replace the saved decl. */
940 pair[0] = decl;
941 decl = NULL_TREE;
942 break;
946 if (decl)
948 vec_safe_reserve (local_entities, 2);
949 local_entities->quick_push (decl);
950 local_entities->quick_push (name);
955 /* True if DECL is a constrained hidden friend as per [temp.friend]/9:
957 A non-template friend declaration with a requires-clause shall be a
958 definition. A friend function template with a constraint that depends on a
959 template parameter from an enclosing template shall be a definition. Such a
960 constrained friend function or function template declaration does not
961 declare the same function or function template as a declaration in any other
962 scope.
964 The ABI calls this a "member-like constrained friend" and mangles it like a
965 member function to avoid collisions. */
967 bool
968 member_like_constrained_friend_p (tree decl)
970 return (TREE_CODE (decl) == FUNCTION_DECL
971 && DECL_UNIQUE_FRIEND_P (decl)
972 && DECL_FRIEND_CONTEXT (decl)
973 && get_constraints (decl)
974 && (!DECL_TEMPLATE_INFO (decl)
975 || !PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
976 || (uses_outer_template_parms_in_constraints
977 (most_general_template (decl)))));
980 /* Returns true if functions FN1 and FN2 have equivalent trailing
981 requires clauses. */
983 static bool
984 function_requirements_equivalent_p (tree newfn, tree oldfn)
986 /* In the concepts TS, the combined constraints are compared. */
987 if (cxx_dialect < cxx20)
989 tree ci1 = get_constraints (oldfn);
990 tree ci2 = get_constraints (newfn);
991 tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
992 tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
993 return cp_tree_equal (req1, req2);
996 /* [temp.friend]/9 "Such a constrained friend function does not declare the
997 same function as a declaration in any other scope." So no need to
998 actually compare the requirements. */
999 if (member_like_constrained_friend_p (newfn)
1000 || member_like_constrained_friend_p (oldfn))
1001 return false;
1003 /* Compare only trailing requirements. */
1004 tree reqs1 = get_trailing_function_requirements (newfn);
1005 tree reqs2 = get_trailing_function_requirements (oldfn);
1006 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
1007 return false;
1009 /* Substitution is needed when friends are involved. */
1010 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
1011 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
1013 return cp_tree_equal (reqs1, reqs2);
1016 /* Two functions of the same name correspond [basic.scope.scope] if
1018 + both declare functions with the same non-object-parameter-type-list,
1019 equivalent ([temp.over.link]) trailing requires-clauses (if any, except as
1020 specified in [temp.friend]), and, if both are non-static members, they have
1021 corresponding object parameters, or
1023 + both declare function templates with equivalent
1024 non-object-parameter-type-lists, return types (if any), template-heads, and
1025 trailing requires-clauses (if any), and, if both are non-static members,
1026 they have corresponding object parameters.
1028 This is a subset of decls_match: it identifies declarations that cannot be
1029 overloaded with one another. This function does not consider DECL_NAME. */
1031 bool
1032 fns_correspond (tree newdecl, tree olddecl)
1034 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1035 return false;
1037 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1039 if (!template_heads_equivalent_p (newdecl, olddecl))
1040 return 0;
1041 newdecl = DECL_TEMPLATE_RESULT (newdecl);
1042 olddecl = DECL_TEMPLATE_RESULT (olddecl);
1045 tree f1 = TREE_TYPE (newdecl);
1046 tree f2 = TREE_TYPE (olddecl);
1048 int rq1 = type_memfn_rqual (f1);
1049 int rq2 = type_memfn_rqual (f2);
1051 /* If only one is a non-static member function, ignore ref-quals. */
1052 if (TREE_CODE (f1) != TREE_CODE (f2))
1053 rq1 = rq2;
1054 /* Two non-static member functions have corresponding object parameters if:
1055 + exactly one is an implicit object member function with no ref-qualifier
1056 and the types of their object parameters ([dcl.fct]), after removing
1057 top-level references, are the same, or
1058 + their object parameters have the same type. */
1059 /* ??? We treat member functions of different classes as corresponding even
1060 though that means the object parameters have different types. */
1061 else if ((rq1 == REF_QUAL_NONE) != (rq2 == REF_QUAL_NONE))
1062 rq1 = rq2;
1064 bool types_match = rq1 == rq2;
1066 if (types_match)
1068 tree p1 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1069 tree p2 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1070 types_match = compparms (p1, p2);
1073 /* Two function declarations match if either has a requires-clause
1074 then both have a requires-clause and their constraints-expressions
1075 are equivalent. */
1076 if (types_match && flag_concepts)
1077 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1079 return types_match;
1082 /* Subroutine of duplicate_decls: return truthvalue of whether
1083 or not types of these decls match.
1085 For C++, we must compare the parameter list so that `int' can match
1086 `int&' in a parameter position, but `int&' is not confused with
1087 `const int&'. */
1090 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
1092 int types_match;
1094 if (newdecl == olddecl)
1095 return 1;
1097 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1098 /* If the two DECLs are not even the same kind of thing, we're not
1099 interested in their types. */
1100 return 0;
1102 gcc_assert (DECL_P (newdecl));
1104 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1106 /* Specializations of different templates are different functions
1107 even if they have the same type. */
1108 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1109 ? DECL_TI_TEMPLATE (newdecl)
1110 : NULL_TREE);
1111 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1112 ? DECL_TI_TEMPLATE (olddecl)
1113 : NULL_TREE);
1114 if (t1 != t2)
1115 return 0;
1117 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1118 && ! (DECL_EXTERN_C_P (newdecl)
1119 && DECL_EXTERN_C_P (olddecl)))
1120 return 0;
1122 /* A new declaration doesn't match a built-in one unless it
1123 is also extern "C". */
1124 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1125 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1126 return 0;
1128 tree f1 = TREE_TYPE (newdecl);
1129 tree f2 = TREE_TYPE (olddecl);
1130 if (TREE_CODE (f1) != TREE_CODE (f2))
1131 return 0;
1133 /* A declaration with deduced return type should use its pre-deduction
1134 type for declaration matching. */
1135 tree r2 = fndecl_declared_return_type (olddecl);
1136 tree r1 = fndecl_declared_return_type (newdecl);
1138 tree p1 = TYPE_ARG_TYPES (f1);
1139 tree p2 = TYPE_ARG_TYPES (f2);
1141 if (same_type_p (r1, r2))
1143 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1144 && fndecl_built_in_p (olddecl))
1146 types_match = self_promoting_args_p (p1);
1147 if (p1 == void_list_node)
1148 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1150 else
1151 types_match =
1152 compparms (p1, p2)
1153 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1154 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1155 || comp_type_attributes (TREE_TYPE (newdecl),
1156 TREE_TYPE (olddecl)) != 0);
1158 else
1159 types_match = 0;
1161 /* Two function declarations match if either has a requires-clause
1162 then both have a requires-clause and their constraints-expressions
1163 are equivalent. */
1164 if (types_match && flag_concepts)
1165 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1167 /* The decls dont match if they correspond to two different versions
1168 of the same function. Disallow extern "C" functions to be
1169 versions for now. */
1170 if (types_match
1171 && !DECL_EXTERN_C_P (newdecl)
1172 && !DECL_EXTERN_C_P (olddecl)
1173 && targetm.target_option.function_versions (newdecl, olddecl))
1175 if (record_versions)
1176 maybe_version_functions (newdecl, olddecl,
1177 (!DECL_FUNCTION_VERSIONED (newdecl)
1178 || !DECL_FUNCTION_VERSIONED (olddecl)));
1179 return 0;
1182 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1184 if (!template_heads_equivalent_p (newdecl, olddecl))
1185 return 0;
1187 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1188 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1190 if (TREE_CODE (newres) != TREE_CODE (oldres))
1191 return 0;
1193 /* Two template types match if they are the same. Otherwise, compare
1194 the underlying declarations. */
1195 if (TREE_CODE (newres) == TYPE_DECL)
1196 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1197 else
1198 types_match = decls_match (newres, oldres);
1200 else
1202 /* Need to check scope for variable declaration (VAR_DECL).
1203 For typedef (TYPE_DECL), scope is ignored. */
1204 if (VAR_P (newdecl)
1205 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1206 /* [dcl.link]
1207 Two declarations for an object with C language linkage
1208 with the same name (ignoring the namespace that qualify
1209 it) that appear in different namespace scopes refer to
1210 the same object. */
1211 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1212 return 0;
1214 if (TREE_TYPE (newdecl) == error_mark_node)
1215 types_match = TREE_TYPE (olddecl) == error_mark_node;
1216 else if (TREE_TYPE (olddecl) == NULL_TREE)
1217 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1218 else if (TREE_TYPE (newdecl) == NULL_TREE)
1219 types_match = 0;
1220 else
1221 types_match = comptypes (TREE_TYPE (newdecl),
1222 TREE_TYPE (olddecl),
1223 COMPARE_REDECLARATION);
1226 return types_match;
1229 /* Mark DECL as versioned if it isn't already. */
1231 static void
1232 maybe_mark_function_versioned (tree decl)
1234 if (!DECL_FUNCTION_VERSIONED (decl))
1236 DECL_FUNCTION_VERSIONED (decl) = 1;
1237 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1238 to include the version marker. */
1239 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1240 mangle_decl (decl);
1244 /* NEWDECL and OLDDECL have identical signatures. If they are
1245 different versions adjust them and return true.
1246 If RECORD is set to true, record function versions. */
1248 bool
1249 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1251 if (!targetm.target_option.function_versions (newdecl, olddecl))
1252 return false;
1254 maybe_mark_function_versioned (olddecl);
1255 if (DECL_LOCAL_DECL_P (olddecl))
1257 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1258 maybe_mark_function_versioned (olddecl);
1261 maybe_mark_function_versioned (newdecl);
1262 if (DECL_LOCAL_DECL_P (newdecl))
1264 /* Unfortunately, we can get here before pushdecl naturally calls
1265 push_local_extern_decl_alias, so we need to call it directly. */
1266 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1267 push_local_extern_decl_alias (newdecl);
1268 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1269 maybe_mark_function_versioned (newdecl);
1272 if (record)
1273 cgraph_node::record_function_versions (olddecl, newdecl);
1275 return true;
1278 /* If NEWDECL is `static' and an `extern' was seen previously,
1279 warn about it. OLDDECL is the previous declaration.
1281 Note that this does not apply to the C++ case of declaring
1282 a variable `extern const' and then later `const'.
1284 Don't complain about built-in functions, since they are beyond
1285 the user's control. */
1287 void
1288 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1290 if (TREE_CODE (newdecl) == TYPE_DECL
1291 || TREE_CODE (newdecl) == TEMPLATE_DECL
1292 || TREE_CODE (newdecl) == CONST_DECL
1293 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1294 return;
1296 /* Don't get confused by static member functions; that's a different
1297 use of `static'. */
1298 if (TREE_CODE (newdecl) == FUNCTION_DECL
1299 && DECL_STATIC_FUNCTION_P (newdecl))
1300 return;
1302 /* If the old declaration was `static', or the new one isn't, then
1303 everything is OK. */
1304 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1305 return;
1307 /* It's OK to declare a builtin function as `static'. */
1308 if (TREE_CODE (olddecl) == FUNCTION_DECL
1309 && DECL_ARTIFICIAL (olddecl))
1310 return;
1312 auto_diagnostic_group d;
1313 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1314 "%qD was declared %<extern%> and later %<static%>", newdecl))
1315 inform (DECL_SOURCE_LOCATION (olddecl),
1316 "previous declaration of %qD", olddecl);
1319 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1320 function templates. If their exception specifications do not
1321 match, issue a diagnostic. */
1323 static void
1324 check_redeclaration_exception_specification (tree new_decl,
1325 tree old_decl)
1327 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1328 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1330 /* Two default specs are equivalent, don't force evaluation. */
1331 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1332 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1333 return;
1335 if (!type_dependent_expression_p (old_decl))
1337 maybe_instantiate_noexcept (new_decl);
1338 maybe_instantiate_noexcept (old_decl);
1340 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1341 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1343 /* [except.spec]
1345 If any declaration of a function has an exception-specification,
1346 all declarations, including the definition and an explicit
1347 specialization, of that function shall have an
1348 exception-specification with the same set of type-ids. */
1349 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1350 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1351 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1353 const char *const msg
1354 = G_("declaration of %qF has a different exception specifier");
1355 bool complained = true;
1356 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1357 auto_diagnostic_group d;
1358 if (DECL_IN_SYSTEM_HEADER (old_decl))
1359 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1360 else if (!flag_exceptions)
1361 /* We used to silently permit mismatched eh specs with
1362 -fno-exceptions, so make them a pedwarn now. */
1363 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1364 else
1365 error_at (new_loc, msg, new_decl);
1366 if (complained)
1367 inform (DECL_SOURCE_LOCATION (old_decl),
1368 "from previous declaration %qF", old_decl);
1372 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1373 Otherwise issue diagnostics. */
1375 static bool
1376 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1378 old_decl = STRIP_TEMPLATE (old_decl);
1379 new_decl = STRIP_TEMPLATE (new_decl);
1380 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1381 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1382 return true;
1383 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1384 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1386 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1387 return true;
1388 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1389 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1390 return true;
1392 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1394 /* With -fimplicit-constexpr, ignore changes in the constexpr
1395 keyword. */
1396 if (flag_implicit_constexpr
1397 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1398 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1399 return true;
1400 if (fndecl_built_in_p (old_decl))
1402 /* Hide a built-in declaration. */
1403 DECL_DECLARED_CONSTEXPR_P (old_decl)
1404 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1405 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1406 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1407 return true;
1409 /* 7.1.5 [dcl.constexpr]
1410 Note: An explicit specialization can differ from the template
1411 declaration with respect to the constexpr specifier. */
1412 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1413 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1414 return true;
1416 const char *kind = "constexpr";
1417 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1418 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1419 kind = "consteval";
1420 error_at (DECL_SOURCE_LOCATION (new_decl),
1421 "redeclaration %qD differs in %qs "
1422 "from previous declaration", new_decl,
1423 kind);
1424 inform (DECL_SOURCE_LOCATION (old_decl),
1425 "previous declaration %qD", old_decl);
1426 return false;
1428 return true;
1431 // If OLDDECL and NEWDECL are concept declarations with the same type
1432 // (i.e., and template parameters), but different requirements,
1433 // emit diagnostics and return true. Otherwise, return false.
1434 static inline bool
1435 check_concept_refinement (tree olddecl, tree newdecl)
1437 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1438 return false;
1440 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1441 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1442 if (TREE_CODE (d1) != TREE_CODE (d2))
1443 return false;
1445 tree t1 = TREE_TYPE (d1);
1446 tree t2 = TREE_TYPE (d2);
1447 if (TREE_CODE (d1) == FUNCTION_DECL)
1449 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1450 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1451 DECL_TEMPLATE_PARMS (newdecl))
1452 && !equivalently_constrained (olddecl, newdecl))
1454 error ("cannot specialize concept %q#D", olddecl);
1455 return true;
1458 return false;
1461 /* DECL is a redeclaration of a function or function template. If
1462 it does have default arguments issue a diagnostic. Note: this
1463 function is used to enforce the requirements in C++11 8.3.6 about
1464 no default arguments in redeclarations. */
1466 static void
1467 check_redeclaration_no_default_args (tree decl)
1469 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1471 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1472 t && t != void_list_node; t = TREE_CHAIN (t))
1473 if (TREE_PURPOSE (t))
1475 permerror (DECL_SOURCE_LOCATION (decl),
1476 "redeclaration of %q#D may not have default "
1477 "arguments", decl);
1478 return;
1482 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1483 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1484 the TEMPLATE_DECLs in case of function templates). This function is used
1485 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1486 "If a friend declaration specifies a default argument expression, that
1487 declaration shall be a definition and shall be the only declaration of
1488 the function or function template in the translation unit." */
1490 static void
1491 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1493 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1494 return;
1496 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1497 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1498 t1 && t1 != void_list_node;
1499 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1500 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1501 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1503 auto_diagnostic_group d;
1504 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1505 "friend declaration of %q#D specifies default "
1506 "arguments and isn%'t the only declaration", newdecl))
1507 inform (DECL_SOURCE_LOCATION (olddecl),
1508 "previous declaration of %q#D", olddecl);
1509 return;
1513 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1514 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1516 static void
1517 merge_attribute_bits (tree newdecl, tree olddecl)
1519 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1520 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1521 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1522 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1523 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1524 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1525 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1526 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1527 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1528 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1529 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1530 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1533 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1534 && lookup_attribute ("gnu_inline", \
1535 DECL_ATTRIBUTES (fn)))
1537 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1538 ambiguates olddecl. Returns true if an error occurs. */
1540 static bool
1541 duplicate_function_template_decls (tree newdecl, tree olddecl)
1544 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1545 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1546 /* Function template declarations can be differentiated by parameter
1547 and return type. */
1548 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1549 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1550 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1551 TREE_TYPE (TREE_TYPE (olddecl))))
1553 /* ... and also by their template-heads and requires-clauses. */
1554 if (template_heads_equivalent_p (newdecl, olddecl)
1555 && function_requirements_equivalent_p (newres, oldres))
1557 error ("ambiguating new declaration %q+#D", newdecl);
1558 inform (DECL_SOURCE_LOCATION (olddecl),
1559 "old declaration %q#D", olddecl);
1560 return true;
1563 /* FIXME: The types are the same but the are differences
1564 in either the template heads or function requirements.
1565 We should be able to diagnose a set of common errors
1566 stemming from these declarations. For example:
1568 template<typename T> requires C void f(...);
1569 template<typename T> void f(...) requires C;
1571 These are functionally equivalent but not equivalent. */
1574 return false;
1577 /* OLD_PARMS is the innermost set of template parameters for some template
1578 declaration, and NEW_PARMS is the corresponding set of template parameters
1579 for a redeclaration of that template. Merge the default arguments within
1580 these two sets of parameters. CLASS_P is true iff the template in
1581 question is a class template. */
1583 bool
1584 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1586 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1587 == TREE_VEC_LENGTH (old_parms));
1588 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1590 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1591 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1592 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1593 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1594 if (error_operand_p (new_parm) || error_operand_p (old_parm))
1595 return false;
1596 if (new_default != NULL_TREE && old_default != NULL_TREE)
1598 auto_diagnostic_group d;
1599 error ("redefinition of default argument for %q+#D", new_parm);
1600 inform (DECL_SOURCE_LOCATION (old_parm),
1601 "original definition appeared here");
1602 return false;
1604 else if (new_default != NULL_TREE)
1605 /* Update the previous template parameters (which are the ones
1606 that will really count) with the new default value. */
1607 old_default = new_default;
1608 else if (class_p && old_default != NULL_TREE)
1609 /* Update the new parameters, too; they'll be used as the
1610 parameters for any members. */
1611 new_default = old_default;
1613 return true;
1616 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1617 If the redeclaration is invalid, a diagnostic is issued, and the
1618 error_mark_node is returned. Otherwise, OLDDECL is returned.
1620 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1621 returned.
1623 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1624 if the old decl was hidden.
1626 Hidden decls can be anticipated builtins, injected friends, or
1627 (coming soon) injected from a local-extern decl. */
1629 tree
1630 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1632 unsigned olddecl_uid = DECL_UID (olddecl);
1633 int types_match = 0;
1634 int new_defines_function = 0;
1635 tree new_template_info;
1636 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1637 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1639 if (newdecl == olddecl)
1640 return olddecl;
1642 types_match = decls_match (newdecl, olddecl);
1644 /* If either the type of the new decl or the type of the old decl is an
1645 error_mark_node, then that implies that we have already issued an
1646 error (earlier) for some bogus type specification, and in that case,
1647 it is rather pointless to harass the user with yet more error message
1648 about the same declaration, so just pretend the types match here. */
1649 if (TREE_TYPE (newdecl) == error_mark_node
1650 || TREE_TYPE (olddecl) == error_mark_node)
1651 return error_mark_node;
1653 /* Check for redeclaration and other discrepancies. */
1654 if (TREE_CODE (olddecl) == FUNCTION_DECL
1655 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1657 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1659 /* Avoid warnings redeclaring built-ins which have not been
1660 explicitly declared. */
1661 if (was_hidden)
1663 if (TREE_PUBLIC (newdecl)
1664 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1665 warning_at (newdecl_loc,
1666 OPT_Wbuiltin_declaration_mismatch,
1667 "built-in function %qD declared as non-function",
1668 newdecl);
1669 return NULL_TREE;
1672 /* If you declare a built-in or predefined function name as static,
1673 the old definition is overridden, but optionally warn this was a
1674 bad choice of name. */
1675 if (! TREE_PUBLIC (newdecl))
1677 warning_at (newdecl_loc,
1678 OPT_Wshadow,
1679 fndecl_built_in_p (olddecl)
1680 ? G_("shadowing built-in function %q#D")
1681 : G_("shadowing library function %q#D"), olddecl);
1682 /* Discard the old built-in function. */
1683 return NULL_TREE;
1685 /* If the built-in is not ansi, then programs can override
1686 it even globally without an error. */
1687 else if (! fndecl_built_in_p (olddecl))
1688 warning_at (newdecl_loc, 0,
1689 "library function %q#D redeclared as non-function %q#D",
1690 olddecl, newdecl);
1691 else
1692 error_at (newdecl_loc,
1693 "declaration of %q#D conflicts with built-in "
1694 "declaration %q#D", newdecl, olddecl);
1695 return NULL_TREE;
1697 else if (!types_match)
1699 /* Avoid warnings redeclaring built-ins which have not been
1700 explicitly declared. */
1701 if (was_hidden)
1703 tree t1, t2;
1705 /* A new declaration doesn't match a built-in one unless it
1706 is also extern "C". */
1707 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1708 gcc_assert (DECL_EXTERN_C_P (olddecl));
1709 if (!DECL_EXTERN_C_P (newdecl))
1710 return NULL_TREE;
1712 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1713 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1714 t1 || t2;
1715 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1717 if (!t1 || !t2)
1718 break;
1719 /* FILE, tm types are not known at the time
1720 we create the builtins. */
1721 for (unsigned i = 0;
1722 i < sizeof (builtin_structptr_types)
1723 / sizeof (builtin_structptr_type);
1724 ++i)
1725 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1727 tree t = TREE_VALUE (t1);
1729 if (TYPE_PTR_P (t)
1730 && TYPE_IDENTIFIER (TREE_TYPE (t))
1731 == get_identifier (builtin_structptr_types[i].str)
1732 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1734 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1736 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1737 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1738 types_match = decls_match (newdecl, olddecl);
1739 if (types_match)
1740 return duplicate_decls (newdecl, olddecl,
1741 hiding, was_hidden);
1742 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1744 goto next_arg;
1747 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1748 break;
1749 next_arg:;
1752 warning_at (newdecl_loc,
1753 OPT_Wbuiltin_declaration_mismatch,
1754 "declaration of %q#D conflicts with built-in "
1755 "declaration %q#D", newdecl, olddecl);
1757 else if ((DECL_EXTERN_C_P (newdecl)
1758 && DECL_EXTERN_C_P (olddecl))
1759 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1760 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1762 /* Don't really override olddecl for __* prefixed builtins
1763 except for __[^b]*_chk, the compiler might be using those
1764 explicitly. */
1765 if (fndecl_built_in_p (olddecl))
1767 tree id = DECL_NAME (olddecl);
1768 const char *name = IDENTIFIER_POINTER (id);
1769 size_t len;
1771 if (name[0] == '_'
1772 && name[1] == '_'
1773 && (startswith (name + 2, "builtin_")
1774 || (len = strlen (name)) <= strlen ("___chk")
1775 || memcmp (name + len - strlen ("_chk"),
1776 "_chk", strlen ("_chk") + 1) != 0))
1778 if (DECL_INITIAL (newdecl))
1780 error_at (newdecl_loc,
1781 "definition of %q#D ambiguates built-in "
1782 "declaration %q#D", newdecl, olddecl);
1783 return error_mark_node;
1785 auto_diagnostic_group d;
1786 if (permerror (newdecl_loc,
1787 "new declaration %q#D ambiguates built-in"
1788 " declaration %q#D", newdecl, olddecl)
1789 && flag_permissive)
1790 inform (newdecl_loc,
1791 "ignoring the %q#D declaration", newdecl);
1792 return flag_permissive ? olddecl : error_mark_node;
1796 /* A near match; override the builtin. */
1798 if (TREE_PUBLIC (newdecl))
1799 warning_at (newdecl_loc,
1800 OPT_Wbuiltin_declaration_mismatch,
1801 "new declaration %q#D ambiguates built-in "
1802 "declaration %q#D", newdecl, olddecl);
1803 else
1804 warning (OPT_Wshadow,
1805 fndecl_built_in_p (olddecl)
1806 ? G_("shadowing built-in function %q#D")
1807 : G_("shadowing library function %q#D"), olddecl);
1809 else
1810 /* Discard the old built-in function. */
1811 return NULL_TREE;
1813 /* Replace the old RTL to avoid problems with inlining. */
1814 COPY_DECL_RTL (newdecl, olddecl);
1816 else
1818 /* Even if the types match, prefer the new declarations type
1819 for built-ins which have not been explicitly declared,
1820 for exception lists, etc... */
1821 tree type = TREE_TYPE (newdecl);
1822 tree attribs = (*targetm.merge_type_attributes)
1823 (TREE_TYPE (olddecl), type);
1825 type = cp_build_type_attribute_variant (type, attribs);
1826 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1829 /* If a function is explicitly declared "throw ()", propagate that to
1830 the corresponding builtin. */
1831 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1832 && was_hidden
1833 && TREE_NOTHROW (newdecl)
1834 && !TREE_NOTHROW (olddecl))
1836 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1837 tree tmpdecl = builtin_decl_explicit (fncode);
1838 if (tmpdecl && tmpdecl != olddecl && types_match)
1839 TREE_NOTHROW (tmpdecl) = 1;
1842 /* Whether or not the builtin can throw exceptions has no
1843 bearing on this declarator. */
1844 TREE_NOTHROW (olddecl) = 0;
1846 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1848 /* If a builtin function is redeclared as `static', merge
1849 the declarations, but make the original one static. */
1850 DECL_THIS_STATIC (olddecl) = 1;
1851 TREE_PUBLIC (olddecl) = 0;
1853 /* Make the old declaration consistent with the new one so
1854 that all remnants of the builtin-ness of this function
1855 will be banished. */
1856 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1857 COPY_DECL_RTL (newdecl, olddecl);
1860 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1862 /* C++ Standard, 3.3, clause 4:
1863 "[Note: a namespace name or a class template name must be unique
1864 in its declarative region (7.3.2, clause 14). ]" */
1865 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1866 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1867 /* Namespace conflicts with not namespace. */;
1868 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1869 || DECL_TYPE_TEMPLATE_P (newdecl))
1870 /* Class template conflicts. */;
1871 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1872 && DECL_TEMPLATE_RESULT (olddecl)
1873 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1874 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1875 && DECL_TEMPLATE_RESULT (newdecl)
1876 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1877 /* Variable template conflicts. */;
1878 else if (concept_definition_p (olddecl)
1879 || concept_definition_p (newdecl))
1880 /* Concept conflicts. */;
1881 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1882 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1883 || (TREE_CODE (olddecl) == FUNCTION_DECL
1884 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1886 /* One is a function and the other is a template
1887 function. */
1888 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1889 return NULL_TREE;
1891 /* There can only be one! */
1892 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1893 && check_raw_literal_operator (olddecl))
1894 error_at (newdecl_loc,
1895 "literal operator %q#D conflicts with"
1896 " raw literal operator", newdecl);
1897 else if (check_raw_literal_operator (newdecl))
1898 error_at (newdecl_loc,
1899 "raw literal operator %q#D conflicts with"
1900 " literal operator template", newdecl);
1901 else
1902 return NULL_TREE;
1904 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1905 return error_mark_node;
1907 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1908 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1909 /* A structured binding must be unique in its declarative region. */;
1910 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1911 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1912 /* One is an implicit typedef, that's ok. */
1913 return NULL_TREE;
1915 error ("%q#D redeclared as different kind of entity", newdecl);
1916 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1918 return error_mark_node;
1920 else if (!types_match)
1922 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1923 /* These are certainly not duplicate declarations; they're
1924 from different scopes. */
1925 return NULL_TREE;
1927 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1929 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1930 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1932 /* The name of a class template may not be declared to refer to
1933 any other template, class, function, object, namespace, value,
1934 or type in the same scope. */
1935 if (TREE_CODE (oldres) == TYPE_DECL
1936 || TREE_CODE (newres) == TYPE_DECL)
1938 error_at (newdecl_loc,
1939 "conflicting declaration of template %q#D", newdecl);
1940 inform (olddecl_loc,
1941 "previous declaration %q#D", olddecl);
1942 return error_mark_node;
1945 else if (TREE_CODE (oldres) == FUNCTION_DECL
1946 && TREE_CODE (newres) == FUNCTION_DECL)
1948 if (duplicate_function_template_decls (newdecl, olddecl))
1949 return error_mark_node;
1950 return NULL_TREE;
1952 else if (check_concept_refinement (olddecl, newdecl))
1953 return error_mark_node;
1954 return NULL_TREE;
1956 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1958 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1960 error_at (newdecl_loc,
1961 "conflicting declaration of C function %q#D",
1962 newdecl);
1963 inform (olddecl_loc,
1964 "previous declaration %q#D", olddecl);
1965 return error_mark_node;
1967 /* For function versions, params and types match, but they
1968 are not ambiguous. */
1969 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1970 && !DECL_FUNCTION_VERSIONED (olddecl))
1971 /* Let constrained hidden friends coexist for now, we'll
1972 check satisfaction later. */
1973 && !member_like_constrained_friend_p (newdecl)
1974 && !member_like_constrained_friend_p (olddecl)
1975 // The functions have the same parameter types.
1976 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1977 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1978 // And the same constraints.
1979 && equivalently_constrained (newdecl, olddecl))
1981 error_at (newdecl_loc,
1982 "ambiguating new declaration of %q#D", newdecl);
1983 inform (olddecl_loc,
1984 "old declaration %q#D", olddecl);
1985 return error_mark_node;
1987 else
1988 return NULL_TREE;
1990 else
1992 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1993 inform (olddecl_loc,
1994 "previous declaration as %q#D", olddecl);
1995 return error_mark_node;
1998 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1999 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
2001 /* OMP UDRs are never duplicates. */
2002 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
2003 error_at (newdecl_loc,
2004 "redeclaration of %<pragma omp declare reduction%>");
2005 inform (olddecl_loc,
2006 "previous %<pragma omp declare reduction%> declaration");
2007 return error_mark_node;
2009 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2010 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
2011 && (!DECL_TEMPLATE_INFO (newdecl)
2012 || (DECL_TI_TEMPLATE (newdecl)
2013 != DECL_TI_TEMPLATE (olddecl))))
2014 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
2015 && (!DECL_TEMPLATE_INFO (olddecl)
2016 || (DECL_TI_TEMPLATE (olddecl)
2017 != DECL_TI_TEMPLATE (newdecl))))))
2018 /* It's OK to have a template specialization and a non-template
2019 with the same type, or to have specializations of two
2020 different templates with the same type. Note that if one is a
2021 specialization, and the other is an instantiation of the same
2022 template, that we do not exit at this point. That situation
2023 can occur if we instantiate a template class, and then
2024 specialize one of its methods. This situation is valid, but
2025 the declarations must be merged in the usual way. */
2026 return NULL_TREE;
2027 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2028 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
2029 && !DECL_USE_TEMPLATE (newdecl))
2030 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
2031 && !DECL_USE_TEMPLATE (olddecl))))
2032 /* One of the declarations is a template instantiation, and the
2033 other is not a template at all. That's OK. */
2034 return NULL_TREE;
2035 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2037 /* In [namespace.alias] we have:
2039 In a declarative region, a namespace-alias-definition can be
2040 used to redefine a namespace-alias declared in that declarative
2041 region to refer only to the namespace to which it already
2042 refers.
2044 Therefore, if we encounter a second alias directive for the same
2045 alias, we can just ignore the second directive. */
2046 if (DECL_NAMESPACE_ALIAS (newdecl)
2047 && (DECL_NAMESPACE_ALIAS (newdecl)
2048 == DECL_NAMESPACE_ALIAS (olddecl)))
2049 return olddecl;
2051 /* Leave it to update_binding to merge or report error. */
2052 return NULL_TREE;
2054 else
2056 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
2057 if (errmsg)
2059 auto_diagnostic_group d;
2060 error_at (newdecl_loc, errmsg, newdecl);
2061 if (DECL_NAME (olddecl) != NULL_TREE)
2062 inform (olddecl_loc,
2063 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
2064 ? G_("%q#D previously defined here")
2065 : G_("%q#D previously declared here"), olddecl);
2066 return error_mark_node;
2068 else if (TREE_CODE (olddecl) == FUNCTION_DECL
2069 && DECL_INITIAL (olddecl) != NULL_TREE
2070 && !prototype_p (TREE_TYPE (olddecl))
2071 && prototype_p (TREE_TYPE (newdecl)))
2073 /* Prototype decl follows defn w/o prototype. */
2074 auto_diagnostic_group d;
2075 if (warning_at (newdecl_loc, 0,
2076 "prototype specified for %q#D", newdecl))
2077 inform (olddecl_loc,
2078 "previous non-prototype definition here");
2080 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
2081 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
2083 /* [dcl.link]
2084 If two declarations of the same function or object
2085 specify different linkage-specifications ..., the program
2086 is ill-formed.... Except for functions with C++ linkage,
2087 a function declaration without a linkage specification
2088 shall not precede the first linkage specification for
2089 that function. A function can be declared without a
2090 linkage specification after an explicit linkage
2091 specification has been seen; the linkage explicitly
2092 specified in the earlier declaration is not affected by
2093 such a function declaration.
2095 DR 563 raises the question why the restrictions on
2096 functions should not also apply to objects. Older
2097 versions of G++ silently ignore the linkage-specification
2098 for this example:
2100 namespace N {
2101 extern int i;
2102 extern "C" int i;
2105 which is clearly wrong. Therefore, we now treat objects
2106 like functions. */
2107 if (current_lang_depth () == 0)
2109 /* There is no explicit linkage-specification, so we use
2110 the linkage from the previous declaration. */
2111 retrofit_lang_decl (newdecl);
2112 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2114 else
2116 auto_diagnostic_group d;
2117 error_at (newdecl_loc,
2118 "conflicting declaration of %q#D with %qL linkage",
2119 newdecl, DECL_LANGUAGE (newdecl));
2120 inform (olddecl_loc,
2121 "previous declaration with %qL linkage",
2122 DECL_LANGUAGE (olddecl));
2126 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2128 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2130 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2131 if (DECL_FUNCTION_MEMBER_P (olddecl)
2132 && (/* grokfndecl passes member function templates too
2133 as FUNCTION_DECLs. */
2134 DECL_TEMPLATE_INFO (olddecl)
2135 /* C++11 8.3.6/6.
2136 Default arguments for a member function of a class
2137 template shall be specified on the initial declaration
2138 of the member function within the class template. */
2139 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2141 check_redeclaration_no_default_args (newdecl);
2143 if (DECL_TEMPLATE_INFO (olddecl)
2144 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2146 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2147 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2148 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2149 tree old_parms
2150 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2151 merge_default_template_args (new_parms, old_parms,
2152 /*class_p=*/false);
2155 else
2157 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2158 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2159 int i = 1;
2161 for (; t1 && t1 != void_list_node;
2162 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2163 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2165 if (simple_cst_equal (TREE_PURPOSE (t1),
2166 TREE_PURPOSE (t2)) == 1)
2168 auto_diagnostic_group d;
2169 if (permerror (newdecl_loc,
2170 "default argument given for parameter "
2171 "%d of %q#D", i, newdecl))
2172 inform (olddecl_loc,
2173 "previous specification in %q#D here",
2174 olddecl);
2176 else
2178 auto_diagnostic_group d;
2179 error_at (newdecl_loc,
2180 "default argument given for parameter %d "
2181 "of %q#D", i, newdecl);
2182 inform (olddecl_loc,
2183 "previous specification in %q#D here",
2184 olddecl);
2188 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2189 argument expression, that declaration... shall be the only
2190 declaration of the function or function template in the
2191 translation unit." */
2192 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2197 /* Do not merge an implicit typedef with an explicit one. In:
2199 class A;
2201 typedef class A A __attribute__ ((foo));
2203 the attribute should apply only to the typedef. */
2204 if (TREE_CODE (olddecl) == TYPE_DECL
2205 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2206 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2207 return NULL_TREE;
2209 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2210 return NULL_TREE;
2212 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2213 return error_mark_node;
2215 if (modules_p ()
2216 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2217 && TREE_CODE (olddecl) != NAMESPACE_DECL
2218 && !hiding)
2220 if (!module_may_redeclare (olddecl))
2222 if (DECL_ARTIFICIAL (olddecl))
2223 error ("declaration %qD conflicts with builtin", newdecl);
2224 else
2226 error ("declaration %qD conflicts with import", newdecl);
2227 inform (olddecl_loc, "import declared %q#D here", olddecl);
2230 return error_mark_node;
2233 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2234 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_ATTACH_P (not_tmpl))
2236 if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (newdecl))
2237 && !DECL_MODULE_EXPORT_P (not_tmpl))
2239 error ("conflicting exporting declaration %qD", newdecl);
2240 inform (olddecl_loc, "previous declaration %q#D here", olddecl);
2243 else if (DECL_MODULE_EXPORT_P (newdecl))
2244 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2247 /* We have committed to returning OLDDECL at this point. */
2249 /* If new decl is `static' and an `extern' was seen previously,
2250 warn about it. */
2251 warn_extern_redeclared_static (newdecl, olddecl);
2253 /* True to merge attributes between the declarations, false to
2254 set OLDDECL's attributes to those of NEWDECL (for template
2255 explicit specializations that specify their own attributes
2256 independent of those specified for the primary template). */
2257 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2258 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2259 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2261 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2263 if (merge_attr)
2265 if (diagnose_mismatched_attributes (olddecl, newdecl))
2266 inform (olddecl_loc, DECL_INITIAL (olddecl)
2267 ? G_("previous definition of %qD here")
2268 : G_("previous declaration of %qD here"), olddecl);
2270 /* [dcl.attr.noreturn]: The first declaration of a function shall
2271 specify the noreturn attribute if any declaration of that function
2272 specifies the noreturn attribute. */
2273 tree a;
2274 if (TREE_THIS_VOLATILE (newdecl)
2275 && !TREE_THIS_VOLATILE (olddecl)
2276 /* This applies to [[noreturn]] only, not its GNU variants. */
2277 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2278 && cxx11_attribute_p (a)
2279 && get_attribute_namespace (a) == NULL_TREE)
2281 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2282 "but its first declaration was not", newdecl);
2283 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2287 /* Now that functions must hold information normally held
2288 by field decls, there is extra work to do so that
2289 declaration information does not get destroyed during
2290 definition. */
2291 if (DECL_VINDEX (olddecl))
2292 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2293 if (DECL_CONTEXT (olddecl))
2294 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2295 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2296 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2297 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2298 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2299 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2300 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2301 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2302 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2303 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2304 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2305 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2306 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2307 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2308 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2310 duplicate_contracts (newdecl, olddecl);
2312 /* Optionally warn about more than one declaration for the same
2313 name, but don't warn about a function declaration followed by a
2314 definition. */
2315 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2316 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2317 /* Don't warn about extern decl followed by definition. */
2318 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2319 /* Don't warn if at least one is/was hidden. */
2320 && !(hiding || was_hidden)
2321 /* Don't warn about declaration followed by specialization. */
2322 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2323 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2325 auto_diagnostic_group d;
2326 if (warning_at (newdecl_loc,
2327 OPT_Wredundant_decls,
2328 "redundant redeclaration of %qD in same scope",
2329 newdecl))
2330 inform (olddecl_loc,
2331 "previous declaration of %qD", olddecl);
2334 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2335 first declaration of the function or, for an explicit specialization
2336 of a function template, the first declaration of that
2337 specialization. */
2338 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2339 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2341 if (DECL_DELETED_FN (newdecl))
2343 auto_diagnostic_group d;
2344 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2345 "is not first declaration", newdecl))
2346 inform (olddecl_loc,
2347 "previous declaration of %qD", olddecl);
2349 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2353 /* Deal with C++: must preserve virtual function table size. */
2354 if (TREE_CODE (olddecl) == TYPE_DECL)
2356 tree newtype = TREE_TYPE (newdecl);
2357 tree oldtype = TREE_TYPE (olddecl);
2359 if (newtype != error_mark_node && oldtype != error_mark_node
2360 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2361 CLASSTYPE_FRIEND_CLASSES (newtype)
2362 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2364 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2367 /* Copy all the DECL_... slots specified in the new decl except for
2368 any that we copy here from the old type. */
2369 if (merge_attr)
2370 DECL_ATTRIBUTES (newdecl)
2371 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2372 else
2373 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2375 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2377 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2378 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2379 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2381 /* The new decl should not already have gathered any
2382 specializations. */
2383 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2385 /* Make sure the contracts are equivalent. */
2386 duplicate_contracts (newdecl, olddecl);
2388 /* Remove contracts from old_result so they aren't appended to
2389 old_result by the merge function. */
2390 remove_contract_attributes (old_result);
2392 DECL_ATTRIBUTES (old_result)
2393 = (*targetm.merge_decl_attributes) (old_result, new_result);
2395 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2397 if (DECL_SOURCE_LOCATION (newdecl)
2398 != DECL_SOURCE_LOCATION (olddecl))
2400 /* Per C++11 8.3.6/4, default arguments cannot be added in
2401 later declarations of a function template. */
2402 check_redeclaration_no_default_args (newdecl);
2403 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2404 argument expression, that declaration... shall be the only
2405 declaration of the function or function template in the
2406 translation unit." */
2407 check_no_redeclaration_friend_default_args
2408 (old_result, new_result);
2410 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2411 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2412 merge_default_template_args (new_parms, old_parms,
2413 /*class_p=*/false);
2415 if (!DECL_UNIQUE_FRIEND_P (new_result))
2416 DECL_UNIQUE_FRIEND_P (old_result) = false;
2418 check_default_args (newdecl);
2420 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2421 && DECL_INITIAL (new_result))
2423 if (DECL_INITIAL (old_result))
2424 DECL_UNINLINABLE (old_result) = 1;
2425 else
2426 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2427 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2428 DECL_NOT_REALLY_EXTERN (old_result)
2429 = DECL_NOT_REALLY_EXTERN (new_result);
2430 DECL_INTERFACE_KNOWN (old_result)
2431 = DECL_INTERFACE_KNOWN (new_result);
2432 DECL_DECLARED_INLINE_P (old_result)
2433 = DECL_DECLARED_INLINE_P (new_result);
2434 DECL_DISREGARD_INLINE_LIMITS (old_result)
2435 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2437 else
2439 DECL_DECLARED_INLINE_P (old_result)
2440 |= DECL_DECLARED_INLINE_P (new_result);
2441 DECL_DISREGARD_INLINE_LIMITS (old_result)
2442 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2443 check_redeclaration_exception_specification (newdecl, olddecl);
2445 merge_attribute_bits (new_result, old_result);
2449 /* If the new declaration is a definition, update the file and
2450 line information on the declaration, and also make
2451 the old declaration the same definition. */
2452 if (DECL_INITIAL (new_result) != NULL_TREE)
2454 DECL_SOURCE_LOCATION (olddecl)
2455 = DECL_SOURCE_LOCATION (old_result)
2456 = DECL_SOURCE_LOCATION (newdecl);
2457 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2458 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2460 DECL_ARGUMENTS (old_result) = DECL_ARGUMENTS (new_result);
2461 for (tree p = DECL_ARGUMENTS (old_result); p; p = DECL_CHAIN (p))
2462 DECL_CONTEXT (p) = old_result;
2464 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2465 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2469 return olddecl;
2472 if (types_match)
2474 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2475 check_redeclaration_exception_specification (newdecl, olddecl);
2477 /* Automatically handles default parameters. */
2478 tree oldtype = TREE_TYPE (olddecl);
2479 tree newtype;
2481 /* For typedefs use the old type, as the new type's DECL_NAME points
2482 at newdecl, which will be ggc_freed. */
2483 if (TREE_CODE (newdecl) == TYPE_DECL)
2485 /* But NEWTYPE might have an attribute, honor that. */
2486 tree tem = TREE_TYPE (newdecl);
2487 newtype = oldtype;
2489 if (TYPE_USER_ALIGN (tem))
2491 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2492 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2493 TYPE_USER_ALIGN (newtype) = true;
2496 /* And remove the new type from the variants list. */
2497 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2499 tree remove = TREE_TYPE (newdecl);
2500 if (TYPE_MAIN_VARIANT (remove) == remove)
2502 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2503 /* If remove is the main variant, no need to remove that
2504 from the list. One of the DECL_ORIGINAL_TYPE
2505 variants, e.g. created for aligned attribute, might still
2506 refer to the newdecl TYPE_DECL though, so remove that one
2507 in that case. */
2508 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2509 if (orig != remove)
2510 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2511 t = TYPE_MAIN_VARIANT (t))
2512 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2514 TYPE_NEXT_VARIANT (t)
2515 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2516 break;
2519 else
2520 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2521 t = TYPE_NEXT_VARIANT (t))
2522 if (TYPE_NEXT_VARIANT (t) == remove)
2524 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2525 break;
2529 else if (merge_attr)
2530 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2531 else
2532 newtype = TREE_TYPE (newdecl);
2534 if (VAR_P (newdecl))
2536 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2537 /* For already initialized vars, TREE_READONLY could have been
2538 cleared in cp_finish_decl, because the var needs runtime
2539 initialization or destruction. Make sure not to set
2540 TREE_READONLY on it again. */
2541 if (DECL_INITIALIZED_P (olddecl)
2542 && !DECL_EXTERNAL (olddecl)
2543 && !TREE_READONLY (olddecl))
2544 TREE_READONLY (newdecl) = 0;
2545 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2546 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2547 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2548 if (DECL_DEPENDENT_INIT_P (olddecl))
2549 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2550 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2551 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2552 DECL_DECLARED_CONSTEXPR_P (newdecl)
2553 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2554 DECL_DECLARED_CONSTINIT_P (newdecl)
2555 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2557 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2558 if (DECL_LANG_SPECIFIC (olddecl)
2559 && CP_DECL_THREADPRIVATE_P (olddecl))
2561 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2562 retrofit_lang_decl (newdecl);
2563 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2567 /* An explicit specialization of a function template or of a member
2568 function of a class template can be declared transaction_safe
2569 independently of whether the corresponding template entity is declared
2570 transaction_safe. */
2571 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2572 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2573 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2574 && tx_safe_fn_type_p (newtype)
2575 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2576 newtype = tx_unsafe_fn_variant (newtype);
2578 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2580 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2581 check_default_args (newdecl);
2583 /* Lay the type out, unless already done. */
2584 if (! same_type_p (newtype, oldtype)
2585 && TREE_TYPE (newdecl) != error_mark_node
2586 && !(processing_template_decl && uses_template_parms (newdecl)))
2587 layout_type (TREE_TYPE (newdecl));
2589 if ((VAR_P (newdecl)
2590 || TREE_CODE (newdecl) == PARM_DECL
2591 || TREE_CODE (newdecl) == RESULT_DECL
2592 || TREE_CODE (newdecl) == FIELD_DECL
2593 || TREE_CODE (newdecl) == TYPE_DECL)
2594 && !(processing_template_decl && uses_template_parms (newdecl)))
2595 layout_decl (newdecl, 0);
2597 /* Merge deprecatedness. */
2598 if (TREE_DEPRECATED (newdecl))
2599 TREE_DEPRECATED (olddecl) = 1;
2601 /* Merge unavailability. */
2602 if (TREE_UNAVAILABLE (newdecl))
2603 TREE_UNAVAILABLE (olddecl) = 1;
2605 /* Preserve function specific target and optimization options */
2606 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2608 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2609 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2610 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2611 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2613 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2614 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2615 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2616 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2618 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2619 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2621 else
2623 /* Merge the const type qualifier. */
2624 if (TREE_READONLY (newdecl))
2625 TREE_READONLY (olddecl) = 1;
2626 /* Merge the volatile type qualifier. */
2627 if (TREE_THIS_VOLATILE (newdecl))
2628 TREE_THIS_VOLATILE (olddecl) = 1;
2631 /* Merge the initialization information. */
2632 if (DECL_INITIAL (newdecl) == NULL_TREE
2633 && DECL_INITIAL (olddecl) != NULL_TREE)
2635 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2636 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2637 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2639 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2640 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2644 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2646 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2647 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2648 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2649 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2650 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2651 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2652 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2653 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2654 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2656 if (merge_attr)
2657 merge_attribute_bits (newdecl, olddecl);
2658 else
2660 /* Merge the noreturn bit. */
2661 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2662 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2663 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2664 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2665 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2667 /* Keep the old RTL. */
2668 COPY_DECL_RTL (olddecl, newdecl);
2670 else if (VAR_P (newdecl)
2671 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2673 /* Keep the old RTL. We cannot keep the old RTL if the old
2674 declaration was for an incomplete object and the new
2675 declaration is not since many attributes of the RTL will
2676 change. */
2677 COPY_DECL_RTL (olddecl, newdecl);
2680 /* If cannot merge, then use the new type and qualifiers,
2681 and don't preserve the old rtl. */
2682 else
2684 /* Clean out any memory we had of the old declaration. */
2685 tree oldstatic = value_member (olddecl, static_aggregates);
2686 if (oldstatic)
2687 TREE_VALUE (oldstatic) = error_mark_node;
2689 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2690 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2691 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2692 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2693 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2696 /* Merge the storage class information. */
2697 merge_weak (newdecl, olddecl);
2699 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2700 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2701 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2702 if (! DECL_EXTERNAL (olddecl))
2703 DECL_EXTERNAL (newdecl) = 0;
2704 if (! DECL_COMDAT (olddecl))
2705 DECL_COMDAT (newdecl) = 0;
2707 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2709 if (!DECL_LOCAL_DECL_P (olddecl))
2710 /* This can happen if olddecl was brought in from the
2711 enclosing namespace via a using-decl. The new decl is
2712 then not a block-scope extern at all. */
2713 DECL_LOCAL_DECL_P (newdecl) = false;
2714 else
2716 retrofit_lang_decl (newdecl);
2717 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2718 = DECL_LOCAL_DECL_ALIAS (olddecl);
2719 DECL_ATTRIBUTES (alias)
2720 = (*targetm.merge_decl_attributes) (alias, newdecl);
2721 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2722 merge_attribute_bits (newdecl, alias);
2726 new_template_info = NULL_TREE;
2727 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2729 bool new_redefines_gnu_inline = false;
2731 if (new_defines_function
2732 && ((DECL_INTERFACE_KNOWN (olddecl)
2733 && TREE_CODE (olddecl) == FUNCTION_DECL)
2734 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2735 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2736 == FUNCTION_DECL))))
2737 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2739 if (!new_redefines_gnu_inline)
2741 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2742 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2743 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2746 if (TREE_CODE (newdecl) != TYPE_DECL)
2748 DECL_TEMPLATE_INSTANTIATED (newdecl)
2749 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2750 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2752 /* If the OLDDECL is an instantiation and/or specialization,
2753 then the NEWDECL must be too. But, it may not yet be marked
2754 as such if the caller has created NEWDECL, but has not yet
2755 figured out that it is a redeclaration. */
2756 if (!DECL_USE_TEMPLATE (newdecl))
2757 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2759 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2760 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2761 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2764 /* Don't really know how much of the language-specific
2765 values we should copy from old to new. */
2766 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2768 if (LANG_DECL_HAS_MIN (newdecl))
2770 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2771 if (DECL_TEMPLATE_INFO (newdecl))
2773 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2774 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2775 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2776 /* Remember the presence of explicit specialization args. */
2777 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2778 = TINFO_USED_TEMPLATE_ID (new_template_info);
2781 /* We don't want to copy template info from a non-templated friend
2782 (PR105761), but these shouldn't have DECL_TEMPLATE_INFO now. */
2783 gcc_checking_assert (!DECL_TEMPLATE_INFO (olddecl)
2784 || !non_templated_friend_p (olddecl));
2785 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2788 if (DECL_DECLARES_FUNCTION_P (newdecl))
2790 /* Only functions have these fields. */
2791 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2792 DECL_BEFRIENDING_CLASSES (newdecl)
2793 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2794 DECL_BEFRIENDING_CLASSES (olddecl));
2795 /* DECL_THUNKS is only valid for virtual functions,
2796 otherwise it is a DECL_FRIEND_CONTEXT. */
2797 if (DECL_VIRTUAL_P (newdecl))
2798 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2799 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2800 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2802 else if (VAR_P (newdecl))
2804 /* Only variables have this field. */
2805 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2806 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2810 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2812 tree parm;
2814 /* Merge parameter attributes. */
2815 tree oldarg, newarg;
2816 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2817 oldarg && newarg;
2818 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2820 DECL_ATTRIBUTES (newarg)
2821 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2822 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2825 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2826 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2828 /* If newdecl is not a specialization, then it is not a
2829 template-related function at all. And that means that we
2830 should have exited above, returning 0. */
2831 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2833 if (DECL_ODR_USED (olddecl))
2834 /* From [temp.expl.spec]:
2836 If a template, a member template or the member of a class
2837 template is explicitly specialized then that
2838 specialization shall be declared before the first use of
2839 that specialization that would cause an implicit
2840 instantiation to take place, in every translation unit in
2841 which such a use occurs. */
2842 error ("explicit specialization of %qD after first use",
2843 olddecl);
2845 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2846 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2847 && DECL_DECLARED_INLINE_P (newdecl));
2849 /* Don't propagate visibility from the template to the
2850 specialization here. We'll do that in determine_visibility if
2851 appropriate. */
2852 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2854 /* [temp.expl.spec/14] We don't inline explicit specialization
2855 just because the primary template says so. */
2856 gcc_assert (!merge_attr);
2858 DECL_DECLARED_INLINE_P (olddecl)
2859 = DECL_DECLARED_INLINE_P (newdecl);
2861 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2862 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2864 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2866 else if (new_defines_function && DECL_INITIAL (olddecl))
2868 /* Never inline re-defined extern inline functions.
2869 FIXME: this could be better handled by keeping both
2870 function as separate declarations. */
2871 DECL_UNINLINABLE (newdecl) = 1;
2873 else
2875 if (DECL_PENDING_INLINE_P (olddecl))
2877 DECL_PENDING_INLINE_P (newdecl) = 1;
2878 DECL_PENDING_INLINE_INFO (newdecl)
2879 = DECL_PENDING_INLINE_INFO (olddecl);
2881 else if (DECL_PENDING_INLINE_P (newdecl))
2883 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2884 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2885 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2887 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2889 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2890 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2892 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2893 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2894 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2895 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2898 /* Preserve abstractness on cloned [cd]tors. */
2899 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2901 /* Update newdecl's parms to point at olddecl. */
2902 for (parm = DECL_ARGUMENTS (newdecl); parm;
2903 parm = DECL_CHAIN (parm))
2904 DECL_CONTEXT (parm) = olddecl;
2906 if (! types_match)
2908 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2909 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2910 COPY_DECL_RTL (newdecl, olddecl);
2912 if (! types_match || new_defines_function)
2914 /* These are the final DECL_ARGUMENTS that will be used within the
2915 body; update any references to old DECL_ARGUMENTS in the
2916 contracts, if present. */
2917 if (tree contracts = DECL_CONTRACTS (newdecl))
2918 remap_contracts (olddecl, newdecl, contracts, true);
2920 /* These need to be copied so that the names are available.
2921 Note that if the types do match, we'll preserve inline
2922 info and other bits, but if not, we won't. */
2923 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2924 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2926 /* In some cases, duplicate_contracts will remove contracts from
2927 OLDDECL, to avoid duplications. Sometimes, the contracts end up
2928 shared. If we removed them, re-add them. */
2929 if (!DECL_CONTRACTS (olddecl))
2930 copy_contract_attributes (olddecl, newdecl);
2932 /* If redeclaring a builtin function, it stays built in
2933 if newdecl is a gnu_inline definition, or if newdecl is just
2934 a declaration. */
2935 if (fndecl_built_in_p (olddecl)
2936 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2938 copy_decl_built_in_function (newdecl, olddecl);
2939 /* If we're keeping the built-in definition, keep the rtl,
2940 regardless of declaration matches. */
2941 COPY_DECL_RTL (olddecl, newdecl);
2942 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2944 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2945 if (builtin_decl_explicit_p (fncode))
2947 /* A compatible prototype of these builtin functions
2948 is seen, assume the runtime implements it with
2949 the expected semantics. */
2950 switch (fncode)
2952 case BUILT_IN_STPCPY:
2953 set_builtin_decl_implicit_p (fncode, true);
2954 break;
2955 default:
2956 set_builtin_decl_declared_p (fncode, true);
2957 break;
2961 copy_attributes_to_builtin (newdecl);
2964 if (new_defines_function)
2965 /* If defining a function declared with other language
2966 linkage, use the previously declared language linkage. */
2967 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2968 else if (types_match)
2970 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2971 /* Don't clear out the arguments if we're just redeclaring a
2972 function. */
2973 if (DECL_ARGUMENTS (olddecl))
2975 /* If we removed contracts from previous definition, re-attach
2976 them. Otherwise, rewrite the contracts so they match the
2977 parameters of the new declaration. */
2978 if (DECL_INITIAL (olddecl)
2979 && DECL_CONTRACTS (newdecl)
2980 && !DECL_CONTRACTS (olddecl))
2981 copy_contract_attributes (olddecl, newdecl);
2982 else
2984 /* Temporarily undo the re-contexting of parameters so we can
2985 actually remap parameters. The inliner won't replace
2986 parameters if we don't do this. */
2987 tree args = DECL_ARGUMENTS (newdecl);
2988 for (tree p = args; p; p = DECL_CHAIN (p))
2989 DECL_CONTEXT (p) = newdecl;
2991 /* Save new argument names for use in contracts parsing,
2992 unless we've already started parsing the body of olddecl
2993 (particular issues arise when newdecl is from a prior
2994 friend decl with no argument names, see
2995 modules/contracts-tpl-friend-1). */
2996 if (tree contracts = DECL_CONTRACTS (olddecl))
2997 remap_contracts (newdecl, olddecl, contracts, true);
2999 /* And reverse this operation again. */
3000 for (tree p = args; p; p = DECL_CHAIN (p))
3001 DECL_CONTEXT (p) = olddecl;
3004 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
3008 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
3009 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
3011 /* Now preserve various other info from the definition. */
3012 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
3013 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
3014 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
3015 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
3017 /* Warn about conflicting visibility specifications. */
3018 if (DECL_VISIBILITY_SPECIFIED (olddecl)
3019 && DECL_VISIBILITY_SPECIFIED (newdecl)
3020 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
3022 auto_diagnostic_group d;
3023 if (warning_at (newdecl_loc, OPT_Wattributes,
3024 "%qD: visibility attribute ignored because it "
3025 "conflicts with previous declaration", newdecl))
3026 inform (olddecl_loc,
3027 "previous declaration of %qD", olddecl);
3029 /* Choose the declaration which specified visibility. */
3030 if (DECL_VISIBILITY_SPECIFIED (olddecl))
3032 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
3033 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
3035 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
3036 so keep this behavior. */
3037 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
3039 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
3040 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
3042 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
3043 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
3045 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
3046 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
3048 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
3049 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
3050 DECL_USER_ALIGN (newdecl) = 1;
3052 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
3053 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
3054 > DECL_WARN_IF_NOT_ALIGN (newdecl))
3055 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
3056 DECL_WARN_IF_NOT_ALIGN (olddecl));
3057 if (TREE_CODE (newdecl) == FIELD_DECL)
3058 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
3060 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
3061 with that from NEWDECL below. */
3062 if (DECL_LANG_SPECIFIC (olddecl))
3064 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
3065 != DECL_LANG_SPECIFIC (newdecl));
3066 ggc_free (DECL_LANG_SPECIFIC (olddecl));
3069 /* Merge the USED information. */
3070 if (TREE_USED (olddecl))
3071 TREE_USED (newdecl) = 1;
3072 else if (TREE_USED (newdecl))
3073 TREE_USED (olddecl) = 1;
3075 if (VAR_P (newdecl))
3077 if (DECL_READ_P (olddecl))
3078 DECL_READ_P (newdecl) = 1;
3079 else if (DECL_READ_P (newdecl))
3080 DECL_READ_P (olddecl) = 1;
3083 if (DECL_PRESERVE_P (olddecl))
3084 DECL_PRESERVE_P (newdecl) = 1;
3085 else if (DECL_PRESERVE_P (newdecl))
3086 DECL_PRESERVE_P (olddecl) = 1;
3088 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
3089 to olddecl and deleted. */
3090 if (TREE_CODE (newdecl) == FUNCTION_DECL
3091 && DECL_FUNCTION_VERSIONED (olddecl))
3093 /* Set the flag for newdecl so that it gets copied to olddecl. */
3094 DECL_FUNCTION_VERSIONED (newdecl) = 1;
3095 /* newdecl will be purged after copying to olddecl and is no longer
3096 a version. */
3097 cgraph_node::delete_function_version_by_decl (newdecl);
3100 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3102 int function_size;
3103 struct symtab_node *snode = symtab_node::get (olddecl);
3105 function_size = sizeof (struct tree_decl_common);
3107 memcpy ((char *) olddecl + sizeof (struct tree_common),
3108 (char *) newdecl + sizeof (struct tree_common),
3109 function_size - sizeof (struct tree_common));
3111 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3112 (char *) newdecl + sizeof (struct tree_decl_common),
3113 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
3115 /* Preserve symtab node mapping. */
3116 olddecl->decl_with_vis.symtab_node = snode;
3118 if (new_template_info)
3119 /* If newdecl is a template instantiation, it is possible that
3120 the following sequence of events has occurred:
3122 o A friend function was declared in a class template. The
3123 class template was instantiated.
3125 o The instantiation of the friend declaration was
3126 recorded on the instantiation list, and is newdecl.
3128 o Later, however, instantiate_class_template called pushdecl
3129 on the newdecl to perform name injection. But, pushdecl in
3130 turn called duplicate_decls when it discovered that another
3131 declaration of a global function with the same name already
3132 existed.
3134 o Here, in duplicate_decls, we decided to clobber newdecl.
3136 If we're going to do that, we'd better make sure that
3137 olddecl, and not newdecl, is on the list of
3138 instantiations so that if we try to do the instantiation
3139 again we won't get the clobbered declaration. */
3140 reregister_specialization (newdecl,
3141 new_template_info,
3142 olddecl);
3144 else
3146 size_t size = tree_code_size (TREE_CODE (newdecl));
3148 memcpy ((char *) olddecl + sizeof (struct tree_common),
3149 (char *) newdecl + sizeof (struct tree_common),
3150 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
3152 switch (TREE_CODE (newdecl))
3154 case LABEL_DECL:
3155 case VAR_DECL:
3156 case RESULT_DECL:
3157 case PARM_DECL:
3158 case FIELD_DECL:
3159 case TYPE_DECL:
3160 case CONST_DECL:
3162 struct symtab_node *snode = NULL;
3164 if (VAR_P (newdecl)
3165 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3166 || DECL_EXTERNAL (olddecl)))
3167 snode = symtab_node::get (olddecl);
3168 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3169 (char *) newdecl + sizeof (struct tree_decl_common),
3170 size - sizeof (struct tree_decl_common)
3171 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3172 if (VAR_P (newdecl))
3173 olddecl->decl_with_vis.symtab_node = snode;
3175 break;
3176 default:
3177 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3178 (char *) newdecl + sizeof (struct tree_decl_common),
3179 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3180 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3181 break;
3185 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3187 if (DECL_EXTERNAL (olddecl)
3188 || TREE_PUBLIC (olddecl)
3189 || TREE_STATIC (olddecl))
3191 /* Merge the section attribute.
3192 We want to issue an error if the sections conflict but that must be
3193 done later in decl_attributes since we are called before attributes
3194 are assigned. */
3195 if (DECL_SECTION_NAME (newdecl) != NULL)
3196 set_decl_section_name (olddecl, newdecl);
3198 if (DECL_ONE_ONLY (newdecl))
3200 struct symtab_node *oldsym, *newsym;
3201 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3202 oldsym = cgraph_node::get_create (olddecl);
3203 else
3204 oldsym = varpool_node::get_create (olddecl);
3205 newsym = symtab_node::get (newdecl);
3206 oldsym->set_comdat_group (newsym->get_comdat_group ());
3210 if (VAR_P (newdecl)
3211 && CP_DECL_THREAD_LOCAL_P (newdecl))
3213 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3214 if (!processing_template_decl)
3215 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3219 DECL_UID (olddecl) = olddecl_uid;
3221 /* NEWDECL contains the merged attribute lists.
3222 Update OLDDECL to be the same. */
3223 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3225 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3226 so that encode_section_info has a chance to look at the new decl
3227 flags and attributes. */
3228 if (DECL_RTL_SET_P (olddecl)
3229 && (TREE_CODE (olddecl) == FUNCTION_DECL
3230 || (VAR_P (olddecl)
3231 && TREE_STATIC (olddecl))))
3232 make_decl_rtl (olddecl);
3234 /* The NEWDECL will no longer be needed. Because every out-of-class
3235 declaration of a member results in a call to duplicate_decls,
3236 freeing these nodes represents in a significant savings.
3238 Before releasing the node, be sore to remove function from symbol
3239 table that might have been inserted there to record comdat group.
3240 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3241 structure is shared in between newdecl and oldecl. */
3242 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3243 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3244 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3246 struct symtab_node *snode = symtab_node::get (newdecl);
3247 if (snode)
3248 snode->remove ();
3251 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3253 tree clone;
3254 FOR_EACH_CLONE (clone, olddecl)
3256 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3257 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3261 /* Remove the associated constraints for newdecl, if any, before
3262 reclaiming memory. */
3263 if (flag_concepts)
3264 remove_constraints (newdecl);
3266 ggc_free (newdecl);
3268 return olddecl;
3271 /* Return zero if the declaration NEWDECL is valid
3272 when the declaration OLDDECL (assumed to be for the same name)
3273 has already been seen.
3274 Otherwise return an error message format string with a %s
3275 where the identifier should go. */
3277 static const char *
3278 redeclaration_error_message (tree newdecl, tree olddecl)
3280 if (TREE_CODE (newdecl) == TYPE_DECL)
3282 /* Because C++ can put things into name space for free,
3283 constructs like "typedef struct foo { ... } foo"
3284 would look like an erroneous redeclaration. */
3285 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3286 return NULL;
3287 else
3288 return G_("redefinition of %q#D");
3290 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3292 /* If this is a pure function, its olddecl will actually be
3293 the original initialization to `0' (which we force to call
3294 abort()). Don't complain about redefinition in this case. */
3295 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3296 && DECL_INITIAL (olddecl) == NULL_TREE)
3297 return NULL;
3299 /* If both functions come from different namespaces, this is not
3300 a redeclaration - this is a conflict with a used function. */
3301 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3302 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3303 && ! decls_match (olddecl, newdecl))
3304 return G_("%qD conflicts with used function");
3306 /* We'll complain about linkage mismatches in
3307 warn_extern_redeclared_static. */
3309 /* Defining the same name twice is no good. */
3310 if (decl_defined_p (olddecl)
3311 && decl_defined_p (newdecl))
3313 if (DECL_NAME (olddecl) == NULL_TREE)
3314 return G_("%q#D not declared in class");
3315 else if (!GNU_INLINE_P (olddecl)
3316 || GNU_INLINE_P (newdecl))
3317 return G_("redefinition of %q#D");
3320 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3322 bool olda = GNU_INLINE_P (olddecl);
3323 bool newa = GNU_INLINE_P (newdecl);
3325 if (olda != newa)
3327 if (newa)
3328 return G_("%q+D redeclared inline with "
3329 "%<gnu_inline%> attribute");
3330 else
3331 return G_("%q+D redeclared inline without "
3332 "%<gnu_inline%> attribute");
3336 /* [class.compare.default]: A definition of a comparison operator as
3337 defaulted that appears in a class shall be the first declaration of
3338 that function. */
3339 special_function_kind sfk = special_function_p (olddecl);
3340 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3341 return G_("comparison operator %q+D defaulted after "
3342 "its first declaration");
3344 check_abi_tag_redeclaration
3345 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3346 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3348 return NULL;
3350 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3352 tree nt, ot;
3354 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3355 return G_("redefinition of %q#D");
3357 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3358 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3359 DECL_TEMPLATE_RESULT (olddecl));
3361 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3362 return NULL;
3364 nt = DECL_TEMPLATE_RESULT (newdecl);
3365 if (DECL_TEMPLATE_INFO (nt))
3366 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3367 ot = DECL_TEMPLATE_RESULT (olddecl);
3368 if (DECL_TEMPLATE_INFO (ot))
3369 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3370 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3371 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3372 return G_("redefinition of %q#D");
3374 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3376 bool olda = GNU_INLINE_P (ot);
3377 bool newa = GNU_INLINE_P (nt);
3379 if (olda != newa)
3381 if (newa)
3382 return G_("%q+D redeclared inline with "
3383 "%<gnu_inline%> attribute");
3384 else
3385 return G_("%q+D redeclared inline without "
3386 "%<gnu_inline%> attribute");
3390 /* Core issue #226 (C++11):
3392 If a friend function template declaration specifies a
3393 default template-argument, that declaration shall be a
3394 definition and shall be the only declaration of the
3395 function template in the translation unit. */
3396 if ((cxx_dialect != cxx98)
3397 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3398 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3399 /*is_primary=*/true,
3400 /*is_partial=*/false,
3401 /*is_friend_decl=*/2))
3402 return G_("redeclaration of friend %q#D "
3403 "may not have default template arguments");
3405 return NULL;
3407 else if (VAR_P (newdecl)
3408 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3409 != CP_DECL_THREAD_LOCAL_P (olddecl))
3410 && (! DECL_LANG_SPECIFIC (olddecl)
3411 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3412 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3414 /* Only variables can be thread-local, and all declarations must
3415 agree on this property. */
3416 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3417 return G_("thread-local declaration of %q#D follows "
3418 "non-thread-local declaration");
3419 else
3420 return G_("non-thread-local declaration of %q#D follows "
3421 "thread-local declaration");
3423 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3425 /* The objects have been declared at namespace scope. If either
3426 is a member of an anonymous union, then this is an invalid
3427 redeclaration. For example:
3429 int i;
3430 union { int i; };
3432 is invalid. */
3433 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3434 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3435 return G_("redeclaration of %q#D");
3436 /* If at least one declaration is a reference, there is no
3437 conflict. For example:
3439 int i = 3;
3440 extern int i;
3442 is valid. */
3443 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3444 return NULL;
3446 /* Static data member declared outside a class definition
3447 if the variable is defined within the class with constexpr
3448 specifier is declaration rather than definition (and
3449 deprecated). */
3450 if (cxx_dialect >= cxx17
3451 && VAR_P (olddecl)
3452 && DECL_CLASS_SCOPE_P (olddecl)
3453 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3454 && !DECL_INITIAL (newdecl))
3456 DECL_EXTERNAL (newdecl) = 1;
3457 /* For now, only warn with explicit -Wdeprecated. */
3458 if (OPTION_SET_P (warn_deprecated))
3460 auto_diagnostic_group d;
3461 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3462 "redundant redeclaration of %<constexpr%> "
3463 "static data member %qD", newdecl))
3464 inform (DECL_SOURCE_LOCATION (olddecl),
3465 "previous declaration of %qD", olddecl);
3467 return NULL;
3470 /* Reject two definitions. */
3471 return G_("redefinition of %q#D");
3473 else
3475 /* Objects declared with block scope: */
3476 /* Reject two definitions, and reject a definition
3477 together with an external reference. */
3478 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3479 return G_("redeclaration of %q#D");
3480 return NULL;
3485 /* Hash and equality functions for the named_label table. */
3487 hashval_t
3488 named_label_hash::hash (const value_type entry)
3490 return IDENTIFIER_HASH_VALUE (entry->name);
3493 bool
3494 named_label_hash::equal (const value_type entry, compare_type name)
3496 return name == entry->name;
3499 /* Look for a label named ID in the current function. If one cannot
3500 be found, create one. Return the named_label_entry, or NULL on
3501 failure. */
3503 static named_label_entry *
3504 lookup_label_1 (tree id, bool making_local_p)
3506 auto_cond_timevar tv (TV_NAME_LOOKUP);
3508 /* You can't use labels at global scope. */
3509 if (current_function_decl == NULL_TREE)
3511 error ("label %qE referenced outside of any function", id);
3512 return NULL;
3515 if (!named_labels)
3516 named_labels = hash_table<named_label_hash>::create_ggc (13);
3518 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3519 named_label_entry **slot
3520 = named_labels->find_slot_with_hash (id, hash, INSERT);
3521 named_label_entry *old = *slot;
3523 if (old && old->label_decl)
3525 if (!making_local_p)
3526 return old;
3528 if (old->binding_level == current_binding_level)
3530 error ("local label %qE conflicts with existing label", id);
3531 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3532 return NULL;
3536 /* We are making a new decl, create or reuse the named_label_entry */
3537 named_label_entry *ent = NULL;
3538 if (old && !old->label_decl)
3539 ent = old;
3540 else
3542 ent = ggc_cleared_alloc<named_label_entry> ();
3543 ent->name = id;
3544 ent->outer = old;
3545 *slot = ent;
3548 /* Now create the LABEL_DECL. */
3549 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3551 DECL_CONTEXT (decl) = current_function_decl;
3552 SET_DECL_MODE (decl, VOIDmode);
3553 if (making_local_p)
3555 C_DECLARED_LABEL_FLAG (decl) = true;
3556 DECL_CHAIN (decl) = current_binding_level->names;
3557 current_binding_level->names = decl;
3560 ent->label_decl = decl;
3562 return ent;
3565 /* Wrapper for lookup_label_1. */
3567 tree
3568 lookup_label (tree id)
3570 named_label_entry *ent = lookup_label_1 (id, false);
3571 return ent ? ent->label_decl : NULL_TREE;
3574 tree
3575 declare_local_label (tree id)
3577 named_label_entry *ent = lookup_label_1 (id, true);
3578 return ent ? ent->label_decl : NULL_TREE;
3581 /* Returns true if it is ill-formed to jump past the declaration of DECL. */
3583 static bool
3584 decl_jump_unsafe (tree decl)
3586 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3587 with automatic storage duration is not in scope to a point where it is
3588 in scope is ill-formed unless the variable has scalar type, class type
3589 with a trivial default constructor and a trivial destructor, a
3590 cv-qualified version of one of these types, or an array of one of the
3591 preceding types and is declared without an initializer (8.5). */
3592 tree type = TREE_TYPE (decl);
3594 return (type != error_mark_node
3595 && VAR_P (decl)
3596 && !TREE_STATIC (decl)
3597 && (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3598 || variably_modified_type_p (type, NULL_TREE)));
3601 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3602 to the user. */
3604 static bool
3605 identify_goto (tree decl, location_t loc, const location_t *locus,
3606 diagnostic_t diag_kind)
3608 bool complained
3609 = emit_diagnostic (diag_kind, loc, 0,
3610 decl ? N_("jump to label %qD")
3611 : N_("jump to case label"), decl);
3612 if (complained && locus)
3613 inform (*locus, " from here");
3614 return complained;
3617 /* Check that a single previously seen jump to a newly defined label
3618 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3619 the jump context; NAMES are the names in scope in LEVEL at the jump
3620 context; LOCUS is the source position of the jump or 0. Returns
3621 true if all is well. */
3623 static bool
3624 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3625 bool exited_omp, const location_t *locus)
3627 cp_binding_level *b;
3628 bool complained = false;
3629 int identified = 0;
3630 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3631 bool saw_ceif = false, saw_se = false;
3633 if (exited_omp)
3635 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3636 if (complained)
3637 inform (input_location, " exits OpenMP structured block");
3638 saw_omp = true;
3639 identified = 2;
3642 for (b = current_binding_level; b ; b = b->level_chain)
3644 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3646 for (new_decls = b->names; new_decls != old_decls;
3647 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3648 : TREE_CHAIN (new_decls)))
3650 bool problem = decl_jump_unsafe (new_decls);
3651 if (! problem)
3652 continue;
3654 if (!identified)
3656 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3657 identified = 1;
3659 if (complained)
3660 inform (DECL_SOURCE_LOCATION (new_decls),
3661 " crosses initialization of %q#D", new_decls);
3664 if (b == level)
3665 break;
3667 const char *inf = NULL;
3668 location_t loc = input_location;
3669 switch (b->kind)
3671 case sk_try:
3672 if (!saw_eh)
3673 inf = G_(" enters %<try%> block");
3674 saw_eh = true;
3675 break;
3677 case sk_catch:
3678 if (!saw_eh)
3679 inf = G_(" enters %<catch%> block");
3680 saw_eh = true;
3681 break;
3683 case sk_omp:
3684 if (!saw_omp)
3685 inf = G_(" enters OpenMP structured block");
3686 saw_omp = true;
3687 break;
3689 case sk_transaction:
3690 if (!saw_tm)
3691 inf = G_(" enters synchronized or atomic statement");
3692 saw_tm = true;
3693 break;
3695 case sk_stmt_expr:
3696 if (!saw_se)
3697 inf = G_(" enters statement expression");
3698 saw_se = true;
3699 break;
3701 case sk_block:
3702 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3704 inf = G_(" enters %<constexpr if%> statement");
3705 loc = EXPR_LOCATION (b->level_chain->this_entity);
3706 saw_cxif = true;
3708 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3710 inf = G_(" enters %<consteval if%> statement");
3711 loc = EXPR_LOCATION (b->level_chain->this_entity);
3712 saw_ceif = true;
3714 break;
3716 default:
3717 break;
3720 if (inf)
3722 if (identified < 2)
3723 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3724 identified = 2;
3725 if (complained)
3726 inform (loc, inf);
3730 return !identified;
3733 static void
3734 check_previous_goto (tree decl, struct named_label_use_entry *use)
3736 check_previous_goto_1 (decl, use->binding_level,
3737 use->names_in_scope, use->in_omp_scope,
3738 &use->o_goto_locus);
3741 static bool
3742 check_switch_goto (cp_binding_level* level)
3744 return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3747 /* Check that a new jump to a label DECL is OK. Called by
3748 finish_goto_stmt. */
3750 void
3751 check_goto (tree decl)
3753 /* We can't know where a computed goto is jumping.
3754 So we assume that it's OK. */
3755 if (TREE_CODE (decl) != LABEL_DECL)
3756 return;
3758 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3759 named_label_entry **slot
3760 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3761 named_label_entry *ent = *slot;
3763 /* If the label hasn't been defined yet, defer checking. */
3764 if (! DECL_INITIAL (decl))
3766 /* Don't bother creating another use if the last goto had the
3767 same data, and will therefore create the same set of errors. */
3768 if (ent->uses
3769 && ent->uses->names_in_scope == current_binding_level->names)
3770 return;
3772 named_label_use_entry *new_use
3773 = ggc_alloc<named_label_use_entry> ();
3774 new_use->binding_level = current_binding_level;
3775 new_use->names_in_scope = current_binding_level->names;
3776 new_use->o_goto_locus = input_location;
3777 new_use->in_omp_scope = false;
3779 new_use->next = ent->uses;
3780 ent->uses = new_use;
3781 return;
3784 bool saw_catch = false, complained = false;
3785 int identified = 0;
3786 tree bad;
3787 unsigned ix;
3789 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3790 || ent->in_constexpr_if || ent->in_consteval_if
3791 || ent->in_omp_scope || ent->in_stmt_expr
3792 || !vec_safe_is_empty (ent->bad_decls))
3794 diagnostic_t diag_kind = DK_PERMERROR;
3795 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3796 || ent->in_consteval_if || ent->in_transaction_scope
3797 || ent->in_omp_scope || ent->in_stmt_expr)
3798 diag_kind = DK_ERROR;
3799 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3800 &input_location, diag_kind);
3801 identified = 1 + (diag_kind == DK_ERROR);
3804 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3806 bool problem = decl_jump_unsafe (bad);
3808 if (problem && DECL_ARTIFICIAL (bad))
3810 /* Can't skip init of __exception_info. */
3811 if (identified == 1)
3813 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3814 &input_location, DK_ERROR);
3815 identified = 2;
3817 if (complained)
3818 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3819 saw_catch = true;
3821 else if (complained)
3822 inform (DECL_SOURCE_LOCATION (bad),
3823 " skips initialization of %q#D", bad);
3826 if (complained)
3828 if (ent->in_try_scope)
3829 inform (input_location, " enters %<try%> block");
3830 else if (ent->in_catch_scope && !saw_catch)
3831 inform (input_location, " enters %<catch%> block");
3832 else if (ent->in_transaction_scope)
3833 inform (input_location, " enters synchronized or atomic statement");
3834 else if (ent->in_constexpr_if)
3835 inform (input_location, " enters %<constexpr if%> statement");
3836 else if (ent->in_consteval_if)
3837 inform (input_location, " enters %<consteval if%> statement");
3838 else if (ent->in_stmt_expr)
3839 inform (input_location, " enters statement expression");
3842 if (ent->in_omp_scope)
3844 if (complained)
3845 inform (input_location, " enters OpenMP structured block");
3847 else if (flag_openmp)
3848 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3850 if (b == ent->binding_level)
3851 break;
3852 if (b->kind == sk_omp)
3854 if (identified < 2)
3856 complained = identify_goto (decl,
3857 DECL_SOURCE_LOCATION (decl),
3858 &input_location, DK_ERROR);
3859 identified = 2;
3861 if (complained)
3862 inform (input_location, " exits OpenMP structured block");
3863 break;
3868 /* Check that a return is ok wrt OpenMP structured blocks.
3869 Called by finish_return_stmt. Returns true if all is well. */
3871 bool
3872 check_omp_return (void)
3874 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3875 if (b->kind == sk_omp)
3877 error ("invalid exit from OpenMP structured block");
3878 return false;
3880 else if (b->kind == sk_function_parms)
3881 break;
3882 return true;
3885 /* Define a label, specifying the location in the source file.
3886 Return the LABEL_DECL node for the label. */
3888 tree
3889 define_label (location_t location, tree name)
3891 auto_cond_timevar tv (TV_NAME_LOOKUP);
3893 /* After labels, make any new cleanups in the function go into their
3894 own new (temporary) binding contour. */
3895 for (cp_binding_level *p = current_binding_level;
3896 p->kind != sk_function_parms;
3897 p = p->level_chain)
3898 p->more_cleanups_ok = 0;
3900 named_label_entry *ent = lookup_label_1 (name, false);
3901 tree decl = ent->label_decl;
3903 if (DECL_INITIAL (decl) != NULL_TREE)
3905 error ("duplicate label %qD", decl);
3906 return error_mark_node;
3908 else
3910 /* Mark label as having been defined. */
3911 DECL_INITIAL (decl) = error_mark_node;
3912 /* Say where in the source. */
3913 DECL_SOURCE_LOCATION (decl) = location;
3915 ent->binding_level = current_binding_level;
3916 ent->names_in_scope = current_binding_level->names;
3918 for (named_label_use_entry *use = ent->uses; use; use = use->next)
3919 check_previous_goto (decl, use);
3920 ent->uses = NULL;
3923 return decl;
3926 struct cp_switch
3928 cp_binding_level *level;
3929 struct cp_switch *next;
3930 /* The SWITCH_STMT being built. */
3931 tree switch_stmt;
3932 /* A splay-tree mapping the low element of a case range to the high
3933 element, or NULL_TREE if there is no high element. Used to
3934 determine whether or not a new case label duplicates an old case
3935 label. We need a tree, rather than simply a hash table, because
3936 of the GNU case range extension. */
3937 splay_tree cases;
3938 /* Remember whether a default: case label has been seen. */
3939 bool has_default_p;
3940 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
3941 bool break_stmt_seen_p;
3942 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3943 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
3944 bool in_loop_body_p;
3947 /* A stack of the currently active switch statements. The innermost
3948 switch statement is on the top of the stack. There is no need to
3949 mark the stack for garbage collection because it is only active
3950 during the processing of the body of a function, and we never
3951 collect at that point. */
3953 static struct cp_switch *switch_stack;
3955 /* Called right after a switch-statement condition is parsed.
3956 SWITCH_STMT is the switch statement being parsed. */
3958 void
3959 push_switch (tree switch_stmt)
3961 struct cp_switch *p = XNEW (struct cp_switch);
3962 p->level = current_binding_level;
3963 p->next = switch_stack;
3964 p->switch_stmt = switch_stmt;
3965 p->cases = splay_tree_new (case_compare, NULL, NULL);
3966 p->has_default_p = false;
3967 p->break_stmt_seen_p = false;
3968 p->in_loop_body_p = false;
3969 switch_stack = p;
3972 void
3973 pop_switch (void)
3975 struct cp_switch *cs = switch_stack;
3977 /* Emit warnings as needed. */
3978 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3979 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3980 const bool bool_cond_p
3981 = (SWITCH_STMT_TYPE (cs->switch_stmt)
3982 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3983 if (!processing_template_decl)
3984 c_do_switch_warnings (cs->cases, switch_location,
3985 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3986 bool_cond_p);
3988 /* For the benefit of block_may_fallthru remember if the switch body
3989 case labels cover all possible values and if there are break; stmts. */
3990 if (cs->has_default_p
3991 || (!processing_template_decl
3992 && c_switch_covers_all_cases_p (cs->cases,
3993 SWITCH_STMT_TYPE (cs->switch_stmt))))
3994 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3995 if (!cs->break_stmt_seen_p)
3996 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3997 /* Now that we're done with the switch warnings, set the switch type
3998 to the type of the condition if the index type was of scoped enum type.
3999 (Such types don't participate in the integer promotions.) We do this
4000 because of bit-fields whose declared type is a scoped enum type:
4001 gimplification will use the lowered index type, but convert the
4002 case values to SWITCH_STMT_TYPE, which would have been the declared type
4003 and verify_gimple_switch doesn't accept that. */
4004 if (is_bitfield_expr_with_lowered_type (cond))
4005 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
4006 gcc_assert (!cs->in_loop_body_p);
4007 splay_tree_delete (cs->cases);
4008 switch_stack = switch_stack->next;
4009 free (cs);
4012 /* Note that a BREAK_STMT is about to be added. If it is inside of
4013 a SWITCH_STMT and not inside of a loop body inside of it, note
4014 in switch_stack we've seen a BREAK_STMT. */
4016 void
4017 note_break_stmt (void)
4019 if (switch_stack && !switch_stack->in_loop_body_p)
4020 switch_stack->break_stmt_seen_p = true;
4023 /* Note the start of processing of an iteration statement's body.
4024 The note_break_stmt function will do nothing while processing it.
4025 Return a flag that should be passed to note_iteration_stmt_body_end. */
4027 bool
4028 note_iteration_stmt_body_start (void)
4030 if (!switch_stack)
4031 return false;
4032 bool ret = switch_stack->in_loop_body_p;
4033 switch_stack->in_loop_body_p = true;
4034 return ret;
4037 /* Note the end of processing of an iteration statement's body. */
4039 void
4040 note_iteration_stmt_body_end (bool prev)
4042 if (switch_stack)
4043 switch_stack->in_loop_body_p = prev;
4046 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
4047 condition. Note that if TYPE and VALUE are already integral we don't
4048 really do the conversion because the language-independent
4049 warning/optimization code will work better that way. */
4051 static tree
4052 case_conversion (tree type, tree value)
4054 if (value == NULL_TREE)
4055 return value;
4057 value = mark_rvalue_use (value);
4059 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
4060 type = type_promotes_to (type);
4062 tree ovalue = value;
4063 /* The constant-expression VALUE shall be a converted constant expression
4064 of the adjusted type of the switch condition, which doesn't allow
4065 narrowing conversions. */
4066 value = build_converted_constant_expr (type, value, tf_warning_or_error);
4068 if (cxx_dialect >= cxx11
4069 && (SCOPED_ENUM_P (type)
4070 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
4071 /* Use the converted value. */;
4072 else
4073 /* The already integral case. */
4074 value = ovalue;
4076 return cxx_constant_value (value);
4079 /* Note that we've seen a definition of a case label, and complain if this
4080 is a bad place for one. */
4082 tree
4083 finish_case_label (location_t loc, tree low_value, tree high_value)
4085 tree cond, r;
4086 cp_binding_level *p;
4087 tree type;
4089 if (low_value == NULL_TREE && high_value == NULL_TREE)
4090 switch_stack->has_default_p = true;
4092 if (processing_template_decl)
4094 tree label;
4096 /* For templates, just add the case label; we'll do semantic
4097 analysis at instantiation-time. */
4098 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
4099 return add_stmt (build_case_label (low_value, high_value, label));
4102 /* Find the condition on which this switch statement depends. */
4103 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
4104 if (cond && TREE_CODE (cond) == TREE_LIST)
4105 cond = TREE_VALUE (cond);
4107 if (!check_switch_goto (switch_stack->level))
4108 return error_mark_node;
4110 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
4111 if (type == error_mark_node)
4112 return error_mark_node;
4114 low_value = case_conversion (type, low_value);
4115 high_value = case_conversion (type, high_value);
4117 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
4119 /* After labels, make any new cleanups in the function go into their
4120 own new (temporary) binding contour. */
4121 for (p = current_binding_level;
4122 p->kind != sk_function_parms;
4123 p = p->level_chain)
4124 p->more_cleanups_ok = 0;
4126 return r;
4129 struct typename_info {
4130 tree scope;
4131 tree name;
4132 tree template_id;
4133 bool enum_p;
4134 bool class_p;
4137 struct typename_hasher : ggc_ptr_hash<tree_node>
4139 typedef typename_info *compare_type;
4141 /* Hash a TYPENAME_TYPE. */
4143 static hashval_t
4144 hash (tree context, tree fullname)
4146 hashval_t hash = 0;
4147 hash = iterative_hash_object (context, hash);
4148 hash = iterative_hash_object (fullname, hash);
4149 return hash;
4152 static hashval_t
4153 hash (const typename_info *ti)
4155 return typename_hasher::hash (ti->scope, ti->template_id);
4158 static hashval_t
4159 hash (tree t)
4161 return typename_hasher::hash (TYPE_CONTEXT (t), TYPENAME_TYPE_FULLNAME (t));
4164 /* Compare two TYPENAME_TYPEs. */
4166 static bool
4167 equal (tree t1, const typename_info *t2)
4169 return (TYPE_IDENTIFIER (t1) == t2->name
4170 && TYPE_CONTEXT (t1) == t2->scope
4171 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4172 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4173 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4177 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4178 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4180 Returns the new TYPENAME_TYPE. */
4182 static GTY (()) hash_table<typename_hasher> *typename_htab;
4184 tree
4185 build_typename_type (tree context, tree name, tree fullname,
4186 enum tag_types tag_type)
4188 typename_info ti;
4190 if (typename_htab == NULL)
4191 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4193 ti.scope = FROB_CONTEXT (context);
4194 ti.name = name;
4195 ti.template_id = fullname;
4196 ti.enum_p = tag_type == enum_type;
4197 ti.class_p = (tag_type == class_type
4198 || tag_type == record_type
4199 || tag_type == union_type);
4200 hashval_t hash = typename_hasher::hash (&ti);
4202 /* See if we already have this type. */
4203 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4204 tree t = *e;
4205 if (*e)
4206 t = *e;
4207 else
4209 /* Build the TYPENAME_TYPE. */
4210 t = cxx_make_type (TYPENAME_TYPE);
4211 TYPE_CONTEXT (t) = ti.scope;
4212 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4213 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4214 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4216 /* Build the corresponding TYPE_DECL. */
4217 tree d = build_decl (input_location, TYPE_DECL, name, t);
4218 TYPE_NAME (t) = d;
4219 TYPE_STUB_DECL (t) = d;
4220 DECL_CONTEXT (d) = ti.scope;
4221 DECL_ARTIFICIAL (d) = 1;
4223 /* Store it in the hash table. */
4224 *e = t;
4226 /* TYPENAME_TYPEs must always be compared structurally, because
4227 they may or may not resolve down to another type depending on
4228 the currently open classes. */
4229 SET_TYPE_STRUCTURAL_EQUALITY (t);
4232 return t;
4235 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4236 provided to name the type. Returns an appropriate type, unless an
4237 error occurs, in which case error_mark_node is returned. If we
4238 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4239 return that, rather than the _TYPE it corresponds to, in other
4240 cases we look through the type decl. If TF_ERROR is set, complain
4241 about errors, otherwise be quiet. */
4243 tree
4244 make_typename_type (tree context, tree name, enum tag_types tag_type,
4245 tsubst_flags_t complain)
4247 tree fullname;
4248 tree t;
4249 bool want_template;
4251 if (name == error_mark_node
4252 || context == NULL_TREE
4253 || context == error_mark_node)
4254 return error_mark_node;
4256 if (TYPE_P (name))
4258 if (!(TYPE_LANG_SPECIFIC (name)
4259 && (CLASSTYPE_IS_TEMPLATE (name)
4260 || CLASSTYPE_USE_TEMPLATE (name))))
4261 name = TYPE_IDENTIFIER (name);
4262 else
4263 /* Create a TEMPLATE_ID_EXPR for the type. */
4264 name = build_nt (TEMPLATE_ID_EXPR,
4265 CLASSTYPE_TI_TEMPLATE (name),
4266 CLASSTYPE_TI_ARGS (name));
4268 else if (TREE_CODE (name) == TYPE_DECL)
4269 name = DECL_NAME (name);
4271 fullname = name;
4273 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4275 name = TREE_OPERAND (name, 0);
4276 if (DECL_TYPE_TEMPLATE_P (name))
4277 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4278 if (TREE_CODE (name) != IDENTIFIER_NODE)
4280 if (complain & tf_error)
4281 error ("%qD is not a type", name);
4282 return error_mark_node;
4285 if (TREE_CODE (name) == TEMPLATE_DECL)
4287 if (complain & tf_error)
4288 error ("%qD used without template arguments", name);
4289 return error_mark_node;
4291 else if (is_overloaded_fn (name))
4293 if (complain & tf_error)
4294 error ("%qD is a function, not a type", name);
4295 return error_mark_node;
4297 gcc_assert (identifier_p (name));
4298 gcc_assert (TYPE_P (context));
4300 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4301 /* This can happen for C++17 variadic using (c++/88986). */;
4302 else if (!MAYBE_CLASS_TYPE_P (context))
4304 if (complain & tf_error)
4305 error ("%q#T is not a class", context);
4306 return error_mark_node;
4309 /* When the CONTEXT is a dependent type, NAME could refer to a
4310 dependent base class of CONTEXT. But look inside it anyway
4311 if CONTEXT is a currently open scope, in case it refers to a
4312 member of the current instantiation or a non-dependent base;
4313 lookup will stop when we hit a dependent base. */
4314 if (!dependent_scope_p (context))
4316 /* We generally don't ignore non-types during TYPENAME_TYPE lookup
4317 (as per [temp.res.general]/3), unless
4318 - the tag corresponds to a class-key or 'enum' so
4319 [basic.lookup.elab] applies, or
4320 - the tag corresponds to scope_type or tf_qualifying_scope is
4321 set so [basic.lookup.qual]/1 applies.
4322 TODO: If we'd set/track the scope_type tag thoroughly on all
4323 TYPENAME_TYPEs that are followed by :: then we wouldn't need the
4324 tf_qualifying_scope flag. */
4325 bool want_type = (tag_type != none_type && tag_type != typename_type)
4326 || (complain & tf_qualifying_scope);
4327 t = lookup_member (context, name, /*protect=*/2, want_type, complain);
4329 else
4330 t = NULL_TREE;
4332 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4333 return build_typename_type (context, name, fullname, tag_type);
4335 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4337 if (!t)
4339 if (complain & tf_error)
4341 if (!COMPLETE_TYPE_P (context))
4342 cxx_incomplete_type_error (NULL_TREE, context);
4343 else
4344 error (want_template ? G_("no class template named %q#T in %q#T")
4345 : G_("no type named %q#T in %q#T"), name, context);
4347 return error_mark_node;
4350 /* Pull out the template from an injected-class-name (or multiple). */
4351 if (want_template)
4352 t = maybe_get_template_decl_from_type_decl (t);
4354 if (TREE_CODE (t) == TREE_LIST)
4356 if (complain & tf_error)
4358 error ("lookup of %qT in %qT is ambiguous", name, context);
4359 print_candidates (t);
4361 return error_mark_node;
4364 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4366 if (complain & tf_error)
4367 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4368 context, name, t);
4369 return error_mark_node;
4371 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4373 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4374 && DECL_TYPE_TEMPLATE_P (t))
4375 /* The caller permits this typename-specifier to name a template
4376 (because it appears in a CTAD-enabled context). */;
4377 else
4379 if (complain & tf_error)
4380 error ("%<typename %T::%D%> names %q#D, which is not a type",
4381 context, name, t);
4382 return error_mark_node;
4386 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4387 context, complain))
4388 return error_mark_node;
4390 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4391 return make_template_placeholder (t);
4393 if (want_template)
4395 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4396 NULL_TREE, context,
4397 /*entering_scope=*/0,
4398 complain | tf_user);
4399 if (t == error_mark_node)
4400 return error_mark_node;
4401 t = TYPE_NAME (t);
4404 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4405 t = TREE_TYPE (t);
4407 maybe_record_typedef_use (t);
4409 return t;
4412 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4413 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4414 in which case error_mark_node is returned.
4416 If PARM_LIST is non-NULL, also make sure that the template parameter
4417 list of TEMPLATE_DECL matches.
4419 If COMPLAIN zero, don't complain about any errors that occur. */
4421 tree
4422 make_unbound_class_template (tree context, tree name, tree parm_list,
4423 tsubst_flags_t complain)
4425 if (TYPE_P (name))
4426 name = TYPE_IDENTIFIER (name);
4427 else if (DECL_P (name))
4428 name = DECL_NAME (name);
4429 gcc_assert (identifier_p (name));
4431 if (!dependent_type_p (context)
4432 || currently_open_class (context))
4434 tree tmpl = NULL_TREE;
4436 if (MAYBE_CLASS_TYPE_P (context))
4437 tmpl = lookup_field (context, name, 0, false);
4439 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4440 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4442 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4444 if (complain & tf_error)
4445 error ("no class template named %q#T in %q#T", name, context);
4446 return error_mark_node;
4449 if (parm_list
4450 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4452 if (complain & tf_error)
4454 error ("template parameters do not match template %qD", tmpl);
4455 inform (DECL_SOURCE_LOCATION (tmpl),
4456 "%qD declared here", tmpl);
4458 return error_mark_node;
4461 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4462 complain))
4463 return error_mark_node;
4465 return tmpl;
4468 return make_unbound_class_template_raw (context, name, parm_list);
4471 /* Build an UNBOUND_CLASS_TEMPLATE. */
4473 tree
4474 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4476 /* Build the UNBOUND_CLASS_TEMPLATE. */
4477 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4478 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4479 TREE_TYPE (t) = NULL_TREE;
4480 SET_TYPE_STRUCTURAL_EQUALITY (t);
4482 /* Build the corresponding TEMPLATE_DECL. */
4483 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4484 TYPE_NAME (t) = d;
4485 TYPE_STUB_DECL (t) = d;
4486 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4487 DECL_ARTIFICIAL (d) = 1;
4488 DECL_TEMPLATE_PARMS (d) = parm_list;
4490 return t;
4495 /* Push the declarations of builtin types into the global namespace.
4496 RID_INDEX is the index of the builtin type in the array
4497 RID_POINTERS. NAME is the name used when looking up the builtin
4498 type. TYPE is the _TYPE node for the builtin type.
4500 The calls to set_global_binding below should be
4501 eliminated. Built-in types should not be looked up name; their
4502 names are keywords that the parser can recognize. However, there
4503 is code in c-common.cc that uses identifier_global_value to look up
4504 built-in types by name. */
4506 void
4507 record_builtin_type (enum rid rid_index,
4508 const char* name,
4509 tree type)
4511 tree decl = NULL_TREE;
4513 if (name)
4515 tree tname = get_identifier (name);
4516 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4517 DECL_ARTIFICIAL (tdecl) = 1;
4518 set_global_binding (tdecl);
4519 decl = tdecl;
4522 if ((int) rid_index < (int) RID_MAX)
4523 if (tree rname = ridpointers[(int) rid_index])
4524 if (!decl || DECL_NAME (decl) != rname)
4526 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4527 DECL_ARTIFICIAL (rdecl) = 1;
4528 set_global_binding (rdecl);
4529 if (!decl)
4530 decl = rdecl;
4533 if (decl)
4535 if (!TYPE_NAME (type))
4536 TYPE_NAME (type) = decl;
4537 debug_hooks->type_decl (decl, 0);
4541 /* Push a type into the namespace so that the back ends ignore it. */
4543 static void
4544 record_unknown_type (tree type, const char* name)
4546 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4547 TYPE_DECL, get_identifier (name), type));
4548 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4549 DECL_IGNORED_P (decl) = 1;
4550 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4551 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4552 SET_TYPE_ALIGN (type, 1);
4553 TYPE_USER_ALIGN (type) = 0;
4554 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4557 /* Create all the predefined identifiers. */
4559 static void
4560 initialize_predefined_identifiers (void)
4562 struct predefined_identifier
4564 const char *name; /* Name. */
4565 tree *node; /* Node to store it in. */
4566 cp_identifier_kind kind; /* Kind of identifier. */
4569 /* A table of identifiers to create at startup. */
4570 static const predefined_identifier predefined_identifiers[] = {
4571 {"C++", &lang_name_cplusplus, cik_normal},
4572 {"C", &lang_name_c, cik_normal},
4573 /* Some of these names have a trailing space so that it is
4574 impossible for them to conflict with names written by users. */
4575 {"__ct ", &ctor_identifier, cik_ctor},
4576 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4577 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4578 {"__dt ", &dtor_identifier, cik_dtor},
4579 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4580 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4581 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4582 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4583 {"__in_chrg", &in_charge_identifier, cik_normal},
4584 {"__as_base ", &as_base_identifier, cik_normal},
4585 {"this", &this_identifier, cik_normal},
4586 {"__delta", &delta_identifier, cik_normal},
4587 {"__pfn", &pfn_identifier, cik_normal},
4588 {"_vptr", &vptr_identifier, cik_normal},
4589 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4590 {"::", &global_identifier, cik_normal},
4591 /* The demangler expects anonymous namespaces to be called
4592 something starting with '_GLOBAL__N_'. It no longer needs
4593 to be unique to the TU. */
4594 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4595 {"auto", &auto_identifier, cik_normal},
4596 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4597 {"initializer_list", &init_list_identifier, cik_normal},
4598 {"__for_range ", &for_range__identifier, cik_normal},
4599 {"__for_begin ", &for_begin__identifier, cik_normal},
4600 {"__for_end ", &for_end__identifier, cik_normal},
4601 {"__for_range", &for_range_identifier, cik_normal},
4602 {"__for_begin", &for_begin_identifier, cik_normal},
4603 {"__for_end", &for_end_identifier, cik_normal},
4604 {"abi_tag", &abi_tag_identifier, cik_normal},
4605 {"aligned", &aligned_identifier, cik_normal},
4606 {"begin", &begin_identifier, cik_normal},
4607 {"end", &end_identifier, cik_normal},
4608 {"get", &get__identifier, cik_normal},
4609 {"gnu", &gnu_identifier, cik_normal},
4610 {"tuple_element", &tuple_element_identifier, cik_normal},
4611 {"tuple_size", &tuple_size_identifier, cik_normal},
4612 {"type", &type_identifier, cik_normal},
4613 {"value", &value_identifier, cik_normal},
4614 {"_FUN", &fun_identifier, cik_normal},
4615 {"__closure", &closure_identifier, cik_normal},
4616 {"heap uninit", &heap_uninit_identifier, cik_normal},
4617 {"heap ", &heap_identifier, cik_normal},
4618 {"heap deleted", &heap_deleted_identifier, cik_normal},
4619 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4620 {"heap []", &heap_vec_identifier, cik_normal},
4621 {"omp", &omp_identifier, cik_normal},
4622 {NULL, NULL, cik_normal}
4625 for (const predefined_identifier *pid = predefined_identifiers;
4626 pid->name; ++pid)
4628 *pid->node = get_identifier (pid->name);
4629 /* Some of these identifiers already have a special kind. */
4630 if (pid->kind != cik_normal)
4631 set_identifier_kind (*pid->node, pid->kind);
4635 /* Create the predefined scalar types of C,
4636 and some nodes representing standard constants (0, 1, (void *)0).
4637 Initialize the global binding level.
4638 Make definitions for built-in primitive functions. */
4640 void
4641 cxx_init_decl_processing (void)
4643 tree void_ftype;
4644 tree void_ftype_ptr;
4646 /* Create all the identifiers we need. */
4647 initialize_predefined_identifiers ();
4649 /* Create the global variables. */
4650 push_to_top_level ();
4652 current_function_decl = NULL_TREE;
4653 current_binding_level = NULL;
4654 /* Enter the global namespace. */
4655 gcc_assert (global_namespace == NULL_TREE);
4656 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4657 void_type_node);
4658 TREE_PUBLIC (global_namespace) = true;
4659 DECL_MODULE_EXPORT_P (global_namespace) = true;
4660 DECL_CONTEXT (global_namespace)
4661 = build_translation_unit_decl (get_identifier (main_input_filename));
4662 /* Remember whether we want the empty class passing ABI change warning
4663 in this TU. */
4664 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4665 = warn_abi && abi_version_crosses (12);
4666 debug_hooks->register_main_translation_unit
4667 (DECL_CONTEXT (global_namespace));
4668 begin_scope (sk_namespace, global_namespace);
4669 current_namespace = global_namespace;
4671 if (flag_visibility_ms_compat)
4672 default_visibility = VISIBILITY_HIDDEN;
4674 /* Initially, C. */
4675 current_lang_name = lang_name_c;
4677 /* Create the `std' namespace. */
4678 push_namespace (get_identifier ("std"));
4679 std_node = current_namespace;
4680 pop_namespace ();
4682 flag_noexcept_type = (cxx_dialect >= cxx17);
4684 c_common_nodes_and_builtins ();
4686 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4687 tree decl
4688 = add_builtin_function ("__builtin_is_constant_evaluated",
4689 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4690 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4691 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4693 /* The concrete return type of __builtin_source_location is
4694 const std::source_location::__impl*, but we can't form the type
4695 at this point. So we initially declare it with an auto return
4696 type which we then "deduce" from require_deduced_type upon first use. */
4697 tree auto_ftype = build_function_type_list (make_auto (), NULL_TREE);
4698 decl = add_builtin_function ("__builtin_source_location",
4699 auto_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4700 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4701 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4703 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4704 NULL_TREE);
4705 decl
4706 = add_builtin_function ("__builtin_is_corresponding_member",
4707 bool_vaftype,
4708 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4709 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4710 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4712 decl
4713 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4714 bool_vaftype,
4715 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4716 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4717 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4719 integer_two_node = build_int_cst (NULL_TREE, 2);
4721 /* Guess at the initial static decls size. */
4722 vec_alloc (static_decls, 500);
4724 /* ... and keyed classes. */
4725 vec_alloc (keyed_classes, 100);
4727 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4728 truthvalue_type_node = boolean_type_node;
4729 truthvalue_false_node = boolean_false_node;
4730 truthvalue_true_node = boolean_true_node;
4732 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4733 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4734 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4735 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4736 NULL_TREE);
4738 #if 0
4739 record_builtin_type (RID_MAX, NULL, string_type_node);
4740 #endif
4742 delta_type_node = ptrdiff_type_node;
4743 vtable_index_type = ptrdiff_type_node;
4745 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4746 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4747 void_ftype_ptr = build_function_type_list (void_type_node,
4748 ptr_type_node, NULL_TREE);
4749 void_ftype_ptr
4750 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4752 /* Create the conversion operator marker. This operator's DECL_NAME
4753 is in the identifier table, so we can use identifier equality to
4754 find it. */
4755 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4756 void_ftype);
4758 /* C++ extensions */
4760 unknown_type_node = make_node (LANG_TYPE);
4761 record_unknown_type (unknown_type_node, "unknown type");
4763 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4764 TREE_TYPE (unknown_type_node) = unknown_type_node;
4766 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4767 result. */
4768 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4769 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4771 init_list_type_node = make_node (LANG_TYPE);
4772 record_unknown_type (init_list_type_node, "init list");
4774 /* Used when parsing to distinguish parameter-lists () and (void). */
4775 explicit_void_list_node = build_tree_list (NULL_TREE, void_type_node);
4778 /* Make sure we get a unique function type, so we can give
4779 its pointer type a name. (This wins for gdb.) */
4780 tree vfunc_type = make_node (FUNCTION_TYPE);
4781 TREE_TYPE (vfunc_type) = integer_type_node;
4782 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4783 layout_type (vfunc_type);
4785 vtable_entry_type = build_pointer_type (vfunc_type);
4787 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4789 vtbl_type_node
4790 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4791 layout_type (vtbl_type_node);
4792 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4793 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4794 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4795 layout_type (vtbl_ptr_type_node);
4796 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4798 push_namespace (get_identifier ("__cxxabiv1"));
4799 abi_node = current_namespace;
4800 pop_namespace ();
4802 any_targ_node = make_node (LANG_TYPE);
4803 record_unknown_type (any_targ_node, "any type");
4805 /* Now, C++. */
4806 current_lang_name = lang_name_cplusplus;
4808 if (aligned_new_threshold > 1
4809 && !pow2p_hwi (aligned_new_threshold))
4811 error ("%<-faligned-new=%d%> is not a power of two",
4812 aligned_new_threshold);
4813 aligned_new_threshold = 1;
4815 if (aligned_new_threshold == -1)
4816 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4817 if (aligned_new_threshold == 1)
4818 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4821 tree newattrs, extvisattr;
4822 tree newtype, deltype;
4823 tree ptr_ftype_sizetype;
4824 tree new_eh_spec;
4826 ptr_ftype_sizetype
4827 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4828 if (cxx_dialect == cxx98)
4830 tree bad_alloc_id;
4831 tree bad_alloc_type_node;
4832 tree bad_alloc_decl;
4834 push_nested_namespace (std_node);
4835 bad_alloc_id = get_identifier ("bad_alloc");
4836 bad_alloc_type_node = make_class_type (RECORD_TYPE);
4837 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4838 bad_alloc_decl
4839 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4840 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4841 pop_nested_namespace (std_node);
4843 new_eh_spec
4844 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4846 else
4847 new_eh_spec = noexcept_false_spec;
4849 /* Ensure attribs.cc is initialized. */
4850 init_attributes ();
4852 extvisattr = build_tree_list (get_identifier ("externally_visible"),
4853 NULL_TREE);
4854 newattrs = tree_cons (get_identifier ("alloc_size"),
4855 build_tree_list (NULL_TREE, integer_one_node),
4856 extvisattr);
4857 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4858 newtype = build_exception_variant (newtype, new_eh_spec);
4859 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4860 deltype = build_exception_variant (deltype, empty_except_spec);
4861 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4862 DECL_IS_MALLOC (opnew) = 1;
4863 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4864 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4865 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4866 DECL_IS_MALLOC (opnew) = 1;
4867 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4868 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4869 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4870 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4871 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4872 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4873 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4874 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4875 if (flag_sized_deallocation)
4877 /* Also push the sized deallocation variants:
4878 void operator delete(void*, std::size_t) throw();
4879 void operator delete[](void*, std::size_t) throw(); */
4880 tree void_ftype_ptr_size
4881 = build_function_type_list (void_type_node, ptr_type_node,
4882 size_type_node, NULL_TREE);
4883 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4884 extvisattr);
4885 deltype = build_exception_variant (deltype, empty_except_spec);
4886 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4887 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4888 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4889 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4890 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4891 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4894 if (aligned_new_threshold)
4896 push_nested_namespace (std_node);
4897 tree align_id = get_identifier ("align_val_t");
4898 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4899 NULL_TREE, /*scoped*/true, NULL);
4900 pop_nested_namespace (std_node);
4902 /* operator new (size_t, align_val_t); */
4903 newtype = build_function_type_list (ptr_type_node, size_type_node,
4904 align_type_node, NULL_TREE);
4905 newtype = cp_build_type_attribute_variant (newtype, newattrs);
4906 newtype = build_exception_variant (newtype, new_eh_spec);
4907 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4908 DECL_IS_MALLOC (opnew) = 1;
4909 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4910 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4911 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4912 DECL_IS_MALLOC (opnew) = 1;
4913 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4914 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4916 /* operator delete (void *, align_val_t); */
4917 deltype = build_function_type_list (void_type_node, ptr_type_node,
4918 align_type_node, NULL_TREE);
4919 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4920 deltype = build_exception_variant (deltype, empty_except_spec);
4921 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4922 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4923 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4924 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4925 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4926 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4928 if (flag_sized_deallocation)
4930 /* operator delete (void *, size_t, align_val_t); */
4931 deltype = build_function_type_list (void_type_node, ptr_type_node,
4932 size_type_node, align_type_node,
4933 NULL_TREE);
4934 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4935 deltype = build_exception_variant (deltype, empty_except_spec);
4936 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4937 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4938 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4939 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4940 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4941 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4945 /* C++-specific nullptr initialization. */
4946 if (abi_version_at_least (9))
4947 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4948 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4951 if (! supports_one_only ())
4952 flag_weak = 0;
4954 abort_fndecl
4955 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4956 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4957 if (flag_weak)
4958 /* If no definition is available, resolve references to NULL. */
4959 declare_weak (abort_fndecl);
4961 /* Perform other language dependent initializations. */
4962 init_class_processing ();
4963 init_rtti_processing ();
4964 init_template_processing ();
4966 if (flag_exceptions)
4967 init_exception_processing ();
4969 if (modules_p ())
4970 init_modules (parse_in);
4972 make_fname_decl = cp_make_fname_decl;
4973 start_fname_decls ();
4975 /* Show we use EH for cleanups. */
4976 if (flag_exceptions)
4977 using_eh_for_cleanups ();
4979 /* Check that the hardware interference sizes are at least
4980 alignof(max_align_t), as required by the standard. */
4981 const int max_align = max_align_t_align () / BITS_PER_UNIT;
4982 if (OPTION_SET_P (param_destruct_interfere_size))
4984 if (param_destruct_interfere_size < max_align)
4985 error ("%<--param destructive-interference-size=%d%> is less than "
4986 "%d", param_destruct_interfere_size, max_align);
4987 else if (param_destruct_interfere_size < param_l1_cache_line_size)
4988 warning (OPT_Winterference_size,
4989 "%<--param destructive-interference-size=%d%> "
4990 "is less than %<--param l1-cache-line-size=%d%>",
4991 param_destruct_interfere_size, param_l1_cache_line_size);
4993 else if (param_destruct_interfere_size)
4994 /* Assume the internal value is OK. */;
4995 else if (param_l1_cache_line_size >= max_align)
4996 param_destruct_interfere_size = param_l1_cache_line_size;
4997 /* else leave it unset. */
4999 if (OPTION_SET_P (param_construct_interfere_size))
5001 if (param_construct_interfere_size < max_align)
5002 error ("%<--param constructive-interference-size=%d%> is less than "
5003 "%d", param_construct_interfere_size, max_align);
5004 else if (param_construct_interfere_size > param_l1_cache_line_size
5005 && param_l1_cache_line_size >= max_align)
5006 warning (OPT_Winterference_size,
5007 "%<--param constructive-interference-size=%d%> "
5008 "is greater than %<--param l1-cache-line-size=%d%>",
5009 param_construct_interfere_size, param_l1_cache_line_size);
5011 else if (param_construct_interfere_size)
5012 /* Assume the internal value is OK. */;
5013 else if (param_l1_cache_line_size >= max_align)
5014 param_construct_interfere_size = param_l1_cache_line_size;
5017 /* Enter an abi node in global-module context. returns a cookie to
5018 give to pop_abi_namespace. */
5020 unsigned
5021 push_abi_namespace (tree node)
5023 push_nested_namespace (node);
5024 push_visibility ("default", 2);
5025 unsigned flags = module_kind;
5026 module_kind = 0;
5027 return flags;
5030 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
5031 you. */
5033 void
5034 pop_abi_namespace (unsigned flags, tree node)
5036 module_kind = flags;
5037 pop_visibility (2);
5038 pop_nested_namespace (node);
5041 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
5042 the decl, LOC is the location to give the decl, NAME is the
5043 initialization string and TYPE_DEP indicates whether NAME depended
5044 on the type of the function. We make use of that to detect
5045 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
5046 at the point of first use, so we mustn't push the decl now. */
5048 static tree
5049 cp_make_fname_decl (location_t loc, tree id, int type_dep)
5051 tree domain = NULL_TREE;
5052 tree init = NULL_TREE;
5054 if (!(type_dep && current_function_decl && in_template_context))
5056 const char *name = NULL;
5057 bool release_name = false;
5059 if (current_function_decl == NULL_TREE)
5060 name = "top level";
5061 else if (type_dep == 0)
5063 /* __FUNCTION__ */
5064 name = fname_as_string (type_dep);
5065 release_name = true;
5067 else
5069 /* __PRETTY_FUNCTION__ */
5070 gcc_checking_assert (type_dep == 1);
5071 name = cxx_printable_name (current_function_decl, 2);
5074 size_t length = strlen (name);
5075 domain = build_index_type (size_int (length));
5076 init = build_string (length + 1, name);
5077 if (release_name)
5078 free (const_cast<char *> (name));
5081 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
5082 type = build_cplus_array_type (type, domain);
5084 if (init)
5085 TREE_TYPE (init) = type;
5086 else
5087 init = error_mark_node;
5089 tree decl = build_decl (loc, VAR_DECL, id, type);
5091 TREE_READONLY (decl) = 1;
5092 DECL_ARTIFICIAL (decl) = 1;
5093 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
5094 TREE_STATIC (decl) = 1;
5096 TREE_USED (decl) = 1;
5098 SET_DECL_VALUE_EXPR (decl, init);
5099 DECL_HAS_VALUE_EXPR_P (decl) = 1;
5100 /* For decl_constant_var_p. */
5101 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5103 if (current_function_decl)
5105 DECL_CONTEXT (decl) = current_function_decl;
5106 decl = pushdecl_outermost_localscope (decl);
5107 if (decl != error_mark_node)
5108 add_decl_expr (decl);
5110 else
5112 DECL_THIS_STATIC (decl) = true;
5113 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
5116 return decl;
5119 /* Install DECL as a builtin function at current global scope. Return
5120 the new decl (if we found an existing version). Also installs it
5121 into ::std, if it's not '_*'. */
5123 tree
5124 cxx_builtin_function (tree decl)
5126 retrofit_lang_decl (decl);
5128 DECL_ARTIFICIAL (decl) = 1;
5129 SET_DECL_LANGUAGE (decl, lang_c);
5130 /* Runtime library routines are, by definition, available in an
5131 external shared object. */
5132 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5133 DECL_VISIBILITY_SPECIFIED (decl) = 1;
5135 tree id = DECL_NAME (decl);
5136 const char *name = IDENTIFIER_POINTER (id);
5137 bool hiding = false;
5138 if (name[0] != '_' || name[1] != '_')
5139 /* In the user's namespace, it must be declared before use. */
5140 hiding = true;
5141 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
5142 && !startswith (name + 2, "builtin_")
5143 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
5144 "_chk", strlen ("_chk") + 1))
5145 /* Treat __*_chk fortification functions as anticipated as well,
5146 unless they are __builtin_*_chk. */
5147 hiding = true;
5149 /* All builtins that don't begin with an '_' should additionally
5150 go in the 'std' namespace. */
5151 if (name[0] != '_')
5153 tree std_decl = copy_decl (decl);
5155 push_nested_namespace (std_node);
5156 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5157 pushdecl (std_decl, hiding);
5158 pop_nested_namespace (std_node);
5161 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5162 decl = pushdecl (decl, hiding);
5164 return decl;
5167 /* Like cxx_builtin_function, but guarantee the function is added to the global
5168 scope. This is to allow function specific options to add new machine
5169 dependent builtins when the target ISA changes via attribute((target(...)))
5170 which saves space on program startup if the program does not use non-generic
5171 ISAs. */
5173 tree
5174 cxx_builtin_function_ext_scope (tree decl)
5176 push_nested_namespace (global_namespace);
5177 decl = cxx_builtin_function (decl);
5178 pop_nested_namespace (global_namespace);
5180 return decl;
5183 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5185 tree
5186 cxx_simulate_builtin_function_decl (tree decl)
5188 retrofit_lang_decl (decl);
5190 DECL_ARTIFICIAL (decl) = 1;
5191 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5192 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5193 return pushdecl (decl);
5196 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5197 function. Not called directly. */
5199 static tree
5200 build_library_fn (tree name, enum tree_code operator_code, tree type,
5201 int ecf_flags)
5203 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5204 DECL_EXTERNAL (fn) = 1;
5205 TREE_PUBLIC (fn) = 1;
5206 DECL_ARTIFICIAL (fn) = 1;
5207 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5208 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5209 SET_DECL_LANGUAGE (fn, lang_c);
5210 /* Runtime library routines are, by definition, available in an
5211 external shared object. */
5212 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5213 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5214 set_call_expr_flags (fn, ecf_flags);
5215 return fn;
5218 /* Returns the _DECL for a library function with C++ linkage. */
5220 static tree
5221 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5222 int ecf_flags)
5224 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5225 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5226 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5227 return fn;
5230 /* Like build_library_fn, but takes a C string instead of an
5231 IDENTIFIER_NODE. */
5233 tree
5234 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5236 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5239 /* Like build_cp_library_fn, but takes a C string instead of an
5240 IDENTIFIER_NODE. */
5242 tree
5243 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5245 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5246 ecf_flags);
5249 /* Like build_library_fn, but also pushes the function so that we will
5250 be able to find it via get_global_binding. Also, the function
5251 may throw exceptions listed in RAISES. */
5253 tree
5254 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5256 if (raises)
5257 type = build_exception_variant (type, raises);
5259 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5260 return pushdecl_top_level (fn);
5263 /* Like build_cp_library_fn, but also pushes the function so that it
5264 will be found by normal lookup. */
5266 static tree
5267 push_cp_library_fn (enum tree_code operator_code, tree type,
5268 int ecf_flags)
5270 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5271 operator_code, type, ecf_flags);
5272 pushdecl (fn);
5273 if (flag_tm)
5274 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5275 return fn;
5278 /* Like push_library_fn, but also note that this function throws
5279 and does not return. Used for __throw_foo and the like. */
5281 tree
5282 push_throw_library_fn (tree name, tree type)
5284 tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
5285 return fn;
5288 /* When we call finish_struct for an anonymous union, we create
5289 default copy constructors and such. But, an anonymous union
5290 shouldn't have such things; this function undoes the damage to the
5291 anonymous union type T.
5293 (The reason that we create the synthesized methods is that we don't
5294 distinguish `union { int i; }' from `typedef union { int i; } U'.
5295 The first is an anonymous union; the second is just an ordinary
5296 union type.) */
5298 void
5299 fixup_anonymous_aggr (tree t)
5301 /* Wipe out memory of synthesized methods. */
5302 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5303 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5304 TYPE_HAS_COPY_CTOR (t) = 0;
5305 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5306 TYPE_HAS_COPY_ASSIGN (t) = 0;
5307 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5309 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5310 invalid members. */
5311 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5313 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5314 *prev_p = DECL_CHAIN (probe);
5315 else
5316 prev_p = &DECL_CHAIN (probe);
5318 if (DECL_ARTIFICIAL (probe)
5319 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5320 || TYPE_ANON_P (TREE_TYPE (probe))))
5321 continue;
5323 if (TREE_CODE (probe) != FIELD_DECL
5324 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5326 /* We already complained about static data members in
5327 finish_static_data_member_decl. */
5328 if (!VAR_P (probe))
5330 auto_diagnostic_group d;
5331 if (permerror (DECL_SOURCE_LOCATION (probe),
5332 TREE_CODE (t) == UNION_TYPE
5333 ? "%q#D invalid; an anonymous union may "
5334 "only have public non-static data members"
5335 : "%q#D invalid; an anonymous struct may "
5336 "only have public non-static data members", probe))
5338 static bool hint;
5339 if (flag_permissive && !hint)
5341 hint = true;
5342 inform (DECL_SOURCE_LOCATION (probe),
5343 "this flexibility is deprecated and will be "
5344 "removed");
5351 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5352 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5353 unsigned store = 0;
5354 for (tree elt : vec)
5355 if (!is_overloaded_fn (elt))
5356 (*vec)[store++] = elt;
5357 vec_safe_truncate (vec, store);
5359 /* Wipe RTTI info. */
5360 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5362 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5363 assignment operators (because they cannot have these methods themselves).
5364 For anonymous unions this is already checked because they are not allowed
5365 in any union, otherwise we have to check it. */
5366 if (TREE_CODE (t) != UNION_TYPE)
5368 tree field, type;
5370 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5372 error_at (location_of (t), "anonymous struct with base classes");
5373 /* Avoid ICE after error on anon-struct9.C. */
5374 TYPE_NEEDS_CONSTRUCTING (t) = false;
5377 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5378 if (TREE_CODE (field) == FIELD_DECL)
5380 type = TREE_TYPE (field);
5381 if (CLASS_TYPE_P (type))
5383 if (TYPE_NEEDS_CONSTRUCTING (type))
5384 error ("member %q+#D with constructor not allowed "
5385 "in anonymous aggregate", field);
5386 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5387 error ("member %q+#D with destructor not allowed "
5388 "in anonymous aggregate", field);
5389 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5390 error ("member %q+#D with copy assignment operator "
5391 "not allowed in anonymous aggregate", field);
5397 /* Warn for an attribute located at LOCATION that appertains to the
5398 class type CLASS_TYPE that has not been properly placed after its
5399 class-key, in it class-specifier. */
5401 void
5402 warn_misplaced_attr_for_class_type (location_t location,
5403 tree class_type)
5405 gcc_assert (OVERLOAD_TYPE_P (class_type));
5407 auto_diagnostic_group d;
5408 if (warning_at (location, OPT_Wattributes,
5409 "attribute ignored in declaration "
5410 "of %q#T", class_type))
5411 inform (location,
5412 "attribute for %q#T must follow the %qs keyword",
5413 class_type, class_key_or_enum_as_string (class_type));
5416 /* Returns the cv-qualifiers that apply to the type specified
5417 by the DECLSPECS. */
5419 static int
5420 get_type_quals (const cp_decl_specifier_seq *declspecs)
5422 int type_quals = TYPE_UNQUALIFIED;
5424 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5425 type_quals |= TYPE_QUAL_CONST;
5426 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5427 type_quals |= TYPE_QUAL_VOLATILE;
5428 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5429 type_quals |= TYPE_QUAL_RESTRICT;
5431 return type_quals;
5434 /* Make sure that a declaration with no declarator is well-formed, i.e.
5435 just declares a tagged type or anonymous union.
5437 Returns the type declared; or NULL_TREE if none. */
5439 tree
5440 check_tag_decl (cp_decl_specifier_seq *declspecs,
5441 bool explicit_type_instantiation_p)
5443 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5444 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5445 /* If a class, struct, or enum type is declared by the DECLSPECS
5446 (i.e, if a class-specifier, enum-specifier, or non-typename
5447 elaborated-type-specifier appears in the DECLSPECS),
5448 DECLARED_TYPE is set to the corresponding type. */
5449 tree declared_type = NULL_TREE;
5450 bool error_p = false;
5452 if (declspecs->multiple_types_p)
5453 error_at (smallest_type_location (declspecs),
5454 "multiple types in one declaration");
5455 else if (declspecs->redefined_builtin_type)
5457 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5458 if (!in_system_header_at (loc))
5459 permerror (loc, "redeclaration of C++ built-in type %qT",
5460 declspecs->redefined_builtin_type);
5461 return NULL_TREE;
5464 if (declspecs->type
5465 && TYPE_P (declspecs->type)
5466 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5467 && MAYBE_CLASS_TYPE_P (declspecs->type))
5468 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5469 declared_type = declspecs->type;
5470 else if (declspecs->type == error_mark_node)
5471 error_p = true;
5473 if (type_uses_auto (declared_type))
5475 error_at (declspecs->locations[ds_type_spec],
5476 "%<auto%> can only be specified for variables "
5477 "or function declarations");
5478 return error_mark_node;
5481 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5482 declared_type = NULL_TREE;
5484 if (!declared_type && !saw_friend && !error_p)
5485 permerror (input_location, "declaration does not declare anything");
5486 /* Check for an anonymous union. */
5487 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5488 && TYPE_UNNAMED_P (declared_type))
5490 /* 7/3 In a simple-declaration, the optional init-declarator-list
5491 can be omitted only when declaring a class (clause 9) or
5492 enumeration (7.2), that is, when the decl-specifier-seq contains
5493 either a class-specifier, an elaborated-type-specifier with
5494 a class-key (9.1), or an enum-specifier. In these cases and
5495 whenever a class-specifier or enum-specifier is present in the
5496 decl-specifier-seq, the identifiers in these specifiers are among
5497 the names being declared by the declaration (as class-name,
5498 enum-names, or enumerators, depending on the syntax). In such
5499 cases, and except for the declaration of an unnamed bit-field (9.6),
5500 the decl-specifier-seq shall introduce one or more names into the
5501 program, or shall redeclare a name introduced by a previous
5502 declaration. [Example:
5503 enum { }; // ill-formed
5504 typedef class { }; // ill-formed
5505 --end example] */
5506 if (saw_typedef)
5508 error_at (declspecs->locations[ds_typedef],
5509 "missing type-name in typedef-declaration");
5510 return NULL_TREE;
5512 /* Anonymous unions are objects, so they can have specifiers. */;
5513 SET_ANON_AGGR_TYPE_P (declared_type);
5515 if (TREE_CODE (declared_type) != UNION_TYPE)
5516 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5517 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5520 else
5522 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5523 error_at (declspecs->locations[ds_inline],
5524 "%<inline%> can only be specified for functions");
5525 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5526 error_at (declspecs->locations[ds_virtual],
5527 "%<virtual%> can only be specified for functions");
5528 else if (saw_friend
5529 && (!current_class_type
5530 || current_scope () != current_class_type))
5531 error_at (declspecs->locations[ds_friend],
5532 "%<friend%> can only be specified inside a class");
5533 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5534 error_at (declspecs->locations[ds_explicit],
5535 "%<explicit%> can only be specified for constructors");
5536 else if (declspecs->storage_class)
5537 error_at (declspecs->locations[ds_storage_class],
5538 "a storage class can only be specified for objects "
5539 "and functions");
5540 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5541 error_at (declspecs->locations[ds_const],
5542 "%<const%> can only be specified for objects and "
5543 "functions");
5544 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5545 error_at (declspecs->locations[ds_volatile],
5546 "%<volatile%> can only be specified for objects and "
5547 "functions");
5548 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5549 error_at (declspecs->locations[ds_restrict],
5550 "%<__restrict%> can only be specified for objects and "
5551 "functions");
5552 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5553 error_at (declspecs->locations[ds_thread],
5554 "%<__thread%> can only be specified for objects "
5555 "and functions");
5556 else if (saw_typedef)
5557 warning_at (declspecs->locations[ds_typedef], 0,
5558 "%<typedef%> was ignored in this declaration");
5559 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5560 error_at (declspecs->locations[ds_constexpr],
5561 "%qs cannot be used for type declarations", "constexpr");
5562 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5563 error_at (declspecs->locations[ds_constinit],
5564 "%qs cannot be used for type declarations", "constinit");
5565 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5566 error_at (declspecs->locations[ds_consteval],
5567 "%qs cannot be used for type declarations", "consteval");
5570 if (declspecs->attributes && warn_attributes && declared_type)
5572 location_t loc;
5573 if (!CLASS_TYPE_P (declared_type)
5574 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5575 /* For a non-template class, use the name location. */
5576 loc = location_of (declared_type);
5577 else
5578 /* For a template class (an explicit instantiation), use the
5579 current location. */
5580 loc = input_location;
5582 if (explicit_type_instantiation_p)
5583 /* [dcl.attr.grammar]/4:
5585 No attribute-specifier-seq shall appertain to an explicit
5586 instantiation. */
5588 if (warning_at (loc, OPT_Wattributes,
5589 "attribute ignored in explicit instantiation %q#T",
5590 declared_type))
5591 inform (loc,
5592 "no attribute can be applied to "
5593 "an explicit instantiation");
5595 else
5596 warn_misplaced_attr_for_class_type (loc, declared_type);
5599 /* Diagnose invalid application of contracts, if any. */
5600 if (find_contract (declspecs->attributes))
5601 diagnose_misapplied_contracts (declspecs->attributes);
5602 else
5603 diagnose_misapplied_contracts (declspecs->std_attributes);
5605 return declared_type;
5608 /* Called when a declaration is seen that contains no names to declare.
5609 If its type is a reference to a structure, union or enum inherited
5610 from a containing scope, shadow that tag name for the current scope
5611 with a forward reference.
5612 If its type defines a new named structure or union
5613 or defines an enum, it is valid but we need not do anything here.
5614 Otherwise, it is an error.
5616 C++: may have to grok the declspecs to learn about static,
5617 complain for anonymous unions.
5619 Returns the TYPE declared -- or NULL_TREE if none. */
5621 tree
5622 shadow_tag (cp_decl_specifier_seq *declspecs)
5624 tree t = check_tag_decl (declspecs,
5625 /*explicit_type_instantiation_p=*/false);
5627 if (!t)
5628 return NULL_TREE;
5630 t = maybe_process_partial_specialization (t);
5631 if (t == error_mark_node)
5632 return NULL_TREE;
5634 /* This is where the variables in an anonymous union are
5635 declared. An anonymous union declaration looks like:
5636 union { ... } ;
5637 because there is no declarator after the union, the parser
5638 sends that declaration here. */
5639 if (ANON_AGGR_TYPE_P (t))
5641 fixup_anonymous_aggr (t);
5643 if (TYPE_FIELDS (t))
5645 tree decl = grokdeclarator (/*declarator=*/NULL,
5646 declspecs, NORMAL, 0, NULL);
5647 finish_anon_union (decl);
5651 return t;
5654 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5656 tree
5657 groktypename (cp_decl_specifier_seq *type_specifiers,
5658 const cp_declarator *declarator,
5659 bool is_template_arg)
5661 tree attrs;
5662 tree type;
5663 enum decl_context context
5664 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5665 attrs = type_specifiers->attributes;
5666 type_specifiers->attributes = NULL_TREE;
5667 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5668 if (attrs && type != error_mark_node)
5670 if (CLASS_TYPE_P (type))
5671 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5672 "outside of definition", type);
5673 else if (MAYBE_CLASS_TYPE_P (type))
5674 /* A template type parameter or other dependent type. */
5675 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5676 "type %qT without an associated declaration", type);
5677 else
5678 cplus_decl_attributes (&type, attrs, 0);
5680 return type;
5683 /* Process a DECLARATOR for a function-scope or namespace-scope
5684 variable or function declaration.
5685 (Function definitions go through start_function; class member
5686 declarations appearing in the body of the class go through
5687 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5688 If an error occurs, the error_mark_node is returned instead.
5690 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5691 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5692 for an explicitly defaulted function, or SD_DELETED for an explicitly
5693 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5694 implicitly initialized via a default constructor. It can also be
5695 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5696 mark the new decl as DECL_DECOMPOSITION_P.
5698 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5699 declaration.
5701 The scope represented by the context of the returned DECL is pushed
5702 (if it is not the global namespace) and is assigned to
5703 *PUSHED_SCOPE_P. The caller is then responsible for calling
5704 pop_scope on *PUSHED_SCOPE_P if it is set. */
5706 tree
5707 start_decl (const cp_declarator *declarator,
5708 cp_decl_specifier_seq *declspecs,
5709 int initialized,
5710 tree attributes,
5711 tree prefix_attributes,
5712 tree *pushed_scope_p)
5714 tree decl;
5715 tree context;
5716 bool was_public;
5717 int flags;
5718 bool alias;
5719 tree initial;
5721 *pushed_scope_p = NULL_TREE;
5723 if (prefix_attributes != error_mark_node)
5724 attributes = attr_chainon (attributes, prefix_attributes);
5726 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5727 &attributes);
5729 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5730 || decl == error_mark_node
5731 || prefix_attributes == error_mark_node)
5732 return error_mark_node;
5734 context = CP_DECL_CONTEXT (decl);
5735 if (context != global_namespace)
5736 *pushed_scope_p = push_scope (context);
5738 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5740 error_at (DECL_SOURCE_LOCATION (decl),
5741 "typedef %qD is initialized (use %qs instead)",
5742 decl, "decltype");
5743 return error_mark_node;
5746 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5747 with attribute validation. */
5748 initial = DECL_INITIAL (decl);
5750 if (initialized)
5752 if (! toplevel_bindings_p ()
5753 && DECL_EXTERNAL (decl))
5754 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5755 decl);
5756 DECL_EXTERNAL (decl) = 0;
5757 if (toplevel_bindings_p ())
5758 TREE_STATIC (decl) = 1;
5759 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5760 even though we might not yet have the initializer expression. */
5761 if (!DECL_INITIAL (decl))
5762 DECL_INITIAL (decl) = error_mark_node;
5764 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5766 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5767 record_key_method_defined (decl);
5769 /* If this is a typedef that names the class for linkage purposes
5770 (7.1.3p8), apply any attributes directly to the type. */
5771 if (TREE_CODE (decl) == TYPE_DECL
5772 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5773 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5774 flags = ATTR_FLAG_TYPE_IN_PLACE;
5775 else
5776 flags = 0;
5778 /* Set attributes here so if duplicate decl, will have proper attributes. */
5779 cplus_decl_attributes (&decl, attributes, flags);
5781 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5782 assist with attribute validation. */
5783 DECL_INITIAL (decl) = initial;
5785 /* Dllimported symbols cannot be defined. Static data members (which
5786 can be initialized in-class and dllimported) go through grokfield,
5787 not here, so we don't need to exclude those decls when checking for
5788 a definition. */
5789 if (initialized && DECL_DLLIMPORT_P (decl))
5791 error_at (DECL_SOURCE_LOCATION (decl),
5792 "definition of %q#D is marked %<dllimport%>", decl);
5793 DECL_DLLIMPORT_P (decl) = 0;
5796 /* If #pragma weak was used, mark the decl weak now. */
5797 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5798 maybe_apply_pragma_weak (decl);
5800 if (TREE_CODE (decl) == FUNCTION_DECL
5801 && DECL_DECLARED_INLINE_P (decl)
5802 && DECL_UNINLINABLE (decl)
5803 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5804 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5805 "inline function %qD given attribute %qs", decl, "noinline");
5807 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5809 bool this_tmpl = (current_template_depth
5810 > template_class_depth (context));
5811 if (VAR_P (decl))
5813 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5814 if (field == NULL_TREE
5815 || !(VAR_P (field) || variable_template_p (field)))
5816 error ("%q+#D is not a static data member of %q#T", decl, context);
5817 else if (variable_template_p (field)
5818 && (DECL_LANG_SPECIFIC (decl)
5819 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5820 /* OK, specialization was already checked. */;
5821 else if (variable_template_p (field) && !this_tmpl)
5823 error_at (DECL_SOURCE_LOCATION (decl),
5824 "non-member-template declaration of %qD", decl);
5825 inform (DECL_SOURCE_LOCATION (field), "does not match "
5826 "member template declaration here");
5827 return error_mark_node;
5829 else
5831 if (variable_template_p (field))
5832 field = DECL_TEMPLATE_RESULT (field);
5834 if (DECL_CONTEXT (field) != context)
5836 if (!same_type_p (DECL_CONTEXT (field), context))
5837 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5838 "to be defined as %<%T::%D%>",
5839 DECL_CONTEXT (field), DECL_NAME (decl),
5840 context, DECL_NAME (decl));
5841 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5843 /* Static data member are tricky; an in-class initialization
5844 still doesn't provide a definition, so the in-class
5845 declaration will have DECL_EXTERNAL set, but will have an
5846 initialization. Thus, duplicate_decls won't warn
5847 about this situation, and so we check here. */
5848 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5849 error ("duplicate initialization of %qD", decl);
5850 field = duplicate_decls (decl, field);
5851 if (field == error_mark_node)
5852 return error_mark_node;
5853 else if (field)
5854 decl = field;
5857 else
5859 tree field = check_classfn (context, decl,
5860 this_tmpl
5861 ? current_template_parms
5862 : NULL_TREE);
5863 if (field && field != error_mark_node
5864 && duplicate_decls (decl, field))
5865 decl = field;
5868 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
5869 DECL_IN_AGGR_P (decl) = 0;
5870 /* Do not mark DECL as an explicit specialization if it was not
5871 already marked as an instantiation; a declaration should
5872 never be marked as a specialization unless we know what
5873 template is being specialized. */
5874 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5876 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5877 if (TREE_CODE (decl) == FUNCTION_DECL)
5878 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5879 && DECL_DECLARED_INLINE_P (decl));
5880 else
5881 DECL_COMDAT (decl) = false;
5883 /* [temp.expl.spec] An explicit specialization of a static data
5884 member of a template is a definition if the declaration
5885 includes an initializer; otherwise, it is a declaration.
5887 We check for processing_specialization so this only applies
5888 to the new specialization syntax. */
5889 if (!initialized && processing_specialization)
5890 DECL_EXTERNAL (decl) = 1;
5893 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5894 /* Aliases are definitions. */
5895 && !alias)
5897 if (DECL_VIRTUAL_P (decl) || !flag_contracts)
5898 permerror (declarator->id_loc,
5899 "declaration of %q#D outside of class is not definition",
5900 decl);
5901 else if (flag_contract_strict_declarations)
5902 warning_at (declarator->id_loc, OPT_fcontract_strict_declarations_,
5903 "declaration of %q#D outside of class is not definition",
5904 decl);
5908 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
5909 if (initialized == SD_DECOMPOSITION)
5910 fit_decomposition_lang_decl (decl, NULL_TREE);
5912 was_public = TREE_PUBLIC (decl);
5914 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5915 && current_function_decl)
5917 /* A function-scope decl of some namespace-scope decl. */
5918 DECL_LOCAL_DECL_P (decl) = true;
5919 if (named_module_purview_p ())
5920 error_at (declarator->id_loc,
5921 "block-scope extern declaration %q#D not permitted"
5922 " in module purview", decl);
5925 /* Enter this declaration into the symbol table. Don't push the plain
5926 VAR_DECL for a variable template. */
5927 if (!template_parm_scope_p ()
5928 || !VAR_P (decl))
5929 decl = maybe_push_decl (decl);
5931 if (processing_template_decl)
5932 decl = push_template_decl (decl);
5934 if (decl == error_mark_node)
5935 return error_mark_node;
5937 if (VAR_P (decl)
5938 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5939 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
5940 /* But not templated variables. */
5941 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
5943 /* This is a const variable with implicit 'static'. Set
5944 DECL_THIS_STATIC so we can tell it from variables that are
5945 !TREE_PUBLIC because of the anonymous namespace. */
5946 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5947 DECL_THIS_STATIC (decl) = 1;
5950 if (current_function_decl && VAR_P (decl)
5951 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
5952 && cxx_dialect < cxx23)
5954 bool ok = false;
5955 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
5956 error_at (DECL_SOURCE_LOCATION (decl),
5957 "%qD defined %<thread_local%> in %qs function only "
5958 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5959 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5960 ? "consteval" : "constexpr");
5961 else if (TREE_STATIC (decl))
5962 error_at (DECL_SOURCE_LOCATION (decl),
5963 "%qD defined %<static%> in %qs function only available "
5964 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5965 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5966 ? "consteval" : "constexpr");
5967 else
5968 ok = true;
5969 if (!ok)
5970 cp_function_chain->invalid_constexpr = true;
5973 if (!processing_template_decl && VAR_P (decl))
5974 start_decl_1 (decl, initialized);
5976 return decl;
5979 /* Process the declaration of a variable DECL. INITIALIZED is true
5980 iff DECL is explicitly initialized. (INITIALIZED is false if the
5981 variable is initialized via an implicitly-called constructor.)
5982 This function must be called for ordinary variables (including, for
5983 example, implicit instantiations of templates), but must not be
5984 called for template declarations. */
5986 void
5987 start_decl_1 (tree decl, bool initialized)
5989 gcc_checking_assert (!processing_template_decl);
5991 if (error_operand_p (decl))
5992 return;
5994 gcc_checking_assert (VAR_P (decl));
5996 tree type = TREE_TYPE (decl);
5997 bool complete_p = COMPLETE_TYPE_P (type);
5998 bool aggregate_definition_p
5999 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
6001 /* If an explicit initializer is present, or if this is a definition
6002 of an aggregate, then we need a complete type at this point.
6003 (Scalars are always complete types, so there is nothing to
6004 check.) This code just sets COMPLETE_P; errors (if necessary)
6005 are issued below. */
6006 if ((initialized || aggregate_definition_p)
6007 && !complete_p
6008 && COMPLETE_TYPE_P (complete_type (type)))
6010 complete_p = true;
6011 /* We will not yet have set TREE_READONLY on DECL if the type
6012 was "const", but incomplete, before this point. But, now, we
6013 have a complete type, so we can try again. */
6014 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
6017 if (initialized)
6018 /* Is it valid for this decl to have an initializer at all? */
6020 /* Don't allow initializations for incomplete types except for
6021 arrays which might be completed by the initialization. */
6022 if (complete_p)
6023 ; /* A complete type is ok. */
6024 else if (type_uses_auto (type))
6025 ; /* An auto type is ok. */
6026 else if (TREE_CODE (type) != ARRAY_TYPE)
6028 auto_diagnostic_group d;
6029 error ("variable %q#D has initializer but incomplete type", decl);
6030 maybe_suggest_missing_header (input_location,
6031 TYPE_IDENTIFIER (type),
6032 CP_TYPE_CONTEXT (type));
6033 type = TREE_TYPE (decl) = error_mark_node;
6035 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
6037 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
6038 error ("elements of array %q#D have incomplete type", decl);
6039 /* else we already gave an error in start_decl. */
6042 else if (aggregate_definition_p && !complete_p)
6044 if (type_uses_auto (type))
6045 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
6046 else
6048 auto_diagnostic_group d;
6049 error ("aggregate %q#D has incomplete type and cannot be defined",
6050 decl);
6051 maybe_suggest_missing_header (input_location,
6052 TYPE_IDENTIFIER (type),
6053 CP_TYPE_CONTEXT (type));
6054 /* Change the type so that assemble_variable will give
6055 DECL an rtl we can live with: (mem (const_int 0)). */
6056 type = TREE_TYPE (decl) = error_mark_node;
6060 /* Create a new scope to hold this declaration if necessary.
6061 Whether or not a new scope is necessary cannot be determined
6062 until after the type has been completed; if the type is a
6063 specialization of a class template it is not until after
6064 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
6065 will be set correctly. */
6066 maybe_push_cleanup_level (type);
6069 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
6070 C++20 P0960. TYPE is the type of the object we're initializing. */
6072 tree
6073 do_aggregate_paren_init (tree init, tree type)
6075 tree val = TREE_VALUE (init);
6077 if (TREE_CHAIN (init) == NULL_TREE)
6079 /* If the list has a single element and it's a string literal,
6080 then it's the initializer for the array as a whole. */
6081 if (TREE_CODE (type) == ARRAY_TYPE
6082 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6083 && TREE_CODE (tree_strip_any_location_wrapper (val))
6084 == STRING_CST)
6085 return val;
6086 /* Handle non-standard extensions like compound literals. This also
6087 prevents triggering aggregate parenthesized-initialization in
6088 compiler-generated code for =default. */
6089 else if (same_type_ignoring_top_level_qualifiers_p (type,
6090 TREE_TYPE (val)))
6091 return val;
6094 init = build_constructor_from_list (init_list_type_node, init);
6095 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6096 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6097 return init;
6100 /* Handle initialization of references. DECL, TYPE, and INIT have the
6101 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
6102 but will be set to a new CLEANUP_STMT if a temporary is created
6103 that must be destroyed subsequently.
6105 Returns an initializer expression to use to initialize DECL, or
6106 NULL if the initialization can be performed statically.
6108 Quotes on semantics can be found in ARM 8.4.3. */
6110 static tree
6111 grok_reference_init (tree decl, tree type, tree init, int flags)
6113 if (init == NULL_TREE)
6115 if ((DECL_LANG_SPECIFIC (decl) == 0
6116 || DECL_IN_AGGR_P (decl) == 0)
6117 && ! DECL_THIS_EXTERN (decl))
6118 error_at (DECL_SOURCE_LOCATION (decl),
6119 "%qD declared as reference but not initialized", decl);
6120 return NULL_TREE;
6123 tree ttype = TREE_TYPE (type);
6124 if (TREE_CODE (init) == TREE_LIST)
6126 /* This handles (C++20 only) code like
6128 const A& r(1, 2, 3);
6130 where we treat the parenthesized list as a CONSTRUCTOR. */
6131 if (TREE_TYPE (init) == NULL_TREE
6132 && CP_AGGREGATE_TYPE_P (ttype)
6133 && !DECL_DECOMPOSITION_P (decl)
6134 && (cxx_dialect >= cxx20))
6136 /* We don't know yet if we should treat const A& r(1) as
6137 const A& r{1}. */
6138 if (list_length (init) == 1)
6140 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
6141 init = build_x_compound_expr_from_list (init, ELK_INIT,
6142 tf_warning_or_error);
6144 /* If the list had more than one element, the code is ill-formed
6145 pre-C++20, so we can build a constructor right away. */
6146 else
6147 init = do_aggregate_paren_init (init, ttype);
6149 else
6150 init = build_x_compound_expr_from_list (init, ELK_INIT,
6151 tf_warning_or_error);
6154 if (TREE_CODE (ttype) != ARRAY_TYPE
6155 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
6156 /* Note: default conversion is only called in very special cases. */
6157 init = decay_conversion (init, tf_warning_or_error);
6159 /* check_initializer handles this for non-reference variables, but for
6160 references we need to do it here or the initializer will get the
6161 incomplete array type and confuse later calls to
6162 cp_complete_array_type. */
6163 if (TREE_CODE (ttype) == ARRAY_TYPE
6164 && TYPE_DOMAIN (ttype) == NULL_TREE
6165 && (BRACE_ENCLOSED_INITIALIZER_P (init)
6166 || TREE_CODE (init) == STRING_CST))
6168 cp_complete_array_type (&ttype, init, false);
6169 if (ttype != TREE_TYPE (type))
6170 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6173 /* Convert INIT to the reference type TYPE. This may involve the
6174 creation of a temporary, whose lifetime must be the same as that
6175 of the reference. If so, a DECL_EXPR for the temporary will be
6176 added just after the DECL_EXPR for DECL. That's why we don't set
6177 DECL_INITIAL for local references (instead assigning to them
6178 explicitly); we need to allow the temporary to be initialized
6179 first. */
6180 return initialize_reference (type, init, flags,
6181 tf_warning_or_error);
6184 /* Designated initializers in arrays are not supported in GNU C++.
6185 The parser cannot detect this error since it does not know whether
6186 a given brace-enclosed initializer is for a class type or for an
6187 array. This function checks that CE does not use a designated
6188 initializer. If it does, an error is issued. Returns true if CE
6189 is valid, i.e., does not have a designated initializer. */
6191 bool
6192 check_array_designated_initializer (constructor_elt *ce,
6193 unsigned HOST_WIDE_INT index)
6195 /* Designated initializers for array elements are not supported. */
6196 if (ce->index)
6198 /* The parser only allows identifiers as designated
6199 initializers. */
6200 if (ce->index == error_mark_node)
6202 error ("name used in a GNU-style designated "
6203 "initializer for an array");
6204 return false;
6206 else if (identifier_p (ce->index))
6208 error ("name %qD used in a GNU-style designated "
6209 "initializer for an array", ce->index);
6210 return false;
6213 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6214 ce->index, true);
6215 if (ce_index
6216 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6217 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6218 == INTEGER_CST))
6220 /* A C99 designator is OK if it matches the current index. */
6221 if (wi::to_wide (ce_index) == index)
6223 ce->index = ce_index;
6224 return true;
6226 else
6227 sorry ("non-trivial designated initializers not supported");
6229 else
6230 error_at (cp_expr_loc_or_input_loc (ce->index),
6231 "C99 designator %qE is not an integral constant-expression",
6232 ce->index);
6234 return false;
6237 return true;
6240 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6241 array until we finish parsing the initializer. If that's the
6242 situation we're in, update DECL accordingly. */
6244 static void
6245 maybe_deduce_size_from_array_init (tree decl, tree init)
6247 tree type = TREE_TYPE (decl);
6249 if (TREE_CODE (type) == ARRAY_TYPE
6250 && TYPE_DOMAIN (type) == NULL_TREE
6251 && TREE_CODE (decl) != TYPE_DECL)
6253 /* do_default is really a C-ism to deal with tentative definitions.
6254 But let's leave it here to ease the eventual merge. */
6255 int do_default = !DECL_EXTERNAL (decl);
6256 tree initializer = init ? init : DECL_INITIAL (decl);
6257 int failure = 0;
6259 /* Check that there are no designated initializers in INIT, as
6260 those are not supported in GNU C++, and as the middle-end
6261 will crash if presented with a non-numeric designated
6262 initializer. */
6263 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6265 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6266 constructor_elt *ce;
6267 HOST_WIDE_INT i;
6268 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6270 if (instantiation_dependent_expression_p (ce->index))
6271 return;
6272 if (!check_array_designated_initializer (ce, i))
6273 failure = 1;
6274 /* If an un-designated initializer is type-dependent, we can't
6275 check brace elision yet. */
6276 if (ce->index == NULL_TREE
6277 && type_dependent_expression_p (ce->value))
6278 return;
6282 if (failure)
6283 TREE_TYPE (decl) = error_mark_node;
6284 else
6286 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6287 do_default);
6288 if (failure == 1)
6290 error_at (cp_expr_loc_or_loc (initializer,
6291 DECL_SOURCE_LOCATION (decl)),
6292 "initializer fails to determine size of %qD", decl);
6294 else if (failure == 2)
6296 if (do_default)
6298 error_at (DECL_SOURCE_LOCATION (decl),
6299 "array size missing in %qD", decl);
6301 /* If a `static' var's size isn't known, make it extern as
6302 well as static, so it does not get allocated. If it's not
6303 `static', then don't mark it extern; finish_incomplete_decl
6304 will give it a default size and it will get allocated. */
6305 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6306 DECL_EXTERNAL (decl) = 1;
6308 else if (failure == 3)
6310 error_at (DECL_SOURCE_LOCATION (decl),
6311 "zero-size array %qD", decl);
6315 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6317 relayout_decl (decl);
6321 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6322 any appropriate error messages regarding the layout. */
6324 static void
6325 layout_var_decl (tree decl)
6327 tree type;
6329 type = TREE_TYPE (decl);
6330 if (type == error_mark_node)
6331 return;
6333 /* If we haven't already laid out this declaration, do so now.
6334 Note that we must not call complete type for an external object
6335 because it's type might involve templates that we are not
6336 supposed to instantiate yet. (And it's perfectly valid to say
6337 `extern X x' for some incomplete type `X'.) */
6338 if (!DECL_EXTERNAL (decl))
6339 complete_type (type);
6340 if (!DECL_SIZE (decl)
6341 && TREE_TYPE (decl) != error_mark_node
6342 && complete_or_array_type_p (type))
6343 layout_decl (decl, 0);
6345 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6347 /* An automatic variable with an incomplete type: that is an error.
6348 Don't talk about array types here, since we took care of that
6349 message in grokdeclarator. */
6350 error_at (DECL_SOURCE_LOCATION (decl),
6351 "storage size of %qD isn%'t known", decl);
6352 TREE_TYPE (decl) = error_mark_node;
6354 #if 0
6355 /* Keep this code around in case we later want to control debug info
6356 based on whether a type is "used". (jason 1999-11-11) */
6358 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6359 /* Let debugger know it should output info for this type. */
6360 note_debug_info_needed (ttype);
6362 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6363 note_debug_info_needed (DECL_CONTEXT (decl));
6364 #endif
6366 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6367 && DECL_SIZE (decl) != NULL_TREE
6368 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6370 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6371 && !DECL_LOCAL_DECL_P (decl))
6372 constant_expression_warning (DECL_SIZE (decl));
6373 else
6375 error_at (DECL_SOURCE_LOCATION (decl),
6376 "storage size of %qD isn%'t constant", decl);
6377 TREE_TYPE (decl) = error_mark_node;
6378 type = error_mark_node;
6382 /* If the final element initializes a flexible array field, add the size of
6383 that initializer to DECL's size. */
6384 if (type != error_mark_node
6385 && DECL_INITIAL (decl)
6386 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6387 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6388 && DECL_SIZE (decl) != NULL_TREE
6389 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6390 && COMPLETE_TYPE_P (type)
6391 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6392 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6394 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6395 if (elt.index)
6397 tree itype = TREE_TYPE (elt.index);
6398 tree vtype = TREE_TYPE (elt.value);
6399 if (TREE_CODE (itype) == ARRAY_TYPE
6400 && TYPE_DOMAIN (itype) == NULL
6401 && TREE_CODE (vtype) == ARRAY_TYPE
6402 && COMPLETE_TYPE_P (vtype))
6404 DECL_SIZE (decl)
6405 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6406 DECL_SIZE_UNIT (decl)
6407 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6408 TYPE_SIZE_UNIT (vtype));
6414 /* If a local static variable is declared in an inline function, or if
6415 we have a weak definition, we must endeavor to create only one
6416 instance of the variable at link-time. */
6418 void
6419 maybe_commonize_var (tree decl)
6421 /* Don't mess with __FUNCTION__ and similar. But do handle structured
6422 bindings. */
6423 if (DECL_ARTIFICIAL (decl) && !DECL_DECOMPOSITION_P (decl))
6424 return;
6426 /* Static data in a function with comdat linkage also has comdat
6427 linkage. */
6428 if ((TREE_STATIC (decl)
6429 && DECL_FUNCTION_SCOPE_P (decl)
6430 && vague_linkage_p (DECL_CONTEXT (decl)))
6431 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6433 if (flag_weak)
6435 /* With weak symbols, we simply make the variable COMDAT;
6436 that will cause copies in multiple translations units to
6437 be merged. */
6438 comdat_linkage (decl);
6440 else
6442 if (DECL_INITIAL (decl) == NULL_TREE
6443 || DECL_INITIAL (decl) == error_mark_node)
6445 /* Without weak symbols, we can use COMMON to merge
6446 uninitialized variables. */
6447 TREE_PUBLIC (decl) = 1;
6448 DECL_COMMON (decl) = 1;
6450 else
6452 /* While for initialized variables, we must use internal
6453 linkage -- which means that multiple copies will not
6454 be merged. */
6455 TREE_PUBLIC (decl) = 0;
6456 DECL_COMMON (decl) = 0;
6457 DECL_INTERFACE_KNOWN (decl) = 1;
6458 const char *msg;
6459 if (DECL_INLINE_VAR_P (decl))
6460 msg = G_("sorry: semantics of inline variable "
6461 "%q#D are wrong (you%'ll wind up with "
6462 "multiple copies)");
6463 else
6464 msg = G_("sorry: semantics of inline function "
6465 "static data %q#D are wrong (you%'ll wind "
6466 "up with multiple copies)");
6467 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6468 msg, decl))
6469 inform (DECL_SOURCE_LOCATION (decl),
6470 "you can work around this by removing the initializer");
6476 /* Issue an error message if DECL is an uninitialized const variable.
6477 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6478 context from potential_constant_expression. Returns true if all is well,
6479 false otherwise. */
6481 bool
6482 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6483 tsubst_flags_t complain)
6485 tree type = strip_array_types (TREE_TYPE (decl));
6487 /* ``Unless explicitly declared extern, a const object does not have
6488 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6489 7.1.6 */
6490 if (VAR_P (decl)
6491 && !TYPE_REF_P (type)
6492 && (CP_TYPE_CONST_P (type)
6493 /* C++20 permits trivial default initialization in constexpr
6494 context (P1331R2). */
6495 || (cxx_dialect < cxx20
6496 && (constexpr_context_p
6497 || var_in_constexpr_fn (decl))))
6498 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6500 tree field = default_init_uninitialized_part (type);
6501 if (!field)
6502 return true;
6504 bool show_notes = true;
6506 if (!constexpr_context_p || cxx_dialect >= cxx20)
6508 if (CP_TYPE_CONST_P (type))
6510 if (complain & tf_error)
6511 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6512 "uninitialized %<const %D%>", decl);
6514 else
6516 if (!is_instantiation_of_constexpr (current_function_decl)
6517 && (complain & tf_error))
6518 error_at (DECL_SOURCE_LOCATION (decl),
6519 "uninitialized variable %qD in %<constexpr%> "
6520 "function", decl);
6521 else
6522 show_notes = false;
6523 cp_function_chain->invalid_constexpr = true;
6526 else if (complain & tf_error)
6527 error_at (DECL_SOURCE_LOCATION (decl),
6528 "uninitialized variable %qD in %<constexpr%> context",
6529 decl);
6531 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6533 tree defaulted_ctor;
6535 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6536 "%q#T has no user-provided default constructor", type);
6537 defaulted_ctor = in_class_defaulted_default_constructor (type);
6538 if (defaulted_ctor)
6539 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6540 "constructor is not user-provided because it is "
6541 "explicitly defaulted in the class body");
6542 inform (DECL_SOURCE_LOCATION (field),
6543 "and the implicitly-defined constructor does not "
6544 "initialize %q#D", field);
6547 return false;
6550 return true;
6553 /* Structure holding the current initializer being processed by reshape_init.
6554 CUR is a pointer to the current element being processed, END is a pointer
6555 after the last element present in the initializer. */
6556 struct reshape_iter
6558 constructor_elt *cur;
6559 constructor_elt *end;
6562 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6564 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6565 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6566 initialized as if for an aggregate class. If there are no more such fields,
6567 the return value will be NULL. */
6569 tree
6570 next_aggregate_field (tree field)
6572 while (field
6573 && (TREE_CODE (field) != FIELD_DECL
6574 || DECL_UNNAMED_BIT_FIELD (field)
6575 || (DECL_ARTIFICIAL (field)
6576 /* In C++17, aggregates can have bases. */
6577 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6578 field = DECL_CHAIN (field);
6580 return field;
6583 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6584 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6585 to a subobject. If there are no more such fields, the return value will be
6586 NULL. */
6588 tree
6589 next_subobject_field (tree field)
6591 while (field
6592 && (TREE_CODE (field) != FIELD_DECL
6593 || DECL_UNNAMED_BIT_FIELD (field)
6594 || (DECL_ARTIFICIAL (field)
6595 && !DECL_FIELD_IS_BASE (field)
6596 && !DECL_VIRTUAL_P (field))))
6597 field = DECL_CHAIN (field);
6599 return field;
6602 /* Return true for [dcl.init.list] direct-list-initialization from
6603 single element of enumeration with a fixed underlying type. */
6605 bool
6606 is_direct_enum_init (tree type, tree init)
6608 if (cxx_dialect >= cxx17
6609 && TREE_CODE (type) == ENUMERAL_TYPE
6610 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6611 && TREE_CODE (init) == CONSTRUCTOR
6612 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6613 && CONSTRUCTOR_NELTS (init) == 1
6614 /* DR 2374: The single element needs to be implicitly
6615 convertible to the underlying type of the enum. */
6616 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6617 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6618 CONSTRUCTOR_ELT (init, 0)->value,
6619 LOOKUP_IMPLICIT, tf_none))
6620 return true;
6621 return false;
6624 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6625 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6626 INTEGER_CST representing the size of the array minus one (the maximum index),
6627 or NULL_TREE if the array was declared without specifying the size. D is
6628 the iterator within the constructor. */
6630 static tree
6631 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6632 tree first_initializer_p, tsubst_flags_t complain)
6634 tree new_init;
6635 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6636 unsigned HOST_WIDE_INT max_index_cst = 0;
6637 unsigned HOST_WIDE_INT index;
6639 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6640 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6641 to build a new one. But don't reuse if not complaining; if this is
6642 tentative, we might also reshape to another type (95319). */
6643 bool reuse = (first_initializer_p
6644 && (complain & tf_error)
6645 && !CP_AGGREGATE_TYPE_P (elt_type)
6646 && !TREE_SIDE_EFFECTS (first_initializer_p));
6647 if (reuse)
6648 new_init = first_initializer_p;
6649 else
6650 new_init = build_constructor (init_list_type_node, NULL);
6652 if (sized_array_p)
6654 /* Minus 1 is used for zero sized arrays. */
6655 if (integer_all_onesp (max_index))
6656 return new_init;
6658 if (tree_fits_uhwi_p (max_index))
6659 max_index_cst = tree_to_uhwi (max_index);
6660 /* sizetype is sign extended, not zero extended. */
6661 else
6662 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6665 /* Loop until there are no more initializers. */
6666 for (index = 0;
6667 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6668 ++index)
6670 tree elt_init;
6671 constructor_elt *old_cur = d->cur;
6673 if (d->cur->index)
6674 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6675 check_array_designated_initializer (d->cur, index);
6676 elt_init = reshape_init_r (elt_type, d,
6677 /*first_initializer_p=*/NULL_TREE,
6678 complain);
6679 if (elt_init == error_mark_node)
6680 return error_mark_node;
6681 tree idx = size_int (index);
6682 if (reuse)
6684 old_cur->index = idx;
6685 old_cur->value = elt_init;
6687 else
6688 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6689 idx, elt_init);
6690 if (!TREE_CONSTANT (elt_init))
6691 TREE_CONSTANT (new_init) = false;
6693 /* This can happen with an invalid initializer (c++/54501). */
6694 if (d->cur == old_cur && !sized_array_p)
6695 break;
6698 return new_init;
6701 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6702 Parameters are the same of reshape_init_r. */
6704 static tree
6705 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6706 tsubst_flags_t complain)
6708 tree max_index = NULL_TREE;
6710 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6712 if (TYPE_DOMAIN (type))
6713 max_index = array_type_nelts (type);
6715 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6716 first_initializer_p, complain);
6719 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6720 Parameters are the same of reshape_init_r. */
6722 static tree
6723 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6725 tree max_index = NULL_TREE;
6727 gcc_assert (VECTOR_TYPE_P (type));
6729 if (COMPOUND_LITERAL_P (d->cur->value))
6731 tree value = d->cur->value;
6732 if (!same_type_p (TREE_TYPE (value), type))
6734 if (complain & tf_error)
6735 error ("invalid type %qT as initializer for a vector of type %qT",
6736 TREE_TYPE (d->cur->value), type);
6737 value = error_mark_node;
6739 ++d->cur;
6740 return value;
6743 /* For a vector, we initialize it as an array of the appropriate size. */
6744 if (VECTOR_TYPE_P (type))
6745 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6747 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6748 NULL_TREE, complain);
6751 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6752 INIT, in isolation from any designator or other initializers. */
6754 static tree
6755 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
6757 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
6758 calling reshape_init, but this way can just live on the stack. */
6759 constructor_elt elt = { /*index=*/NULL_TREE, init };
6760 reshape_iter iter = { &elt, &elt + 1 };
6761 return reshape_init_r (type, &iter,
6762 /*first_initializer_p=*/NULL_TREE,
6763 complain);
6766 /* Subroutine of reshape_init_r, processes the initializers for classes
6767 or union. Parameters are the same of reshape_init_r. */
6769 static tree
6770 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6771 tsubst_flags_t complain)
6773 tree field;
6774 tree new_init;
6776 gcc_assert (CLASS_TYPE_P (type));
6778 /* The initializer for a class is always a CONSTRUCTOR. */
6779 new_init = build_constructor (init_list_type_node, NULL);
6781 int binfo_idx = -1;
6782 tree binfo = TYPE_BINFO (type);
6783 tree base_binfo = NULL_TREE;
6784 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6786 /* We get here from maybe_aggr_guide for C++20 class template argument
6787 deduction. In this case we need to look through the binfo because a
6788 template doesn't have base fields. */
6789 binfo_idx = 0;
6790 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6792 if (base_binfo)
6793 field = base_binfo;
6794 else
6795 field = next_aggregate_field (TYPE_FIELDS (type));
6797 if (!field)
6799 /* [dcl.init.aggr]
6801 An initializer for an aggregate member that is an
6802 empty class shall have the form of an empty
6803 initializer-list {}. */
6804 if (!first_initializer_p)
6806 if (complain & tf_error)
6807 error ("initializer for %qT must be brace-enclosed", type);
6808 return error_mark_node;
6810 return new_init;
6813 /* For C++20 CTAD, handle pack expansions in the base list. */
6814 tree last_was_pack_expansion = NULL_TREE;
6816 /* Loop through the initializable fields, gathering initializers. */
6817 while (d->cur != d->end)
6819 tree field_init;
6820 constructor_elt *old_cur = d->cur;
6821 bool direct_desig = false;
6823 /* Handle C++20 designated initializers. */
6824 if (d->cur->index)
6826 if (d->cur->index == error_mark_node)
6827 return error_mark_node;
6829 if (TREE_CODE (d->cur->index) == FIELD_DECL)
6831 /* We already reshaped this; we should have returned early from
6832 reshape_init. */
6833 gcc_checking_assert (false);
6834 if (field != d->cur->index)
6836 if (tree id = DECL_NAME (d->cur->index))
6837 gcc_checking_assert (d->cur->index
6838 == get_class_binding (type, id));
6839 field = d->cur->index;
6842 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6844 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6845 field = get_class_binding (type, d->cur->index);
6846 direct_desig = true;
6848 else
6850 if (complain & tf_error)
6851 error ("%<[%E] =%> used in a GNU-style designated initializer"
6852 " for class %qT", d->cur->index, type);
6853 return error_mark_node;
6856 if (!field && ANON_AGGR_TYPE_P (type))
6857 /* Apparently the designator isn't for a member of this anonymous
6858 struct, so head back to the enclosing class. */
6859 break;
6861 if (!field || TREE_CODE (field) != FIELD_DECL)
6863 if (complain & tf_error)
6864 error ("%qT has no non-static data member named %qD", type,
6865 d->cur->index);
6866 return error_mark_node;
6869 /* If the element is an anonymous union object and the initializer
6870 list is a designated-initializer-list, the anonymous union object
6871 is initialized by the designated-initializer-list { D }, where D
6872 is the designated-initializer-clause naming a member of the
6873 anonymous union object. */
6874 tree ictx = DECL_CONTEXT (field);
6875 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
6877 /* Find the anon aggr that is a direct member of TYPE. */
6878 while (ANON_AGGR_TYPE_P (ictx))
6880 tree cctx = TYPE_CONTEXT (ictx);
6881 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
6882 goto found;
6883 ictx = cctx;
6886 /* Not found, e.g. FIELD is a member of a base class. */
6887 if (complain & tf_error)
6888 error ("%qD is not a direct member of %qT", field, type);
6889 return error_mark_node;
6891 found:
6892 /* Now find the TYPE member with that anon aggr type. */
6893 tree aafield = TYPE_FIELDS (type);
6894 for (; aafield; aafield = TREE_CHAIN (aafield))
6895 if (TREE_TYPE (aafield) == ictx)
6896 break;
6897 gcc_assert (aafield);
6898 field = aafield;
6899 direct_desig = false;
6903 /* If we processed all the member of the class, we are done. */
6904 if (!field)
6905 break;
6907 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6908 ? field : NULL_TREE);
6909 if (last_was_pack_expansion)
6910 /* Each non-trailing aggregate element that is a pack expansion is
6911 assumed to correspond to no elements of the initializer list. */
6912 goto continue_;
6914 if (direct_desig)
6916 /* The designated field F is initialized from this one element.
6918 Note that we don't want to do this if we found the designator
6919 inside an anon aggr above; we use the normal code to implement:
6921 "If the element is an anonymous union member and the initializer
6922 list is a brace-enclosed designated- initializer-list, the element
6923 is initialized by the designated-initializer-list { D }, where D
6924 is the designated- initializer-clause naming a member of the
6925 anonymous union member." */
6926 field_init = reshape_single_init (TREE_TYPE (field),
6927 d->cur->value, complain);
6928 d->cur++;
6930 else
6931 field_init = reshape_init_r (TREE_TYPE (field), d,
6932 /*first_initializer_p=*/NULL_TREE,
6933 complain);
6935 if (field_init == error_mark_node)
6936 return error_mark_node;
6938 if (d->cur == old_cur && d->cur->index)
6940 /* This can happen with an invalid initializer for a flexible
6941 array member (c++/54441). */
6942 if (complain & tf_error)
6943 error ("invalid initializer for %q#D", field);
6944 return error_mark_node;
6947 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6949 /* [dcl.init.aggr]
6951 When a union is initialized with a brace-enclosed
6952 initializer, the braces shall only contain an
6953 initializer for the first member of the union. */
6954 if (TREE_CODE (type) == UNION_TYPE)
6955 break;
6957 continue_:
6958 if (base_binfo)
6960 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
6961 field = base_binfo;
6962 else
6963 field = next_aggregate_field (TYPE_FIELDS (type));
6965 else
6966 field = next_aggregate_field (DECL_CHAIN (field));
6969 /* A trailing aggregate element that is a pack expansion is assumed to
6970 correspond to all remaining elements of the initializer list (if any). */
6971 if (last_was_pack_expansion)
6973 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6974 last_was_pack_expansion, d->cur->value);
6975 while (d->cur != d->end)
6976 d->cur++;
6979 return new_init;
6982 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
6983 designators are not valid; either complain or return true to indicate
6984 that reshape_init_r should return error_mark_node. */
6986 static bool
6987 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6989 if (d->cur->index)
6991 if (complain & tf_error)
6992 error_at (cp_expr_loc_or_input_loc (d->cur->index),
6993 "C99 designator %qE outside aggregate initializer",
6994 d->cur->index);
6995 else
6996 return true;
6998 return false;
7001 /* Subroutine of reshape_init, which processes a single initializer (part of
7002 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
7003 iterator within the CONSTRUCTOR which points to the initializer to process.
7004 If this is the first initializer of the outermost CONSTRUCTOR node,
7005 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
7007 static tree
7008 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
7009 tsubst_flags_t complain)
7011 tree init = d->cur->value;
7013 if (error_operand_p (init))
7014 return error_mark_node;
7016 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
7017 && has_designator_problem (d, complain))
7018 return error_mark_node;
7020 tree stripped_init = tree_strip_any_location_wrapper (init);
7022 if (TREE_CODE (type) == COMPLEX_TYPE)
7024 /* A complex type can be initialized from one or two initializers,
7025 but braces are not elided. */
7026 d->cur++;
7027 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
7029 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
7031 if (complain & tf_error)
7032 error ("too many initializers for %qT", type);
7033 else
7034 return error_mark_node;
7037 else if (first_initializer_p && d->cur != d->end)
7039 vec<constructor_elt, va_gc> *v = 0;
7040 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
7041 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
7042 if (has_designator_problem (d, complain))
7043 return error_mark_node;
7044 d->cur++;
7045 init = build_constructor (init_list_type_node, v);
7047 return init;
7050 /* A non-aggregate type is always initialized with a single
7051 initializer. */
7052 if (!CP_AGGREGATE_TYPE_P (type)
7053 /* As is an array with dependent bound, which we can see
7054 during C++20 aggregate CTAD. */
7055 || (cxx_dialect >= cxx20
7056 && TREE_CODE (type) == ARRAY_TYPE
7057 && uses_template_parms (TYPE_DOMAIN (type))))
7059 /* It is invalid to initialize a non-aggregate type with a
7060 brace-enclosed initializer before C++0x.
7061 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
7062 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
7063 a CONSTRUCTOR (with a record type). */
7064 if (TREE_CODE (stripped_init) == CONSTRUCTOR
7065 /* Don't complain about a capture-init. */
7066 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
7067 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
7069 if (SCALAR_TYPE_P (type))
7071 if (cxx_dialect < cxx11)
7073 if (complain & tf_error)
7074 error ("braces around scalar initializer for type %qT",
7075 type);
7076 init = error_mark_node;
7078 else if (first_initializer_p
7079 || (CONSTRUCTOR_NELTS (stripped_init) > 0
7080 && (BRACE_ENCLOSED_INITIALIZER_P
7081 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
7083 if (complain & tf_error)
7084 error ("too many braces around scalar initializer "
7085 "for type %qT", type);
7086 init = error_mark_node;
7089 else
7090 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7093 d->cur++;
7094 return init;
7097 /* "If T is a class type and the initializer list has a single element of
7098 type cv U, where U is T or a class derived from T, the object is
7099 initialized from that element." Even if T is an aggregate. */
7100 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
7101 && first_initializer_p
7102 /* But not if it's a designated init. */
7103 && !d->cur->index
7104 && d->end - d->cur == 1
7105 && reference_related_p (type, TREE_TYPE (init)))
7107 d->cur++;
7108 return init;
7111 /* [dcl.init.aggr]
7113 All implicit type conversions (clause _conv_) are considered when
7114 initializing the aggregate member with an initializer from an
7115 initializer-list. If the initializer can initialize a member,
7116 the member is initialized. Otherwise, if the member is itself a
7117 non-empty subaggregate, brace elision is assumed and the
7118 initializer is considered for the initialization of the first
7119 member of the subaggregate. */
7120 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
7121 /* But don't try this for the first initializer, since that would be
7122 looking through the outermost braces; A a2 = { a1 }; is not a
7123 valid aggregate initialization. */
7124 && !first_initializer_p
7125 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
7126 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
7127 complain)))
7129 d->cur++;
7130 return init;
7133 /* [dcl.init.string]
7135 A char array (whether plain char, signed char, or unsigned char)
7136 can be initialized by a string-literal (optionally enclosed in
7137 braces); a wchar_t array can be initialized by a wide
7138 string-literal (optionally enclosed in braces). */
7139 if (TREE_CODE (type) == ARRAY_TYPE
7140 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
7142 tree str_init = init;
7143 tree stripped_str_init = stripped_init;
7144 reshape_iter stripd = {};
7146 /* Strip one level of braces if and only if they enclose a single
7147 element (as allowed by [dcl.init.string]). */
7148 if (!first_initializer_p
7149 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
7150 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
7152 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
7153 str_init = stripd.cur->value;
7154 stripped_str_init = tree_strip_any_location_wrapper (str_init);
7157 /* If it's a string literal, then it's the initializer for the array
7158 as a whole. Otherwise, continue with normal initialization for
7159 array types (one value per array element). */
7160 if (TREE_CODE (stripped_str_init) == STRING_CST)
7162 if ((first_initializer_p && has_designator_problem (d, complain))
7163 || (stripd.cur && has_designator_problem (&stripd, complain)))
7164 return error_mark_node;
7165 d->cur++;
7166 return str_init;
7170 /* The following cases are about aggregates. If we are not within a full
7171 initializer already, and there is not a CONSTRUCTOR, it means that there
7172 is a missing set of braces (that is, we are processing the case for
7173 which reshape_init exists). */
7174 bool braces_elided_p = false;
7175 if (!first_initializer_p)
7177 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7179 tree init_type = TREE_TYPE (init);
7180 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7181 /* There is no need to call reshape_init for pointer-to-member
7182 function initializers, as they are always constructed correctly
7183 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7184 which is missing outermost braces. We should warn below, and
7185 one of the routines below will wrap it in additional { }. */;
7186 /* For a nested compound literal, proceed to specialized routines,
7187 to handle initialization of arrays and similar. */
7188 else if (COMPOUND_LITERAL_P (stripped_init))
7189 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7190 /* If we have an unresolved designator, we need to find the member it
7191 designates within TYPE, so proceed to the routines below. For
7192 FIELD_DECL or INTEGER_CST designators, we're already initializing
7193 the designated element. */
7194 else if (d->cur->index
7195 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7196 /* Brace elision with designators is only permitted for anonymous
7197 aggregates. */
7198 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7199 /* A CONSTRUCTOR of the target's type is a previously
7200 digested initializer. */
7201 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7203 ++d->cur;
7204 return init;
7206 else
7208 /* Something that hasn't been reshaped yet. */
7209 ++d->cur;
7210 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7211 return reshape_init (type, init, complain);
7215 if (complain & tf_warning)
7216 warning (OPT_Wmissing_braces,
7217 "missing braces around initializer for %qT",
7218 type);
7219 braces_elided_p = true;
7222 /* Dispatch to specialized routines. */
7223 tree new_init;
7224 if (CLASS_TYPE_P (type))
7225 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7226 else if (TREE_CODE (type) == ARRAY_TYPE)
7227 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7228 else if (VECTOR_TYPE_P (type))
7229 new_init = reshape_init_vector (type, d, complain);
7230 else
7231 gcc_unreachable();
7233 if (braces_elided_p
7234 && TREE_CODE (new_init) == CONSTRUCTOR)
7235 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7237 return new_init;
7240 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7241 brace-enclosed aggregate initializer.
7243 INIT is the CONSTRUCTOR containing the list of initializers describing
7244 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7245 It may not presently match the shape of the TYPE; for example:
7247 struct S { int a; int b; };
7248 struct S a[] = { 1, 2, 3, 4 };
7250 Here INIT will hold a vector of four elements, rather than a
7251 vector of two elements, each itself a vector of two elements. This
7252 routine transforms INIT from the former form into the latter. The
7253 revised CONSTRUCTOR node is returned. */
7255 tree
7256 reshape_init (tree type, tree init, tsubst_flags_t complain)
7258 vec<constructor_elt, va_gc> *v;
7259 reshape_iter d;
7260 tree new_init;
7262 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7264 v = CONSTRUCTOR_ELTS (init);
7266 /* An empty constructor does not need reshaping, and it is always a valid
7267 initializer. */
7268 if (vec_safe_is_empty (v))
7269 return init;
7271 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7272 /* Already reshaped. */
7273 return init;
7275 /* Brace elision is not performed for a CONSTRUCTOR representing
7276 parenthesized aggregate initialization. */
7277 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7279 tree elt = (*v)[0].value;
7280 /* If we're initializing a char array from a string-literal that is
7281 enclosed in braces, unwrap it here. */
7282 if (TREE_CODE (type) == ARRAY_TYPE
7283 && vec_safe_length (v) == 1
7284 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7285 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7286 return elt;
7287 return init;
7290 /* Handle [dcl.init.list] direct-list-initialization from
7291 single element of enumeration with a fixed underlying type. */
7292 if (is_direct_enum_init (type, init))
7294 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7295 type = cv_unqualified (type);
7296 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7298 warning_sentinel w (warn_useless_cast);
7299 warning_sentinel w2 (warn_ignored_qualifiers);
7300 return cp_build_c_cast (input_location, type, elt,
7301 tf_warning_or_error);
7303 else
7304 return error_mark_node;
7307 /* Recurse on this CONSTRUCTOR. */
7308 d.cur = &(*v)[0];
7309 d.end = d.cur + v->length ();
7311 new_init = reshape_init_r (type, &d, init, complain);
7312 if (new_init == error_mark_node)
7313 return error_mark_node;
7315 /* Make sure all the element of the constructor were used. Otherwise,
7316 issue an error about exceeding initializers. */
7317 if (d.cur != d.end)
7319 if (complain & tf_error)
7320 error ("too many initializers for %qT", type);
7321 return error_mark_node;
7324 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7325 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7326 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7327 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7328 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7329 gcc_checking_assert (CONSTRUCTOR_IS_DESIGNATED_INIT (new_init)
7330 || seen_error ());
7332 return new_init;
7335 /* Verify array initializer. Returns true if errors have been reported. */
7337 bool
7338 check_array_initializer (tree decl, tree type, tree init)
7340 tree element_type = TREE_TYPE (type);
7342 /* Structured binding when initialized with an array type needs
7343 to have complete type. */
7344 if (decl
7345 && DECL_DECOMPOSITION_P (decl)
7346 && !DECL_DECOMP_BASE (decl)
7347 && !COMPLETE_TYPE_P (type))
7349 error_at (DECL_SOURCE_LOCATION (decl),
7350 "structured binding has incomplete type %qT", type);
7351 TREE_TYPE (decl) = error_mark_node;
7352 return true;
7355 /* The array type itself need not be complete, because the
7356 initializer may tell us how many elements are in the array.
7357 But, the elements of the array must be complete. */
7358 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7360 if (decl)
7361 error_at (DECL_SOURCE_LOCATION (decl),
7362 "elements of array %q#D have incomplete type", decl);
7363 else
7364 error ("elements of array %q#T have incomplete type", type);
7365 return true;
7368 location_t loc = (decl ? location_of (decl) : input_location);
7369 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7370 return true;
7372 /* A compound literal can't have variable size. */
7373 if (init && !decl
7374 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7375 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7377 error ("variable-sized compound literal");
7378 return true;
7380 return false;
7383 /* Subroutine of check_initializer; args are passed down from that function.
7384 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7386 static tree
7387 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7389 gcc_assert (stmts_are_full_exprs_p ());
7390 if (init)
7391 maybe_warn_pessimizing_move (init, TREE_TYPE (decl), /*return_p*/false);
7392 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7395 /* Verify INIT (the initializer for DECL), and record the
7396 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7397 grok_reference_init.
7399 If the return value is non-NULL, it is an expression that must be
7400 evaluated dynamically to initialize DECL. */
7402 static tree
7403 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7405 tree type;
7406 tree init_code = NULL;
7407 tree core_type;
7409 /* Things that are going to be initialized need to have complete
7410 type. */
7411 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7413 if (DECL_HAS_VALUE_EXPR_P (decl))
7415 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7416 it doesn't have storage to be initialized. */
7417 gcc_assert (init == NULL_TREE);
7418 return NULL_TREE;
7421 if (type == error_mark_node)
7422 /* We will have already complained. */
7423 return NULL_TREE;
7425 if (TREE_CODE (type) == ARRAY_TYPE)
7427 if (check_array_initializer (decl, type, init))
7428 return NULL_TREE;
7430 else if (!COMPLETE_TYPE_P (type))
7432 error_at (DECL_SOURCE_LOCATION (decl),
7433 "%q#D has incomplete type", decl);
7434 TREE_TYPE (decl) = error_mark_node;
7435 return NULL_TREE;
7437 else
7438 /* There is no way to make a variable-sized class type in GNU C++. */
7439 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7441 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7443 int init_len = CONSTRUCTOR_NELTS (init);
7444 if (SCALAR_TYPE_P (type))
7446 if (init_len == 0)
7448 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7449 init = build_zero_init (type, NULL_TREE, false);
7451 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7453 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7454 "scalar object %qD requires one element in "
7455 "initializer", decl);
7456 TREE_TYPE (decl) = error_mark_node;
7457 return NULL_TREE;
7462 if (TREE_CODE (decl) == CONST_DECL)
7464 gcc_assert (!TYPE_REF_P (type));
7466 DECL_INITIAL (decl) = init;
7468 gcc_assert (init != NULL_TREE);
7469 init = NULL_TREE;
7471 else if (!init && DECL_REALLY_EXTERN (decl))
7473 else if (init || type_build_ctor_call (type)
7474 || TYPE_REF_P (type))
7476 if (TYPE_REF_P (type))
7478 init = grok_reference_init (decl, type, init, flags);
7479 flags |= LOOKUP_ALREADY_DIGESTED;
7481 else if (!init)
7482 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7483 tf_warning_or_error);
7484 /* Do not reshape constructors of vectors (they don't need to be
7485 reshaped. */
7486 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7488 if (is_std_init_list (type))
7490 init = perform_implicit_conversion (type, init,
7491 tf_warning_or_error);
7492 flags |= LOOKUP_ALREADY_DIGESTED;
7494 else if (TYPE_NON_AGGREGATE_CLASS (type))
7496 /* Don't reshape if the class has constructors. */
7497 if (cxx_dialect == cxx98)
7498 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7499 "in C++98 %qD must be initialized by "
7500 "constructor, not by %<{...}%>",
7501 decl);
7503 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7505 error ("opaque vector types cannot be initialized");
7506 init = error_mark_node;
7508 else
7510 init = reshape_init (type, init, tf_warning_or_error);
7511 flags |= LOOKUP_NO_NARROWING;
7514 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7515 is initialized as follows..." So handle things like
7517 int a[](1, 2, 3);
7519 which is permitted in C++20 by P0960. */
7520 else if (TREE_CODE (init) == TREE_LIST
7521 && TREE_TYPE (init) == NULL_TREE
7522 && TREE_CODE (type) == ARRAY_TYPE
7523 && !DECL_DECOMPOSITION_P (decl)
7524 && (cxx_dialect >= cxx20))
7525 init = do_aggregate_paren_init (init, type);
7526 else if (TREE_CODE (init) == TREE_LIST
7527 && TREE_TYPE (init) != unknown_type_node
7528 && !MAYBE_CLASS_TYPE_P (type))
7530 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7532 /* We get here with code like `int a (2);' */
7533 init = build_x_compound_expr_from_list (init, ELK_INIT,
7534 tf_warning_or_error);
7537 /* If DECL has an array type without a specific bound, deduce the
7538 array size from the initializer. */
7539 maybe_deduce_size_from_array_init (decl, init);
7540 type = TREE_TYPE (decl);
7541 if (type == error_mark_node)
7542 return NULL_TREE;
7544 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7545 && !(flags & LOOKUP_ALREADY_DIGESTED)
7546 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7547 && CP_AGGREGATE_TYPE_P (type)
7548 && (CLASS_TYPE_P (type)
7549 /* The call to build_aggr_init below could end up
7550 calling build_vec_init, which may break when we
7551 are processing a template. */
7552 || processing_template_decl
7553 || !TYPE_NEEDS_CONSTRUCTING (type)
7554 || type_has_extended_temps (type))))
7555 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7557 init_code = build_aggr_init_full_exprs (decl, init, flags);
7559 /* A constructor call is a non-trivial initializer even if
7560 it isn't explicitly written. */
7561 if (TREE_SIDE_EFFECTS (init_code))
7562 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7564 /* If this is a constexpr initializer, expand_default_init will
7565 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7566 case, pull the initializer back out and pass it down into
7567 store_init_value. */
7568 while (true)
7570 if (TREE_CODE (init_code) == EXPR_STMT
7571 || TREE_CODE (init_code) == STMT_EXPR
7572 || TREE_CODE (init_code) == CONVERT_EXPR)
7573 init_code = TREE_OPERAND (init_code, 0);
7574 else if (TREE_CODE (init_code) == BIND_EXPR)
7575 init_code = BIND_EXPR_BODY (init_code);
7576 else
7577 break;
7579 if (TREE_CODE (init_code) == INIT_EXPR)
7581 /* In C++20, the call to build_aggr_init could have created
7582 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7583 A(1, 2). */
7584 tree rhs = TREE_OPERAND (init_code, 1);
7585 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7586 /* Avoid leaking TARGET_EXPR into template trees. */
7587 rhs = build_implicit_conv_flags (type, init, flags);
7588 init = rhs;
7590 init_code = NULL_TREE;
7591 /* Don't call digest_init; it's unnecessary and will complain
7592 about aggregate initialization of non-aggregate classes. */
7593 flags |= LOOKUP_ALREADY_DIGESTED;
7595 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7596 || DECL_DECLARED_CONSTINIT_P (decl))
7598 /* Declared constexpr or constinit, but no suitable initializer;
7599 massage init appropriately so we can pass it into
7600 store_init_value for the error. */
7601 tree new_init = NULL_TREE;
7602 if (!processing_template_decl
7603 && TREE_CODE (init_code) == CALL_EXPR)
7604 new_init = build_cplus_new (type, init_code, tf_none);
7605 else if (CLASS_TYPE_P (type)
7606 && (!init || TREE_CODE (init) == TREE_LIST))
7607 new_init = build_functional_cast (input_location, type,
7608 init, tf_none);
7609 if (new_init)
7611 init = new_init;
7612 if (TREE_CODE (init) == TARGET_EXPR
7613 && !(flags & LOOKUP_ONLYCONVERTING))
7614 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7616 init_code = NULL_TREE;
7618 else
7619 init = NULL_TREE;
7622 if (init && TREE_CODE (init) != TREE_VEC)
7624 init_code = store_init_value (decl, init, cleanups, flags);
7626 if (DECL_INITIAL (decl)
7627 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7628 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7630 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7631 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7632 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7633 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7636 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7637 && DECL_INITIAL (decl)
7638 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7639 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7640 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7641 DECL_SOURCE_LOCATION (decl)),
7642 0, "array %qD initialized by parenthesized "
7643 "string literal %qE",
7644 decl, DECL_INITIAL (decl));
7645 init = NULL_TREE;
7648 else
7650 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7651 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7652 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7653 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7654 /*complain=*/true);
7656 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7657 tf_warning_or_error);
7660 if (init && init != error_mark_node)
7661 init_code = cp_build_init_expr (decl, init);
7663 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7664 && init_code != error_mark_node)
7665 init_code = NULL_TREE;
7667 if (init_code)
7669 /* We might have set these in cp_finish_decl. */
7670 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7671 TREE_CONSTANT (decl) = false;
7674 if (init_code
7675 && DECL_IN_AGGR_P (decl)
7676 && DECL_INITIALIZED_IN_CLASS_P (decl))
7678 static int explained = 0;
7680 if (cxx_dialect < cxx11)
7681 error ("initializer invalid for static member with constructor");
7682 else if (cxx_dialect < cxx17)
7683 error ("non-constant in-class initialization invalid for static "
7684 "member %qD", decl);
7685 else
7686 error ("non-constant in-class initialization invalid for non-inline "
7687 "static member %qD", decl);
7688 if (!explained)
7690 inform (input_location,
7691 "(an out of class initialization is required)");
7692 explained = 1;
7694 return NULL_TREE;
7697 return init_code;
7700 /* If DECL is not a local variable, give it RTL. */
7702 static void
7703 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7705 int toplev = toplevel_bindings_p ();
7706 int defer_p;
7708 /* Set the DECL_ASSEMBLER_NAME for the object. */
7709 if (asmspec)
7711 /* The `register' keyword, when used together with an
7712 asm-specification, indicates that the variable should be
7713 placed in a particular register. */
7714 if (VAR_P (decl) && DECL_REGISTER (decl))
7716 set_user_assembler_name (decl, asmspec);
7717 DECL_HARD_REGISTER (decl) = 1;
7719 else
7721 if (TREE_CODE (decl) == FUNCTION_DECL
7722 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7723 set_builtin_user_assembler_name (decl, asmspec);
7724 set_user_assembler_name (decl, asmspec);
7725 if (DECL_LOCAL_DECL_P (decl))
7726 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7727 /* We have to propagate the name to the ns-alias.
7728 This is horrible, as we're affecting a
7729 possibly-shared decl. Again, a one-true-decl
7730 model breaks down. */
7731 if (ns_decl != error_mark_node)
7732 set_user_assembler_name (ns_decl, asmspec);
7736 /* Handle non-variables up front. */
7737 if (!VAR_P (decl))
7739 rest_of_decl_compilation (decl, toplev, at_eof);
7740 return;
7743 /* If we see a class member here, it should be a static data
7744 member. */
7745 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7747 gcc_assert (TREE_STATIC (decl));
7748 /* An in-class declaration of a static data member should be
7749 external; it is only a declaration, and not a definition. */
7750 if (init == NULL_TREE)
7751 gcc_assert (DECL_EXTERNAL (decl)
7752 || !TREE_PUBLIC (decl));
7755 /* We don't create any RTL for local variables. */
7756 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7757 return;
7759 /* We defer emission of local statics until the corresponding
7760 DECL_EXPR is expanded. But with constexpr its function might never
7761 be expanded, so go ahead and tell cgraph about the variable now. */
7762 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7763 && !var_in_maybe_constexpr_fn (decl))
7764 || DECL_VIRTUAL_P (decl));
7766 /* Defer template instantiations. */
7767 if (DECL_LANG_SPECIFIC (decl)
7768 && DECL_IMPLICIT_INSTANTIATION (decl))
7769 defer_p = 1;
7771 /* If we're not deferring, go ahead and assemble the variable. */
7772 if (!defer_p)
7773 rest_of_decl_compilation (decl, toplev, at_eof);
7776 /* walk_tree helper for wrap_temporary_cleanups, below. */
7778 static tree
7779 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7781 /* Stop at types or full-expression boundaries. */
7782 if (TYPE_P (*stmt_p)
7783 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7785 *walk_subtrees = 0;
7786 return NULL_TREE;
7789 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7791 tree guard = (tree)data;
7792 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7794 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
7795 && !expr_noexcept_p (tcleanup, tf_none))
7797 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7798 /* Tell honor_protect_cleanup_actions to handle this as a separate
7799 cleanup. */
7800 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7801 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7805 return NULL_TREE;
7808 /* We're initializing a local variable which has a cleanup GUARD. If there
7809 are any temporaries used in the initializer INIT of this variable, we
7810 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7811 variable will be cleaned up properly if one of them throws.
7813 Unfortunately, there's no way to express this properly in terms of
7814 nesting, as the regions for the temporaries overlap the region for the
7815 variable itself; if there are two temporaries, the variable needs to be
7816 the first thing destroyed if either of them throws. However, we only
7817 want to run the variable's cleanup if it actually got constructed. So
7818 we need to guard the temporary cleanups with the variable's cleanup if
7819 they are run on the normal path, but not if they are run on the
7820 exceptional path. We implement this by telling
7821 honor_protect_cleanup_actions to strip the variable cleanup from the
7822 exceptional path.
7824 Another approach could be to make the variable cleanup region enclose
7825 initialization, but depend on a flag to indicate that the variable is
7826 initialized; that's effectively what we do for arrays. But the current
7827 approach works fine for non-arrays, and has no code overhead in the usual
7828 case where the temporary destructors are noexcept. */
7830 static void
7831 wrap_temporary_cleanups (tree init, tree guard)
7833 if (TREE_CODE (guard) == BIND_EXPR)
7835 /* An array cleanup region already encloses any temporary cleanups,
7836 don't wrap it around them again. */
7837 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
7838 return;
7840 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7843 /* Generate code to initialize DECL (a local variable). */
7845 static void
7846 initialize_local_var (tree decl, tree init)
7848 tree type = TREE_TYPE (decl);
7849 tree cleanup;
7850 int already_used;
7852 gcc_assert (VAR_P (decl)
7853 || TREE_CODE (decl) == RESULT_DECL);
7854 gcc_assert (!TREE_STATIC (decl));
7856 if (DECL_SIZE (decl) == NULL_TREE)
7858 /* If we used it already as memory, it must stay in memory. */
7859 DECL_INITIAL (decl) = NULL_TREE;
7860 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7861 return;
7864 if (type == error_mark_node)
7865 return;
7867 /* Compute and store the initial value. */
7868 already_used = TREE_USED (decl) || TREE_USED (type);
7869 if (TREE_USED (type))
7870 DECL_READ_P (decl) = 1;
7872 /* Generate a cleanup, if necessary. */
7873 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7875 /* Perform the initialization. */
7876 if (init)
7878 tree rinit = (TREE_CODE (init) == INIT_EXPR
7879 ? TREE_OPERAND (init, 1) : NULL_TREE);
7880 if (rinit && !TREE_SIDE_EFFECTS (rinit)
7881 && TREE_OPERAND (init, 0) == decl)
7883 /* Stick simple initializers in DECL_INITIAL so that
7884 -Wno-init-self works (c++/34772). */
7885 DECL_INITIAL (decl) = rinit;
7887 if (warn_init_self && TYPE_REF_P (type))
7889 STRIP_NOPS (rinit);
7890 if (rinit == decl)
7891 warning_at (DECL_SOURCE_LOCATION (decl),
7892 OPT_Winit_self,
7893 "reference %qD is initialized with itself", decl);
7896 else
7898 int saved_stmts_are_full_exprs_p;
7900 /* If we're only initializing a single object, guard the
7901 destructors of any temporaries used in its initializer with
7902 its destructor. */
7903 if (cleanup)
7904 wrap_temporary_cleanups (init, cleanup);
7906 gcc_assert (building_stmt_list_p ());
7907 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7908 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7909 finish_expr_stmt (init);
7910 current_stmt_tree ()->stmts_are_full_exprs_p =
7911 saved_stmts_are_full_exprs_p;
7915 /* Set this to 0 so we can tell whether an aggregate which was
7916 initialized was ever used. Don't do this if it has a
7917 destructor, so we don't complain about the 'resource
7918 allocation is initialization' idiom. Now set
7919 attribute((unused)) on types so decls of that type will be
7920 marked used. (see TREE_USED, above.) */
7921 if (TYPE_NEEDS_CONSTRUCTING (type)
7922 && ! already_used
7923 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7924 && DECL_NAME (decl))
7925 TREE_USED (decl) = 0;
7926 else if (already_used)
7927 TREE_USED (decl) = 1;
7929 if (cleanup)
7930 finish_decl_cleanup (decl, cleanup);
7933 /* DECL is a VAR_DECL for a compiler-generated variable with static
7934 storage duration (like a virtual table) whose initializer is a
7935 compile-time constant. Initialize the variable and provide it to the
7936 back end. */
7938 void
7939 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7941 tree init;
7942 gcc_assert (DECL_ARTIFICIAL (decl));
7943 init = build_constructor (TREE_TYPE (decl), v);
7944 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7945 DECL_INITIAL (decl) = init;
7946 DECL_INITIALIZED_P (decl) = 1;
7947 /* Mark the decl as constexpr so that we can access its content
7948 at compile time. */
7949 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7950 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7951 determine_visibility (decl);
7952 layout_var_decl (decl);
7953 maybe_commonize_var (decl);
7954 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7957 /* INIT is the initializer for a variable, as represented by the
7958 parser. Returns true iff INIT is value-dependent. */
7960 static bool
7961 value_dependent_init_p (tree init)
7963 if (TREE_CODE (init) == TREE_LIST)
7964 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7965 return any_value_dependent_elements_p (init);
7966 else if (TREE_CODE (init) == CONSTRUCTOR)
7967 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7969 if (dependent_type_p (TREE_TYPE (init)))
7970 return true;
7972 vec<constructor_elt, va_gc> *elts;
7973 size_t nelts;
7974 size_t i;
7976 elts = CONSTRUCTOR_ELTS (init);
7977 nelts = vec_safe_length (elts);
7978 for (i = 0; i < nelts; ++i)
7979 if (value_dependent_init_p ((*elts)[i].value))
7980 return true;
7982 else
7983 /* It must be a simple expression, e.g., int i = 3; */
7984 return value_dependent_expression_p (init);
7986 return false;
7989 // Returns true if a DECL is VAR_DECL with the concept specifier.
7990 static inline bool
7991 is_concept_var (tree decl)
7993 return (VAR_P (decl)
7994 // Not all variables have DECL_LANG_SPECIFIC.
7995 && DECL_LANG_SPECIFIC (decl)
7996 && DECL_DECLARED_CONCEPT_P (decl));
7999 /* A helper function to be called via walk_tree. If any label exists
8000 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
8002 static tree
8003 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
8005 if (TYPE_P (*tp))
8006 *walk_subtrees = 0;
8007 if (TREE_CODE (*tp) == LABEL_DECL)
8008 cfun->has_forced_label_in_static = 1;
8009 return NULL_TREE;
8012 /* Return true if DECL has either a trivial destructor, or for C++20
8013 is constexpr and has a constexpr destructor. */
8015 static bool
8016 decl_maybe_constant_destruction (tree decl, tree type)
8018 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8019 || (cxx_dialect >= cxx20
8020 && VAR_P (decl)
8021 && DECL_DECLARED_CONSTEXPR_P (decl)
8022 && type_has_constexpr_destructor (strip_array_types (type))));
8025 static tree declare_simd_adjust_this (tree *, int *, void *);
8027 /* Helper function of omp_declare_variant_finalize. Finalize one
8028 "omp declare variant base" attribute. Return true if it should be
8029 removed. */
8031 static bool
8032 omp_declare_variant_finalize_one (tree decl, tree attr)
8034 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8036 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
8037 DECL_ARGUMENTS (decl), NULL);
8038 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
8039 DECL_ARGUMENTS (decl), NULL);
8042 tree ctx = TREE_VALUE (TREE_VALUE (attr));
8043 tree simd = omp_get_context_selector (ctx, "construct", "simd");
8044 if (simd)
8046 TREE_VALUE (simd)
8047 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
8048 TREE_VALUE (simd));
8049 /* FIXME, adjusting simd args unimplemented. */
8050 return true;
8053 tree chain = TREE_CHAIN (TREE_VALUE (attr));
8054 location_t varid_loc
8055 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
8056 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
8057 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
8058 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
8060 location_t save_loc = input_location;
8061 input_location = varid_loc;
8063 releasing_vec args;
8064 tree parm = DECL_ARGUMENTS (decl);
8065 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8066 parm = DECL_CHAIN (parm);
8067 for (; parm; parm = DECL_CHAIN (parm))
8068 if (type_dependent_expression_p (parm))
8069 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
8070 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
8071 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
8072 else
8073 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
8075 bool koenig_p = false;
8076 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
8078 if (identifier_p (variant)
8079 /* In C++20, we may need to perform ADL for a template
8080 name. */
8081 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
8082 && identifier_p (TREE_OPERAND (variant, 0))))
8084 if (!args->is_empty ())
8086 koenig_p = true;
8087 if (!any_type_dependent_arguments_p (args))
8088 variant = perform_koenig_lookup (variant, args,
8089 tf_warning_or_error);
8091 else
8092 variant = unqualified_fn_lookup_error (variant);
8094 else if (!args->is_empty () && is_overloaded_fn (variant))
8096 tree fn = get_first_fn (variant);
8097 fn = STRIP_TEMPLATE (fn);
8098 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
8099 || DECL_FUNCTION_MEMBER_P (fn)
8100 || DECL_LOCAL_DECL_P (fn)))
8102 koenig_p = true;
8103 if (!any_type_dependent_arguments_p (args))
8104 variant = perform_koenig_lookup (variant, args,
8105 tf_warning_or_error);
8110 if (idk == CP_ID_KIND_QUALIFIED)
8111 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
8112 koenig_p, tf_warning_or_error);
8113 else
8114 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
8115 koenig_p, tf_warning_or_error);
8116 if (variant == error_mark_node && !processing_template_decl)
8117 return true;
8119 variant = cp_get_callee_fndecl_nofold (variant);
8120 input_location = save_loc;
8122 if (variant)
8124 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
8125 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
8127 error_at (varid_loc, "variant %qD and base %qD have incompatible "
8128 "types", variant, decl);
8129 return true;
8131 if (fndecl_built_in_p (variant)
8132 && (startswith (varname, "__builtin_")
8133 || startswith (varname, "__sync_")
8134 || startswith (varname, "__atomic_")))
8136 error_at (varid_loc, "variant %qD is a built-in", variant);
8137 return true;
8139 else
8141 tree construct = omp_get_context_selector (ctx, "construct", NULL);
8142 omp_mark_declare_variant (match_loc, variant, construct);
8143 if (!omp_context_selector_matches (ctx))
8144 return true;
8145 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
8148 else if (!processing_template_decl)
8150 error_at (varid_loc, "could not find variant declaration");
8151 return true;
8154 return false;
8157 /* Helper function, finish up "omp declare variant base" attribute
8158 now that there is a DECL. ATTR is the first "omp declare variant base"
8159 attribute. */
8161 void
8162 omp_declare_variant_finalize (tree decl, tree attr)
8164 size_t attr_len = strlen ("omp declare variant base");
8165 tree *list = &DECL_ATTRIBUTES (decl);
8166 bool remove_all = false;
8167 location_t match_loc = DECL_SOURCE_LOCATION (decl);
8168 if (TREE_CHAIN (TREE_VALUE (attr))
8169 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
8170 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
8171 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
8172 if (DECL_CONSTRUCTOR_P (decl))
8174 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
8175 remove_all = true;
8177 else if (DECL_DESTRUCTOR_P (decl))
8179 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8180 remove_all = true;
8182 else if (DECL_DEFAULTED_FN (decl))
8184 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8185 remove_all = true;
8187 else if (DECL_DELETED_FN (decl))
8189 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8190 remove_all = true;
8192 else if (DECL_VIRTUAL_P (decl))
8194 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8195 remove_all = true;
8197 /* This loop is like private_lookup_attribute, except that it works
8198 with tree * rather than tree, as we might want to remove the
8199 attributes that are diagnosed as errorneous. */
8200 while (*list)
8202 tree attr = get_attribute_name (*list);
8203 size_t ident_len = IDENTIFIER_LENGTH (attr);
8204 if (cmp_attribs ("omp declare variant base", attr_len,
8205 IDENTIFIER_POINTER (attr), ident_len))
8207 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8209 *list = TREE_CHAIN (*list);
8210 continue;
8213 list = &TREE_CHAIN (*list);
8217 static void cp_maybe_mangle_decomp (tree, cp_decomp *);
8219 /* Finish processing of a declaration;
8220 install its line number and initial value.
8221 If the length of an array type is not known before,
8222 it must be determined now, from the initial value, or it is an error.
8224 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8225 true, then INIT is an integral constant expression.
8227 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8228 if the (init) syntax was used.
8230 DECOMP is first identifier's DECL and identifier count in a structured
8231 bindings, nullptr if not a structured binding. */
8233 void
8234 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8235 tree asmspec_tree, int flags, cp_decomp *decomp)
8237 vec<tree, va_gc> *cleanups = NULL;
8238 const char *asmspec = NULL;
8239 int was_readonly = 0;
8240 bool var_definition_p = false;
8241 tree auto_node;
8243 if (decl == error_mark_node)
8244 return;
8245 else if (! decl)
8247 if (init)
8248 error ("assignment (not initialization) in declaration");
8249 return;
8252 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8253 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8254 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8256 tree type = TREE_TYPE (decl);
8257 if (type == error_mark_node)
8258 return;
8260 if (VAR_P (decl) && is_copy_initialization (init))
8261 flags |= LOOKUP_ONLYCONVERTING;
8263 /* Warn about register storage specifiers except when in GNU global
8264 or local register variable extension. */
8265 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8267 if (cxx_dialect >= cxx17)
8268 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8269 "ISO C++17 does not allow %<register%> storage "
8270 "class specifier");
8271 else
8272 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8273 "%<register%> storage class specifier used");
8276 /* If a name was specified, get the string. */
8277 if (at_namespace_scope_p ())
8278 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8279 if (asmspec_tree && asmspec_tree != error_mark_node)
8280 asmspec = TREE_STRING_POINTER (asmspec_tree);
8282 bool in_class_decl
8283 = (current_class_type
8284 && CP_DECL_CONTEXT (decl) == current_class_type
8285 && TYPE_BEING_DEFINED (current_class_type)
8286 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8288 if (in_class_decl
8289 && (DECL_INITIAL (decl) || init))
8290 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8292 if (VAR_P (decl)
8293 && (auto_node = type_uses_auto (type)))
8295 tree d_init;
8296 if (init == NULL_TREE)
8298 if (DECL_LANG_SPECIFIC (decl)
8299 && DECL_TEMPLATE_INSTANTIATION (decl)
8300 && !DECL_TEMPLATE_INSTANTIATED (decl))
8302 /* init is null because we're deferring instantiating the
8303 initializer until we need it. Well, we need it now. */
8304 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8305 return;
8308 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8309 /* Class deduction with no initializer is OK. */;
8310 else
8312 /* Ordinary auto deduction without an initializer, a situation
8313 which grokdeclarator already detects and rejects for the most
8314 part. But we can still get here if we're instantiating a
8315 variable template before we've fully parsed (and attached) its
8316 initializer, e.g. template<class> auto x = x<int>; */
8317 error_at (DECL_SOURCE_LOCATION (decl),
8318 "declaration of %q#D has no initializer", decl);
8319 TREE_TYPE (decl) = error_mark_node;
8320 return;
8323 d_init = init;
8324 if (d_init)
8326 if (TREE_CODE (d_init) == TREE_LIST
8327 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8328 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8329 tf_warning_or_error);
8330 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8331 /* Force auto deduction now. Use tf_none to avoid redundant warnings
8332 on deprecated-14.C. */
8333 mark_single_function (d_init, tf_none);
8335 enum auto_deduction_context adc = adc_variable_type;
8336 if (DECL_DECOMPOSITION_P (decl))
8337 adc = adc_decomp_type;
8338 tree outer_targs = NULL_TREE;
8339 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8340 && DECL_LANG_SPECIFIC (decl)
8341 && DECL_TEMPLATE_INFO (decl)
8342 && !DECL_FUNCTION_SCOPE_P (decl))
8343 /* The outer template arguments might be needed for satisfaction.
8344 (For function scope variables, do_auto_deduction will obtain the
8345 outer template arguments from current_function_decl.) */
8346 outer_targs = DECL_TI_ARGS (decl);
8347 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8348 tf_warning_or_error, adc,
8349 outer_targs, flags);
8350 if (type == error_mark_node)
8351 return;
8352 if (TREE_CODE (type) == FUNCTION_TYPE)
8354 error ("initializer for %<decltype(auto) %D%> has function type; "
8355 "did you forget the %<()%>?", decl);
8356 TREE_TYPE (decl) = error_mark_node;
8357 return;
8359 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8360 if (!processing_template_decl
8361 && !type_uses_auto (type)
8362 && !COMPLETE_TYPE_P (complete_type (type)))
8364 error_at (location_of (decl),
8365 "deduced type %qT for %qD is incomplete", type, decl);
8366 cxx_incomplete_type_inform (type);
8367 TREE_TYPE (decl) = error_mark_node;
8368 return;
8370 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8372 /* Update the type of the corresponding TEMPLATE_DECL to match. */
8373 if (DECL_LANG_SPECIFIC (decl)
8374 && DECL_TEMPLATE_INFO (decl)
8375 && DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) == decl)
8376 TREE_TYPE (DECL_TI_TEMPLATE (decl)) = type;
8379 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8381 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8382 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8384 init = NULL_TREE;
8385 DECL_EXTERNAL (decl) = 1;
8389 if (VAR_P (decl)
8390 && DECL_CLASS_SCOPE_P (decl)
8391 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8392 TCTX_STATIC_STORAGE, type)
8393 && DECL_INITIALIZED_IN_CLASS_P (decl))
8394 check_static_variable_definition (decl, type);
8396 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8398 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8399 ? TCTX_THREAD_STORAGE
8400 : TCTX_STATIC_STORAGE);
8401 verify_type_context (input_location, context, TREE_TYPE (decl));
8404 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8406 tree clone;
8407 if (init == ridpointers[(int)RID_DELETE])
8409 /* FIXME check this is 1st decl. */
8410 DECL_DELETED_FN (decl) = 1;
8411 DECL_DECLARED_INLINE_P (decl) = 1;
8412 DECL_INITIAL (decl) = error_mark_node;
8413 FOR_EACH_CLONE (clone, decl)
8415 DECL_DELETED_FN (clone) = 1;
8416 DECL_DECLARED_INLINE_P (clone) = 1;
8417 DECL_INITIAL (clone) = error_mark_node;
8419 init = NULL_TREE;
8421 else if (init == ridpointers[(int)RID_DEFAULT])
8423 if (defaultable_fn_check (decl))
8424 DECL_DEFAULTED_FN (decl) = 1;
8425 else
8426 DECL_INITIAL (decl) = NULL_TREE;
8430 if (init && VAR_P (decl))
8432 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8433 /* If DECL is a reference, then we want to know whether init is a
8434 reference constant; init_const_expr_p as passed tells us whether
8435 it's an rvalue constant. */
8436 if (TYPE_REF_P (type))
8437 init_const_expr_p = potential_constant_expression (init);
8438 if (init_const_expr_p)
8440 /* Set these flags now for templates. We'll update the flags in
8441 store_init_value for instantiations. */
8442 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8443 if (decl_maybe_constant_var_p (decl)
8444 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8445 && !TYPE_REF_P (type))
8446 TREE_CONSTANT (decl) = true;
8448 /* This is handled mostly by gimplify.cc, but we have to deal with
8449 not warning about int x = x; as it is a GCC extension to turn off
8450 this warning but only if warn_init_self is zero. */
8451 if (!DECL_EXTERNAL (decl)
8452 && !TREE_STATIC (decl)
8453 && decl == tree_strip_any_location_wrapper (init)
8454 && !warning_enabled_at (DECL_SOURCE_LOCATION (decl), OPT_Winit_self))
8455 suppress_warning (decl, OPT_Winit_self);
8457 else if (VAR_P (decl)
8458 && COMPLETE_TYPE_P (type)
8459 && !TYPE_REF_P (type)
8460 && !dependent_type_p (type)
8461 && is_really_empty_class (type, /*ignore_vptr*/false))
8462 /* We have no initializer but there's nothing to initialize anyway.
8463 Treat DECL as constant due to c++/109876. */
8464 TREE_CONSTANT (decl) = true;
8466 if (flag_openmp
8467 && TREE_CODE (decl) == FUNCTION_DECL
8468 /* #pragma omp declare variant on methods handled in finish_struct
8469 instead. */
8470 && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
8471 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8472 if (tree attr = lookup_attribute ("omp declare variant base",
8473 DECL_ATTRIBUTES (decl)))
8474 omp_declare_variant_finalize (decl, attr);
8476 if (processing_template_decl)
8478 bool type_dependent_p;
8480 /* Add this declaration to the statement-tree. */
8481 if (at_function_scope_p ())
8482 add_decl_expr (decl);
8484 type_dependent_p = dependent_type_p (type);
8486 if (check_for_bare_parameter_packs (init))
8488 init = NULL_TREE;
8489 DECL_INITIAL (decl) = NULL_TREE;
8492 /* Generally, initializers in templates are expanded when the
8493 template is instantiated. But, if DECL is a variable constant
8494 then it can be used in future constant expressions, so its value
8495 must be available. */
8497 bool dep_init = false;
8499 if (!VAR_P (decl) || type_dependent_p)
8500 /* We can't do anything if the decl has dependent type. */;
8501 else if (!init && is_concept_var (decl))
8503 error ("variable concept has no initializer");
8504 init = boolean_true_node;
8506 else if (init
8507 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8508 && !TYPE_REF_P (type)
8509 && decl_maybe_constant_var_p (decl)
8510 && !(dep_init = value_dependent_init_p (init)))
8512 /* This variable seems to be a non-dependent constant, so process
8513 its initializer. If check_initializer returns non-null the
8514 initialization wasn't constant after all. */
8515 tree init_code;
8516 cleanups = make_tree_vector ();
8517 init_code = check_initializer (decl, init, flags, &cleanups);
8518 if (init_code == NULL_TREE)
8519 init = NULL_TREE;
8520 release_tree_vector (cleanups);
8522 else
8524 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8525 /* Try to deduce array size. */
8526 maybe_deduce_size_from_array_init (decl, init);
8527 /* And complain about multiple initializers. */
8528 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8529 && !MAYBE_CLASS_TYPE_P (type))
8530 init = build_x_compound_expr_from_list (init, ELK_INIT,
8531 tf_warning_or_error);
8534 if (init)
8535 DECL_INITIAL (decl) = init;
8537 if (dep_init)
8539 retrofit_lang_decl (decl);
8540 SET_DECL_DEPENDENT_INIT_P (decl, true);
8543 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8545 set_user_assembler_name (decl, asmspec);
8546 DECL_HARD_REGISTER (decl) = 1;
8548 return;
8551 /* Just store non-static data member initializers for later. */
8552 if (init && TREE_CODE (decl) == FIELD_DECL)
8553 DECL_INITIAL (decl) = init;
8555 /* Take care of TYPE_DECLs up front. */
8556 if (TREE_CODE (decl) == TYPE_DECL)
8558 if (type != error_mark_node
8559 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8561 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8562 warning (0, "shadowing previous type declaration of %q#D", decl);
8563 set_identifier_type_value (DECL_NAME (decl), decl);
8566 /* If we have installed this as the canonical typedef for this
8567 type, and that type has not been defined yet, delay emitting
8568 the debug information for it, as we will emit it later. */
8569 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8570 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8571 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8573 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8574 at_eof);
8575 return;
8578 /* A reference will be modified here, as it is initialized. */
8579 if (! DECL_EXTERNAL (decl)
8580 && TREE_READONLY (decl)
8581 && TYPE_REF_P (type))
8583 was_readonly = 1;
8584 TREE_READONLY (decl) = 0;
8587 /* This needs to happen before extend_ref_init_temps. */
8588 if (VAR_OR_FUNCTION_DECL_P (decl))
8590 if (VAR_P (decl))
8591 maybe_commonize_var (decl);
8592 determine_visibility (decl);
8595 if (VAR_P (decl))
8597 duration_kind dk = decl_storage_duration (decl);
8598 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8599 only to a declaration of a variable with static or thread storage
8600 duration." */
8601 if (DECL_DECLARED_CONSTINIT_P (decl)
8602 && !(dk == dk_thread || dk == dk_static))
8604 error_at (DECL_SOURCE_LOCATION (decl),
8605 "%<constinit%> can only be applied to a variable with "
8606 "static or thread storage duration");
8607 return;
8610 if (decomp)
8611 cp_maybe_mangle_decomp (decl, decomp);
8613 /* If this is a local variable that will need a mangled name,
8614 register it now. We must do this before processing the
8615 initializer for the variable, since the initialization might
8616 require a guard variable, and since the mangled name of the
8617 guard variable will depend on the mangled name of this
8618 variable. */
8619 if (DECL_FUNCTION_SCOPE_P (decl)
8620 && TREE_STATIC (decl)
8621 && !DECL_ARTIFICIAL (decl))
8623 /* The variable holding an anonymous union will have had its
8624 discriminator set in finish_anon_union, after which it's
8625 NAME will have been cleared. */
8626 if (DECL_NAME (decl))
8627 determine_local_discriminator (decl);
8628 /* Normally has_forced_label_in_static is set during GIMPLE
8629 lowering, but [cd]tors are never actually compiled directly.
8630 We need to set this early so we can deal with the label
8631 address extension. */
8632 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8633 || DECL_DESTRUCTOR_P (current_function_decl))
8634 && init)
8636 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8637 add_local_decl (cfun, decl);
8639 /* And make sure it's in the symbol table for
8640 c_parse_final_cleanups to find. */
8641 varpool_node::get_create (decl);
8644 /* Convert the initializer to the type of DECL, if we have not
8645 already initialized DECL. */
8646 if (!DECL_INITIALIZED_P (decl)
8647 /* If !DECL_EXTERNAL then DECL is being defined. In the
8648 case of a static data member initialized inside the
8649 class-specifier, there can be an initializer even if DECL
8650 is *not* defined. */
8651 && (!DECL_EXTERNAL (decl) || init))
8653 cleanups = make_tree_vector ();
8654 init = check_initializer (decl, init, flags, &cleanups);
8656 /* Handle:
8658 [dcl.init]
8660 The memory occupied by any object of static storage
8661 duration is zero-initialized at program startup before
8662 any other initialization takes place.
8664 We cannot create an appropriate initializer until after
8665 the type of DECL is finalized. If DECL_INITIAL is set,
8666 then the DECL is statically initialized, and any
8667 necessary zero-initialization has already been performed. */
8668 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8669 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8670 /*nelts=*/NULL_TREE,
8671 /*static_storage_p=*/true);
8672 /* Remember that the initialization for this variable has
8673 taken place. */
8674 DECL_INITIALIZED_P (decl) = 1;
8675 /* This declaration is the definition of this variable,
8676 unless we are initializing a static data member within
8677 the class specifier. */
8678 if (!DECL_EXTERNAL (decl))
8679 var_definition_p = true;
8681 /* If the variable has an array type, lay out the type, even if
8682 there is no initializer. It is valid to index through the
8683 array, and we must get TYPE_ALIGN set correctly on the array
8684 type. */
8685 else if (TREE_CODE (type) == ARRAY_TYPE)
8686 layout_type (type);
8688 if (TREE_STATIC (decl)
8689 && !at_function_scope_p ()
8690 && current_function_decl == NULL)
8691 /* So decl is a global variable or a static member of a
8692 non local class. Record the types it uses
8693 so that we can decide later to emit debug info for them. */
8694 record_types_used_by_current_var_decl (decl);
8697 /* Add this declaration to the statement-tree. This needs to happen
8698 after the call to check_initializer so that the DECL_EXPR for a
8699 reference temp is added before the DECL_EXPR for the reference itself. */
8700 if (DECL_FUNCTION_SCOPE_P (decl))
8702 /* If we're building a variable sized type, and we might be
8703 reachable other than via the top of the current binding
8704 level, then create a new BIND_EXPR so that we deallocate
8705 the object at the right time. */
8706 if (VAR_P (decl)
8707 && DECL_SIZE (decl)
8708 && !TREE_CONSTANT (DECL_SIZE (decl))
8709 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8711 tree bind;
8712 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8713 TREE_SIDE_EFFECTS (bind) = 1;
8714 add_stmt (bind);
8715 BIND_EXPR_BODY (bind) = push_stmt_list ();
8717 add_decl_expr (decl);
8720 /* Let the middle end know about variables and functions -- but not
8721 static data members in uninstantiated class templates. */
8722 if (VAR_OR_FUNCTION_DECL_P (decl))
8724 if (VAR_P (decl))
8726 layout_var_decl (decl);
8727 if (!flag_weak)
8728 /* Check again now that we have an initializer. */
8729 maybe_commonize_var (decl);
8730 /* A class-scope constexpr variable with an out-of-class declaration.
8731 C++17 makes them implicitly inline, but still force it out. */
8732 if (DECL_INLINE_VAR_P (decl)
8733 && !DECL_VAR_DECLARED_INLINE_P (decl)
8734 && !DECL_TEMPLATE_INSTANTIATION (decl)
8735 && !in_class_decl)
8736 mark_needed (decl);
8739 if (var_definition_p
8740 /* With -fmerge-all-constants, gimplify_init_constructor
8741 might add TREE_STATIC to aggregate variables. */
8742 && (TREE_STATIC (decl)
8743 || (flag_merge_constants >= 2
8744 && AGGREGATE_TYPE_P (type))))
8746 /* If a TREE_READONLY variable needs initialization
8747 at runtime, it is no longer readonly and we need to
8748 avoid MEM_READONLY_P being set on RTL created for it. */
8749 if (init)
8751 if (TREE_READONLY (decl))
8752 TREE_READONLY (decl) = 0;
8753 was_readonly = 0;
8755 else if (was_readonly)
8756 TREE_READONLY (decl) = 1;
8758 /* Likewise if it needs destruction. */
8759 if (!decl_maybe_constant_destruction (decl, type))
8760 TREE_READONLY (decl) = 0;
8762 else if (VAR_P (decl)
8763 && CP_DECL_THREAD_LOCAL_P (decl)
8764 && (!DECL_EXTERNAL (decl) || flag_extern_tls_init)
8765 && (was_readonly || TREE_READONLY (decl))
8766 && var_needs_tls_wrapper (decl))
8768 /* TLS variables need dynamic initialization by the TLS wrapper
8769 function, we don't want to hoist accesses to it before the
8770 wrapper. */
8771 was_readonly = 0;
8772 TREE_READONLY (decl) = 0;
8775 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8777 /* Check for abstractness of the type. */
8778 if (var_definition_p)
8779 abstract_virtuals_error (decl, type);
8781 if (TREE_TYPE (decl) == error_mark_node)
8782 /* No initialization required. */
8784 else if (TREE_CODE (decl) == FUNCTION_DECL)
8786 if (init)
8788 if (init == ridpointers[(int)RID_DEFAULT])
8790 /* An out-of-class default definition is defined at
8791 the point where it is explicitly defaulted. */
8792 if (DECL_DELETED_FN (decl))
8793 maybe_explain_implicit_delete (decl);
8794 else if (DECL_INITIAL (decl) == error_mark_node)
8795 synthesize_method (decl);
8797 else
8798 error_at (cp_expr_loc_or_loc (init,
8799 DECL_SOURCE_LOCATION (decl)),
8800 "function %q#D is initialized like a variable",
8801 decl);
8803 /* else no initialization required. */
8805 else if (DECL_EXTERNAL (decl)
8806 && ! (DECL_LANG_SPECIFIC (decl)
8807 && DECL_NOT_REALLY_EXTERN (decl)))
8809 /* check_initializer will have done any constant initialization. */
8811 /* A variable definition. */
8812 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8813 /* Initialize the local variable. */
8814 initialize_local_var (decl, init);
8816 /* If a variable is defined, and then a subsequent
8817 definition with external linkage is encountered, we will
8818 get here twice for the same variable. We want to avoid
8819 calling expand_static_init more than once. For variables
8820 that are not static data members, we can call
8821 expand_static_init only when we actually process the
8822 initializer. It is not legal to redeclare a static data
8823 member, so this issue does not arise in that case. */
8824 else if (var_definition_p && TREE_STATIC (decl))
8825 expand_static_init (decl, init);
8828 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
8829 reference, insert it in the statement-tree now. */
8830 if (cleanups)
8832 for (tree t : *cleanups)
8834 push_cleanup (NULL_TREE, t, false);
8835 /* As in initialize_local_var. */
8836 wrap_temporary_cleanups (init, t);
8838 release_tree_vector (cleanups);
8841 if (was_readonly)
8842 TREE_READONLY (decl) = 1;
8844 if (flag_openmp
8845 && VAR_P (decl)
8846 && lookup_attribute ("omp declare target implicit",
8847 DECL_ATTRIBUTES (decl)))
8849 DECL_ATTRIBUTES (decl)
8850 = remove_attribute ("omp declare target implicit",
8851 DECL_ATTRIBUTES (decl));
8852 complete_type (TREE_TYPE (decl));
8853 if (!omp_mappable_type (TREE_TYPE (decl)))
8855 error ("%q+D in declare target directive does not have mappable"
8856 " type", decl);
8857 if (TREE_TYPE (decl) != error_mark_node
8858 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8859 cxx_incomplete_type_inform (TREE_TYPE (decl));
8861 else if (!lookup_attribute ("omp declare target",
8862 DECL_ATTRIBUTES (decl))
8863 && !lookup_attribute ("omp declare target link",
8864 DECL_ATTRIBUTES (decl)))
8866 DECL_ATTRIBUTES (decl)
8867 = tree_cons (get_identifier ("omp declare target"),
8868 NULL_TREE, DECL_ATTRIBUTES (decl));
8869 symtab_node *node = symtab_node::get (decl);
8870 if (node != NULL)
8872 node->offloadable = 1;
8873 if (ENABLE_OFFLOADING)
8875 g->have_offload = true;
8876 if (is_a <varpool_node *> (node))
8877 vec_safe_push (offload_vars, decl);
8883 /* This is the last point we can lower alignment so give the target the
8884 chance to do so. */
8885 if (VAR_P (decl)
8886 && !is_global_var (decl)
8887 && !DECL_HARD_REGISTER (decl))
8888 targetm.lower_local_decl_alignment (decl);
8890 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8893 /* For class TYPE return itself or some its bases that contain
8894 any direct non-static data members. Return error_mark_node if an
8895 error has been diagnosed. */
8897 static tree
8898 find_decomp_class_base (location_t loc, tree type, tree ret)
8900 bool member_seen = false;
8901 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8902 if (TREE_CODE (field) != FIELD_DECL
8903 || DECL_ARTIFICIAL (field)
8904 || DECL_UNNAMED_BIT_FIELD (field))
8905 continue;
8906 else if (ret)
8907 return type;
8908 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8910 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8911 error_at (loc, "cannot decompose class type %qT because it has an "
8912 "anonymous struct member", type);
8913 else
8914 error_at (loc, "cannot decompose class type %qT because it has an "
8915 "anonymous union member", type);
8916 inform (DECL_SOURCE_LOCATION (field), "declared here");
8917 return error_mark_node;
8919 else if (!accessible_p (type, field, true))
8921 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8922 field, type);
8923 inform (DECL_SOURCE_LOCATION (field),
8924 TREE_PRIVATE (field)
8925 ? G_("declared private here")
8926 : G_("declared protected here"));
8927 return error_mark_node;
8929 else
8930 member_seen = true;
8932 tree base_binfo, binfo;
8933 tree orig_ret = ret;
8934 int i;
8935 if (member_seen)
8936 ret = type;
8937 for (binfo = TYPE_BINFO (type), i = 0;
8938 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8940 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8941 if (t == error_mark_node)
8942 return error_mark_node;
8943 if (t != NULL_TREE && t != ret)
8945 if (ret == type)
8947 error_at (loc, "cannot decompose class type %qT: both it and "
8948 "its base class %qT have non-static data members",
8949 type, t);
8950 return error_mark_node;
8952 else if (orig_ret != NULL_TREE)
8953 return t;
8954 else if (ret != NULL_TREE)
8956 error_at (loc, "cannot decompose class type %qT: its base "
8957 "classes %qT and %qT have non-static data "
8958 "members", type, ret, t);
8959 return error_mark_node;
8961 else
8962 ret = t;
8965 return ret;
8968 /* Return std::tuple_size<TYPE>::value. */
8970 static tree
8971 get_tuple_size (tree type)
8973 tree args = make_tree_vec (1);
8974 TREE_VEC_ELT (args, 0) = type;
8975 tree inst = lookup_template_class (tuple_size_identifier, args,
8976 /*in_decl*/NULL_TREE,
8977 /*context*/std_node,
8978 /*entering_scope*/false, tf_none);
8979 inst = complete_type (inst);
8980 if (inst == error_mark_node
8981 || !COMPLETE_TYPE_P (inst)
8982 || !CLASS_TYPE_P (type))
8983 return NULL_TREE;
8984 tree val = lookup_qualified_name (inst, value_identifier,
8985 LOOK_want::NORMAL, /*complain*/false);
8986 if (val == error_mark_node)
8987 return NULL_TREE;
8988 if (VAR_P (val) || TREE_CODE (val) == CONST_DECL)
8989 val = maybe_constant_value (val);
8990 if (TREE_CODE (val) == INTEGER_CST)
8991 return val;
8992 else
8993 return error_mark_node;
8996 /* Return std::tuple_element<I,TYPE>::type. */
8998 static tree
8999 get_tuple_element_type (tree type, unsigned i)
9001 tree args = make_tree_vec (2);
9002 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
9003 TREE_VEC_ELT (args, 1) = type;
9004 tree inst = lookup_template_class (tuple_element_identifier, args,
9005 /*in_decl*/NULL_TREE,
9006 /*context*/std_node,
9007 /*entering_scope*/false,
9008 tf_warning_or_error);
9009 return make_typename_type (inst, type_identifier,
9010 none_type, tf_warning_or_error);
9013 /* Return e.get<i>() or get<i>(e). */
9015 static tree
9016 get_tuple_decomp_init (tree decl, unsigned i)
9018 tree targs = make_tree_vec (1);
9019 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
9021 tree etype = TREE_TYPE (decl);
9022 tree e = convert_from_reference (decl);
9024 /* [The id-expression] e is an lvalue if the type of the entity e is an
9025 lvalue reference and an xvalue otherwise. */
9026 if (!TYPE_REF_P (etype)
9027 || TYPE_REF_IS_RVALUE (etype))
9028 e = move (e);
9030 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
9031 LOOK_want::NORMAL, /*complain*/false);
9032 bool use_member_get = false;
9034 /* To use a member get, member lookup must find at least one
9035 declaration that is a function template
9036 whose first template parameter is a non-type parameter. */
9037 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
9039 tree fn = *iter;
9040 if (TREE_CODE (fn) == TEMPLATE_DECL)
9042 tree tparms = DECL_TEMPLATE_PARMS (fn);
9043 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
9044 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
9046 use_member_get = true;
9047 break;
9052 if (use_member_get)
9054 fns = lookup_template_function (fns, targs);
9055 return build_new_method_call (e, fns, /*args*/NULL,
9056 /*path*/NULL_TREE, LOOKUP_NORMAL,
9057 /*fn_p*/NULL, tf_warning_or_error);
9059 else
9061 releasing_vec args (make_tree_vector_single (e));
9062 fns = lookup_template_function (get__identifier, targs);
9063 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
9064 return finish_call_expr (fns, &args, /*novirt*/false,
9065 /*koenig*/true, tf_warning_or_error);
9069 /* It's impossible to recover the decltype of a tuple decomposition variable
9070 based on the actual type of the variable, so store it in a hash table. */
9072 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
9074 tree
9075 lookup_decomp_type (tree v)
9077 return *decomp_type_table->get (v);
9080 /* Mangle a decomposition declaration if needed. Arguments like
9081 in cp_finish_decomp. */
9083 static void
9084 cp_maybe_mangle_decomp (tree decl, cp_decomp *decomp)
9086 if (!processing_template_decl
9087 && !error_operand_p (decl)
9088 && TREE_STATIC (decl))
9090 auto_vec<tree, 16> v;
9091 v.safe_grow (decomp->count, true);
9092 tree d = decomp->decl;
9093 for (unsigned int i = 0; i < decomp->count; i++, d = DECL_CHAIN (d))
9094 v[decomp->count - i - 1] = d;
9095 if (DECL_FUNCTION_SCOPE_P (decl))
9097 size_t sz = 3;
9098 for (unsigned int i = 0; i < decomp->count; ++i)
9099 sz += IDENTIFIER_LENGTH (DECL_NAME (v[i])) + 1;
9100 char *name = XALLOCAVEC (char, sz);
9101 name[0] = 'D';
9102 name[1] = 'C';
9103 char *p = name + 2;
9104 for (unsigned int i = 0; i < decomp->count; ++i)
9106 size_t len = IDENTIFIER_LENGTH (DECL_NAME (v[i]));
9107 *p++ = ' ';
9108 memcpy (p, IDENTIFIER_POINTER (DECL_NAME (v[i])), len);
9109 p += len;
9111 *p = '\0';
9112 determine_local_discriminator (decl, get_identifier (name));
9114 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
9115 maybe_apply_pragma_weak (decl);
9119 /* Finish a decomposition declaration. DECL is the underlying declaration
9120 "e", FIRST is the head of a chain of decls for the individual identifiers
9121 chained through DECL_CHAIN in reverse order and COUNT is the number of
9122 those decls. */
9124 void
9125 cp_finish_decomp (tree decl, cp_decomp *decomp)
9127 tree first = decomp->decl;
9128 unsigned count = decomp->count;
9129 if (error_operand_p (decl))
9131 error_out:
9132 while (count--)
9134 TREE_TYPE (first) = error_mark_node;
9135 if (DECL_HAS_VALUE_EXPR_P (first))
9137 SET_DECL_VALUE_EXPR (first, NULL_TREE);
9138 DECL_HAS_VALUE_EXPR_P (first) = 0;
9140 first = DECL_CHAIN (first);
9142 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
9143 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
9144 return;
9147 location_t loc = DECL_SOURCE_LOCATION (decl);
9148 if (type_dependent_expression_p (decl)
9149 /* This happens for range for when not in templates.
9150 Still add the DECL_VALUE_EXPRs for later processing. */
9151 || (!processing_template_decl
9152 && type_uses_auto (TREE_TYPE (decl))))
9154 for (unsigned int i = 0; i < count; i++)
9156 if (!DECL_HAS_VALUE_EXPR_P (first))
9158 tree v = build_nt (ARRAY_REF, decl,
9159 size_int (count - i - 1),
9160 NULL_TREE, NULL_TREE);
9161 SET_DECL_VALUE_EXPR (first, v);
9162 DECL_HAS_VALUE_EXPR_P (first) = 1;
9164 if (processing_template_decl)
9165 fit_decomposition_lang_decl (first, decl);
9166 first = DECL_CHAIN (first);
9168 return;
9171 auto_vec<tree, 16> v;
9172 v.safe_grow (count, true);
9173 tree d = first;
9174 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9176 v[count - i - 1] = d;
9177 fit_decomposition_lang_decl (d, decl);
9180 tree type = TREE_TYPE (decl);
9181 tree dexp = decl;
9183 if (TYPE_REF_P (type))
9185 dexp = convert_from_reference (dexp);
9186 type = complete_type (TREE_TYPE (type));
9187 if (type == error_mark_node)
9188 goto error_out;
9189 if (!COMPLETE_TYPE_P (type))
9191 error_at (loc, "structured binding refers to incomplete type %qT",
9192 type);
9193 goto error_out;
9197 tree eltype = NULL_TREE;
9198 unsigned HOST_WIDE_INT eltscnt = 0;
9199 if (TREE_CODE (type) == ARRAY_TYPE)
9201 tree nelts;
9202 nelts = array_type_nelts_top (type);
9203 if (nelts == error_mark_node)
9204 goto error_out;
9205 if (!tree_fits_uhwi_p (nelts))
9207 error_at (loc, "cannot decompose variable length array %qT", type);
9208 goto error_out;
9210 eltscnt = tree_to_uhwi (nelts);
9211 if (count != eltscnt)
9213 cnt_mismatch:
9214 if (count > eltscnt)
9215 error_n (loc, count,
9216 "%u name provided for structured binding",
9217 "%u names provided for structured binding", count);
9218 else
9219 error_n (loc, count,
9220 "only %u name provided for structured binding",
9221 "only %u names provided for structured binding", count);
9222 inform_n (loc, eltscnt,
9223 "while %qT decomposes into %wu element",
9224 "while %qT decomposes into %wu elements",
9225 type, eltscnt);
9226 goto error_out;
9228 eltype = TREE_TYPE (type);
9229 for (unsigned int i = 0; i < count; i++)
9231 TREE_TYPE (v[i]) = eltype;
9232 layout_decl (v[i], 0);
9233 if (processing_template_decl)
9234 continue;
9235 tree t = unshare_expr (dexp);
9236 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9237 SET_DECL_VALUE_EXPR (v[i], t);
9238 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9241 /* 2 GNU extensions. */
9242 else if (TREE_CODE (type) == COMPLEX_TYPE)
9244 eltscnt = 2;
9245 if (count != eltscnt)
9246 goto cnt_mismatch;
9247 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9248 for (unsigned int i = 0; i < count; i++)
9250 TREE_TYPE (v[i]) = eltype;
9251 layout_decl (v[i], 0);
9252 if (processing_template_decl)
9253 continue;
9254 tree t = unshare_expr (dexp);
9255 t = build1 (i ? IMAGPART_EXPR : REALPART_EXPR, eltype, t);
9256 SET_DECL_VALUE_EXPR (v[i], t);
9257 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9260 else if (TREE_CODE (type) == VECTOR_TYPE)
9262 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9264 error_at (loc, "cannot decompose variable length vector %qT", type);
9265 goto error_out;
9267 if (count != eltscnt)
9268 goto cnt_mismatch;
9269 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9270 for (unsigned int i = 0; i < count; i++)
9272 TREE_TYPE (v[i]) = eltype;
9273 layout_decl (v[i], 0);
9274 if (processing_template_decl)
9275 continue;
9276 tree t = unshare_expr (dexp);
9277 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9278 &t, size_int (i));
9279 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9280 SET_DECL_VALUE_EXPR (v[i], t);
9281 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9284 else if (tree tsize = get_tuple_size (type))
9286 if (tsize == error_mark_node)
9288 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9289 "constant expression", type);
9290 goto error_out;
9292 if (!tree_fits_uhwi_p (tsize))
9294 error_n (loc, count,
9295 "%u name provided for structured binding",
9296 "%u names provided for structured binding", count);
9297 inform (loc, "while %qT decomposes into %E elements",
9298 type, tsize);
9299 goto error_out;
9301 eltscnt = tree_to_uhwi (tsize);
9302 if (count != eltscnt)
9303 goto cnt_mismatch;
9304 int save_read = DECL_READ_P (decl);
9305 for (unsigned i = 0; i < count; ++i)
9307 location_t sloc = input_location;
9308 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9310 input_location = dloc;
9311 tree init = get_tuple_decomp_init (decl, i);
9312 tree eltype = (init == error_mark_node ? error_mark_node
9313 : get_tuple_element_type (type, i));
9314 input_location = sloc;
9316 if (VOID_TYPE_P (eltype))
9318 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9319 i, type);
9320 eltype = error_mark_node;
9322 if (init == error_mark_node || eltype == error_mark_node)
9324 inform (dloc, "in initialization of structured binding "
9325 "variable %qD", v[i]);
9326 goto error_out;
9328 /* Save the decltype away before reference collapse. */
9329 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9330 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9331 TREE_TYPE (v[i]) = eltype;
9332 layout_decl (v[i], 0);
9333 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9335 /* In this case the names are variables, not just proxies. */
9336 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9337 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9339 if (!processing_template_decl)
9341 copy_linkage (v[i], decl);
9342 cp_finish_decl (v[i], init, /*constexpr*/false,
9343 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9346 /* Ignore reads from the underlying decl performed during initialization
9347 of the individual variables. If those will be read, we'll mark
9348 the underlying decl as read at that point. */
9349 DECL_READ_P (decl) = save_read;
9351 else if (TREE_CODE (type) == UNION_TYPE)
9353 error_at (loc, "cannot decompose union type %qT", type);
9354 goto error_out;
9356 else if (!CLASS_TYPE_P (type))
9358 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9359 goto error_out;
9361 else if (LAMBDA_TYPE_P (type))
9363 error_at (loc, "cannot decompose lambda closure type %qT", type);
9364 goto error_out;
9366 else if (processing_template_decl && complete_type (type) == error_mark_node)
9367 goto error_out;
9368 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9369 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9370 type);
9371 else
9373 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9374 if (btype == error_mark_node)
9375 goto error_out;
9376 else if (btype == NULL_TREE)
9378 error_at (loc, "cannot decompose class type %qT without non-static "
9379 "data members", type);
9380 goto error_out;
9382 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9383 if (TREE_CODE (field) != FIELD_DECL
9384 || DECL_ARTIFICIAL (field)
9385 || DECL_UNNAMED_BIT_FIELD (field))
9386 continue;
9387 else
9388 eltscnt++;
9389 if (count != eltscnt)
9390 goto cnt_mismatch;
9391 tree t = dexp;
9392 if (type != btype)
9394 t = convert_to_base (t, btype, /*check_access*/true,
9395 /*nonnull*/false, tf_warning_or_error);
9396 type = btype;
9398 unsigned int i = 0;
9399 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9400 if (TREE_CODE (field) != FIELD_DECL
9401 || DECL_ARTIFICIAL (field)
9402 || DECL_UNNAMED_BIT_FIELD (field))
9403 continue;
9404 else
9406 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9407 NULL_TREE);
9408 if (REFERENCE_REF_P (tt))
9409 tt = TREE_OPERAND (tt, 0);
9410 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9411 layout_decl (v[i], 0);
9412 if (!processing_template_decl)
9414 SET_DECL_VALUE_EXPR (v[i], tt);
9415 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9417 i++;
9420 if (processing_template_decl)
9422 for (unsigned int i = 0; i < count; i++)
9423 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9425 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9426 NULL_TREE, NULL_TREE);
9427 SET_DECL_VALUE_EXPR (v[i], a);
9428 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9433 /* Returns a declaration for a VAR_DECL as if:
9435 extern "C" TYPE NAME;
9437 had been seen. Used to create compiler-generated global
9438 variables. */
9440 static tree
9441 declare_global_var (tree name, tree type)
9443 auto cookie = push_abi_namespace (global_namespace);
9444 tree decl = build_decl (input_location, VAR_DECL, name, type);
9445 TREE_PUBLIC (decl) = 1;
9446 DECL_EXTERNAL (decl) = 1;
9447 DECL_ARTIFICIAL (decl) = 1;
9448 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9449 /* If the user has explicitly declared this variable (perhaps
9450 because the code we are compiling is part of a low-level runtime
9451 library), then it is possible that our declaration will be merged
9452 with theirs by pushdecl. */
9453 decl = pushdecl (decl);
9454 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9455 pop_abi_namespace (cookie, global_namespace);
9457 return decl;
9460 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
9461 if "__cxa_atexit" is not being used) corresponding to the function
9462 to be called when the program exits. */
9464 static tree
9465 get_atexit_fn_ptr_type (void)
9467 tree fn_type;
9469 if (!atexit_fn_ptr_type_node)
9471 tree arg_type;
9472 if (flag_use_cxa_atexit
9473 && !targetm.cxx.use_atexit_for_cxa_atexit ())
9474 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
9475 arg_type = ptr_type_node;
9476 else
9477 /* The parameter to "atexit" is "void (*)(void)". */
9478 arg_type = NULL_TREE;
9480 fn_type = build_function_type_list (void_type_node,
9481 arg_type, NULL_TREE);
9482 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9485 return atexit_fn_ptr_type_node;
9488 /* Returns a pointer to the `atexit' function. Note that if
9489 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9490 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9492 static tree
9493 get_atexit_node (void)
9495 tree atexit_fndecl;
9496 tree fn_type;
9497 tree fn_ptr_type;
9498 const char *name;
9499 bool use_aeabi_atexit;
9500 tree ctx = global_namespace;
9502 if (atexit_node)
9503 return atexit_node;
9505 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9507 /* The declaration for `__cxa_atexit' is:
9509 int __cxa_atexit (void (*)(void *), void *, void *)
9511 We build up the argument types and then the function type
9512 itself. */
9513 tree argtype0, argtype1, argtype2;
9515 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9516 /* First, build the pointer-to-function type for the first
9517 argument. */
9518 fn_ptr_type = get_atexit_fn_ptr_type ();
9519 /* Then, build the rest of the argument types. */
9520 argtype2 = ptr_type_node;
9521 if (use_aeabi_atexit)
9523 argtype1 = fn_ptr_type;
9524 argtype0 = ptr_type_node;
9526 else
9528 argtype1 = ptr_type_node;
9529 argtype0 = fn_ptr_type;
9531 /* And the final __cxa_atexit type. */
9532 fn_type = build_function_type_list (integer_type_node,
9533 argtype0, argtype1, argtype2,
9534 NULL_TREE);
9535 /* ... which needs noexcept. */
9536 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9537 if (use_aeabi_atexit)
9539 name = "__aeabi_atexit";
9540 push_to_top_level ();
9541 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9542 ctx = current_namespace;
9543 while (n--)
9544 pop_namespace ();
9545 pop_from_top_level ();
9547 else
9549 name = "__cxa_atexit";
9550 ctx = abi_node;
9553 else
9555 /* The declaration for `atexit' is:
9557 int atexit (void (*)());
9559 We build up the argument types and then the function type
9560 itself. */
9561 fn_ptr_type = get_atexit_fn_ptr_type ();
9562 /* Build the final atexit type. */
9563 fn_type = build_function_type_list (integer_type_node,
9564 fn_ptr_type, NULL_TREE);
9565 /* ... which needs noexcept. */
9566 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9567 name = "atexit";
9570 /* Now, build the function declaration. */
9571 push_lang_context (lang_name_c);
9572 auto cookie = push_abi_namespace (ctx);
9573 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9574 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9575 /* Install as hidden builtin so we're (a) more relaxed about
9576 exception spec matching and (b) will not give a confusing location
9577 in diagnostic and (c) won't magically appear in user-visible name
9578 lookups. */
9579 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9580 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9581 pop_abi_namespace (cookie, ctx);
9582 mark_used (atexit_fndecl);
9583 pop_lang_context ();
9584 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9586 return atexit_node;
9589 /* Like get_atexit_node, but for thread-local cleanups. */
9591 static tree
9592 get_thread_atexit_node (void)
9594 /* The declaration for `__cxa_thread_atexit' is:
9596 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9597 tree fn_type = build_function_type_list (integer_type_node,
9598 get_atexit_fn_ptr_type (),
9599 ptr_type_node, ptr_type_node,
9600 NULL_TREE);
9602 /* Now, build the function declaration. */
9603 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9604 ECF_LEAF | ECF_NOTHROW);
9605 return decay_conversion (atexit_fndecl, tf_warning_or_error);
9608 /* Returns the __dso_handle VAR_DECL. */
9610 static tree
9611 get_dso_handle_node (void)
9613 if (dso_handle_node)
9614 return dso_handle_node;
9616 /* Declare the variable. */
9617 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9618 ptr_type_node);
9620 #ifdef HAVE_GAS_HIDDEN
9621 if (dso_handle_node != error_mark_node)
9623 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9624 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9626 #endif
9628 return dso_handle_node;
9631 /* Begin a new function with internal linkage whose job will be simply
9632 to destroy some particular variable. */
9634 static GTY(()) int start_cleanup_cnt;
9636 static tree
9637 start_cleanup_fn (void)
9639 char name[32];
9641 push_to_top_level ();
9643 /* No need to mangle this. */
9644 push_lang_context (lang_name_c);
9646 /* Build the name of the function. */
9647 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9648 /* Build the function declaration. */
9649 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9650 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9651 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9652 /* It's a function with internal linkage, generated by the
9653 compiler. */
9654 TREE_PUBLIC (fndecl) = 0;
9655 DECL_ARTIFICIAL (fndecl) = 1;
9656 /* Make the function `inline' so that it is only emitted if it is
9657 actually needed. It is unlikely that it will be inlined, since
9658 it is only called via a function pointer, but we avoid unnecessary
9659 emissions this way. */
9660 DECL_DECLARED_INLINE_P (fndecl) = 1;
9661 DECL_INTERFACE_KNOWN (fndecl) = 1;
9662 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9664 /* Build the parameter. */
9665 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9666 TREE_USED (parmdecl) = 1;
9667 DECL_READ_P (parmdecl) = 1;
9668 DECL_ARGUMENTS (fndecl) = parmdecl;
9671 fndecl = pushdecl (fndecl, /*hidden=*/true);
9672 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9674 pop_lang_context ();
9676 return current_function_decl;
9679 /* Finish the cleanup function begun by start_cleanup_fn. */
9681 static void
9682 end_cleanup_fn (void)
9684 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9686 pop_from_top_level ();
9689 /* Generate code to handle the destruction of DECL, an object with
9690 static storage duration. */
9692 tree
9693 register_dtor_fn (tree decl)
9695 tree cleanup;
9696 tree addr;
9697 tree compound_stmt;
9698 tree fcall;
9699 tree type;
9700 bool ob_parm, dso_parm, use_dtor;
9701 tree arg0, arg1, arg2;
9702 tree atex_node;
9704 type = TREE_TYPE (decl);
9705 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9706 return void_node;
9708 if (decl_maybe_constant_destruction (decl, type)
9709 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9711 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9712 return void_node;
9715 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9716 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9717 destructor to "__cxa_atexit"; we don't have to build a temporary
9718 function to do the cleanup. */
9719 dso_parm = (flag_use_cxa_atexit
9720 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9721 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9722 use_dtor = ob_parm && CLASS_TYPE_P (type);
9723 if (use_dtor)
9725 cleanup = get_class_binding (type, complete_dtor_identifier);
9727 /* Make sure it is accessible. */
9728 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9729 tf_warning_or_error);
9731 else
9733 /* Call build_cleanup before we enter the anonymous function so
9734 that any access checks will be done relative to the current
9735 scope, rather than the scope of the anonymous function. */
9736 build_cleanup (decl);
9738 /* Now start the function. */
9739 cleanup = start_cleanup_fn ();
9741 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9742 to the original function, rather than the anonymous one. That
9743 will make the back end think that nested functions are in use,
9744 which causes confusion. */
9745 push_deferring_access_checks (dk_no_check);
9746 fcall = build_cleanup (decl);
9747 pop_deferring_access_checks ();
9749 /* Create the body of the anonymous function. */
9750 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9751 finish_expr_stmt (fcall);
9752 finish_compound_stmt (compound_stmt);
9753 end_cleanup_fn ();
9756 /* Call atexit with the cleanup function. */
9757 mark_used (cleanup);
9758 cleanup = build_address (cleanup);
9760 if (CP_DECL_THREAD_LOCAL_P (decl))
9761 atex_node = get_thread_atexit_node ();
9762 else
9763 atex_node = get_atexit_node ();
9765 if (use_dtor)
9767 /* We must convert CLEANUP to the type that "__cxa_atexit"
9768 expects. */
9769 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9770 /* "__cxa_atexit" will pass the address of DECL to the
9771 cleanup function. */
9772 mark_used (decl);
9773 addr = build_address (decl);
9774 /* The declared type of the parameter to "__cxa_atexit" is
9775 "void *". For plain "T*", we could just let the
9776 machinery in cp_build_function_call convert it -- but if the
9777 type is "cv-qualified T *", then we need to convert it
9778 before passing it in, to avoid spurious errors. */
9779 addr = build_nop (ptr_type_node, addr);
9781 else
9782 /* Since the cleanup functions we build ignore the address
9783 they're given, there's no reason to pass the actual address
9784 in, and, in general, it's cheaper to pass NULL than any
9785 other value. */
9786 addr = null_pointer_node;
9788 if (dso_parm)
9789 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9790 tf_warning_or_error);
9791 else if (ob_parm)
9792 /* Just pass NULL to the dso handle parm if we don't actually
9793 have a DSO handle on this target. */
9794 arg2 = null_pointer_node;
9795 else
9796 arg2 = NULL_TREE;
9798 if (ob_parm)
9800 if (!CP_DECL_THREAD_LOCAL_P (decl)
9801 && targetm.cxx.use_aeabi_atexit ())
9803 arg1 = cleanup;
9804 arg0 = addr;
9806 else
9808 arg1 = addr;
9809 arg0 = cleanup;
9812 else
9814 arg0 = cleanup;
9815 arg1 = NULL_TREE;
9817 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
9818 arg0, arg1, arg2, NULL_TREE);
9821 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
9822 is its initializer. Generate code to handle the construction
9823 and destruction of DECL. */
9825 static void
9826 expand_static_init (tree decl, tree init)
9828 gcc_assert (VAR_P (decl));
9829 gcc_assert (TREE_STATIC (decl));
9831 /* Some variables require no dynamic initialization. */
9832 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
9834 /* Make sure the destructor is callable. */
9835 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9836 if (!init)
9837 return;
9840 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
9841 && !DECL_FUNCTION_SCOPE_P (decl))
9843 location_t dloc = DECL_SOURCE_LOCATION (decl);
9844 if (init)
9845 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9846 "needs dynamic initialization", decl);
9847 else
9848 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9849 "has a non-trivial destructor", decl);
9850 static bool informed;
9851 if (!informed)
9853 inform (dloc, "C++11 %<thread_local%> allows dynamic "
9854 "initialization and destruction");
9855 informed = true;
9857 return;
9860 if (DECL_FUNCTION_SCOPE_P (decl))
9862 /* Emit code to perform this initialization but once. */
9863 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
9864 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
9865 tree guard, guard_addr;
9866 tree flag, begin;
9867 /* We don't need thread-safety code for thread-local vars. */
9868 bool thread_guard = (flag_threadsafe_statics
9869 && !CP_DECL_THREAD_LOCAL_P (decl));
9871 /* Emit code to perform this initialization but once. This code
9872 looks like:
9874 static <type> guard;
9875 if (!__atomic_load (guard.first_byte)) {
9876 if (__cxa_guard_acquire (&guard)) {
9877 bool flag = false;
9878 try {
9879 // Do initialization.
9880 flag = true; __cxa_guard_release (&guard);
9881 // Register variable for destruction at end of program.
9882 } catch {
9883 if (!flag) __cxa_guard_abort (&guard);
9888 Note that the `flag' variable is only set to 1 *after* the
9889 initialization is complete. This ensures that an exception,
9890 thrown during the construction, will cause the variable to
9891 reinitialized when we pass through this code again, as per:
9893 [stmt.dcl]
9895 If the initialization exits by throwing an exception, the
9896 initialization is not complete, so it will be tried again
9897 the next time control enters the declaration.
9899 This process should be thread-safe, too; multiple threads
9900 should not be able to initialize the variable more than
9901 once. */
9903 /* Create the guard variable. */
9904 guard = get_guard (decl);
9906 /* Begin the conditional initialization. */
9907 if_stmt = begin_if_stmt ();
9909 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
9910 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9912 if (thread_guard)
9914 tree vfntype = NULL_TREE;
9915 tree acquire_name, release_name, abort_name;
9916 tree acquire_fn, release_fn, abort_fn;
9917 guard_addr = build_address (guard);
9919 acquire_name = get_identifier ("__cxa_guard_acquire");
9920 release_name = get_identifier ("__cxa_guard_release");
9921 abort_name = get_identifier ("__cxa_guard_abort");
9922 acquire_fn = get_global_binding (acquire_name);
9923 release_fn = get_global_binding (release_name);
9924 abort_fn = get_global_binding (abort_name);
9925 if (!acquire_fn)
9926 acquire_fn = push_library_fn
9927 (acquire_name, build_function_type_list (integer_type_node,
9928 TREE_TYPE (guard_addr),
9929 NULL_TREE),
9930 NULL_TREE, ECF_NOTHROW);
9931 if (!release_fn || !abort_fn)
9932 vfntype = build_function_type_list (void_type_node,
9933 TREE_TYPE (guard_addr),
9934 NULL_TREE);
9935 if (!release_fn)
9936 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9937 ECF_NOTHROW);
9938 if (!abort_fn)
9939 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9940 ECF_NOTHROW | ECF_LEAF);
9942 inner_if_stmt = begin_if_stmt ();
9943 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9944 inner_if_stmt);
9946 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9947 begin = get_target_expr (boolean_false_node);
9948 flag = TARGET_EXPR_SLOT (begin);
9950 TARGET_EXPR_CLEANUP (begin)
9951 = build3 (COND_EXPR, void_type_node, flag,
9952 void_node,
9953 build_call_n (abort_fn, 1, guard_addr));
9954 CLEANUP_EH_ONLY (begin) = 1;
9956 /* Do the initialization itself. */
9957 init = add_stmt_to_compound (begin, init);
9958 init = add_stmt_to_compound (init,
9959 build2 (MODIFY_EXPR, void_type_node,
9960 flag, boolean_true_node));
9962 /* Use atexit to register a function for destroying this static
9963 variable. Do this before calling __cxa_guard_release. */
9964 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9966 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9967 guard_addr));
9969 else
9971 init = add_stmt_to_compound (init, set_guard (guard));
9973 /* Use atexit to register a function for destroying this static
9974 variable. */
9975 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9978 finish_expr_stmt (init);
9980 if (thread_guard)
9982 finish_compound_stmt (inner_then_clause);
9983 finish_then_clause (inner_if_stmt);
9984 finish_if_stmt (inner_if_stmt);
9987 finish_compound_stmt (then_clause);
9988 finish_then_clause (if_stmt);
9989 finish_if_stmt (if_stmt);
9991 else if (CP_DECL_THREAD_LOCAL_P (decl))
9992 tls_aggregates = tree_cons (init, decl, tls_aggregates);
9993 else
9994 static_aggregates = tree_cons (init, decl, static_aggregates);
9998 /* Make TYPE a complete type based on INITIAL_VALUE.
9999 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
10000 2 if there was no information (in which case assume 0 if DO_DEFAULT),
10001 3 if the initializer list is empty (in pedantic mode). */
10004 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
10006 int failure;
10007 tree type, elt_type;
10009 /* Don't get confused by a CONSTRUCTOR for some other type. */
10010 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
10011 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
10012 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
10013 return 1;
10015 if (initial_value)
10017 /* An array of character type can be initialized from a
10018 brace-enclosed string constant so call reshape_init to
10019 remove the optional braces from a braced string literal. */
10020 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
10021 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
10022 initial_value = reshape_init (*ptype, initial_value,
10023 tf_warning_or_error);
10025 /* If any of the elements are parameter packs, we can't actually
10026 complete this type now because the array size is dependent. */
10027 if (TREE_CODE (initial_value) == CONSTRUCTOR)
10028 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
10029 if (PACK_EXPANSION_P (e.value))
10030 return 0;
10033 failure = complete_array_type (ptype, initial_value, do_default);
10035 /* We can create the array before the element type is complete, which
10036 means that we didn't have these two bits set in the original type
10037 either. In completing the type, we are expected to propagate these
10038 bits. See also complete_type which does the same thing for arrays
10039 of fixed size. */
10040 type = *ptype;
10041 if (type != error_mark_node && TYPE_DOMAIN (type))
10043 elt_type = TREE_TYPE (type);
10044 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
10045 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
10046 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
10049 return failure;
10052 /* As above, but either give an error or reject zero-size arrays, depending
10053 on COMPLAIN. */
10056 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
10057 bool do_default, tsubst_flags_t complain)
10059 int failure;
10060 bool sfinae = !(complain & tf_error);
10061 /* In SFINAE context we can't be lenient about zero-size arrays. */
10062 if (sfinae)
10063 ++pedantic;
10064 failure = cp_complete_array_type (ptype, initial_value, do_default);
10065 if (sfinae)
10066 --pedantic;
10067 if (failure)
10069 if (sfinae)
10070 /* Not an error. */;
10071 else if (failure == 1)
10072 error ("initializer fails to determine size of %qT", *ptype);
10073 else if (failure == 2)
10075 if (do_default)
10076 error ("array size missing in %qT", *ptype);
10078 else if (failure == 3)
10079 error ("zero-size array %qT", *ptype);
10080 *ptype = error_mark_node;
10082 return failure;
10085 /* Return zero if something is declared to be a member of type
10086 CTYPE when in the context of CUR_TYPE. STRING is the error
10087 message to print in that case. Otherwise, quietly return 1. */
10089 static int
10090 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
10092 if (ctype && ctype != cur_type)
10094 if (flags == DTOR_FLAG)
10095 error ("destructor for alien class %qT cannot be a member", ctype);
10096 else
10097 error ("constructor for alien class %qT cannot be a member", ctype);
10098 return 0;
10100 return 1;
10103 /* Subroutine of `grokdeclarator'. */
10105 /* Generate errors possibly applicable for a given set of specifiers.
10106 This is for ARM $7.1.2. */
10108 static void
10109 bad_specifiers (tree object,
10110 enum bad_spec_place type,
10111 int virtualp,
10112 int quals,
10113 int inlinep,
10114 int friendp,
10115 int raises,
10116 const location_t* locations)
10118 switch (type)
10120 case BSP_VAR:
10121 if (virtualp)
10122 error_at (locations[ds_virtual],
10123 "%qD declared as a %<virtual%> variable", object);
10124 if (quals)
10125 error ("%<const%> and %<volatile%> function specifiers on "
10126 "%qD invalid in variable declaration", object);
10127 break;
10128 case BSP_PARM:
10129 if (virtualp)
10130 error_at (locations[ds_virtual],
10131 "%qD declared as a %<virtual%> parameter", object);
10132 if (inlinep)
10133 error_at (locations[ds_inline],
10134 "%qD declared as an %<inline%> parameter", object);
10135 if (quals)
10136 error ("%<const%> and %<volatile%> function specifiers on "
10137 "%qD invalid in parameter declaration", object);
10138 break;
10139 case BSP_TYPE:
10140 if (virtualp)
10141 error_at (locations[ds_virtual],
10142 "%qD declared as a %<virtual%> type", object);
10143 if (inlinep)
10144 error_at (locations[ds_inline],
10145 "%qD declared as an %<inline%> type", object);
10146 if (quals)
10147 error ("%<const%> and %<volatile%> function specifiers on "
10148 "%qD invalid in type declaration", object);
10149 break;
10150 case BSP_FIELD:
10151 if (virtualp)
10152 error_at (locations[ds_virtual],
10153 "%qD declared as a %<virtual%> field", object);
10154 if (inlinep)
10155 error_at (locations[ds_inline],
10156 "%qD declared as an %<inline%> field", object);
10157 if (quals)
10158 error ("%<const%> and %<volatile%> function specifiers on "
10159 "%qD invalid in field declaration", object);
10160 break;
10161 default:
10162 gcc_unreachable();
10164 if (friendp)
10165 error ("%q+D declared as a friend", object);
10166 if (raises
10167 && !flag_noexcept_type
10168 && (TREE_CODE (object) == TYPE_DECL
10169 || (!TYPE_PTRFN_P (TREE_TYPE (object))
10170 && !TYPE_REFFN_P (TREE_TYPE (object))
10171 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
10172 error ("%q+D declared with an exception specification", object);
10175 /* DECL is a member function or static data member and is presently
10176 being defined. Check that the definition is taking place in a
10177 valid namespace. */
10179 static void
10180 check_class_member_definition_namespace (tree decl)
10182 /* These checks only apply to member functions and static data
10183 members. */
10184 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
10185 /* We check for problems with specializations in pt.cc in
10186 check_specialization_namespace, where we can issue better
10187 diagnostics. */
10188 if (processing_specialization)
10189 return;
10190 /* We check this in check_explicit_instantiation_namespace. */
10191 if (processing_explicit_instantiation)
10192 return;
10193 /* [class.mfct]
10195 A member function definition that appears outside of the
10196 class definition shall appear in a namespace scope enclosing
10197 the class definition.
10199 [class.static.data]
10201 The definition for a static data member shall appear in a
10202 namespace scope enclosing the member's class definition. */
10203 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
10204 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
10205 decl, DECL_CONTEXT (decl));
10208 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
10209 METHOD_TYPE for a non-static member function; QUALS are the
10210 cv-qualifiers that apply to the function. */
10212 tree
10213 build_this_parm (tree fn, tree type, cp_cv_quals quals)
10215 tree this_type;
10216 tree qual_type;
10217 tree parm;
10218 cp_cv_quals this_quals;
10220 if (CLASS_TYPE_P (type))
10222 this_type
10223 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
10224 this_type = build_pointer_type (this_type);
10226 else
10227 this_type = type_of_this_parm (type);
10228 /* The `this' parameter is implicitly `const'; it cannot be
10229 assigned to. */
10230 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
10231 qual_type = cp_build_qualified_type (this_type, this_quals);
10232 parm = build_artificial_parm (fn, this_identifier, qual_type);
10233 cp_apply_type_quals_to_decl (this_quals, parm);
10234 return parm;
10237 /* DECL is a static member function. Complain if it was declared
10238 with function-cv-quals. */
10240 static void
10241 check_static_quals (tree decl, cp_cv_quals quals)
10243 if (quals != TYPE_UNQUALIFIED)
10244 error ("static member function %q#D declared with type qualifiers",
10245 decl);
10248 // Check that FN takes no arguments and returns bool.
10249 static void
10250 check_concept_fn (tree fn)
10252 // A constraint is nullary.
10253 if (DECL_ARGUMENTS (fn))
10254 error_at (DECL_SOURCE_LOCATION (fn),
10255 "concept %q#D declared with function parameters", fn);
10257 // The declared return type of the concept shall be bool, and
10258 // it shall not be deduced from it definition.
10259 tree type = TREE_TYPE (TREE_TYPE (fn));
10260 if (is_auto (type))
10261 error_at (DECL_SOURCE_LOCATION (fn),
10262 "concept %q#D declared with a deduced return type", fn);
10263 else if (type != boolean_type_node)
10264 error_at (DECL_SOURCE_LOCATION (fn),
10265 "concept %q#D with non-%<bool%> return type %qT", fn, type);
10268 /* Helper function. Replace the temporary this parameter injected
10269 during cp_finish_omp_declare_simd with the real this parameter. */
10271 static tree
10272 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10274 tree this_parm = (tree) data;
10275 if (TREE_CODE (*tp) == PARM_DECL
10276 && DECL_NAME (*tp) == this_identifier
10277 && *tp != this_parm)
10278 *tp = this_parm;
10279 else if (TYPE_P (*tp))
10280 *walk_subtrees = 0;
10281 return NULL_TREE;
10284 /* CTYPE is class type, or null if non-class.
10285 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10286 or METHOD_TYPE.
10287 DECLARATOR is the function's name.
10288 PARMS is a chain of PARM_DECLs for the function.
10289 VIRTUALP is truthvalue of whether the function is virtual or not.
10290 FLAGS are to be passed through to `grokclassfn'.
10291 QUALS are qualifiers indicating whether the function is `const'
10292 or `volatile'.
10293 RAISES is a list of exceptions that this function can raise.
10294 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10295 not look, and -1 if we should not call `grokclassfn' at all.
10297 SFK is the kind of special function (if any) for the new function.
10299 Returns `NULL_TREE' if something goes wrong, after issuing
10300 applicable error messages. */
10302 static tree
10303 grokfndecl (tree ctype,
10304 tree type,
10305 tree declarator,
10306 tree parms,
10307 tree orig_declarator,
10308 const cp_decl_specifier_seq *declspecs,
10309 tree decl_reqs,
10310 int virtualp,
10311 enum overload_flags flags,
10312 cp_cv_quals quals,
10313 cp_ref_qualifier rqual,
10314 tree raises,
10315 int check,
10316 int friendp,
10317 int publicp,
10318 int inlinep,
10319 bool deletedp,
10320 special_function_kind sfk,
10321 bool funcdef_flag,
10322 bool late_return_type_p,
10323 int template_count,
10324 tree in_namespace,
10325 tree* attrlist,
10326 location_t location)
10328 tree decl;
10329 int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
10330 tree t;
10332 if (location == UNKNOWN_LOCATION)
10333 location = input_location;
10335 /* Was the concept specifier present? */
10336 bool concept_p = inlinep & 4;
10338 /* Concept declarations must have a corresponding definition. */
10339 if (concept_p && !funcdef_flag)
10341 error_at (location, "concept %qD has no definition", declarator);
10342 return NULL_TREE;
10345 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10347 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10349 /* Set the constraints on the declaration. */
10350 if (flag_concepts)
10352 tree tmpl_reqs = NULL_TREE;
10353 tree ctx = friendp ? current_class_type : ctype;
10354 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10355 bool memtmpl = (!block_local
10356 && (current_template_depth
10357 > template_class_depth (ctx)));
10358 if (memtmpl)
10360 if (!current_template_parms)
10361 /* If there are no template parameters, something must have
10362 gone wrong. */
10363 gcc_assert (seen_error ());
10364 else
10365 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10367 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10368 if (concept_p && ci)
10370 error_at (location, "a function concept cannot be constrained");
10371 ci = NULL_TREE;
10373 /* C++20 CA378: Remove non-templated constrained functions. */
10374 /* [temp.friend]/9 A non-template friend declaration with a
10375 requires-clause shall be a definition. A friend function template with
10376 a constraint that depends on a template parameter from an enclosing
10377 template shall be a definition. */
10378 if (ci
10379 && (block_local
10380 || (!flag_concepts_ts
10381 && (!processing_template_decl
10382 || (friendp && !memtmpl && !funcdef_flag)))))
10384 if (!friendp || !processing_template_decl)
10385 error_at (location, "constraints on a non-templated function");
10386 else
10387 error_at (location, "constrained non-template friend declaration"
10388 " must be a definition");
10389 ci = NULL_TREE;
10391 set_constraints (decl, ci);
10392 if (ci && friendp && memtmpl && !funcdef_flag
10393 && uses_outer_template_parms_in_constraints (decl, ctx))
10394 error_at (location, "friend function template with constraints that "
10395 "depend on outer template parameters must be a definition");
10398 if (TREE_CODE (type) == METHOD_TYPE)
10400 tree parm = build_this_parm (decl, type, quals);
10401 DECL_CHAIN (parm) = parms;
10402 parms = parm;
10404 /* Allocate space to hold the vptr bit if needed. */
10405 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10408 DECL_ARGUMENTS (decl) = parms;
10409 for (t = parms; t; t = DECL_CHAIN (t))
10410 DECL_CONTEXT (t) = decl;
10412 /* Propagate volatile out from type to decl. */
10413 if (TYPE_VOLATILE (type))
10414 TREE_THIS_VOLATILE (decl) = 1;
10416 /* Setup decl according to sfk. */
10417 switch (sfk)
10419 case sfk_constructor:
10420 case sfk_copy_constructor:
10421 case sfk_move_constructor:
10422 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10423 DECL_NAME (decl) = ctor_identifier;
10424 break;
10425 case sfk_destructor:
10426 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10427 DECL_NAME (decl) = dtor_identifier;
10428 break;
10429 case sfk_deduction_guide:
10430 /* Give deduction guides a definition even though they don't really
10431 have one: the restriction that you can't repeat a deduction guide
10432 makes them more like a definition anyway. */
10433 DECL_INITIAL (decl) = void_node;
10434 break;
10435 default:
10436 break;
10439 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10441 if (funcdef_flag)
10442 error_at (location,
10443 "defining explicit specialization %qD in friend declaration",
10444 orig_declarator);
10445 else
10447 tree fns = TREE_OPERAND (orig_declarator, 0);
10448 tree args = TREE_OPERAND (orig_declarator, 1);
10450 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10452 /* Something like `template <class T> friend void f<T>()'. */
10453 error_at (location,
10454 "invalid use of template-id %qD in declaration "
10455 "of primary template",
10456 orig_declarator);
10457 return NULL_TREE;
10460 /* A friend declaration of the form friend void f<>(). Record
10461 the information in the TEMPLATE_ID_EXPR. */
10462 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10464 gcc_assert (identifier_p (fns) || OVL_P (fns));
10465 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10467 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10468 if (TREE_PURPOSE (t)
10469 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10471 error_at (defparse_location (TREE_PURPOSE (t)),
10472 "default arguments are not allowed in declaration "
10473 "of friend template specialization %qD",
10474 decl);
10475 return NULL_TREE;
10478 if (inlinep & 1)
10480 error_at (declspecs->locations[ds_inline],
10481 "%<inline%> is not allowed in declaration of friend "
10482 "template specialization %qD",
10483 decl);
10484 return NULL_TREE;
10489 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10490 expression, that declaration shall be a definition..." */
10491 if (friendp && !funcdef_flag)
10493 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10494 t && t != void_list_node; t = TREE_CHAIN (t))
10495 if (TREE_PURPOSE (t))
10497 permerror (DECL_SOURCE_LOCATION (decl),
10498 "friend declaration of %qD specifies default "
10499 "arguments and isn%'t a definition", decl);
10500 break;
10504 /* If this decl has namespace scope, set that up. */
10505 if (in_namespace)
10506 set_decl_namespace (decl, in_namespace, friendp);
10507 else if (ctype)
10508 DECL_CONTEXT (decl) = ctype;
10509 else
10510 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10512 /* `main' and builtins have implicit 'C' linkage. */
10513 if (ctype == NULL_TREE
10514 && DECL_FILE_SCOPE_P (decl)
10515 && current_lang_name == lang_name_cplusplus
10516 && (MAIN_NAME_P (declarator)
10517 || (IDENTIFIER_LENGTH (declarator) > 10
10518 && IDENTIFIER_POINTER (declarator)[0] == '_'
10519 && IDENTIFIER_POINTER (declarator)[1] == '_'
10520 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10521 "builtin_"))
10522 || (targetcm.cxx_implicit_extern_c
10523 && (targetcm.cxx_implicit_extern_c
10524 (IDENTIFIER_POINTER (declarator))))))
10525 SET_DECL_LANGUAGE (decl, lang_c);
10527 /* Should probably propagate const out from type to decl I bet (mrs). */
10528 if (staticp)
10530 DECL_STATIC_FUNCTION_P (decl) = 1;
10531 DECL_CONTEXT (decl) = ctype;
10534 if (deletedp)
10535 DECL_DELETED_FN (decl) = 1;
10537 if (ctype && funcdef_flag)
10538 check_class_member_definition_namespace (decl);
10540 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10542 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10543 error_at (location, "cannot declare %<::main%> to be a template");
10544 if (inlinep & 1)
10545 error_at (declspecs->locations[ds_inline],
10546 "cannot declare %<::main%> to be inline");
10547 if (inlinep & 2)
10548 error_at (declspecs->locations[ds_constexpr],
10549 "cannot declare %<::main%> to be %qs", "constexpr");
10550 if (inlinep & 8)
10551 error_at (declspecs->locations[ds_consteval],
10552 "cannot declare %<::main%> to be %qs", "consteval");
10553 if (!publicp)
10554 error_at (location, "cannot declare %<::main%> to be static");
10555 inlinep = 0;
10556 publicp = 1;
10559 /* Members of anonymous types and local classes have no linkage; make
10560 them internal. If a typedef is made later, this will be changed. */
10561 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10562 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10563 publicp = 0;
10565 if (publicp && cxx_dialect == cxx98)
10567 /* [basic.link]: A name with no linkage (notably, the name of a class
10568 or enumeration declared in a local scope) shall not be used to
10569 declare an entity with linkage.
10571 DR 757 relaxes this restriction for C++0x. */
10572 no_linkage_error (decl);
10575 TREE_PUBLIC (decl) = publicp;
10576 if (! publicp)
10578 DECL_INTERFACE_KNOWN (decl) = 1;
10579 DECL_NOT_REALLY_EXTERN (decl) = 1;
10582 /* If the declaration was declared inline, mark it as such. */
10583 if (inlinep)
10585 DECL_DECLARED_INLINE_P (decl) = 1;
10586 if (publicp)
10587 DECL_COMDAT (decl) = 1;
10589 if (inlinep & 2)
10590 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10591 else if (inlinep & 8)
10593 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10594 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10597 // If the concept declaration specifier was found, check
10598 // that the declaration satisfies the necessary requirements.
10599 if (concept_p)
10601 DECL_DECLARED_CONCEPT_P (decl) = true;
10602 check_concept_fn (decl);
10605 DECL_EXTERNAL (decl) = 1;
10606 if (TREE_CODE (type) == FUNCTION_TYPE)
10608 if (quals || rqual)
10609 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10610 TYPE_UNQUALIFIED,
10611 REF_QUAL_NONE);
10613 if (quals)
10615 error (ctype
10616 ? G_("static member function %qD cannot have cv-qualifier")
10617 : G_("non-member function %qD cannot have cv-qualifier"),
10618 decl);
10619 quals = TYPE_UNQUALIFIED;
10622 if (rqual)
10624 error (ctype
10625 ? G_("static member function %qD cannot have ref-qualifier")
10626 : G_("non-member function %qD cannot have ref-qualifier"),
10627 decl);
10628 rqual = REF_QUAL_NONE;
10632 if (deduction_guide_p (decl))
10634 tree type = TREE_TYPE (DECL_NAME (decl));
10635 if (in_namespace == NULL_TREE
10636 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10638 error_at (location, "deduction guide %qD must be declared in the "
10639 "same scope as %qT", decl, type);
10640 inform (location_of (type), " declared here");
10641 return NULL_TREE;
10643 if (DECL_CLASS_SCOPE_P (decl)
10644 && current_access_specifier != declared_access (TYPE_NAME (type)))
10646 error_at (location, "deduction guide %qD must have the same access "
10647 "as %qT", decl, type);
10648 inform (location_of (type), " declared here");
10650 if (funcdef_flag)
10651 error_at (location,
10652 "deduction guide %qD must not have a function body", decl);
10654 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10655 && !grok_op_properties (decl, /*complain=*/true))
10656 return NULL_TREE;
10657 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10659 bool long_long_unsigned_p;
10660 bool long_double_p;
10661 const char *suffix = NULL;
10662 /* [over.literal]/6: Literal operators shall not have C linkage. */
10663 if (DECL_LANGUAGE (decl) == lang_c)
10665 error_at (location, "literal operator with C linkage");
10666 maybe_show_extern_c_location ();
10667 return NULL_TREE;
10670 if (DECL_NAMESPACE_SCOPE_P (decl))
10672 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10673 &long_double_p))
10675 error_at (location, "%qD has invalid argument list", decl);
10676 return NULL_TREE;
10679 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10680 if (long_long_unsigned_p)
10682 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10683 warning_at (location, 0, "integer suffix %qs"
10684 " shadowed by implementation", suffix);
10686 else if (long_double_p)
10688 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10689 warning_at (location, 0, "floating-point suffix %qs"
10690 " shadowed by implementation", suffix);
10692 /* 17.6.3.3.5 */
10693 if (suffix[0] != '_'
10694 && !current_function_decl && !(friendp && !funcdef_flag))
10695 warning_at (location, OPT_Wliteral_suffix,
10696 "literal operator suffixes not preceded by %<_%>"
10697 " are reserved for future standardization");
10699 else
10701 error_at (location, "%qD must be a non-member function", decl);
10702 return NULL_TREE;
10706 if (funcdef_flag)
10707 /* Make the init_value nonzero so pushdecl knows this is not
10708 tentative. error_mark_node is replaced later with the BLOCK. */
10709 DECL_INITIAL (decl) = error_mark_node;
10711 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10712 TREE_NOTHROW (decl) = 1;
10714 if (flag_openmp || flag_openmp_simd)
10716 /* Adjust "omp declare simd" attributes. */
10717 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10718 if (ods)
10720 tree attr;
10721 for (attr = ods; attr;
10722 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10724 if (TREE_CODE (type) == METHOD_TYPE)
10725 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10726 DECL_ARGUMENTS (decl), NULL);
10727 if (TREE_VALUE (attr) != NULL_TREE)
10729 tree cl = TREE_VALUE (TREE_VALUE (attr));
10730 cl = c_omp_declare_simd_clauses_to_numbers
10731 (DECL_ARGUMENTS (decl), cl);
10732 if (cl)
10733 TREE_VALUE (TREE_VALUE (attr)) = cl;
10734 else
10735 TREE_VALUE (attr) = NULL_TREE;
10741 /* Caller will do the rest of this. */
10742 if (check < 0)
10743 return decl;
10745 if (ctype != NULL_TREE)
10746 grokclassfn (ctype, decl, flags);
10748 /* 12.4/3 */
10749 if (cxx_dialect >= cxx11
10750 && DECL_DESTRUCTOR_P (decl)
10751 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10752 && !processing_template_decl)
10753 deduce_noexcept_on_destructor (decl);
10755 set_originating_module (decl);
10757 decl = check_explicit_specialization (orig_declarator, decl,
10758 template_count,
10759 2 * funcdef_flag +
10760 4 * (friendp != 0) +
10761 8 * concept_p,
10762 *attrlist);
10763 if (decl == error_mark_node)
10764 return NULL_TREE;
10766 if (DECL_STATIC_FUNCTION_P (decl))
10767 check_static_quals (decl, quals);
10769 if (attrlist)
10771 cplus_decl_attributes (&decl, *attrlist, 0);
10772 *attrlist = NULL_TREE;
10775 if (DECL_HAS_CONTRACTS_P (decl))
10776 rebuild_postconditions (decl);
10778 /* Check main's type after attributes have been applied. */
10779 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10781 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10782 integer_type_node))
10784 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10785 tree newtype;
10786 error_at (declspecs->locations[ds_type_spec],
10787 "%<::main%> must return %<int%>");
10788 newtype = build_function_type (integer_type_node, oldtypeargs);
10789 TREE_TYPE (decl) = newtype;
10791 if (warn_main)
10792 check_main_parameter_types (decl);
10795 if (ctype != NULL_TREE && check)
10797 tree old_decl = check_classfn (ctype, decl,
10798 (current_template_depth
10799 > template_class_depth (ctype))
10800 ? current_template_parms
10801 : NULL_TREE);
10803 if (old_decl == error_mark_node)
10804 return NULL_TREE;
10806 if (old_decl)
10808 tree ok;
10809 tree pushed_scope;
10811 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
10812 /* Because grokfndecl is always supposed to return a
10813 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
10814 here. We depend on our callers to figure out that its
10815 really a template that's being returned. */
10816 old_decl = DECL_TEMPLATE_RESULT (old_decl);
10818 if (DECL_STATIC_FUNCTION_P (old_decl)
10819 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
10821 /* Remove the `this' parm added by grokclassfn. */
10822 revert_static_member_fn (decl);
10823 check_static_quals (decl, quals);
10825 if (DECL_ARTIFICIAL (old_decl))
10827 error ("definition of implicitly-declared %qD", old_decl);
10828 return NULL_TREE;
10830 else if (DECL_DEFAULTED_FN (old_decl))
10832 error ("definition of explicitly-defaulted %q+D", decl);
10833 inform (DECL_SOURCE_LOCATION (old_decl),
10834 "%q#D explicitly defaulted here", old_decl);
10835 return NULL_TREE;
10838 /* Since we've smashed OLD_DECL to its
10839 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
10840 if (TREE_CODE (decl) == TEMPLATE_DECL)
10841 decl = DECL_TEMPLATE_RESULT (decl);
10843 /* Attempt to merge the declarations. This can fail, in
10844 the case of some invalid specialization declarations. */
10845 pushed_scope = push_scope (ctype);
10846 ok = duplicate_decls (decl, old_decl);
10847 if (pushed_scope)
10848 pop_scope (pushed_scope);
10849 if (!ok)
10851 error ("no %q#D member function declared in class %qT",
10852 decl, ctype);
10853 return NULL_TREE;
10855 if (ok == error_mark_node)
10856 return NULL_TREE;
10857 return old_decl;
10861 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
10862 return NULL_TREE;
10864 if (ctype == NULL_TREE || check)
10865 return decl;
10867 if (virtualp)
10868 DECL_VIRTUAL_P (decl) = 1;
10870 return decl;
10873 /* decl is a FUNCTION_DECL.
10874 specifiers are the parsed virt-specifiers.
10876 Set flags to reflect the virt-specifiers.
10878 Returns decl. */
10880 static tree
10881 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
10883 if (decl == NULL_TREE)
10884 return decl;
10885 if (specifiers & VIRT_SPEC_OVERRIDE)
10886 DECL_OVERRIDE_P (decl) = 1;
10887 if (specifiers & VIRT_SPEC_FINAL)
10888 DECL_FINAL_P (decl) = 1;
10889 return decl;
10892 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
10893 the linkage that DECL will receive in the object file. */
10895 static void
10896 set_linkage_for_static_data_member (tree decl)
10898 /* A static data member always has static storage duration and
10899 external linkage. Note that static data members are forbidden in
10900 local classes -- the only situation in which a class has
10901 non-external linkage. */
10902 TREE_PUBLIC (decl) = 1;
10903 TREE_STATIC (decl) = 1;
10904 /* For non-template classes, static data members are always put
10905 out in exactly those files where they are defined, just as
10906 with ordinary namespace-scope variables. */
10907 if (!processing_template_decl)
10908 DECL_INTERFACE_KNOWN (decl) = 1;
10911 /* Create a VAR_DECL named NAME with the indicated TYPE.
10913 If SCOPE is non-NULL, it is the class type or namespace containing
10914 the variable. If SCOPE is NULL, the variable should is created in
10915 the innermost enclosing scope. */
10917 static tree
10918 grokvardecl (tree type,
10919 tree name,
10920 tree orig_declarator,
10921 const cp_decl_specifier_seq *declspecs,
10922 int initialized,
10923 int type_quals,
10924 int inlinep,
10925 bool conceptp,
10926 int template_count,
10927 tree scope,
10928 location_t location)
10930 tree decl;
10931 tree explicit_scope;
10933 gcc_assert (!name || identifier_p (name));
10935 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
10936 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
10938 /* Compute the scope in which to place the variable, but remember
10939 whether or not that scope was explicitly specified by the user. */
10940 explicit_scope = scope;
10941 if (!scope)
10943 /* An explicit "extern" specifier indicates a namespace-scope
10944 variable. */
10945 if (declspecs->storage_class == sc_extern)
10946 scope = current_decl_namespace ();
10947 else if (!at_function_scope_p ())
10948 scope = current_scope ();
10951 if (scope
10952 && (/* If the variable is a namespace-scope variable declared in a
10953 template, we need DECL_LANG_SPECIFIC. */
10954 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10955 /* Similarly for namespace-scope variables with language linkage
10956 other than C++. */
10957 || (TREE_CODE (scope) == NAMESPACE_DECL
10958 && current_lang_name != lang_name_cplusplus)
10959 /* Similarly for static data members. */
10960 || TYPE_P (scope)
10961 /* Similarly for explicit specializations. */
10962 || (orig_declarator
10963 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10964 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10965 else
10966 decl = build_decl (location, VAR_DECL, name, type);
10968 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10969 set_decl_namespace (decl, explicit_scope, 0);
10970 else
10971 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10973 if (declspecs->storage_class == sc_extern)
10975 DECL_THIS_EXTERN (decl) = 1;
10976 DECL_EXTERNAL (decl) = !initialized;
10979 if (DECL_CLASS_SCOPE_P (decl))
10981 set_linkage_for_static_data_member (decl);
10982 /* This function is only called with out-of-class definitions. */
10983 DECL_EXTERNAL (decl) = 0;
10984 check_class_member_definition_namespace (decl);
10986 /* At top level, either `static' or no s.c. makes a definition
10987 (perhaps tentative), and absence of `static' makes it public. */
10988 else if (toplevel_bindings_p ())
10990 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10991 && (DECL_THIS_EXTERN (decl)
10992 || ! constp
10993 || volatilep
10994 || inlinep));
10995 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10997 /* Not at top level, only `static' makes a static definition. */
10998 else
11000 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
11001 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
11004 set_originating_module (decl);
11006 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
11008 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
11010 CP_DECL_THREAD_LOCAL_P (decl) = true;
11011 if (!processing_template_decl)
11012 set_decl_tls_model (decl, decl_default_tls_model (decl));
11014 if (declspecs->gnu_thread_keyword_p)
11015 SET_DECL_GNU_TLS_P (decl);
11018 /* If the type of the decl has no linkage, make sure that we'll
11019 notice that in mark_used. */
11020 if (cxx_dialect > cxx98
11021 && decl_linkage (decl) != lk_none
11022 && DECL_LANG_SPECIFIC (decl) == NULL
11023 && !DECL_EXTERN_C_P (decl)
11024 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
11025 retrofit_lang_decl (decl);
11027 if (TREE_PUBLIC (decl))
11029 /* [basic.link]: A name with no linkage (notably, the name of a class
11030 or enumeration declared in a local scope) shall not be used to
11031 declare an entity with linkage.
11033 DR 757 relaxes this restriction for C++0x. */
11034 if (cxx_dialect < cxx11)
11035 no_linkage_error (decl);
11037 else
11038 DECL_INTERFACE_KNOWN (decl) = 1;
11040 if (DECL_NAME (decl)
11041 && MAIN_NAME_P (DECL_NAME (decl))
11042 && scope == global_namespace)
11043 error_at (DECL_SOURCE_LOCATION (decl),
11044 "cannot declare %<::main%> to be a global variable");
11046 /* Check that the variable can be safely declared as a concept.
11047 Note that this also forbids explicit specializations. */
11048 if (conceptp)
11050 if (!processing_template_decl)
11052 error_at (declspecs->locations[ds_concept],
11053 "a non-template variable cannot be %<concept%>");
11054 return NULL_TREE;
11056 else if (!at_namespace_scope_p ())
11058 error_at (declspecs->locations[ds_concept],
11059 "concept must be defined at namespace scope");
11060 return NULL_TREE;
11062 else
11063 DECL_DECLARED_CONCEPT_P (decl) = true;
11064 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
11065 error_at (declspecs->locations[ds_type_spec],
11066 "concept must have type %<bool%>");
11067 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
11069 error_at (location, "a variable concept cannot be constrained");
11070 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
11073 else if (flag_concepts
11074 && current_template_depth > template_class_depth (scope))
11076 tree ci = current_template_constraints ();
11077 set_constraints (decl, ci);
11080 // Handle explicit specializations and instantiations of variable templates.
11081 if (orig_declarator)
11082 decl = check_explicit_specialization (orig_declarator, decl,
11083 template_count, conceptp * 8);
11085 return decl != error_mark_node ? decl : NULL_TREE;
11088 /* Create and return a canonical pointer to member function type, for
11089 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
11091 tree
11092 build_ptrmemfunc_type (tree type)
11094 tree field, fields;
11095 tree t;
11097 if (type == error_mark_node)
11098 return type;
11100 /* Make sure that we always have the unqualified pointer-to-member
11101 type first. */
11102 if (cp_cv_quals quals = cp_type_quals (type))
11104 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
11105 return cp_build_qualified_type (unqual, quals);
11108 /* If a canonical type already exists for this type, use it. We use
11109 this method instead of type_hash_canon, because it only does a
11110 simple equality check on the list of field members. */
11112 t = TYPE_PTRMEMFUNC_TYPE (type);
11113 if (t)
11114 return t;
11116 t = make_node (RECORD_TYPE);
11118 /* Let the front end know this is a pointer to member function. */
11119 TYPE_PTRMEMFUNC_FLAG (t) = 1;
11121 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
11122 DECL_NONADDRESSABLE_P (field) = 1;
11123 fields = field;
11125 field = build_decl (input_location, FIELD_DECL, delta_identifier,
11126 delta_type_node);
11127 DECL_NONADDRESSABLE_P (field) = 1;
11128 DECL_CHAIN (field) = fields;
11129 fields = field;
11131 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
11133 /* Zap out the name so that the back end will give us the debugging
11134 information for this anonymous RECORD_TYPE. */
11135 TYPE_NAME (t) = NULL_TREE;
11137 /* Cache this pointer-to-member type so that we can find it again
11138 later. */
11139 TYPE_PTRMEMFUNC_TYPE (type) = t;
11141 if (TYPE_STRUCTURAL_EQUALITY_P (type))
11142 SET_TYPE_STRUCTURAL_EQUALITY (t);
11143 else if (TYPE_CANONICAL (type) != type)
11144 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
11146 return t;
11149 /* Create and return a pointer to data member type. */
11151 tree
11152 build_ptrmem_type (tree class_type, tree member_type)
11154 if (TREE_CODE (member_type) == METHOD_TYPE)
11156 cp_cv_quals quals = type_memfn_quals (member_type);
11157 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
11158 member_type = build_memfn_type (member_type, class_type, quals, rqual);
11159 return build_ptrmemfunc_type (build_pointer_type (member_type));
11161 else
11163 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
11164 return build_offset_type (class_type, member_type);
11168 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
11169 Check to see that the definition is valid. Issue appropriate error
11170 messages. */
11172 static void
11173 check_static_variable_definition (tree decl, tree type)
11175 /* Avoid redundant diagnostics on out-of-class definitions. */
11176 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
11178 /* Can't check yet if we don't know the type. */
11179 else if (dependent_type_p (type))
11181 /* If DECL is declared constexpr, we'll do the appropriate checks
11182 in check_initializer. Similarly for inline static data members. */
11183 else if (DECL_P (decl)
11184 && (DECL_DECLARED_CONSTEXPR_P (decl)
11185 || DECL_VAR_DECLARED_INLINE_P (decl)))
11187 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11189 if (!COMPLETE_TYPE_P (type))
11190 error_at (DECL_SOURCE_LOCATION (decl),
11191 "in-class initialization of static data member %q#D of "
11192 "incomplete type", decl);
11193 else if (literal_type_p (type))
11194 permerror (DECL_SOURCE_LOCATION (decl),
11195 "%<constexpr%> needed for in-class initialization of "
11196 "static data member %q#D of non-integral type", decl);
11197 else
11198 error_at (DECL_SOURCE_LOCATION (decl),
11199 "in-class initialization of static data member %q#D of "
11200 "non-literal type", decl);
11202 /* Motion 10 at San Diego: If a static const integral data member is
11203 initialized with an integral constant expression, the initializer
11204 may appear either in the declaration (within the class), or in
11205 the definition, but not both. If it appears in the class, the
11206 member is a member constant. The file-scope definition is always
11207 required. */
11208 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
11209 error_at (DECL_SOURCE_LOCATION (decl),
11210 "invalid in-class initialization of static data member "
11211 "of non-integral type %qT",
11212 type);
11213 else if (!CP_TYPE_CONST_P (type))
11214 error_at (DECL_SOURCE_LOCATION (decl),
11215 "ISO C++ forbids in-class initialization of non-const "
11216 "static member %qD",
11217 decl);
11218 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11219 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
11220 "ISO C++ forbids initialization of member constant "
11221 "%qD of non-integral type %qT", decl, type);
11224 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
11225 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
11226 expressions out into temporary variables so that walk_tree doesn't
11227 step into them (c++/15764). */
11229 static tree
11230 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
11232 hash_set<tree> *pset = (hash_set<tree> *)data;
11233 tree expr = *expr_p;
11234 if (TREE_CODE (expr) == SAVE_EXPR)
11236 tree op = TREE_OPERAND (expr, 0);
11237 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
11238 if (TREE_SIDE_EFFECTS (op))
11239 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
11240 *walk_subtrees = 0;
11242 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
11243 *walk_subtrees = 0;
11244 return NULL;
11247 /* Entry point for the above. */
11249 static void
11250 stabilize_vla_size (tree size)
11252 hash_set<tree> pset;
11253 /* Break out any function calls into temporary variables. */
11254 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
11257 /* Reduce a SIZEOF_EXPR to its value. */
11259 tree
11260 fold_sizeof_expr (tree t)
11262 tree r;
11263 if (SIZEOF_EXPR_TYPE_P (t))
11264 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11265 TREE_TYPE (TREE_OPERAND (t, 0)),
11266 SIZEOF_EXPR, false, false);
11267 else if (TYPE_P (TREE_OPERAND (t, 0)))
11268 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11269 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11270 false, false);
11271 else
11272 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
11273 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11274 false, false);
11275 if (r == error_mark_node)
11276 r = size_one_node;
11277 return r;
11280 /* Given the SIZE (i.e., number of elements) in an array, compute
11281 an appropriate index type for the array. If non-NULL, NAME is
11282 the name of the entity being declared. */
11284 static tree
11285 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11286 tsubst_flags_t complain)
11288 if (error_operand_p (size))
11289 return error_mark_node;
11291 /* The type of the index being computed. */
11292 tree itype;
11294 /* The original numeric size as seen in the source code before
11295 conversion to size_t. */
11296 tree origsize = size;
11298 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11300 if (!type_dependent_expression_p (size))
11302 origsize = size = mark_rvalue_use (size);
11304 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11305 && TREE_SIDE_EFFECTS (size))
11306 /* In C++98, we mark a non-constant array bound with a magic
11307 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11308 else
11310 size = build_converted_constant_expr (size_type_node, size, complain);
11311 /* Pedantically a constant expression is required here and so
11312 __builtin_is_constant_evaluated () should fold to true if it
11313 is successfully folded into a constant. */
11314 size = fold_non_dependent_expr (size, complain,
11315 /*manifestly_const_eval=*/true);
11317 if (!TREE_CONSTANT (size))
11318 size = origsize;
11321 if (error_operand_p (size))
11322 return error_mark_node;
11324 /* The array bound must be an integer type. */
11325 tree type = TREE_TYPE (size);
11326 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11328 if (!(complain & tf_error))
11329 return error_mark_node;
11330 if (name)
11331 error_at (loc, "size of array %qD has non-integral type %qT",
11332 name, type);
11333 else
11334 error_at (loc, "size of array has non-integral type %qT", type);
11335 size = integer_one_node;
11339 /* A type is dependent if it is...an array type constructed from any
11340 dependent type or whose size is specified by a constant expression
11341 that is value-dependent. */
11342 /* We can only call value_dependent_expression_p on integral constant
11343 expressions. */
11344 if (processing_template_decl
11345 && potential_constant_expression (size)
11346 && value_dependent_expression_p (size))
11348 /* Just build the index type and mark that it requires
11349 structural equality checks. */
11350 in_template:
11351 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11352 size, size_one_node));
11353 TYPE_DEPENDENT_P (itype) = 1;
11354 TYPE_DEPENDENT_P_VALID (itype) = 1;
11355 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11356 return itype;
11359 if (TREE_CODE (size) != INTEGER_CST)
11361 tree folded = cp_fully_fold (size);
11362 if (TREE_CODE (folded) == INTEGER_CST)
11364 if (name)
11365 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11366 "integral constant-expression", name);
11367 else
11368 pedwarn (loc, OPT_Wpedantic,
11369 "size of array is not an integral constant-expression");
11371 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11372 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11373 folding a conversion from a pointer to integral type. In that
11374 case issue an error below and don't treat this as a VLA. */;
11375 else
11376 /* Use the folded result for VLAs, too; it will have resolved
11377 SIZEOF_EXPR. */
11378 size = folded;
11381 /* Normally, the array-bound will be a constant. */
11382 if (TREE_CODE (size) == INTEGER_CST)
11384 /* The size to use in diagnostics that reflects the constant
11385 size used in the source, rather than SIZE massaged above. */
11386 tree diagsize = size;
11388 /* If the original size before conversion to size_t was signed
11389 and negative, convert it to ssizetype to restore the sign. */
11390 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11391 && TREE_CODE (size) == INTEGER_CST
11392 && tree_int_cst_sign_bit (size))
11394 diagsize = fold_convert (ssizetype, size);
11396 /* Clear the overflow bit that may have been set as a result
11397 of the conversion from the sizetype of the new size to
11398 ssizetype. */
11399 TREE_OVERFLOW (diagsize) = false;
11402 /* Verify that the array has a positive number of elements
11403 and issue the appropriate diagnostic if it doesn't. */
11404 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11406 if (!(complain & tf_error))
11407 return error_mark_node;
11408 size = integer_one_node;
11410 /* As an extension we allow zero-sized arrays. */
11411 else if (integer_zerop (size))
11413 if (!(complain & tf_error))
11414 /* We must fail if performing argument deduction (as
11415 indicated by the state of complain), so that
11416 another substitution can be found. */
11417 return error_mark_node;
11418 else if (name)
11419 pedwarn (loc, OPT_Wpedantic,
11420 "ISO C++ forbids zero-size array %qD", name);
11421 else
11422 pedwarn (loc, OPT_Wpedantic,
11423 "ISO C++ forbids zero-size array");
11426 else if (TREE_CONSTANT (size)
11427 /* We don't allow VLAs at non-function scopes, or during
11428 tentative template substitution. */
11429 || !at_function_scope_p ()
11430 || !(complain & tf_error))
11432 if (!(complain & tf_error))
11433 return error_mark_node;
11434 /* `(int) &fn' is not a valid array bound. */
11435 if (name)
11436 error_at (loc,
11437 "size of array %qD is not an integral constant-expression",
11438 name);
11439 else
11440 error_at (loc, "size of array is not an integral constant-expression");
11441 size = integer_one_node;
11443 else if (pedantic && warn_vla != 0)
11445 if (name)
11446 pedwarn (name_loc, OPT_Wvla,
11447 "ISO C++ forbids variable length array %qD", name);
11448 else
11449 pedwarn (input_location, OPT_Wvla,
11450 "ISO C++ forbids variable length array");
11452 else if (warn_vla > 0)
11454 if (name)
11455 warning_at (name_loc, OPT_Wvla,
11456 "variable length array %qD is used", name);
11457 else
11458 warning (OPT_Wvla,
11459 "variable length array is used");
11462 if (processing_template_decl && !TREE_CONSTANT (size))
11463 goto in_template;
11464 else
11466 if (!TREE_CONSTANT (size))
11468 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11469 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11470 that happens when building TYPE_SIZE. */
11471 size = variable_size (size);
11472 stabilize_vla_size (size);
11475 /* Compute the index of the largest element in the array. It is
11476 one less than the number of elements in the array. We save
11477 and restore PROCESSING_TEMPLATE_DECL so that computations in
11478 cp_build_binary_op will be appropriately folded. */
11480 processing_template_decl_sentinel s;
11481 itype = cp_build_binary_op (input_location,
11482 MINUS_EXPR,
11483 cp_convert (ssizetype, size, complain),
11484 cp_convert (ssizetype, integer_one_node,
11485 complain),
11486 complain);
11487 itype = maybe_constant_value (itype, NULL_TREE, mce_true);
11490 if (!TREE_CONSTANT (itype))
11492 if (sanitize_flags_p (SANITIZE_VLA)
11493 && current_function_decl != NULL_TREE)
11495 /* We have to add 1 -- in the ubsan routine we generate
11496 LE_EXPR rather than LT_EXPR. */
11497 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11498 build_one_cst (TREE_TYPE (itype)));
11499 t = ubsan_instrument_vla (input_location, t);
11500 finish_expr_stmt (t);
11503 /* Make sure that there was no overflow when creating to a signed
11504 index type. (For example, on a 32-bit machine, an array with
11505 size 2^32 - 1 is too big.) */
11506 else if (TREE_CODE (itype) == INTEGER_CST
11507 && TREE_OVERFLOW (itype))
11509 if (!(complain & tf_error))
11510 return error_mark_node;
11511 error ("overflow in array dimension");
11512 TREE_OVERFLOW (itype) = 0;
11516 /* Create and return the appropriate index type. */
11517 itype = build_index_type (itype);
11519 /* If the index type were dependent, we would have returned early, so
11520 remember that it isn't. */
11521 TYPE_DEPENDENT_P (itype) = 0;
11522 TYPE_DEPENDENT_P_VALID (itype) = 1;
11523 return itype;
11526 tree
11527 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11529 return compute_array_index_type_loc (input_location, name, size, complain);
11532 /* Returns the scope (if any) in which the entity declared by
11533 DECLARATOR will be located. If the entity was declared with an
11534 unqualified name, NULL_TREE is returned. */
11536 tree
11537 get_scope_of_declarator (const cp_declarator *declarator)
11539 while (declarator && declarator->kind != cdk_id)
11540 declarator = declarator->declarator;
11542 /* If the declarator-id is a SCOPE_REF, the scope in which the
11543 declaration occurs is the first operand. */
11544 if (declarator
11545 && declarator->u.id.qualifying_scope)
11546 return declarator->u.id.qualifying_scope;
11548 /* Otherwise, the declarator is not a qualified name; the entity will
11549 be declared in the current scope. */
11550 return NULL_TREE;
11553 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11554 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11555 with this type. */
11557 static tree
11558 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11560 tree itype = NULL_TREE;
11562 /* If things have already gone awry, bail now. */
11563 if (type == error_mark_node || size == error_mark_node)
11564 return error_mark_node;
11566 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11567 for a deduced class type. */
11568 if (template_placeholder_p (type))
11570 if (name)
11571 error_at (loc, "%qD declared as array of template placeholder "
11572 "type %qT", name, type);
11573 else
11574 error ("creating array of template placeholder type %qT", type);
11575 return error_mark_node;
11578 /* If there are some types which cannot be array elements,
11579 issue an error-message and return. */
11580 switch (TREE_CODE (type))
11582 case VOID_TYPE:
11583 if (name)
11584 error_at (loc, "declaration of %qD as array of void", name);
11585 else
11586 error ("creating array of void");
11587 return error_mark_node;
11589 case FUNCTION_TYPE:
11590 if (name)
11591 error_at (loc, "declaration of %qD as array of functions", name);
11592 else
11593 error ("creating array of functions");
11594 return error_mark_node;
11596 case REFERENCE_TYPE:
11597 if (name)
11598 error_at (loc, "declaration of %qD as array of references", name);
11599 else
11600 error ("creating array of references");
11601 return error_mark_node;
11603 case METHOD_TYPE:
11604 if (name)
11605 error_at (loc, "declaration of %qD as array of function members",
11606 name);
11607 else
11608 error ("creating array of function members");
11609 return error_mark_node;
11611 default:
11612 break;
11615 if (!verify_type_context (name ? loc : input_location,
11616 TCTX_ARRAY_ELEMENT, type))
11617 return error_mark_node;
11619 /* [dcl.array]
11621 The constant expressions that specify the bounds of the arrays
11622 can be omitted only for the first member of the sequence. */
11623 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11625 if (name)
11626 error_at (loc, "declaration of %qD as multidimensional array must "
11627 "have bounds for all dimensions except the first",
11628 name);
11629 else
11630 error ("multidimensional array must have bounds for all "
11631 "dimensions except the first");
11633 return error_mark_node;
11636 /* Figure out the index type for the array. */
11637 if (size)
11639 itype = compute_array_index_type_loc (loc, name, size,
11640 tf_warning_or_error);
11641 if (type_uses_auto (type)
11642 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11644 sorry_at (loc, "variable-length array of %<auto%>");
11645 return error_mark_node;
11649 return build_cplus_array_type (type, itype);
11652 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11654 static location_t
11655 min_location (location_t loca, location_t locb)
11657 if (loca == UNKNOWN_LOCATION
11658 || (locb != UNKNOWN_LOCATION
11659 && linemap_location_before_p (line_table, locb, loca)))
11660 return locb;
11661 return loca;
11664 /* Returns the smallest location != UNKNOWN_LOCATION among the
11665 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11666 and LOCATIONS[ds_restrict]. */
11668 static location_t
11669 smallest_type_quals_location (int type_quals, const location_t* locations)
11671 location_t loc = UNKNOWN_LOCATION;
11673 if (type_quals & TYPE_QUAL_CONST)
11674 loc = locations[ds_const];
11676 if (type_quals & TYPE_QUAL_VOLATILE)
11677 loc = min_location (loc, locations[ds_volatile]);
11679 if (type_quals & TYPE_QUAL_RESTRICT)
11680 loc = min_location (loc, locations[ds_restrict]);
11682 return loc;
11685 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11687 static location_t
11688 smallest_type_location (int type_quals, const location_t* locations)
11690 location_t loc = smallest_type_quals_location (type_quals, locations);
11691 return min_location (loc, locations[ds_type_spec]);
11694 static location_t
11695 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11697 int type_quals = get_type_quals (declspecs);
11698 return smallest_type_location (type_quals, declspecs->locations);
11701 /* Check that it's OK to declare a function with the indicated TYPE
11702 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11703 that this function is. OPTYPE is the type given in a conversion
11704 operator declaration, or the class type for a constructor/destructor.
11705 Returns the actual return type of the function; that may be different
11706 than TYPE if an error occurs, or for certain special functions. */
11708 static tree
11709 check_special_function_return_type (special_function_kind sfk,
11710 tree type,
11711 tree optype,
11712 int type_quals,
11713 const location_t* locations)
11715 switch (sfk)
11717 case sfk_constructor:
11718 if (type)
11719 error_at (smallest_type_location (type_quals, locations),
11720 "return type specification for constructor invalid");
11721 else if (type_quals != TYPE_UNQUALIFIED)
11722 error_at (smallest_type_quals_location (type_quals, locations),
11723 "qualifiers are not allowed on constructor declaration");
11725 if (targetm.cxx.cdtor_returns_this ())
11726 type = build_pointer_type (optype);
11727 else
11728 type = void_type_node;
11729 break;
11731 case sfk_destructor:
11732 if (type)
11733 error_at (smallest_type_location (type_quals, locations),
11734 "return type specification for destructor invalid");
11735 else if (type_quals != TYPE_UNQUALIFIED)
11736 error_at (smallest_type_quals_location (type_quals, locations),
11737 "qualifiers are not allowed on destructor declaration");
11739 /* We can't use the proper return type here because we run into
11740 problems with ambiguous bases and covariant returns. */
11741 if (targetm.cxx.cdtor_returns_this ())
11742 type = build_pointer_type (void_type_node);
11743 else
11744 type = void_type_node;
11745 break;
11747 case sfk_conversion:
11748 if (type)
11749 error_at (smallest_type_location (type_quals, locations),
11750 "return type specified for %<operator %T%>", optype);
11751 else if (type_quals != TYPE_UNQUALIFIED)
11752 error_at (smallest_type_quals_location (type_quals, locations),
11753 "qualifiers are not allowed on declaration of "
11754 "%<operator %T%>", optype);
11756 type = optype;
11757 break;
11759 case sfk_deduction_guide:
11760 if (type)
11761 error_at (smallest_type_location (type_quals, locations),
11762 "return type specified for deduction guide");
11763 else if (type_quals != TYPE_UNQUALIFIED)
11764 error_at (smallest_type_quals_location (type_quals, locations),
11765 "qualifiers are not allowed on declaration of "
11766 "deduction guide");
11767 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11769 error ("template template parameter %qT in declaration of "
11770 "deduction guide", optype);
11771 type = error_mark_node;
11773 else
11774 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11775 for (int i = 0; i < ds_last; ++i)
11776 if (i != ds_explicit && locations[i])
11777 error_at (locations[i],
11778 "%<decl-specifier%> in declaration of deduction guide");
11779 break;
11781 default:
11782 gcc_unreachable ();
11785 return type;
11788 /* A variable or data member (whose unqualified name is IDENTIFIER)
11789 has been declared with the indicated TYPE. If the TYPE is not
11790 acceptable, issue an error message and return a type to use for
11791 error-recovery purposes. */
11793 tree
11794 check_var_type (tree identifier, tree type, location_t loc)
11796 if (VOID_TYPE_P (type))
11798 if (!identifier)
11799 error_at (loc, "unnamed variable or field declared void");
11800 else if (identifier_p (identifier))
11802 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
11803 error_at (loc, "variable or field %qE declared void",
11804 identifier);
11806 else
11807 error_at (loc, "variable or field declared void");
11808 type = error_mark_node;
11811 return type;
11814 /* Handle declaring DECL as an inline variable. */
11816 static void
11817 mark_inline_variable (tree decl, location_t loc)
11819 bool inlinep = true;
11820 if (! toplevel_bindings_p ())
11822 error_at (loc, "%<inline%> specifier invalid for variable "
11823 "%qD declared at block scope", decl);
11824 inlinep = false;
11826 else if (cxx_dialect < cxx17)
11827 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
11828 "with %<-std=c++17%> or %<-std=gnu++17%>");
11829 if (inlinep)
11831 retrofit_lang_decl (decl);
11832 SET_DECL_VAR_DECLARED_INLINE_P (decl);
11837 /* Assign a typedef-given name to a class or enumeration type declared
11838 as anonymous at first. This was split out of grokdeclarator
11839 because it is also used in libcc1. */
11841 void
11842 name_unnamed_type (tree type, tree decl)
11844 gcc_assert (TYPE_UNNAMED_P (type));
11846 /* Replace the anonymous decl with the real decl. Be careful not to
11847 rename other typedefs (such as the self-reference) of type. */
11848 tree orig = TYPE_NAME (type);
11849 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
11850 if (TYPE_NAME (t) == orig)
11851 TYPE_NAME (t) = decl;
11853 /* If this is a typedef within a template class, the nested
11854 type is a (non-primary) template. The name for the
11855 template needs updating as well. */
11856 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
11857 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
11859 /* Adjust linkage now that we aren't unnamed anymore. */
11860 reset_type_linkage (type);
11862 /* FIXME remangle member functions; member functions of a
11863 type with external linkage have external linkage. */
11865 /* Check that our job is done, and that it would fail if we
11866 attempted to do it again. */
11867 gcc_assert (!TYPE_UNNAMED_P (type));
11870 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
11871 is allowed. TYPE might contain a decltype(auto). Returns true if
11872 there was a problem, false otherwise. */
11874 static bool
11875 check_decltype_auto (location_t loc, tree type)
11877 if (tree a = type_uses_auto (type))
11879 if (AUTO_IS_DECLTYPE (a))
11881 if (a != type)
11883 error_at (loc, "%qT as type rather than plain "
11884 "%<decltype(auto)%>", type);
11885 return true;
11887 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
11889 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
11890 return true;
11894 return false;
11897 /* Given declspecs and a declarator (abstract or otherwise), determine
11898 the name and type of the object declared and construct a DECL node
11899 for it.
11901 DECLSPECS points to the representation of declaration-specifier
11902 sequence that precedes declarator.
11904 DECL_CONTEXT says which syntactic context this declaration is in:
11905 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
11906 FUNCDEF for a function definition. Like NORMAL but a few different
11907 error messages in each case. Return value may be zero meaning
11908 this definition is too screwy to try to parse.
11909 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
11910 handle member functions (which have FIELD context).
11911 Return value may be zero meaning this definition is too screwy to
11912 try to parse.
11913 PARM for a parameter declaration (either within a function prototype
11914 or before a function body). Make a PARM_DECL, or return void_type_node.
11915 TPARM for a template parameter declaration.
11916 CATCHPARM for a parameter declaration before a catch clause.
11917 TYPENAME if for a typename (in a cast or sizeof).
11918 Don't make a DECL node; just return the ..._TYPE node.
11919 FIELD for a struct or union field; make a FIELD_DECL.
11920 BITFIELD for a field with specified width.
11922 INITIALIZED is as for start_decl.
11924 ATTRLIST is a pointer to the list of attributes, which may be NULL
11925 if there are none; *ATTRLIST may be modified if attributes from inside
11926 the declarator should be applied to the declaration.
11928 When this function is called, scoping variables (such as
11929 CURRENT_CLASS_TYPE) should reflect the scope in which the
11930 declaration occurs, not the scope in which the new declaration will
11931 be placed. For example, on:
11933 void S::f() { ... }
11935 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
11936 should not be `S'.
11938 Returns a DECL (if a declarator is present), a TYPE (if there is no
11939 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
11940 error occurs. */
11942 tree
11943 grokdeclarator (const cp_declarator *declarator,
11944 cp_decl_specifier_seq *declspecs,
11945 enum decl_context decl_context,
11946 int initialized,
11947 tree* attrlist)
11949 tree type = NULL_TREE;
11950 int longlong = 0;
11951 int explicit_intN = 0;
11952 int int_n_alt = 0;
11953 int virtualp, explicitp, friendp, inlinep, staticp;
11954 int explicit_int = 0;
11955 int explicit_char = 0;
11956 int defaulted_int = 0;
11958 tree typedef_decl = NULL_TREE;
11959 const char *name = NULL;
11960 tree typedef_type = NULL_TREE;
11961 /* True if this declarator is a function definition. */
11962 bool funcdef_flag = false;
11963 cp_declarator_kind innermost_code = cdk_error;
11964 int bitfield = 0;
11965 #if 0
11966 /* See the code below that used this. */
11967 tree decl_attr = NULL_TREE;
11968 #endif
11970 /* Keep track of what sort of function is being processed
11971 so that we can warn about default return values, or explicit
11972 return values which do not match prescribed defaults. */
11973 special_function_kind sfk = sfk_none;
11975 tree dname = NULL_TREE;
11976 tree ctor_return_type = NULL_TREE;
11977 enum overload_flags flags = NO_SPECIAL;
11978 /* cv-qualifiers that apply to the declarator, for a declaration of
11979 a member function. */
11980 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11981 /* virt-specifiers that apply to the declarator, for a declaration of
11982 a member function. */
11983 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11984 /* ref-qualifier that applies to the declarator, for a declaration of
11985 a member function. */
11986 cp_ref_qualifier rqual = REF_QUAL_NONE;
11987 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
11988 int type_quals = get_type_quals (declspecs);
11989 tree raises = NULL_TREE;
11990 int template_count = 0;
11991 tree returned_attrs = NULL_TREE;
11992 tree parms = NULL_TREE;
11993 const cp_declarator *id_declarator;
11994 /* The unqualified name of the declarator; either an
11995 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
11996 tree unqualified_id;
11997 /* The class type, if any, in which this entity is located,
11998 or NULL_TREE if none. Note that this value may be different from
11999 the current class type; for example if an attempt is made to declare
12000 "A::f" inside "B", this value will be "A". */
12001 tree ctype = current_class_type;
12002 /* The NAMESPACE_DECL for the namespace in which this entity is
12003 located. If an unqualified name is used to declare the entity,
12004 this value will be NULL_TREE, even if the entity is located at
12005 namespace scope. */
12006 tree in_namespace = NULL_TREE;
12007 cp_storage_class storage_class;
12008 bool unsigned_p, signed_p, short_p, long_p, thread_p;
12009 bool type_was_error_mark_node = false;
12010 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
12011 bool template_type_arg = false;
12012 bool template_parm_flag = false;
12013 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
12014 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
12015 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
12016 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
12017 bool late_return_type_p = false;
12018 bool array_parameter_p = false;
12019 tree reqs = NULL_TREE;
12021 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
12022 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
12023 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
12024 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
12025 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
12026 explicit_intN = declspecs->explicit_intN_p;
12027 int_n_alt = declspecs->int_n_alt;
12028 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
12030 // Was concept_p specified? Note that ds_concept
12031 // implies ds_constexpr!
12032 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
12033 if (concept_p)
12034 constexpr_p = true;
12036 if (decl_context == FUNCDEF)
12037 funcdef_flag = true, decl_context = NORMAL;
12038 else if (decl_context == MEMFUNCDEF)
12039 funcdef_flag = true, decl_context = FIELD;
12040 else if (decl_context == BITFIELD)
12041 bitfield = 1, decl_context = FIELD;
12042 else if (decl_context == TEMPLATE_TYPE_ARG)
12043 template_type_arg = true, decl_context = TYPENAME;
12044 else if (decl_context == TPARM)
12045 template_parm_flag = true, decl_context = PARM;
12047 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
12048 funcdef_flag = true;
12050 location_t typespec_loc = loc_or_input_loc (smallest_type_location
12051 (type_quals,
12052 declspecs->locations));
12053 location_t id_loc;
12054 location_t init_loc;
12055 if (declarator)
12057 id_loc = loc_or_input_loc (declarator->id_loc);
12058 init_loc = loc_or_input_loc (declarator->init_loc);
12060 else
12061 init_loc = id_loc = input_location;
12063 /* Look inside a declarator for the name being declared
12064 and get it as a string, for an error message. */
12065 for (id_declarator = declarator;
12066 id_declarator;
12067 id_declarator = id_declarator->declarator)
12069 if (id_declarator->kind != cdk_id)
12070 innermost_code = id_declarator->kind;
12072 switch (id_declarator->kind)
12074 case cdk_function:
12075 if (id_declarator->declarator
12076 && id_declarator->declarator->kind == cdk_id)
12078 sfk = id_declarator->declarator->u.id.sfk;
12079 if (sfk == sfk_destructor)
12080 flags = DTOR_FLAG;
12082 break;
12084 case cdk_id:
12086 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
12087 tree decl = id_declarator->u.id.unqualified_name;
12088 if (!decl)
12089 break;
12090 if (qualifying_scope)
12092 if (check_for_bare_parameter_packs (qualifying_scope,
12093 id_declarator->id_loc))
12094 return error_mark_node;
12095 if (at_function_scope_p ())
12097 /* [dcl.meaning]
12099 A declarator-id shall not be qualified except
12100 for ...
12102 None of the cases are permitted in block
12103 scope. */
12104 if (qualifying_scope == global_namespace)
12105 error ("invalid use of qualified-name %<::%D%>",
12106 decl);
12107 else if (TYPE_P (qualifying_scope))
12108 error ("invalid use of qualified-name %<%T::%D%>",
12109 qualifying_scope, decl);
12110 else
12111 error ("invalid use of qualified-name %<%D::%D%>",
12112 qualifying_scope, decl);
12113 return error_mark_node;
12115 else if (TYPE_P (qualifying_scope))
12117 ctype = qualifying_scope;
12118 if (!MAYBE_CLASS_TYPE_P (ctype))
12120 error_at (id_declarator->id_loc,
12121 "%q#T is not a class or namespace", ctype);
12122 ctype = NULL_TREE;
12124 else if (innermost_code != cdk_function
12125 && current_class_type
12126 && !uniquely_derived_from_p (ctype,
12127 current_class_type))
12129 error_at (id_declarator->id_loc,
12130 "invalid use of qualified-name %<%T::%D%>",
12131 qualifying_scope, decl);
12132 return error_mark_node;
12135 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
12136 in_namespace = qualifying_scope;
12138 switch (TREE_CODE (decl))
12140 case BIT_NOT_EXPR:
12142 if (innermost_code != cdk_function)
12144 error_at (EXPR_LOCATION (decl),
12145 "declaration of %qE as non-function", decl);
12146 return error_mark_node;
12148 else if (!qualifying_scope
12149 && !(current_class_type && at_class_scope_p ()))
12151 error_at (EXPR_LOCATION (decl),
12152 "declaration of %qE as non-member", decl);
12153 return error_mark_node;
12156 tree type = TREE_OPERAND (decl, 0);
12157 if (TYPE_P (type))
12158 type = constructor_name (type);
12159 name = identifier_to_locale (IDENTIFIER_POINTER (type));
12160 dname = decl;
12162 break;
12164 case TEMPLATE_ID_EXPR:
12166 tree fns = TREE_OPERAND (decl, 0);
12168 dname = fns;
12169 if (!identifier_p (dname))
12170 dname = OVL_NAME (dname);
12172 /* Fall through. */
12174 case IDENTIFIER_NODE:
12175 if (identifier_p (decl))
12176 dname = decl;
12178 if (IDENTIFIER_KEYWORD_P (dname))
12180 error ("declarator-id missing; using reserved word %qD",
12181 dname);
12182 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12184 else if (!IDENTIFIER_CONV_OP_P (dname))
12185 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12186 else
12188 gcc_assert (flags == NO_SPECIAL);
12189 flags = TYPENAME_FLAG;
12190 sfk = sfk_conversion;
12191 tree glob = get_global_binding (dname);
12192 if (glob && TREE_CODE (glob) == TYPE_DECL)
12193 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12194 else
12195 name = "<invalid operator>";
12197 break;
12199 default:
12200 gcc_unreachable ();
12202 break;
12205 case cdk_array:
12206 case cdk_pointer:
12207 case cdk_reference:
12208 case cdk_ptrmem:
12209 break;
12211 case cdk_decomp:
12212 name = "structured binding";
12213 break;
12215 case cdk_error:
12216 return error_mark_node;
12218 default:
12219 gcc_unreachable ();
12221 if (id_declarator->kind == cdk_id)
12222 break;
12225 /* [dcl.fct.edf]
12227 The declarator in a function-definition shall have the form
12228 D1 ( parameter-declaration-clause) ... */
12229 if (funcdef_flag && innermost_code != cdk_function)
12231 error_at (id_loc, "function definition does not declare parameters");
12232 return error_mark_node;
12235 if (flags == TYPENAME_FLAG
12236 && innermost_code != cdk_function
12237 && ! (ctype && !declspecs->any_specifiers_p))
12239 error_at (id_loc, "declaration of %qD as non-function", dname);
12240 return error_mark_node;
12243 if (dname && identifier_p (dname))
12245 if (UDLIT_OPER_P (dname)
12246 && innermost_code != cdk_function)
12248 error_at (id_loc, "declaration of %qD as non-function", dname);
12249 return error_mark_node;
12252 if (IDENTIFIER_ANY_OP_P (dname))
12254 if (typedef_p)
12256 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
12257 return error_mark_node;
12259 else if (decl_context == PARM || decl_context == CATCHPARM)
12261 error_at (id_loc, "declaration of %qD as parameter", dname);
12262 return error_mark_node;
12267 /* Anything declared one level down from the top level
12268 must be one of the parameters of a function
12269 (because the body is at least two levels down). */
12271 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
12272 by not allowing C++ class definitions to specify their parameters
12273 with xdecls (must be spec.d in the parmlist).
12275 Since we now wait to push a class scope until we are sure that
12276 we are in a legitimate method context, we must set oldcname
12277 explicitly (since current_class_name is not yet alive).
12279 We also want to avoid calling this a PARM if it is in a namespace. */
12281 if (decl_context == NORMAL && !toplevel_bindings_p ())
12283 cp_binding_level *b = current_binding_level;
12284 current_binding_level = b->level_chain;
12285 if (current_binding_level != 0 && toplevel_bindings_p ())
12286 decl_context = PARM;
12287 current_binding_level = b;
12290 if (name == NULL)
12291 name = decl_context == PARM ? "parameter" : "type name";
12293 if (consteval_p && constexpr_p)
12295 error_at (declspecs->locations[ds_consteval],
12296 "both %qs and %qs specified", "constexpr", "consteval");
12297 return error_mark_node;
12300 if (concept_p && typedef_p)
12302 error_at (declspecs->locations[ds_concept],
12303 "%qs cannot appear in a typedef declaration", "concept");
12304 return error_mark_node;
12307 if (constexpr_p && typedef_p)
12309 error_at (declspecs->locations[ds_constexpr],
12310 "%qs cannot appear in a typedef declaration", "constexpr");
12311 return error_mark_node;
12314 if (consteval_p && typedef_p)
12316 error_at (declspecs->locations[ds_consteval],
12317 "%qs cannot appear in a typedef declaration", "consteval");
12318 return error_mark_node;
12321 if (constinit_p && typedef_p)
12323 error_at (declspecs->locations[ds_constinit],
12324 "%qs cannot appear in a typedef declaration", "constinit");
12325 return error_mark_node;
12328 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12329 keywords shall appear in a decl-specifier-seq." */
12330 if (constinit_p && constexpr_p)
12332 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12333 richloc.add_range (declspecs->locations[ds_constexpr]);
12334 error_at (&richloc,
12335 "can use at most one of the %<constinit%> and %<constexpr%> "
12336 "specifiers");
12337 return error_mark_node;
12340 /* If there were multiple types specified in the decl-specifier-seq,
12341 issue an error message. */
12342 if (declspecs->multiple_types_p)
12344 error_at (typespec_loc,
12345 "two or more data types in declaration of %qs", name);
12346 return error_mark_node;
12349 if (declspecs->conflicting_specifiers_p)
12350 return error_mark_node;
12352 /* Extract the basic type from the decl-specifier-seq. */
12353 type = declspecs->type;
12354 if (type == error_mark_node)
12356 type = NULL_TREE;
12357 type_was_error_mark_node = true;
12360 /* Ignore erroneous attributes. */
12361 if (attrlist && *attrlist == error_mark_node)
12362 *attrlist = NULL_TREE;
12364 /* An object declared as __attribute__((unavailable)) suppresses
12365 any reports of being declared with unavailable or deprecated
12366 items. An object declared as __attribute__((deprecated))
12367 suppresses warnings of uses of other deprecated items. */
12368 auto ds = make_temp_override (deprecated_state);
12369 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12370 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12371 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12372 deprecated_state = DEPRECATED_SUPPRESS;
12374 cp_handle_deprecated_or_unavailable (type);
12375 if (type && TREE_CODE (type) == TYPE_DECL)
12377 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12378 typedef_decl = type;
12379 type = TREE_TYPE (typedef_decl);
12380 if (DECL_ARTIFICIAL (typedef_decl))
12381 cp_handle_deprecated_or_unavailable (type);
12383 /* No type at all: default to `int', and set DEFAULTED_INT
12384 because it was not a user-defined typedef. */
12385 if (type == NULL_TREE)
12387 if (signed_p || unsigned_p || long_p || short_p)
12389 /* These imply 'int'. */
12390 type = integer_type_node;
12391 defaulted_int = 1;
12393 /* If we just have "complex", it is equivalent to "complex double". */
12394 else if (!longlong && !explicit_intN
12395 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12397 type = double_type_node;
12398 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12399 "ISO C++ does not support plain %<complex%> meaning "
12400 "%<double complex%>");
12403 /* Gather flags. */
12404 explicit_int = declspecs->explicit_int_p;
12405 explicit_char = declspecs->explicit_char_p;
12407 #if 0
12408 /* See the code below that used this. */
12409 if (typedef_decl)
12410 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12411 #endif
12412 typedef_type = type;
12414 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12415 ctor_return_type = TREE_TYPE (dname);
12416 else
12417 ctor_return_type = ctype;
12419 if (sfk != sfk_none)
12421 type = check_special_function_return_type (sfk, type,
12422 ctor_return_type,
12423 type_quals,
12424 declspecs->locations);
12425 type_quals = TYPE_UNQUALIFIED;
12427 else if (type == NULL_TREE)
12429 int is_main;
12431 explicit_int = -1;
12433 /* We handle `main' specially here, because 'main () { }' is so
12434 common. With no options, it is allowed. With -Wreturn-type,
12435 it is a warning. It is only an error with -pedantic-errors. */
12436 is_main = (funcdef_flag
12437 && dname && identifier_p (dname)
12438 && MAIN_NAME_P (dname)
12439 && ctype == NULL_TREE
12440 && in_namespace == NULL_TREE
12441 && current_namespace == global_namespace);
12443 if (type_was_error_mark_node)
12444 /* We've already issued an error, don't complain more. */;
12445 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12446 /* Allow it, sigh. */;
12447 else if (! is_main)
12448 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12449 name);
12450 else if (pedantic)
12451 pedwarn (id_loc, OPT_Wpedantic,
12452 "ISO C++ forbids declaration of %qs with no type", name);
12453 else
12454 warning_at (id_loc, OPT_Wreturn_type,
12455 "ISO C++ forbids declaration of %qs with no type", name);
12457 if (type_was_error_mark_node && template_parm_flag)
12458 /* FIXME we should be able to propagate the error_mark_node as is
12459 for other contexts too. */
12460 type = error_mark_node;
12461 else
12462 type = integer_type_node;
12465 ctype = NULL_TREE;
12467 if (explicit_intN)
12469 if (! int_n_enabled_p[declspecs->int_n_idx])
12471 error_at (declspecs->locations[ds_type_spec],
12472 "%<__int%d%> is not supported by this target",
12473 int_n_data[declspecs->int_n_idx].bitsize);
12474 explicit_intN = false;
12476 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12477 of "__intN". */
12478 else if (!int_n_alt && pedantic)
12479 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12480 "ISO C++ does not support %<__int%d%> for %qs",
12481 int_n_data[declspecs->int_n_idx].bitsize, name);
12484 /* Now process the modifiers that were specified
12485 and check for invalid combinations. */
12487 /* Long double is a special combination. */
12488 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12490 long_p = false;
12491 type = cp_build_qualified_type (long_double_type_node,
12492 cp_type_quals (type));
12495 /* Check all other uses of type modifiers. */
12497 if (unsigned_p || signed_p || long_p || short_p)
12499 location_t loc;
12500 const char *key;
12501 if (unsigned_p)
12503 key = "unsigned";
12504 loc = declspecs->locations[ds_unsigned];
12506 else if (signed_p)
12508 key = "signed";
12509 loc = declspecs->locations[ds_signed];
12511 else if (longlong)
12513 key = "long long";
12514 loc = declspecs->locations[ds_long_long];
12516 else if (long_p)
12518 key = "long";
12519 loc = declspecs->locations[ds_long];
12521 else /* if (short_p) */
12523 key = "short";
12524 loc = declspecs->locations[ds_short];
12527 int ok = 0;
12529 if (signed_p && unsigned_p)
12531 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12532 richloc.add_range (declspecs->locations[ds_unsigned]);
12533 error_at (&richloc,
12534 "%<signed%> and %<unsigned%> specified together");
12536 else if (long_p && short_p)
12538 gcc_rich_location richloc (declspecs->locations[ds_long]);
12539 richloc.add_range (declspecs->locations[ds_short]);
12540 error_at (&richloc, "%<long%> and %<short%> specified together");
12542 else if (TREE_CODE (type) != INTEGER_TYPE
12543 || type == char8_type_node
12544 || type == char16_type_node
12545 || type == char32_type_node
12546 || ((long_p || short_p)
12547 && (explicit_char || explicit_intN)))
12548 error_at (loc, "%qs specified with %qT", key, type);
12549 else if (!explicit_int && !defaulted_int
12550 && !explicit_char && !explicit_intN)
12552 if (typedef_decl)
12554 pedwarn (loc, OPT_Wpedantic,
12555 "%qs specified with typedef-name %qD",
12556 key, typedef_decl);
12557 ok = !flag_pedantic_errors;
12558 /* PR108099: __int128_t comes from c_common_nodes_and_builtins,
12559 and is not built as a typedef. */
12560 if (is_typedef_decl (typedef_decl))
12561 type = DECL_ORIGINAL_TYPE (typedef_decl);
12563 else if (declspecs->decltype_p)
12564 error_at (loc, "%qs specified with %<decltype%>", key);
12565 else
12566 error_at (loc, "%qs specified with %<typeof%>", key);
12568 else
12569 ok = 1;
12571 /* Discard the type modifiers if they are invalid. */
12572 if (! ok)
12574 unsigned_p = false;
12575 signed_p = false;
12576 long_p = false;
12577 short_p = false;
12578 longlong = 0;
12582 /* Decide whether an integer type is signed or not.
12583 Optionally treat bitfields as signed by default. */
12584 if (unsigned_p
12585 /* [class.bit]
12587 It is implementation-defined whether a plain (neither
12588 explicitly signed or unsigned) char, short, int, or long
12589 bit-field is signed or unsigned.
12591 Naturally, we extend this to long long as well. Note that
12592 this does not include wchar_t. */
12593 || (bitfield && !flag_signed_bitfields
12594 && !signed_p
12595 /* A typedef for plain `int' without `signed' can be
12596 controlled just like plain `int', but a typedef for
12597 `signed int' cannot be so controlled. */
12598 && !(typedef_decl
12599 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12600 && TREE_CODE (type) == INTEGER_TYPE
12601 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12603 if (explicit_intN)
12604 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12605 else if (longlong)
12606 type = long_long_unsigned_type_node;
12607 else if (long_p)
12608 type = long_unsigned_type_node;
12609 else if (short_p)
12610 type = short_unsigned_type_node;
12611 else if (type == char_type_node)
12612 type = unsigned_char_type_node;
12613 else if (typedef_decl)
12614 type = c_common_unsigned_type (type);
12615 else
12616 type = unsigned_type_node;
12618 else if (signed_p && type == char_type_node)
12619 type = signed_char_type_node;
12620 else if (explicit_intN)
12621 type = int_n_trees[declspecs->int_n_idx].signed_type;
12622 else if (longlong)
12623 type = long_long_integer_type_node;
12624 else if (long_p)
12625 type = long_integer_type_node;
12626 else if (short_p)
12627 type = short_integer_type_node;
12628 else if (signed_p && typedef_decl)
12629 type = c_common_signed_type (type);
12631 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12633 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12634 error_at (declspecs->locations[ds_complex],
12635 "complex invalid for %qs", name);
12636 /* If a modifier is specified, the resulting complex is the complex
12637 form of TYPE. E.g, "complex short" is "complex short int". */
12638 else if (type == integer_type_node)
12639 type = complex_integer_type_node;
12640 else if (type == float_type_node)
12641 type = complex_float_type_node;
12642 else if (type == double_type_node)
12643 type = complex_double_type_node;
12644 else if (type == long_double_type_node)
12645 type = complex_long_double_type_node;
12646 else
12647 type = build_complex_type (type);
12650 /* If we're using the injected-class-name to form a compound type or a
12651 declaration, replace it with the underlying class so we don't get
12652 redundant typedefs in the debug output. But if we are returning the
12653 type unchanged, leave it alone so that it's available to
12654 maybe_get_template_decl_from_type_decl. */
12655 if (CLASS_TYPE_P (type)
12656 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12657 && type == TREE_TYPE (TYPE_NAME (type))
12658 && (declarator || type_quals))
12659 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12661 type_quals |= cp_type_quals (type);
12662 type = cp_build_qualified_type
12663 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12664 || declspecs->decltype_p)
12665 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12666 /* We might have ignored or rejected some of the qualifiers. */
12667 type_quals = cp_type_quals (type);
12669 if (cxx_dialect >= cxx17 && type && is_auto (type)
12670 && innermost_code != cdk_function
12671 /* Placeholder in parm gets a better error below. */
12672 && !(decl_context == PARM || decl_context == CATCHPARM)
12673 && id_declarator && declarator != id_declarator)
12674 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12676 auto_diagnostic_group g;
12677 gcc_rich_location richloc (typespec_loc);
12678 richloc.add_fixit_insert_after ("<>");
12679 error_at (&richloc, "missing template argument list after %qE; "
12680 "for deduction, template placeholder must be followed "
12681 "by a simple declarator-id", tmpl);
12682 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12683 type = error_mark_node;
12686 staticp = 0;
12687 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12688 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12689 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12691 storage_class = declspecs->storage_class;
12692 if (storage_class == sc_static)
12693 staticp = 1 + (decl_context == FIELD);
12694 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12695 /* Treat class-scope deduction guides as static member functions
12696 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12697 staticp = 2;
12699 if (virtualp)
12701 if (staticp == 2)
12703 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12704 richloc.add_range (declspecs->locations[ds_storage_class]);
12705 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12706 "and %<static%>", dname);
12707 storage_class = sc_none;
12708 staticp = 0;
12710 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12712 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12713 richloc.add_range (declspecs->locations[ds_constexpr]);
12714 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12715 "declared both %<virtual%> and %<constexpr%> only in "
12716 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12719 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12721 /* Issue errors about use of storage classes for parameters. */
12722 if (decl_context == PARM)
12724 if (typedef_p)
12726 error_at (declspecs->locations[ds_typedef],
12727 "typedef declaration invalid in parameter declaration");
12728 return error_mark_node;
12730 else if (template_parm_flag && storage_class != sc_none)
12732 error_at (min_location (declspecs->locations[ds_thread],
12733 declspecs->locations[ds_storage_class]),
12734 "storage class specified for template parameter %qs",
12735 name);
12736 return error_mark_node;
12738 else if (storage_class == sc_static
12739 || storage_class == sc_extern
12740 || thread_p)
12742 error_at (min_location (declspecs->locations[ds_thread],
12743 declspecs->locations[ds_storage_class]),
12744 "storage class specified for parameter %qs", name);
12745 return error_mark_node;
12748 /* Function parameters cannot be concept. */
12749 if (concept_p)
12751 error_at (declspecs->locations[ds_concept],
12752 "a parameter cannot be declared %qs", "concept");
12753 concept_p = 0;
12754 constexpr_p = 0;
12756 /* Function parameters cannot be constexpr. If we saw one, moan
12757 and pretend it wasn't there. */
12758 else if (constexpr_p)
12760 error_at (declspecs->locations[ds_constexpr],
12761 "a parameter cannot be declared %qs", "constexpr");
12762 constexpr_p = 0;
12764 if (constinit_p)
12766 error_at (declspecs->locations[ds_constinit],
12767 "a parameter cannot be declared %qs", "constinit");
12768 constinit_p = 0;
12770 if (consteval_p)
12772 error_at (declspecs->locations[ds_consteval],
12773 "a parameter cannot be declared %qs", "consteval");
12774 consteval_p = 0;
12778 /* Give error if `virtual' is used outside of class declaration. */
12779 if (virtualp
12780 && (current_class_name == NULL_TREE || decl_context != FIELD))
12782 error_at (declspecs->locations[ds_virtual],
12783 "%<virtual%> outside class declaration");
12784 virtualp = 0;
12787 if (innermost_code == cdk_decomp)
12789 location_t loc = (declarator->kind == cdk_reference
12790 ? declarator->declarator->id_loc : declarator->id_loc);
12791 if (inlinep)
12792 error_at (declspecs->locations[ds_inline],
12793 "structured binding declaration cannot be %qs", "inline");
12794 if (typedef_p)
12795 error_at (declspecs->locations[ds_typedef],
12796 "structured binding declaration cannot be %qs", "typedef");
12797 if (constexpr_p && !concept_p)
12798 error_at (declspecs->locations[ds_constexpr], "structured "
12799 "binding declaration cannot be %qs", "constexpr");
12800 if (consteval_p)
12801 error_at (declspecs->locations[ds_consteval], "structured "
12802 "binding declaration cannot be %qs", "consteval");
12803 if (thread_p && cxx_dialect < cxx20)
12804 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
12805 "structured binding declaration can be %qs only in "
12806 "%<-std=c++20%> or %<-std=gnu++20%>",
12807 declspecs->gnu_thread_keyword_p
12808 ? "__thread" : "thread_local");
12809 if (concept_p)
12810 error_at (declspecs->locations[ds_concept],
12811 "structured binding declaration cannot be %qs", "concept");
12812 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
12813 if (type_quals & TYPE_QUAL_VOLATILE)
12814 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
12815 "%<volatile%>-qualified structured binding is deprecated");
12816 switch (storage_class)
12818 case sc_none:
12819 break;
12820 case sc_register:
12821 error_at (loc, "structured binding declaration cannot be %qs",
12822 "register");
12823 break;
12824 case sc_static:
12825 if (cxx_dialect < cxx20)
12826 pedwarn (loc, OPT_Wc__20_extensions,
12827 "structured binding declaration can be %qs only in "
12828 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
12829 break;
12830 case sc_extern:
12831 error_at (loc, "structured binding declaration cannot be %qs",
12832 "extern");
12833 break;
12834 case sc_mutable:
12835 error_at (loc, "structured binding declaration cannot be %qs",
12836 "mutable");
12837 break;
12838 case sc_auto:
12839 error_at (loc, "structured binding declaration cannot be "
12840 "C++98 %<auto%>");
12841 break;
12842 default:
12843 gcc_unreachable ();
12845 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
12846 || TYPE_IDENTIFIER (type) != auto_identifier)
12848 if (type != error_mark_node)
12850 auto_diagnostic_group d;
12851 error_at (loc, "structured binding declaration cannot have "
12852 "type %qT", type);
12853 inform (loc,
12854 "type must be cv-qualified %<auto%> or reference to "
12855 "cv-qualified %<auto%>");
12857 type = build_qualified_type (make_auto (), type_quals);
12858 declspecs->type = type;
12860 else if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type))
12861 pedwarn (loc, OPT_Wpedantic,
12862 "structured binding declaration cannot have constrained "
12863 "%<auto%> type %qT", type);
12864 inlinep = 0;
12865 typedef_p = 0;
12866 constexpr_p = 0;
12867 consteval_p = 0;
12868 concept_p = 0;
12869 if (storage_class != sc_static)
12871 storage_class = sc_none;
12872 declspecs->storage_class = sc_none;
12876 /* Static anonymous unions are dealt with here. */
12877 if (staticp && decl_context == TYPENAME
12878 && declspecs->type
12879 && ANON_AGGR_TYPE_P (declspecs->type))
12880 decl_context = FIELD;
12882 /* Warn about storage classes that are invalid for certain
12883 kinds of declarations (parameters, typenames, etc.). */
12884 if (thread_p
12885 && ((storage_class
12886 && storage_class != sc_extern
12887 && storage_class != sc_static)
12888 || typedef_p))
12890 location_t loc
12891 = min_location (declspecs->locations[ds_thread],
12892 declspecs->locations[ds_storage_class]);
12893 error_at (loc, "multiple storage classes in declaration of %qs", name);
12894 thread_p = false;
12896 if (decl_context != NORMAL
12897 && ((storage_class != sc_none
12898 && storage_class != sc_mutable)
12899 || thread_p))
12901 if ((decl_context == PARM || decl_context == CATCHPARM)
12902 && (storage_class == sc_register
12903 || storage_class == sc_auto))
12905 else if (typedef_p)
12907 else if (decl_context == FIELD
12908 /* C++ allows static class elements. */
12909 && storage_class == sc_static)
12910 /* C++ also allows inlines and signed and unsigned elements,
12911 but in those cases we don't come in here. */
12913 else
12915 location_t loc
12916 = min_location (declspecs->locations[ds_thread],
12917 declspecs->locations[ds_storage_class]);
12918 if (decl_context == FIELD)
12919 error_at (loc, "storage class specified for %qs", name);
12920 else if (decl_context == PARM || decl_context == CATCHPARM)
12921 error_at (loc, "storage class specified for parameter %qs", name);
12922 else
12923 error_at (loc, "storage class specified for typename");
12924 if (storage_class == sc_register
12925 || storage_class == sc_auto
12926 || storage_class == sc_extern
12927 || thread_p)
12928 storage_class = sc_none;
12931 else if (storage_class == sc_extern && funcdef_flag
12932 && ! toplevel_bindings_p ())
12933 error ("nested function %qs declared %<extern%>", name);
12934 else if (toplevel_bindings_p ())
12936 if (storage_class == sc_auto)
12937 error_at (declspecs->locations[ds_storage_class],
12938 "top-level declaration of %qs specifies %<auto%>", name);
12940 else if (thread_p
12941 && storage_class != sc_extern
12942 && storage_class != sc_static)
12944 if (declspecs->gnu_thread_keyword_p)
12945 pedwarn (declspecs->locations[ds_thread],
12946 0, "function-scope %qs implicitly auto and "
12947 "declared %<__thread%>", name);
12949 /* When thread_local is applied to a variable of block scope the
12950 storage-class-specifier static is implied if it does not appear
12951 explicitly. */
12952 storage_class = declspecs->storage_class = sc_static;
12953 staticp = 1;
12956 if (storage_class && friendp)
12958 error_at (min_location (declspecs->locations[ds_thread],
12959 declspecs->locations[ds_storage_class]),
12960 "storage class specifiers invalid in friend function "
12961 "declarations");
12962 storage_class = sc_none;
12963 staticp = 0;
12966 if (!id_declarator)
12967 unqualified_id = NULL_TREE;
12968 else
12970 unqualified_id = id_declarator->u.id.unqualified_name;
12971 switch (TREE_CODE (unqualified_id))
12973 case BIT_NOT_EXPR:
12974 unqualified_id = TREE_OPERAND (unqualified_id, 0);
12975 if (TYPE_P (unqualified_id))
12976 unqualified_id = constructor_name (unqualified_id);
12977 break;
12979 case IDENTIFIER_NODE:
12980 case TEMPLATE_ID_EXPR:
12981 break;
12983 default:
12984 gcc_unreachable ();
12988 if (declspecs->std_attributes
12989 && !diagnose_misapplied_contracts (declspecs->std_attributes))
12991 location_t attr_loc = declspecs->locations[ds_std_attribute];
12992 if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
12993 inform (attr_loc, "an attribute that appertains to a type-specifier "
12994 "is ignored");
12997 if (attrlist)
12998 diagnose_misapplied_contracts (*attrlist);
13000 /* Determine the type of the entity declared by recurring on the
13001 declarator. */
13002 for (; declarator; declarator = declarator->declarator)
13004 const cp_declarator *inner_declarator;
13005 tree attrs;
13007 if (type == error_mark_node)
13008 return error_mark_node;
13010 attrs = declarator->attributes;
13011 if (attrs)
13013 int attr_flags;
13015 attr_flags = 0;
13016 if (declarator->kind == cdk_id)
13017 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
13018 if (declarator->kind == cdk_function)
13019 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
13020 if (declarator->kind == cdk_array)
13021 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
13022 tree late_attrs = NULL_TREE;
13023 if (decl_context != PARM && decl_context != TYPENAME)
13024 /* Assume that any attributes that get applied late to
13025 templates will DTRT when applied to the declaration
13026 as a whole. */
13027 late_attrs = splice_template_attributes (&attrs, type);
13028 returned_attrs = decl_attributes (&type,
13029 attr_chainon (returned_attrs,
13030 attrs),
13031 attr_flags);
13032 returned_attrs = attr_chainon (late_attrs, returned_attrs);
13035 inner_declarator = declarator->declarator;
13037 /* Check that contracts aren't misapplied. */
13038 if (tree contract_attr = find_contract (declarator->std_attributes))
13039 if (declarator->kind != cdk_function
13040 || innermost_code != cdk_function)
13041 diagnose_misapplied_contracts (contract_attr);
13043 /* We don't want to warn in parameter context because we don't
13044 yet know if the parse will succeed, and this might turn out
13045 to be a constructor call. */
13046 if (decl_context != PARM
13047 && decl_context != TYPENAME
13048 && !typedef_p
13049 && declarator->parenthesized != UNKNOWN_LOCATION
13050 /* If the type is class-like and the inner name used a
13051 global namespace qualifier, we need the parens.
13052 Unfortunately all we can tell is whether a qualified name
13053 was used or not. */
13054 && !(inner_declarator
13055 && inner_declarator->kind == cdk_id
13056 && inner_declarator->u.id.qualifying_scope
13057 && (MAYBE_CLASS_TYPE_P (type)
13058 || TREE_CODE (type) == ENUMERAL_TYPE)))
13060 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
13061 "unnecessary parentheses in declaration of %qs",
13062 name))
13064 gcc_rich_location iloc (declarator->parenthesized);
13065 iloc.add_fixit_remove (get_start (declarator->parenthesized));
13066 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
13067 inform (&iloc, "remove parentheses");
13070 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
13071 break;
13073 switch (declarator->kind)
13075 case cdk_array:
13076 type = create_array_type_for_decl (dname, type,
13077 declarator->u.array.bounds,
13078 declarator->id_loc);
13079 if (!valid_array_size_p (dname
13080 ? declarator->id_loc : input_location,
13081 type, dname))
13082 type = error_mark_node;
13084 if (declarator->std_attributes)
13085 /* [dcl.array]/1:
13087 The optional attribute-specifier-seq appertains to the
13088 array. */
13089 returned_attrs = attr_chainon (returned_attrs,
13090 declarator->std_attributes);
13091 break;
13093 case cdk_function:
13095 tree arg_types;
13096 int funcdecl_p;
13098 /* Declaring a function type. */
13100 /* Pick up type qualifiers which should be applied to `this'. */
13101 memfn_quals = declarator->u.function.qualifiers;
13102 /* Pick up virt-specifiers. */
13103 virt_specifiers = declarator->u.function.virt_specifiers;
13104 /* And ref-qualifier, too */
13105 rqual = declarator->u.function.ref_qualifier;
13106 /* And tx-qualifier. */
13107 tree tx_qual = declarator->u.function.tx_qualifier;
13108 /* Pick up the exception specifications. */
13109 raises = declarator->u.function.exception_specification;
13110 /* If the exception-specification is ill-formed, let's pretend
13111 there wasn't one. */
13112 if (raises == error_mark_node)
13113 raises = NULL_TREE;
13115 if (reqs)
13116 error_at (location_of (reqs), "requires-clause on return type");
13117 reqs = declarator->u.function.requires_clause;
13119 /* Say it's a definition only for the CALL_EXPR
13120 closest to the identifier. */
13121 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13123 /* Handle a late-specified return type. */
13124 tree late_return_type = declarator->u.function.late_return_type;
13125 if (tree auto_node = type_uses_auto (type))
13127 if (!late_return_type)
13129 if (!funcdecl_p)
13130 /* auto (*fp)() = f; is OK. */;
13131 else if (current_class_type
13132 && LAMBDA_TYPE_P (current_class_type))
13133 /* OK for C++11 lambdas. */;
13134 else if (cxx_dialect < cxx14)
13136 error_at (typespec_loc, "%qs function uses "
13137 "%<auto%> type specifier without "
13138 "trailing return type", name);
13139 inform (typespec_loc,
13140 "deduced return type only available "
13141 "with %<-std=c++14%> or %<-std=gnu++14%>");
13143 else if (virtualp)
13145 error_at (typespec_loc, "virtual function "
13146 "cannot have deduced return type");
13147 virtualp = false;
13150 else if (!is_auto (type) && sfk != sfk_conversion)
13152 error_at (typespec_loc, "%qs function with trailing "
13153 "return type has %qT as its type rather "
13154 "than plain %<auto%>", name, type);
13155 return error_mark_node;
13157 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13159 if (funcdecl_p)
13160 error_at (typespec_loc,
13161 "%qs function with trailing return type "
13162 "has %<decltype(auto)%> as its type "
13163 "rather than plain %<auto%>", name);
13164 else
13165 error_at (typespec_loc,
13166 "invalid use of %<decltype(auto)%>");
13167 return error_mark_node;
13169 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13170 if (!tmpl)
13171 if (tree late_auto = type_uses_auto (late_return_type))
13172 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13173 if (tmpl)
13175 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13177 auto_diagnostic_group g;
13178 error_at (typespec_loc, "deduced class "
13179 "type %qD in function return type",
13180 DECL_NAME (tmpl));
13181 inform (DECL_SOURCE_LOCATION (tmpl),
13182 "%qD declared here", tmpl);
13183 return error_mark_node;
13185 else if (!late_return_type)
13187 error_at (declarator->id_loc, "deduction guide "
13188 "for %qT must have trailing return "
13189 "type", TREE_TYPE (tmpl));
13190 inform (DECL_SOURCE_LOCATION (tmpl),
13191 "%qD declared here", tmpl);
13192 return error_mark_node;
13194 else if (CLASS_TYPE_P (late_return_type)
13195 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13196 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13197 == tmpl))
13198 /* OK */;
13199 else
13200 error ("trailing return type %qT of deduction guide "
13201 "is not a specialization of %qT",
13202 late_return_type, TREE_TYPE (tmpl));
13205 else if (late_return_type
13206 && sfk != sfk_conversion)
13208 if (late_return_type == error_mark_node)
13209 return error_mark_node;
13210 if (cxx_dialect < cxx11)
13211 /* Not using maybe_warn_cpp0x because this should
13212 always be an error. */
13213 error_at (typespec_loc,
13214 "trailing return type only available "
13215 "with %<-std=c++11%> or %<-std=gnu++11%>");
13216 else
13217 error_at (typespec_loc, "%qs function with trailing "
13218 "return type not declared with %<auto%> "
13219 "type specifier", name);
13220 return error_mark_node;
13222 if (late_return_type && sfk == sfk_conversion)
13224 error ("a conversion function cannot have a trailing return type");
13225 return error_mark_node;
13227 type = splice_late_return_type (type, late_return_type);
13228 if (type == error_mark_node)
13229 return error_mark_node;
13231 if (late_return_type)
13233 late_return_type_p = true;
13234 type_quals = cp_type_quals (type);
13237 if (type_quals != TYPE_UNQUALIFIED)
13239 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13240 warning for
13241 static_assert(!is_same_v<void(*)(), const void(*)()>);
13242 because there the qualifier matters. */
13243 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13244 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13245 "qualifiers ignored on function return type");
13246 /* [dcl.fct] "A volatile-qualified return type is
13247 deprecated." */
13248 if (type_quals & TYPE_QUAL_VOLATILE)
13249 warning_at (typespec_loc, OPT_Wvolatile,
13250 "%<volatile%>-qualified return type is "
13251 "deprecated");
13253 /* We now know that the TYPE_QUALS don't apply to the
13254 decl, but to its return type. */
13255 type_quals = TYPE_UNQUALIFIED;
13258 /* Error about some types functions can't return. */
13260 if (TREE_CODE (type) == FUNCTION_TYPE)
13262 error_at (typespec_loc, "%qs declared as function returning "
13263 "a function", name);
13264 return error_mark_node;
13266 if (TREE_CODE (type) == ARRAY_TYPE)
13268 error_at (typespec_loc, "%qs declared as function returning "
13269 "an array", name);
13270 return error_mark_node;
13272 if (constinit_p && funcdecl_p)
13274 error_at (declspecs->locations[ds_constinit],
13275 "%<constinit%> on function return type is not "
13276 "allowed");
13277 return error_mark_node;
13280 if (check_decltype_auto (typespec_loc, type))
13281 return error_mark_node;
13283 if (ctype == NULL_TREE
13284 && decl_context == FIELD
13285 && funcdecl_p
13286 && friendp == 0)
13287 ctype = current_class_type;
13289 if (ctype && (sfk == sfk_constructor
13290 || sfk == sfk_destructor))
13292 /* We are within a class's scope. If our declarator name
13293 is the same as the class name, and we are defining
13294 a function, then it is a constructor/destructor, and
13295 therefore returns a void type. */
13297 /* ISO C++ 12.4/2. A destructor may not be declared
13298 const or volatile. A destructor may not be static.
13299 A destructor may not be declared with ref-qualifier.
13301 ISO C++ 12.1. A constructor may not be declared
13302 const or volatile. A constructor may not be
13303 virtual. A constructor may not be static.
13304 A constructor may not be declared with ref-qualifier. */
13305 if (staticp == 2)
13306 error_at (declspecs->locations[ds_storage_class],
13307 (flags == DTOR_FLAG)
13308 ? G_("destructor cannot be static member "
13309 "function")
13310 : G_("constructor cannot be static member "
13311 "function"));
13312 if (memfn_quals)
13314 error ((flags == DTOR_FLAG)
13315 ? G_("destructors may not be cv-qualified")
13316 : G_("constructors may not be cv-qualified"));
13317 memfn_quals = TYPE_UNQUALIFIED;
13320 if (rqual)
13322 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13323 error ((flags == DTOR_FLAG)
13324 ? G_("destructors may not be ref-qualified")
13325 : G_("constructors may not be ref-qualified"));
13326 rqual = REF_QUAL_NONE;
13329 if (decl_context == FIELD
13330 && !member_function_or_else (ctype,
13331 current_class_type,
13332 flags))
13333 return error_mark_node;
13335 if (flags != DTOR_FLAG)
13337 /* It's a constructor. */
13338 if (explicitp == 1)
13339 explicitp = 2;
13340 if (virtualp)
13342 permerror (declspecs->locations[ds_virtual],
13343 "constructors cannot be declared %<virtual%>");
13344 virtualp = 0;
13346 if (decl_context == FIELD
13347 && sfk != sfk_constructor)
13348 return error_mark_node;
13350 if (decl_context == FIELD)
13351 staticp = 0;
13353 else if (friendp)
13355 if (virtualp)
13357 /* Cannot be both friend and virtual. */
13358 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13359 richloc.add_range (declspecs->locations[ds_friend]);
13360 error_at (&richloc, "virtual functions cannot be friends");
13361 friendp = 0;
13363 if (decl_context == NORMAL)
13364 error_at (declarator->id_loc,
13365 "friend declaration not in class definition");
13366 if (current_function_decl && funcdef_flag)
13368 error_at (declarator->id_loc,
13369 "cannot define friend function %qs in a local "
13370 "class definition", name);
13371 friendp = 0;
13373 /* [class.friend]/6: A function can be defined in a friend
13374 declaration if the function name is unqualified. */
13375 if (funcdef_flag && in_namespace)
13377 if (in_namespace == global_namespace)
13378 error_at (declarator->id_loc,
13379 "friend function definition %qs cannot have "
13380 "a name qualified with %<::%>", name);
13381 else
13382 error_at (declarator->id_loc,
13383 "friend function definition %qs cannot have "
13384 "a name qualified with %<%D::%>", name,
13385 in_namespace);
13388 else if (ctype && sfk == sfk_conversion)
13390 if (explicitp == 1)
13392 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13393 explicitp = 2;
13396 else if (sfk == sfk_deduction_guide)
13398 if (explicitp == 1)
13399 explicitp = 2;
13402 tree pushed_scope = NULL_TREE;
13403 if (funcdecl_p
13404 && decl_context != FIELD
13405 && inner_declarator->u.id.qualifying_scope
13406 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13407 pushed_scope
13408 = push_scope (inner_declarator->u.id.qualifying_scope);
13410 arg_types = grokparms (declarator->u.function.parameters, &parms);
13412 if (pushed_scope)
13413 pop_scope (pushed_scope);
13415 if (inner_declarator
13416 && inner_declarator->kind == cdk_id
13417 && inner_declarator->u.id.sfk == sfk_destructor
13418 && arg_types != void_list_node)
13420 error_at (declarator->id_loc,
13421 "destructors may not have parameters");
13422 arg_types = void_list_node;
13423 parms = NULL_TREE;
13426 type = build_function_type (type, arg_types);
13428 tree attrs = declarator->std_attributes;
13429 if (tx_qual)
13431 tree att = build_tree_list (tx_qual, NULL_TREE);
13432 /* transaction_safe applies to the type, but
13433 transaction_safe_dynamic applies to the function. */
13434 if (is_attribute_p ("transaction_safe", tx_qual))
13435 attrs = attr_chainon (attrs, att);
13436 else
13437 returned_attrs = attr_chainon (returned_attrs, att);
13440 /* Actually apply the contract attributes to the declaration. */
13441 for (tree *p = &attrs; *p;)
13443 tree l = *p;
13444 if (cxx_contract_attribute_p (l))
13446 *p = TREE_CHAIN (l);
13447 /* Intentionally reverse order of contracts so they're
13448 reversed back into their lexical order. */
13449 TREE_CHAIN (l) = NULL_TREE;
13450 returned_attrs = chainon (l, returned_attrs);
13452 else
13453 p = &TREE_CHAIN (l);
13456 if (attrs)
13457 /* [dcl.fct]/2:
13459 The optional attribute-specifier-seq appertains to
13460 the function type. */
13461 cplus_decl_attributes (&type, attrs, 0);
13463 if (raises)
13464 type = build_exception_variant (type, raises);
13466 break;
13468 case cdk_pointer:
13469 case cdk_reference:
13470 case cdk_ptrmem:
13471 /* Filter out pointers-to-references and references-to-references.
13472 We can get these if a TYPE_DECL is used. */
13474 if (TYPE_REF_P (type))
13476 if (declarator->kind != cdk_reference)
13478 error ("cannot declare pointer to %q#T", type);
13479 type = TREE_TYPE (type);
13482 /* In C++0x, we allow reference to reference declarations
13483 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13484 and template type arguments [14.3.1/4 temp.arg.type]. The
13485 check for direct reference to reference declarations, which
13486 are still forbidden, occurs below. Reasoning behind the change
13487 can be found in DR106, DR540, and the rvalue reference
13488 proposals. */
13489 else if (cxx_dialect == cxx98)
13491 error ("cannot declare reference to %q#T", type);
13492 type = TREE_TYPE (type);
13495 else if (VOID_TYPE_P (type))
13497 if (declarator->kind == cdk_reference)
13498 error ("cannot declare reference to %q#T", type);
13499 else if (declarator->kind == cdk_ptrmem)
13500 error ("cannot declare pointer to %q#T member", type);
13503 /* We now know that the TYPE_QUALS don't apply to the decl,
13504 but to the target of the pointer. */
13505 type_quals = TYPE_UNQUALIFIED;
13507 /* This code used to handle METHOD_TYPE, but I don't think it's
13508 possible to get it here anymore. */
13509 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13510 if (declarator->kind == cdk_ptrmem
13511 && TREE_CODE (type) == FUNCTION_TYPE)
13513 memfn_quals |= type_memfn_quals (type);
13514 type = build_memfn_type (type,
13515 declarator->u.pointer.class_type,
13516 memfn_quals,
13517 rqual);
13518 if (type == error_mark_node)
13519 return error_mark_node;
13521 rqual = REF_QUAL_NONE;
13522 memfn_quals = TYPE_UNQUALIFIED;
13525 if (TREE_CODE (type) == FUNCTION_TYPE
13526 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13527 || type_memfn_rqual (type) != REF_QUAL_NONE))
13528 error (declarator->kind == cdk_reference
13529 ? G_("cannot declare reference to qualified function type %qT")
13530 : G_("cannot declare pointer to qualified function type %qT"),
13531 type);
13533 /* When the pointed-to type involves components of variable size,
13534 care must be taken to ensure that the size evaluation code is
13535 emitted early enough to dominate all the possible later uses
13536 and late enough for the variables on which it depends to have
13537 been assigned.
13539 This is expected to happen automatically when the pointed-to
13540 type has a name/declaration of it's own, but special attention
13541 is required if the type is anonymous.
13543 We handle the NORMAL and FIELD contexts here by inserting a
13544 dummy statement that just evaluates the size at a safe point
13545 and ensures it is not deferred until e.g. within a deeper
13546 conditional context (c++/43555).
13548 We expect nothing to be needed here for PARM or TYPENAME.
13549 Evaluating the size at this point for TYPENAME would
13550 actually be incorrect, as we might be in the middle of an
13551 expression with side effects on the pointed-to type size
13552 "arguments" prior to the pointer declaration point and the
13553 size evaluation could end up prior to the side effects. */
13555 if (!TYPE_NAME (type)
13556 && (decl_context == NORMAL || decl_context == FIELD)
13557 && at_function_scope_p ()
13558 && variably_modified_type_p (type, NULL_TREE))
13560 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13561 NULL_TREE, type);
13562 add_decl_expr (TYPE_NAME (type));
13565 if (declarator->kind == cdk_reference)
13567 /* In C++0x, the type we are creating a reference to might be
13568 a typedef which is itself a reference type. In that case,
13569 we follow the reference collapsing rules in
13570 [7.1.3/8 dcl.typedef] to create the final reference type:
13572 "If a typedef TD names a type that is a reference to a type
13573 T, an attempt to create the type 'lvalue reference to cv TD'
13574 creates the type 'lvalue reference to T,' while an attempt
13575 to create the type "rvalue reference to cv TD' creates the
13576 type TD."
13578 if (VOID_TYPE_P (type))
13579 /* We already gave an error. */;
13580 else if (TYPE_REF_P (type))
13582 if (declarator->u.reference.rvalue_ref)
13583 /* Leave type alone. */;
13584 else
13585 type = cp_build_reference_type (TREE_TYPE (type), false);
13587 else
13588 type = cp_build_reference_type
13589 (type, declarator->u.reference.rvalue_ref);
13591 /* In C++0x, we need this check for direct reference to
13592 reference declarations, which are forbidden by
13593 [8.3.2/5 dcl.ref]. Reference to reference declarations
13594 are only allowed indirectly through typedefs and template
13595 type arguments. Example:
13597 void foo(int & &); // invalid ref-to-ref decl
13599 typedef int & int_ref;
13600 void foo(int_ref &); // valid ref-to-ref decl
13602 if (inner_declarator && inner_declarator->kind == cdk_reference)
13603 error ("cannot declare reference to %q#T, which is not "
13604 "a typedef or a template type argument", type);
13606 else if (TREE_CODE (type) == METHOD_TYPE)
13607 type = build_ptrmemfunc_type (build_pointer_type (type));
13608 else if (declarator->kind == cdk_ptrmem)
13610 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13611 != NAMESPACE_DECL);
13612 if (declarator->u.pointer.class_type == error_mark_node)
13613 /* We will already have complained. */
13614 type = error_mark_node;
13615 else
13616 type = build_ptrmem_type (declarator->u.pointer.class_type,
13617 type);
13619 else
13620 type = build_pointer_type (type);
13622 /* Process a list of type modifier keywords (such as
13623 const or volatile) that were given inside the `*' or `&'. */
13625 if (declarator->u.pointer.qualifiers)
13627 type
13628 = cp_build_qualified_type (type,
13629 declarator->u.pointer.qualifiers);
13630 type_quals = cp_type_quals (type);
13633 /* Apply C++11 attributes to the pointer, and not to the
13634 type pointed to. This is unlike what is done for GNU
13635 attributes above. It is to comply with [dcl.ptr]/1:
13637 [the optional attribute-specifier-seq (7.6.1) appertains
13638 to the pointer and not to the object pointed to]. */
13639 if (declarator->std_attributes)
13640 decl_attributes (&type, declarator->std_attributes,
13643 ctype = NULL_TREE;
13644 break;
13646 case cdk_error:
13647 break;
13649 default:
13650 gcc_unreachable ();
13654 id_loc = declarator ? declarator->id_loc : input_location;
13656 if (innermost_code != cdk_function
13657 /* Don't check this if it can be the artifical decltype(auto)
13658 we created when building a constraint in a compound-requirement:
13659 that the type-constraint is plain is going to be checked in
13660 cp_parser_compound_requirement. */
13661 && decl_context != TYPENAME
13662 && check_decltype_auto (id_loc, type))
13663 return error_mark_node;
13665 /* A `constexpr' specifier used in an object declaration declares
13666 the object as `const'. */
13667 if (constexpr_p && innermost_code != cdk_function)
13669 /* DR1688 says that a `constexpr' specifier in combination with
13670 `volatile' is valid. */
13672 if (!TYPE_REF_P (type))
13674 type_quals |= TYPE_QUAL_CONST;
13675 type = cp_build_qualified_type (type, type_quals);
13679 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
13680 && !FUNC_OR_METHOD_TYPE_P (type)
13681 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
13683 error ("template-id %qD used as a declarator",
13684 unqualified_id);
13685 unqualified_id = dname;
13688 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
13689 qualified with a class-name, turn it into a METHOD_TYPE, unless
13690 we know that the function is static. We take advantage of this
13691 opportunity to do other processing that pertains to entities
13692 explicitly declared to be class members. Note that if DECLARATOR
13693 is non-NULL, we know it is a cdk_id declarator; otherwise, we
13694 would not have exited the loop above. */
13695 if (declarator
13696 && declarator->kind == cdk_id
13697 && declarator->u.id.qualifying_scope
13698 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
13700 ctype = declarator->u.id.qualifying_scope;
13701 ctype = TYPE_MAIN_VARIANT (ctype);
13702 template_count = num_template_headers_for_class (ctype);
13704 if (ctype == current_class_type)
13706 if (friendp)
13708 permerror (declspecs->locations[ds_friend],
13709 "member functions are implicitly "
13710 "friends of their class");
13711 friendp = 0;
13713 else
13714 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
13715 ctype, name);
13717 else if (/* If the qualifying type is already complete, then we
13718 can skip the following checks. */
13719 !COMPLETE_TYPE_P (ctype)
13720 && (/* If the function is being defined, then
13721 qualifying type must certainly be complete. */
13722 funcdef_flag
13723 /* A friend declaration of "T::f" is OK, even if
13724 "T" is a template parameter. But, if this
13725 function is not a friend, the qualifying type
13726 must be a class. */
13727 || (!friendp && !CLASS_TYPE_P (ctype))
13728 /* For a declaration, the type need not be
13729 complete, if either it is dependent (since there
13730 is no meaningful definition of complete in that
13731 case) or the qualifying class is currently being
13732 defined. */
13733 || !(dependent_type_p (ctype)
13734 || currently_open_class (ctype)))
13735 /* Check that the qualifying type is complete. */
13736 && !complete_type_or_else (ctype, NULL_TREE))
13737 return error_mark_node;
13738 else if (TREE_CODE (type) == FUNCTION_TYPE)
13740 if (current_class_type
13741 && (!friendp || funcdef_flag || initialized))
13743 error_at (id_loc, funcdef_flag || initialized
13744 ? G_("cannot define member function %<%T::%s%> "
13745 "within %qT")
13746 : G_("cannot declare member function %<%T::%s%> "
13747 "within %qT"),
13748 ctype, name, current_class_type);
13749 return error_mark_node;
13752 else if (typedef_p && current_class_type)
13754 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
13755 ctype, name, current_class_type);
13756 return error_mark_node;
13760 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
13761 ctype = current_class_type;
13763 /* Now TYPE has the actual type. */
13765 if (returned_attrs)
13767 if (attrlist)
13768 *attrlist = attr_chainon (returned_attrs, *attrlist);
13769 else
13770 attrlist = &returned_attrs;
13773 if (declarator
13774 && declarator->kind == cdk_id
13775 && declarator->std_attributes
13776 && attrlist != NULL)
13778 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
13779 a declarator-id appertains to the entity that is declared. */
13780 if (declarator->std_attributes != error_mark_node)
13781 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
13782 else
13783 /* We should have already diagnosed the issue (c++/78344). */
13784 gcc_assert (seen_error ());
13787 /* Handle parameter packs. */
13788 if (parameter_pack_p)
13790 if (decl_context == PARM)
13791 /* Turn the type into a pack expansion.*/
13792 type = make_pack_expansion (type);
13793 else
13794 error ("non-parameter %qs cannot be a parameter pack", name);
13797 if ((decl_context == FIELD || decl_context == PARM)
13798 && !processing_template_decl
13799 && variably_modified_type_p (type, NULL_TREE))
13801 if (decl_context == FIELD)
13802 error_at (id_loc,
13803 "data member may not have variably modified type %qT", type);
13804 else
13805 error_at (id_loc,
13806 "parameter may not have variably modified type %qT", type);
13807 type = error_mark_node;
13810 if (explicitp == 1 || (explicitp && friendp))
13812 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
13813 in the declaration of a constructor or conversion function within
13814 a class definition. */
13815 if (!current_class_type)
13816 error_at (declspecs->locations[ds_explicit],
13817 "%<explicit%> outside class declaration");
13818 else if (friendp)
13819 error_at (declspecs->locations[ds_explicit],
13820 "%<explicit%> in friend declaration");
13821 else
13822 error_at (declspecs->locations[ds_explicit],
13823 "only declarations of constructors and conversion operators "
13824 "can be %<explicit%>");
13825 explicitp = 0;
13828 if (storage_class == sc_mutable)
13830 location_t sloc = declspecs->locations[ds_storage_class];
13831 if (decl_context != FIELD || friendp)
13833 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
13834 name);
13835 storage_class = sc_none;
13837 else if (decl_context == TYPENAME || typedef_p)
13839 error_at (sloc,
13840 "non-object member %qs cannot be declared %<mutable%>",
13841 name);
13842 storage_class = sc_none;
13844 else if (FUNC_OR_METHOD_TYPE_P (type))
13846 error_at (sloc, "function %qs cannot be declared %<mutable%>",
13847 name);
13848 storage_class = sc_none;
13850 else if (staticp)
13852 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
13853 name);
13854 storage_class = sc_none;
13856 else if (type_quals & TYPE_QUAL_CONST)
13858 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
13859 name);
13860 storage_class = sc_none;
13862 else if (TYPE_REF_P (type))
13864 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
13865 name);
13866 storage_class = sc_none;
13870 /* If this is declaring a typedef name, return a TYPE_DECL. */
13871 if (typedef_p && decl_context != TYPENAME)
13873 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
13874 tree decl;
13876 if (funcdef_flag)
13878 if (decl_context == NORMAL)
13879 error_at (id_loc,
13880 "typedef may not be a function definition");
13881 else
13882 error_at (id_loc,
13883 "typedef may not be a member function definition");
13884 return error_mark_node;
13887 /* This declaration:
13889 typedef void f(int) const;
13891 declares a function type which is not a member of any
13892 particular class, but which is cv-qualified; for
13893 example "f S::*" declares a pointer to a const-qualified
13894 member function of S. We record the cv-qualification in the
13895 function type. */
13896 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
13898 type = apply_memfn_quals (type, memfn_quals, rqual);
13900 /* We have now dealt with these qualifiers. */
13901 memfn_quals = TYPE_UNQUALIFIED;
13902 rqual = REF_QUAL_NONE;
13905 if (type_uses_auto (type))
13907 if (alias_p)
13908 error_at (declspecs->locations[ds_type_spec],
13909 "%<auto%> not allowed in alias declaration");
13910 else
13911 error_at (declspecs->locations[ds_type_spec],
13912 "typedef declared %<auto%>");
13913 type = error_mark_node;
13916 if (reqs)
13917 error_at (location_of (reqs), "requires-clause on typedef");
13919 if (id_declarator && declarator->u.id.qualifying_scope)
13921 error_at (id_loc, "typedef name may not be a nested-name-specifier");
13922 type = error_mark_node;
13925 if (decl_context == FIELD)
13926 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
13927 else
13928 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
13930 if (decl_context != FIELD)
13932 if (!current_function_decl)
13933 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
13934 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
13935 /* The TYPE_DECL is "abstract" because there will be
13936 clones of this constructor/destructor, and there will
13937 be copies of this TYPE_DECL generated in those
13938 clones. The decloning optimization (for space) may
13939 revert this subsequently if it determines that
13940 the clones should share a common implementation. */
13941 DECL_ABSTRACT_P (decl) = true;
13943 set_originating_module (decl);
13945 else if (current_class_type
13946 && constructor_name_p (unqualified_id, current_class_type))
13947 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
13948 "as enclosing class",
13949 unqualified_id);
13951 /* If the user declares "typedef struct {...} foo" then the
13952 struct will have an anonymous name. Fill that name in now.
13953 Nothing can refer to it, so nothing needs know about the name
13954 change. */
13955 if (type != error_mark_node
13956 && unqualified_id
13957 && TYPE_NAME (type)
13958 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
13959 && TYPE_UNNAMED_P (type)
13960 && declspecs->type_definition_p
13961 && attributes_naming_typedef_ok (*attrlist)
13962 && cp_type_quals (type) == TYPE_UNQUALIFIED)
13963 name_unnamed_type (type, decl);
13965 if (signed_p
13966 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
13967 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
13969 bad_specifiers (decl, BSP_TYPE, virtualp,
13970 memfn_quals != TYPE_UNQUALIFIED,
13971 inlinep, friendp, raises != NULL_TREE,
13972 declspecs->locations);
13974 if (alias_p)
13975 /* Acknowledge that this was written:
13976 `using analias = atype;'. */
13977 TYPE_DECL_ALIAS_P (decl) = 1;
13979 return decl;
13982 /* Detect the case of an array type of unspecified size
13983 which came, as such, direct from a typedef name.
13984 We must copy the type, so that the array's domain can be
13985 individually set by the object's initializer. */
13987 if (type && typedef_type
13988 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
13989 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
13990 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13992 /* Detect where we're using a typedef of function type to declare a
13993 function. PARMS will not be set, so we must create it now. */
13995 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
13997 tree decls = NULL_TREE;
13998 tree args;
14000 for (args = TYPE_ARG_TYPES (type);
14001 args && args != void_list_node;
14002 args = TREE_CHAIN (args))
14004 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
14005 TREE_VALUE (args));
14007 DECL_CHAIN (decl) = decls;
14008 decls = decl;
14011 parms = nreverse (decls);
14013 if (decl_context != TYPENAME)
14015 /* The qualifiers on the function type become the qualifiers on
14016 the non-static member function. */
14017 memfn_quals |= type_memfn_quals (type);
14018 rqual = type_memfn_rqual (type);
14019 type_quals = TYPE_UNQUALIFIED;
14020 raises = TYPE_RAISES_EXCEPTIONS (type);
14024 /* If this is a type name (such as, in a cast or sizeof),
14025 compute the type and return it now. */
14027 if (decl_context == TYPENAME)
14029 /* Note that here we don't care about type_quals. */
14031 /* Special case: "friend class foo" looks like a TYPENAME context. */
14032 if (friendp)
14034 if (inlinep)
14036 error ("%<inline%> specified for friend class declaration");
14037 inlinep = 0;
14040 if (!current_aggr)
14042 /* Don't allow friend declaration without a class-key. */
14043 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14044 permerror (input_location, "template parameters cannot be friends");
14045 else if (TREE_CODE (type) == TYPENAME_TYPE)
14046 permerror (input_location, "friend declaration requires class-key, "
14047 "i.e. %<friend class %T::%D%>",
14048 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
14049 else
14050 permerror (input_location, "friend declaration requires class-key, "
14051 "i.e. %<friend %#T%>",
14052 type);
14055 /* Only try to do this stuff if we didn't already give up. */
14056 if (type != integer_type_node)
14058 /* A friendly class? */
14059 if (current_class_type)
14060 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
14061 /*complain=*/true);
14062 else
14063 error ("trying to make class %qT a friend of global scope",
14064 type);
14066 type = void_type_node;
14069 else if (memfn_quals || rqual)
14071 if (ctype == NULL_TREE
14072 && TREE_CODE (type) == METHOD_TYPE)
14073 ctype = TYPE_METHOD_BASETYPE (type);
14075 if (ctype)
14076 type = build_memfn_type (type, ctype, memfn_quals, rqual);
14077 /* Core issue #547: need to allow this in template type args.
14078 Allow it in general in C++11 for alias-declarations. */
14079 else if ((template_type_arg || cxx_dialect >= cxx11)
14080 && TREE_CODE (type) == FUNCTION_TYPE)
14081 type = apply_memfn_quals (type, memfn_quals, rqual);
14082 else
14083 error ("invalid qualifiers on non-member function type");
14086 if (reqs)
14087 error_at (location_of (reqs), "requires-clause on type-id");
14089 return type;
14091 else if (unqualified_id == NULL_TREE && decl_context != PARM
14092 && decl_context != CATCHPARM
14093 && TREE_CODE (type) != UNION_TYPE
14094 && ! bitfield
14095 && innermost_code != cdk_decomp)
14097 error ("abstract declarator %qT used as declaration", type);
14098 return error_mark_node;
14101 if (!FUNC_OR_METHOD_TYPE_P (type))
14103 /* Only functions may be declared using an operator-function-id. */
14104 if (dname && IDENTIFIER_ANY_OP_P (dname))
14106 error_at (id_loc, "declaration of %qD as non-function", dname);
14107 return error_mark_node;
14110 if (reqs)
14111 error_at (location_of (reqs),
14112 "requires-clause on declaration of non-function type %qT",
14113 type);
14116 /* We don't check parameter types here because we can emit a better
14117 error message later. */
14118 if (decl_context != PARM)
14120 type = check_var_type (unqualified_id, type, id_loc);
14121 if (type == error_mark_node)
14122 return error_mark_node;
14125 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14126 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14128 if (decl_context == PARM || decl_context == CATCHPARM)
14130 if (ctype || in_namespace)
14131 error ("cannot use %<::%> in parameter declaration");
14133 tree auto_node = type_uses_auto (type);
14134 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14136 if (cxx_dialect >= cxx14)
14138 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14139 error_at (typespec_loc,
14140 "cannot declare a parameter with %<decltype(auto)%>");
14141 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14143 auto_diagnostic_group g;
14144 gcc_rich_location richloc (typespec_loc);
14145 richloc.add_fixit_insert_after ("<>");
14146 error_at (&richloc,
14147 "missing template argument list after %qE; template "
14148 "placeholder not permitted in parameter", c);
14149 if (decl_context == PARM && cxx_dialect >= cxx20)
14150 inform (typespec_loc, "or use %<auto%> for an "
14151 "abbreviated function template");
14152 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14154 else
14155 error_at (typespec_loc,
14156 "%<auto%> parameter not permitted in this context");
14158 else
14159 error_at (typespec_loc, "parameter declared %<auto%>");
14160 type = error_mark_node;
14163 /* A parameter declared as an array of T is really a pointer to T.
14164 One declared as a function is really a pointer to a function.
14165 One declared as a member is really a pointer to member. */
14167 if (TREE_CODE (type) == ARRAY_TYPE)
14169 /* Transfer const-ness of array into that of type pointed to. */
14170 type = build_pointer_type (TREE_TYPE (type));
14171 type_quals = TYPE_UNQUALIFIED;
14172 array_parameter_p = true;
14174 else if (TREE_CODE (type) == FUNCTION_TYPE)
14175 type = build_pointer_type (type);
14178 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14179 && !(unqualified_id
14180 && identifier_p (unqualified_id)
14181 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14183 cp_cv_quals real_quals = memfn_quals;
14184 if (cxx_dialect < cxx14 && constexpr_p
14185 && sfk != sfk_constructor && sfk != sfk_destructor)
14186 real_quals |= TYPE_QUAL_CONST;
14187 type = build_memfn_type (type, ctype, real_quals, rqual);
14191 tree decl = NULL_TREE;
14193 if (decl_context == PARM)
14195 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14196 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14198 bad_specifiers (decl, BSP_PARM, virtualp,
14199 memfn_quals != TYPE_UNQUALIFIED,
14200 inlinep, friendp, raises != NULL_TREE,
14201 declspecs->locations);
14203 else if (decl_context == FIELD)
14205 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14206 if (tree auto_node = type_uses_auto (type))
14208 location_t tloc = declspecs->locations[ds_type_spec];
14209 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14210 error_at (tloc, "invalid use of template-name %qE without an "
14211 "argument list",
14212 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14213 else
14214 error_at (tloc, "non-static data member declared with "
14215 "placeholder %qT", auto_node);
14216 type = error_mark_node;
14219 /* The C99 flexible array extension. */
14220 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14221 && TYPE_DOMAIN (type) == NULL_TREE)
14223 if (ctype
14224 && (TREE_CODE (ctype) == UNION_TYPE
14225 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14227 error_at (id_loc, "flexible array member in union");
14228 type = error_mark_node;
14230 else
14232 /* Array is a flexible member. */
14233 if (name)
14234 pedwarn (id_loc, OPT_Wpedantic,
14235 "ISO C++ forbids flexible array member %qs", name);
14236 else
14237 pedwarn (input_location, OPT_Wpedantic,
14238 "ISO C++ forbids flexible array members");
14240 /* Flexible array member has a null domain. */
14241 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14245 if (type == error_mark_node)
14247 /* Happens when declaring arrays of sizes which
14248 are error_mark_node, for example. */
14249 decl = NULL_TREE;
14251 else if (in_namespace && !friendp)
14253 /* Something like struct S { int N::j; }; */
14254 error_at (id_loc, "invalid use of %<::%>");
14255 return error_mark_node;
14257 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14259 int publicp = 0;
14260 tree function_context;
14262 if (friendp == 0)
14264 /* This should never happen in pure C++ (the check
14265 could be an assert). It could happen in
14266 Objective-C++ if someone writes invalid code that
14267 uses a function declaration for an instance
14268 variable or property (instance variables and
14269 properties are parsed as FIELD_DECLs, but they are
14270 part of an Objective-C class, not a C++ class).
14271 That code is invalid and is caught by this
14272 check. */
14273 if (!ctype)
14275 error ("declaration of function %qD in invalid context",
14276 unqualified_id);
14277 return error_mark_node;
14280 /* ``A union may [ ... ] not [ have ] virtual functions.''
14281 ARM 9.5 */
14282 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14284 error_at (declspecs->locations[ds_virtual],
14285 "function %qD declared %<virtual%> inside a union",
14286 unqualified_id);
14287 return error_mark_node;
14290 if (virtualp
14291 && identifier_p (unqualified_id)
14292 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14294 error_at (declspecs->locations[ds_virtual],
14295 "%qD cannot be declared %<virtual%>, since it "
14296 "is always static", unqualified_id);
14297 virtualp = 0;
14301 /* Check that the name used for a destructor makes sense. */
14302 if (sfk == sfk_destructor)
14304 tree uqname = id_declarator->u.id.unqualified_name;
14306 if (!ctype)
14308 gcc_assert (friendp);
14309 error_at (id_loc, "expected qualified name in friend "
14310 "declaration for destructor %qD", uqname);
14311 return error_mark_node;
14314 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14316 error_at (id_loc, "declaration of %qD as member of %qT",
14317 uqname, ctype);
14318 return error_mark_node;
14320 if (concept_p)
14322 error_at (declspecs->locations[ds_concept],
14323 "a destructor cannot be %qs", "concept");
14324 return error_mark_node;
14326 if (constexpr_p && cxx_dialect < cxx20)
14328 error_at (declspecs->locations[ds_constexpr],
14329 "%<constexpr%> destructors only available"
14330 " with %<-std=c++20%> or %<-std=gnu++20%>");
14331 return error_mark_node;
14333 if (consteval_p)
14335 error_at (declspecs->locations[ds_consteval],
14336 "a destructor cannot be %qs", "consteval");
14337 return error_mark_node;
14340 else if (sfk == sfk_constructor && friendp && !ctype)
14342 error ("expected qualified name in friend declaration "
14343 "for constructor %qD",
14344 id_declarator->u.id.unqualified_name);
14345 return error_mark_node;
14347 if (sfk == sfk_constructor)
14348 if (concept_p)
14350 error_at (declspecs->locations[ds_concept],
14351 "a constructor cannot be %<concept%>");
14352 return error_mark_node;
14354 if (concept_p)
14356 error_at (declspecs->locations[ds_concept],
14357 "a concept cannot be a member function");
14358 concept_p = false;
14360 else if (consteval_p
14361 && identifier_p (unqualified_id)
14362 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14364 error_at (declspecs->locations[ds_consteval],
14365 "%qD cannot be %qs", unqualified_id, "consteval");
14366 consteval_p = false;
14369 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14371 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14372 if (variable_template_p (tmpl))
14374 error_at (id_loc, "specialization of variable template "
14375 "%qD declared as function", tmpl);
14376 inform (DECL_SOURCE_LOCATION (tmpl),
14377 "variable template declared here");
14378 return error_mark_node;
14382 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14383 function_context
14384 = (ctype != NULL_TREE
14385 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14386 publicp = ((! friendp || ! staticp)
14387 && function_context == NULL_TREE);
14389 decl = grokfndecl (ctype, type,
14390 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14391 ? unqualified_id : dname,
14392 parms,
14393 unqualified_id,
14394 declspecs,
14395 reqs,
14396 virtualp, flags, memfn_quals, rqual, raises,
14397 friendp ? -1 : 0, friendp, publicp,
14398 inlinep | (2 * constexpr_p) | (4 * concept_p)
14399 | (8 * consteval_p),
14400 initialized == SD_DELETED, sfk,
14401 funcdef_flag, late_return_type_p,
14402 template_count, in_namespace,
14403 attrlist, id_loc);
14404 decl = set_virt_specifiers (decl, virt_specifiers);
14405 if (decl == NULL_TREE)
14406 return error_mark_node;
14407 #if 0
14408 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14409 /* The decl and setting of decl_attr is also turned off. */
14410 decl = build_decl_attribute_variant (decl, decl_attr);
14411 #endif
14413 /* [class.conv.ctor]
14415 A constructor declared without the function-specifier
14416 explicit that can be called with a single parameter
14417 specifies a conversion from the type of its first
14418 parameter to the type of its class. Such a constructor
14419 is called a converting constructor. */
14420 if (explicitp == 2)
14421 DECL_NONCONVERTING_P (decl) = 1;
14423 if (declspecs->explicit_specifier)
14424 store_explicit_specifier (decl, declspecs->explicit_specifier);
14426 else if (!staticp
14427 && ((current_class_type
14428 && same_type_p (type, current_class_type))
14429 || (!dependent_type_p (type)
14430 && !COMPLETE_TYPE_P (complete_type (type))
14431 && (!complete_or_array_type_p (type)
14432 || initialized == SD_UNINITIALIZED))))
14434 if (TREE_CODE (type) != ARRAY_TYPE
14435 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14437 if (unqualified_id)
14439 error_at (id_loc, "field %qD has incomplete type %qT",
14440 unqualified_id, type);
14441 cxx_incomplete_type_inform (strip_array_types (type));
14443 else
14444 error ("name %qT has incomplete type", type);
14446 type = error_mark_node;
14447 decl = NULL_TREE;
14450 else if (!verify_type_context (input_location,
14451 staticp
14452 ? TCTX_STATIC_STORAGE
14453 : TCTX_FIELD, type))
14455 type = error_mark_node;
14456 decl = NULL_TREE;
14458 else
14460 if (friendp)
14462 if (unqualified_id)
14463 error_at (id_loc,
14464 "%qE is neither function nor member function; "
14465 "cannot be declared friend", unqualified_id);
14466 else
14467 error ("unnamed field is neither function nor member "
14468 "function; cannot be declared friend");
14469 return error_mark_node;
14471 decl = NULL_TREE;
14474 if (friendp)
14476 /* Packages tend to use GNU attributes on friends, so we only
14477 warn for standard attributes. */
14478 if (attrlist
14479 && !funcdef_flag
14480 && cxx11_attribute_p (*attrlist)
14481 && !all_attributes_are_contracts_p (*attrlist))
14483 *attrlist = NULL_TREE;
14484 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14485 inform (id_loc, "an attribute that appertains to a friend "
14486 "declaration that is not a definition is ignored");
14488 /* Friends are treated specially. */
14489 if (ctype == current_class_type)
14490 ; /* We already issued a permerror. */
14491 else if (decl && DECL_NAME (decl))
14493 set_originating_module (decl, true);
14495 if (initialized)
14496 /* Kludge: We need funcdef_flag to be true in do_friend for
14497 in-class defaulted functions, but that breaks grokfndecl.
14498 So set it here. */
14499 funcdef_flag = true;
14501 cplus_decl_attributes (&decl, *attrlist, 0);
14502 *attrlist = NULL_TREE;
14504 tree scope = ctype ? ctype : in_namespace;
14505 decl = do_friend (scope, unqualified_id, decl,
14506 flags, funcdef_flag);
14507 return decl;
14509 else
14510 return error_mark_node;
14513 /* Structure field. It may not be a function, except for C++. */
14515 if (decl == NULL_TREE)
14517 if (staticp)
14519 /* C++ allows static class members. All other work
14520 for this is done by grokfield. */
14521 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14522 dname, type);
14523 if (unqualified_id
14524 && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14526 decl = check_explicit_specialization (unqualified_id, decl,
14527 template_count,
14528 concept_p * 8);
14529 if (decl == error_mark_node)
14530 return error_mark_node;
14532 set_linkage_for_static_data_member (decl);
14533 if (concept_p)
14534 error_at (declspecs->locations[ds_concept],
14535 "static data member %qE declared %qs",
14536 unqualified_id, "concept");
14537 else if (constexpr_p && !initialized)
14539 error_at (DECL_SOURCE_LOCATION (decl),
14540 "%<constexpr%> static data member %qD must "
14541 "have an initializer", decl);
14542 constexpr_p = false;
14544 if (consteval_p)
14545 error_at (declspecs->locations[ds_consteval],
14546 "static data member %qE declared %qs",
14547 unqualified_id, "consteval");
14549 if (inlinep)
14550 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14552 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14553 && !(cxx_dialect >= cxx17 && constexpr_p))
14554 /* Even if there is an in-class initialization, DECL
14555 is considered undefined until an out-of-class
14556 definition is provided, unless this is an inline
14557 variable. */
14558 DECL_EXTERNAL (decl) = 1;
14560 if (thread_p)
14562 CP_DECL_THREAD_LOCAL_P (decl) = true;
14563 if (!processing_template_decl)
14564 set_decl_tls_model (decl, decl_default_tls_model (decl));
14565 if (declspecs->gnu_thread_keyword_p)
14566 SET_DECL_GNU_TLS_P (decl);
14569 /* Set the constraints on the declaration. */
14570 bool memtmpl = (current_template_depth
14571 > template_class_depth (current_class_type));
14572 if (memtmpl)
14574 tree ci = current_template_constraints ();
14575 set_constraints (decl, ci);
14578 else
14580 if (concept_p)
14582 error_at (declspecs->locations[ds_concept],
14583 "non-static data member %qE declared %qs",
14584 unqualified_id, "concept");
14585 concept_p = false;
14586 constexpr_p = false;
14588 else if (constexpr_p)
14590 error_at (declspecs->locations[ds_constexpr],
14591 "non-static data member %qE declared %qs",
14592 unqualified_id, "constexpr");
14593 constexpr_p = false;
14595 if (constinit_p)
14597 error_at (declspecs->locations[ds_constinit],
14598 "non-static data member %qE declared %qs",
14599 unqualified_id, "constinit");
14600 constinit_p = false;
14602 if (consteval_p)
14604 error_at (declspecs->locations[ds_consteval],
14605 "non-static data member %qE declared %qs",
14606 unqualified_id, "consteval");
14607 consteval_p = false;
14609 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14610 DECL_NONADDRESSABLE_P (decl) = bitfield;
14611 if (bitfield && !unqualified_id)
14612 DECL_PADDING_P (decl) = 1;
14614 if (storage_class == sc_mutable)
14616 DECL_MUTABLE_P (decl) = 1;
14617 storage_class = sc_none;
14620 if (initialized)
14622 /* An attempt is being made to initialize a non-static
14623 member. This is new in C++11. */
14624 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14626 /* If this has been parsed with static storage class, but
14627 errors forced staticp to be cleared, ensure NSDMI is
14628 not present. */
14629 if (declspecs->storage_class == sc_static)
14630 DECL_INITIAL (decl) = error_mark_node;
14634 bad_specifiers (decl, BSP_FIELD, virtualp,
14635 memfn_quals != TYPE_UNQUALIFIED,
14636 staticp ? false : inlinep, friendp,
14637 raises != NULL_TREE,
14638 declspecs->locations);
14641 else if (FUNC_OR_METHOD_TYPE_P (type))
14643 tree original_name;
14644 int publicp = 0;
14646 if (!unqualified_id)
14647 return error_mark_node;
14649 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14650 original_name = dname;
14651 else
14652 original_name = unqualified_id;
14653 // FIXME:gcc_assert (original_name == dname);
14655 if (storage_class == sc_auto)
14656 error_at (declspecs->locations[ds_storage_class],
14657 "storage class %<auto%> invalid for function %qs", name);
14658 else if (storage_class == sc_register)
14659 error_at (declspecs->locations[ds_storage_class],
14660 "storage class %<register%> invalid for function %qs",
14661 name);
14662 else if (thread_p)
14664 if (declspecs->gnu_thread_keyword_p)
14665 error_at (declspecs->locations[ds_thread],
14666 "storage class %<__thread%> invalid for function %qs",
14667 name);
14668 else
14669 error_at (declspecs->locations[ds_thread],
14670 "storage class %<thread_local%> invalid for "
14671 "function %qs", name);
14673 else if (constinit_p)
14674 error_at (declspecs->locations[ds_constinit],
14675 "%<constinit%> specifier invalid for function %qs", name);
14677 if (virt_specifiers)
14678 error ("virt-specifiers in %qs not allowed outside a class "
14679 "definition", name);
14680 /* Function declaration not at top level.
14681 Storage classes other than `extern' are not allowed
14682 and `extern' makes no difference. */
14683 if (! toplevel_bindings_p ()
14684 && (storage_class == sc_static
14685 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
14686 && pedantic)
14688 if (storage_class == sc_static)
14689 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
14690 "%<static%> specifier invalid for function %qs "
14691 "declared out of global scope", name);
14692 else
14693 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
14694 "%<inline%> specifier invalid for function %qs "
14695 "declared out of global scope", name);
14698 if (ctype == NULL_TREE)
14700 if (virtualp)
14702 error ("virtual non-class function %qs", name);
14703 virtualp = 0;
14705 else if (sfk == sfk_constructor
14706 || sfk == sfk_destructor)
14708 error (funcdef_flag
14709 ? G_("%qs defined in a non-class scope")
14710 : G_("%qs declared in a non-class scope"), name);
14711 sfk = sfk_none;
14714 if (consteval_p
14715 && identifier_p (unqualified_id)
14716 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14718 error_at (declspecs->locations[ds_consteval],
14719 "%qD cannot be %qs", unqualified_id, "consteval");
14720 consteval_p = false;
14723 /* Record whether the function is public. */
14724 publicp = (ctype != NULL_TREE
14725 || storage_class != sc_static);
14727 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
14728 declspecs,
14729 reqs, virtualp, flags, memfn_quals, rqual, raises,
14730 1, friendp,
14731 publicp,
14732 inlinep | (2 * constexpr_p) | (4 * concept_p)
14733 | (8 * consteval_p),
14734 initialized == SD_DELETED,
14735 sfk,
14736 funcdef_flag,
14737 late_return_type_p,
14738 template_count, in_namespace, attrlist,
14739 id_loc);
14740 if (decl == NULL_TREE)
14741 return error_mark_node;
14743 if (explicitp == 2)
14744 DECL_NONCONVERTING_P (decl) = 1;
14745 if (staticp == 1)
14747 int invalid_static = 0;
14749 /* Don't allow a static member function in a class, and forbid
14750 declaring main to be static. */
14751 if (TREE_CODE (type) == METHOD_TYPE)
14753 permerror (input_location, "cannot declare member function %qD to have "
14754 "static linkage", decl);
14755 invalid_static = 1;
14757 else if (current_function_decl)
14759 /* 7.1.1: There can be no static function declarations within a
14760 block. */
14761 error_at (declspecs->locations[ds_storage_class],
14762 "cannot declare static function inside another function");
14763 invalid_static = 1;
14766 if (invalid_static)
14768 staticp = 0;
14769 storage_class = sc_none;
14772 if (declspecs->explicit_specifier)
14773 store_explicit_specifier (decl, declspecs->explicit_specifier);
14775 else
14777 /* It's a variable. */
14779 /* An uninitialized decl with `extern' is a reference. */
14780 decl = grokvardecl (type, dname, unqualified_id,
14781 declspecs,
14782 initialized,
14783 type_quals,
14784 inlinep,
14785 concept_p,
14786 template_count,
14787 ctype ? ctype : in_namespace,
14788 id_loc);
14789 if (decl == NULL_TREE)
14790 return error_mark_node;
14792 bad_specifiers (decl, BSP_VAR, virtualp,
14793 memfn_quals != TYPE_UNQUALIFIED,
14794 inlinep, friendp, raises != NULL_TREE,
14795 declspecs->locations);
14797 if (ctype)
14799 DECL_CONTEXT (decl) = ctype;
14800 if (staticp == 1)
14802 permerror (declspecs->locations[ds_storage_class],
14803 "%<static%> may not be used when defining "
14804 "(as opposed to declaring) a static data member");
14805 staticp = 0;
14806 storage_class = sc_none;
14808 if (storage_class == sc_register && TREE_STATIC (decl))
14810 error ("static member %qD declared %<register%>", decl);
14811 storage_class = sc_none;
14813 if (storage_class == sc_extern && pedantic)
14815 pedwarn (input_location, OPT_Wpedantic,
14816 "cannot explicitly declare member %q#D to have "
14817 "extern linkage", decl);
14818 storage_class = sc_none;
14821 else if (constexpr_p && DECL_EXTERNAL (decl))
14823 error_at (DECL_SOURCE_LOCATION (decl),
14824 "declaration of %<constexpr%> variable %qD "
14825 "is not a definition", decl);
14826 constexpr_p = false;
14828 if (consteval_p)
14830 error_at (DECL_SOURCE_LOCATION (decl),
14831 "a variable cannot be declared %<consteval%>");
14832 consteval_p = false;
14835 if (inlinep)
14836 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14837 if (innermost_code == cdk_decomp)
14839 gcc_assert (declarator && declarator->kind == cdk_decomp);
14840 DECL_SOURCE_LOCATION (decl) = id_loc;
14841 DECL_ARTIFICIAL (decl) = 1;
14842 fit_decomposition_lang_decl (decl, NULL_TREE);
14846 if (VAR_P (decl) && !initialized)
14847 if (tree auto_node = type_uses_auto (type))
14848 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14850 location_t loc = declspecs->locations[ds_type_spec];
14851 error_at (loc, "declaration of %q#D has no initializer", decl);
14852 TREE_TYPE (decl) = error_mark_node;
14855 if (storage_class == sc_extern && initialized && !funcdef_flag)
14857 if (toplevel_bindings_p ())
14859 /* It's common practice (and completely valid) to have a const
14860 be initialized and declared extern. */
14861 if (!(type_quals & TYPE_QUAL_CONST))
14862 warning_at (DECL_SOURCE_LOCATION (decl), 0,
14863 "%qs initialized and declared %<extern%>", name);
14865 else
14867 error_at (DECL_SOURCE_LOCATION (decl),
14868 "%qs has both %<extern%> and initializer", name);
14869 return error_mark_node;
14873 /* Record `register' declaration for warnings on &
14874 and in case doing stupid register allocation. */
14876 if (storage_class == sc_register)
14878 DECL_REGISTER (decl) = 1;
14879 /* Warn about register storage specifiers on PARM_DECLs. */
14880 if (TREE_CODE (decl) == PARM_DECL)
14882 if (cxx_dialect >= cxx17)
14883 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14884 "ISO C++17 does not allow %<register%> storage "
14885 "class specifier");
14886 else
14887 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14888 "%<register%> storage class specifier used");
14891 else if (storage_class == sc_extern)
14892 DECL_THIS_EXTERN (decl) = 1;
14893 else if (storage_class == sc_static)
14894 DECL_THIS_STATIC (decl) = 1;
14896 if (VAR_P (decl))
14898 /* Set constexpr flag on vars (functions got it in grokfndecl). */
14899 if (constexpr_p)
14900 DECL_DECLARED_CONSTEXPR_P (decl) = true;
14901 /* And the constinit flag (which only applies to variables). */
14902 else if (constinit_p)
14903 DECL_DECLARED_CONSTINIT_P (decl) = true;
14905 else if (TREE_CODE (decl) == FUNCTION_DECL)
14907 /* If we saw a return type, record its location. */
14908 location_t loc = declspecs->locations[ds_type_spec];
14909 if (loc == UNKNOWN_LOCATION)
14910 /* Build DECL_RESULT in start_preparsed_function. */;
14911 else if (!DECL_RESULT (decl))
14913 tree restype = TREE_TYPE (TREE_TYPE (decl));
14914 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
14915 DECL_ARTIFICIAL (resdecl) = 1;
14916 DECL_IGNORED_P (resdecl) = 1;
14917 DECL_RESULT (decl) = resdecl;
14919 else if (funcdef_flag)
14920 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
14923 /* Record constancy and volatility on the DECL itself . There's
14924 no need to do this when processing a template; we'll do this
14925 for the instantiated declaration based on the type of DECL. */
14926 if (!processing_template_decl)
14927 cp_apply_type_quals_to_decl (type_quals, decl);
14929 return decl;
14933 /* Subroutine of start_function. Ensure that each of the parameter
14934 types (as listed in PARMS) is complete, as is required for a
14935 function definition. */
14937 static void
14938 require_complete_types_for_parms (tree parms)
14940 for (; parms; parms = DECL_CHAIN (parms))
14942 if (dependent_type_p (TREE_TYPE (parms)))
14943 continue;
14944 if (!VOID_TYPE_P (TREE_TYPE (parms))
14945 && complete_type_or_else (TREE_TYPE (parms), parms))
14947 relayout_decl (parms);
14948 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
14950 abstract_virtuals_error (parms, TREE_TYPE (parms));
14951 maybe_warn_parm_abi (TREE_TYPE (parms),
14952 DECL_SOURCE_LOCATION (parms));
14954 else
14955 /* grokparms or complete_type_or_else will have already issued
14956 an error. */
14957 TREE_TYPE (parms) = error_mark_node;
14961 /* Returns nonzero if T is a local variable. */
14964 local_variable_p (const_tree t)
14966 if ((VAR_P (t)
14967 && (DECL_LOCAL_DECL_P (t)
14968 || !DECL_CONTEXT (t)
14969 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
14970 || (TREE_CODE (t) == PARM_DECL))
14971 return 1;
14973 return 0;
14976 /* Like local_variable_p, but suitable for use as a tree-walking
14977 function. */
14979 static tree
14980 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
14981 void * /*data*/)
14983 if (unevaluated_p (TREE_CODE (*tp)))
14985 /* DR 2082 permits local variables in unevaluated contexts
14986 within a default argument. */
14987 *walk_subtrees = 0;
14988 return NULL_TREE;
14991 if (local_variable_p (*tp)
14992 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
14993 return *tp;
14994 else if (TYPE_P (*tp))
14995 *walk_subtrees = 0;
14997 return NULL_TREE;
15000 /* Check that ARG, which is a default-argument expression for a
15001 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
15002 something goes wrong. DECL may also be a _TYPE node, rather than a
15003 DECL, if there is no DECL available. */
15005 tree
15006 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
15008 tree var;
15009 tree decl_type;
15011 if (TREE_CODE (arg) == DEFERRED_PARSE)
15012 /* We get a DEFERRED_PARSE when looking at an in-class declaration
15013 with a default argument. Ignore the argument for now; we'll
15014 deal with it after the class is complete. */
15015 return arg;
15017 if (TYPE_P (decl))
15019 decl_type = decl;
15020 decl = NULL_TREE;
15022 else
15023 decl_type = TREE_TYPE (decl);
15025 if (arg == error_mark_node
15026 || decl == error_mark_node
15027 || TREE_TYPE (arg) == error_mark_node
15028 || decl_type == error_mark_node)
15029 /* Something already went wrong. There's no need to check
15030 further. */
15031 return error_mark_node;
15033 /* [dcl.fct.default]
15035 A default argument expression is implicitly converted to the
15036 parameter type. */
15037 ++cp_unevaluated_operand;
15038 /* Avoid digest_init clobbering the initializer. */
15039 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
15040 perform_implicit_conversion_flags (decl_type, carg, complain,
15041 LOOKUP_IMPLICIT);
15042 --cp_unevaluated_operand;
15044 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
15045 the call sites. */
15046 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
15047 && null_ptr_cst_p (arg)
15048 /* Don't lose side-effects as in PR90473. */
15049 && !TREE_SIDE_EFFECTS (arg))
15050 return nullptr_node;
15052 /* [dcl.fct.default]
15054 Local variables shall not be used in default argument
15055 expressions.
15057 The keyword `this' shall not be used in a default argument of a
15058 member function. */
15059 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
15060 if (var)
15062 if (complain & tf_warning_or_error)
15064 if (DECL_NAME (var) == this_identifier)
15065 permerror (input_location, "default argument %qE uses %qD",
15066 arg, var);
15067 else
15068 error ("default argument %qE uses local variable %qD", arg, var);
15070 return error_mark_node;
15073 /* All is well. */
15074 return arg;
15077 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
15079 static tree
15080 type_is_deprecated (tree type)
15082 enum tree_code code;
15083 if (TREE_DEPRECATED (type))
15084 return type;
15085 if (TYPE_NAME (type))
15087 if (TREE_DEPRECATED (TYPE_NAME (type)))
15088 return type;
15089 else
15091 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15092 return NULL_TREE;
15096 /* Do warn about using typedefs to a deprecated class. */
15097 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15098 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15100 code = TREE_CODE (type);
15102 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15103 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15104 || code == METHOD_TYPE || code == ARRAY_TYPE)
15105 return type_is_deprecated (TREE_TYPE (type));
15107 if (TYPE_PTRMEMFUNC_P (type))
15108 return type_is_deprecated
15109 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15111 return NULL_TREE;
15114 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
15116 static tree
15117 type_is_unavailable (tree type)
15119 enum tree_code code;
15120 if (TREE_UNAVAILABLE (type))
15121 return type;
15122 if (TYPE_NAME (type))
15124 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
15125 return type;
15126 else
15128 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15129 return NULL_TREE;
15133 /* Do warn about using typedefs to a deprecated class. */
15134 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15135 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15137 code = TREE_CODE (type);
15139 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15140 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15141 || code == METHOD_TYPE || code == ARRAY_TYPE)
15142 return type_is_unavailable (TREE_TYPE (type));
15144 if (TYPE_PTRMEMFUNC_P (type))
15145 return type_is_unavailable
15146 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15148 return NULL_TREE;
15151 /* Decode the list of parameter types for a function type.
15152 Given the list of things declared inside the parens,
15153 return a list of types.
15155 If this parameter does not end with an ellipsis, we append
15156 void_list_node.
15158 *PARMS is set to the chain of PARM_DECLs created. */
15160 tree
15161 grokparms (tree parmlist, tree *parms)
15163 tree result = NULL_TREE;
15164 tree decls = NULL_TREE;
15165 tree parm;
15166 int any_error = 0;
15168 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15170 tree type = NULL_TREE;
15171 tree init = TREE_PURPOSE (parm);
15172 tree decl = TREE_VALUE (parm);
15174 if (parm == void_list_node || parm == explicit_void_list_node)
15175 break;
15177 if (! decl || TREE_TYPE (decl) == error_mark_node)
15179 any_error = 1;
15180 continue;
15183 type = TREE_TYPE (decl);
15184 if (VOID_TYPE_P (type))
15186 if (same_type_p (type, void_type_node)
15187 && !init
15188 && !DECL_NAME (decl) && !result
15189 && TREE_CHAIN (parm) == void_list_node)
15190 /* DR 577: A parameter list consisting of a single
15191 unnamed parameter of non-dependent type 'void'. */
15192 break;
15193 else if (cv_qualified_p (type))
15194 error_at (DECL_SOURCE_LOCATION (decl),
15195 "invalid use of cv-qualified type %qT in "
15196 "parameter declaration", type);
15197 else
15198 error_at (DECL_SOURCE_LOCATION (decl),
15199 "invalid use of type %<void%> in parameter "
15200 "declaration");
15201 /* It's not a good idea to actually create parameters of
15202 type `void'; other parts of the compiler assume that a
15203 void type terminates the parameter list. */
15204 type = error_mark_node;
15205 TREE_TYPE (decl) = error_mark_node;
15208 if (type != error_mark_node)
15210 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15212 tree unavailtype = type_is_unavailable (type);
15213 if (unavailtype)
15214 cp_handle_deprecated_or_unavailable (unavailtype);
15216 if (deprecated_state != DEPRECATED_SUPPRESS
15217 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15219 tree deptype = type_is_deprecated (type);
15220 if (deptype)
15221 cp_handle_deprecated_or_unavailable (deptype);
15224 /* [dcl.fct] "A parameter with volatile-qualified type is
15225 deprecated." */
15226 if (CP_TYPE_VOLATILE_P (type))
15227 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15228 "%<volatile%>-qualified parameter is "
15229 "deprecated");
15231 /* Top-level qualifiers on the parameters are
15232 ignored for function types. */
15233 type = cp_build_qualified_type (type, 0);
15234 if (TREE_CODE (type) == METHOD_TYPE)
15236 error ("parameter %qD invalidly declared method type", decl);
15237 type = build_pointer_type (type);
15238 TREE_TYPE (decl) = type;
15240 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15242 /* Before C++17 DR 393:
15243 [dcl.fct]/6, parameter types cannot contain pointers
15244 (references) to arrays of unknown bound. */
15245 tree t = TREE_TYPE (type);
15246 int ptr = TYPE_PTR_P (type);
15248 while (1)
15250 if (TYPE_PTR_P (t))
15251 ptr = 1;
15252 else if (TREE_CODE (t) != ARRAY_TYPE)
15253 break;
15254 else if (!TYPE_DOMAIN (t))
15255 break;
15256 t = TREE_TYPE (t);
15258 if (TREE_CODE (t) == ARRAY_TYPE)
15259 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15261 ? G_("parameter %qD includes pointer to array of "
15262 "unknown bound %qT")
15263 : G_("parameter %qD includes reference to array of "
15264 "unknown bound %qT"),
15265 decl, t);
15268 if (init && !processing_template_decl)
15269 init = check_default_argument (decl, init, tf_warning_or_error);
15272 DECL_CHAIN (decl) = decls;
15273 decls = decl;
15274 result = tree_cons (init, type, result);
15276 decls = nreverse (decls);
15277 result = nreverse (result);
15278 if (parm)
15279 result = chainon (result, void_list_node);
15280 *parms = decls;
15281 if (any_error)
15282 result = NULL_TREE;
15284 if (any_error)
15285 /* We had parm errors, recover by giving the function (...) type. */
15286 result = NULL_TREE;
15288 return result;
15292 /* D is a constructor or overloaded `operator='.
15294 Let T be the class in which D is declared. Then, this function
15295 returns:
15297 -1 if D's is an ill-formed constructor or copy assignment operator
15298 whose first parameter is of type `T'.
15299 0 if D is not a copy constructor or copy assignment
15300 operator.
15301 1 if D is a copy constructor or copy assignment operator whose
15302 first parameter is a reference to non-const qualified T.
15303 2 if D is a copy constructor or copy assignment operator whose
15304 first parameter is a reference to const qualified T.
15306 This function can be used as a predicate. Positive values indicate
15307 a copy constructor and nonzero values indicate a copy assignment
15308 operator. */
15311 copy_fn_p (const_tree d)
15313 tree args;
15314 tree arg_type;
15315 int result = 1;
15317 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15319 if (TREE_CODE (d) == TEMPLATE_DECL
15320 || (DECL_TEMPLATE_INFO (d)
15321 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15322 /* Instantiations of template member functions are never copy
15323 functions. Note that member functions of templated classes are
15324 represented as template functions internally, and we must
15325 accept those as copy functions. */
15326 return 0;
15328 if (!DECL_CONSTRUCTOR_P (d)
15329 && DECL_NAME (d) != assign_op_identifier)
15330 return 0;
15332 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15333 if (!args)
15334 return 0;
15336 arg_type = TREE_VALUE (args);
15337 if (arg_type == error_mark_node)
15338 return 0;
15340 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15342 /* Pass by value copy assignment operator. */
15343 result = -1;
15345 else if (TYPE_REF_P (arg_type)
15346 && !TYPE_REF_IS_RVALUE (arg_type)
15347 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15349 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15350 result = 2;
15352 else
15353 return 0;
15355 args = TREE_CHAIN (args);
15357 if (args && args != void_list_node && !TREE_PURPOSE (args))
15358 /* There are more non-optional args. */
15359 return 0;
15361 return result;
15364 /* D is a constructor or overloaded `operator='.
15366 Let T be the class in which D is declared. Then, this function
15367 returns true when D is a move constructor or move assignment
15368 operator, false otherwise. */
15370 bool
15371 move_fn_p (const_tree d)
15373 if (cxx_dialect == cxx98)
15374 /* There are no move constructors if we are in C++98 mode. */
15375 return false;
15377 if (TREE_CODE (d) == TEMPLATE_DECL
15378 || (DECL_TEMPLATE_INFO (d)
15379 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15380 /* Instantiations of template member functions are never move
15381 functions. Note that member functions of templated classes are
15382 represented as template functions internally, and we must
15383 accept those as move functions. */
15384 return 0;
15386 return move_signature_fn_p (d);
15389 /* D is a constructor or overloaded `operator='.
15391 Then, this function returns true when D has the same signature as a move
15392 constructor or move assignment operator (because either it is such a
15393 ctor/op= or it is a template specialization with the same signature),
15394 false otherwise. */
15396 bool
15397 move_signature_fn_p (const_tree d)
15399 tree args;
15400 tree arg_type;
15401 bool result = false;
15403 if (!DECL_CONSTRUCTOR_P (d)
15404 && DECL_NAME (d) != assign_op_identifier)
15405 return 0;
15407 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15408 if (!args)
15409 return 0;
15411 arg_type = TREE_VALUE (args);
15412 if (arg_type == error_mark_node)
15413 return 0;
15415 if (TYPE_REF_P (arg_type)
15416 && TYPE_REF_IS_RVALUE (arg_type)
15417 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15418 DECL_CONTEXT (d)))
15419 result = true;
15421 args = TREE_CHAIN (args);
15423 if (args && args != void_list_node && !TREE_PURPOSE (args))
15424 /* There are more non-optional args. */
15425 return false;
15427 return result;
15430 /* Remember any special properties of member function DECL. */
15432 void
15433 grok_special_member_properties (tree decl)
15435 tree class_type;
15437 if (TREE_CODE (decl) == USING_DECL
15438 || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
15439 return;
15441 class_type = DECL_CONTEXT (decl);
15442 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15444 int ctor = copy_fn_p (decl);
15446 if (!DECL_ARTIFICIAL (decl))
15447 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15449 if (ctor > 0)
15451 /* [class.copy]
15453 A non-template constructor for class X is a copy
15454 constructor if its first parameter is of type X&, const
15455 X&, volatile X& or const volatile X&, and either there
15456 are no other parameters or else all other parameters have
15457 default arguments. */
15458 TYPE_HAS_COPY_CTOR (class_type) = 1;
15459 if (ctor > 1)
15460 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15463 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15464 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15466 if (is_list_ctor (decl))
15467 TYPE_HAS_LIST_CTOR (class_type) = 1;
15469 if (maybe_constexpr_fn (decl)
15470 && !ctor && !move_fn_p (decl))
15471 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15473 else if (DECL_NAME (decl) == assign_op_identifier)
15475 /* [class.copy]
15477 A non-template assignment operator for class X is a copy
15478 assignment operator if its parameter is of type X, X&, const
15479 X&, volatile X& or const volatile X&. */
15481 int assop = copy_fn_p (decl);
15483 if (assop)
15485 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15486 if (assop != 1)
15487 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15490 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15491 TYPE_HAS_CONVERSION (class_type) = true;
15493 /* Destructors are handled in check_methods. */
15496 /* Check a constructor DECL has the correct form. Complains
15497 if the class has a constructor of the form X(X). */
15499 bool
15500 grok_ctor_properties (const_tree ctype, const_tree decl)
15502 int ctor_parm = copy_fn_p (decl);
15504 if (ctor_parm < 0)
15506 /* [class.copy]
15508 A declaration of a constructor for a class X is ill-formed if
15509 its first parameter is of type (optionally cv-qualified) X
15510 and either there are no other parameters or else all other
15511 parameters have default arguments.
15513 We *don't* complain about member template instantiations that
15514 have this form, though; they can occur as we try to decide
15515 what constructor to use during overload resolution. Since
15516 overload resolution will never prefer such a constructor to
15517 the non-template copy constructor (which is either explicitly
15518 or implicitly defined), there's no need to worry about their
15519 existence. Theoretically, they should never even be
15520 instantiated, but that's hard to forestall. */
15521 error_at (DECL_SOURCE_LOCATION (decl),
15522 "invalid constructor; you probably meant %<%T (const %T&)%>",
15523 ctype, ctype);
15524 return false;
15527 return true;
15530 /* DECL is a declaration for an overloaded or conversion operator. If
15531 COMPLAIN is true, errors are issued for invalid declarations. */
15533 bool
15534 grok_op_properties (tree decl, bool complain)
15536 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15537 bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
15538 tree name = DECL_NAME (decl);
15539 location_t loc = DECL_SOURCE_LOCATION (decl);
15541 tree class_type = DECL_CONTEXT (decl);
15542 if (class_type && !CLASS_TYPE_P (class_type))
15543 class_type = NULL_TREE;
15545 tree_code operator_code;
15546 unsigned op_flags;
15547 if (IDENTIFIER_CONV_OP_P (name))
15549 /* Conversion operators are TYPE_EXPR for the purposes of this
15550 function. */
15551 operator_code = TYPE_EXPR;
15552 op_flags = OVL_OP_FLAG_UNARY;
15554 else
15556 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15558 operator_code = ovl_op->tree_code;
15559 op_flags = ovl_op->flags;
15560 gcc_checking_assert (operator_code != ERROR_MARK);
15561 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15564 if (op_flags & OVL_OP_FLAG_ALLOC)
15566 /* operator new and operator delete are quite special. */
15567 if (class_type)
15568 switch (op_flags)
15570 case OVL_OP_FLAG_ALLOC:
15571 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15572 break;
15574 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15575 TYPE_GETS_DELETE (class_type) |= 1;
15576 break;
15578 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15579 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15580 break;
15582 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15583 TYPE_GETS_DELETE (class_type) |= 2;
15584 break;
15586 default:
15587 gcc_unreachable ();
15590 /* [basic.std.dynamic.allocation]/1:
15592 A program is ill-formed if an allocation function is declared
15593 in a namespace scope other than global scope or declared
15594 static in global scope.
15596 The same also holds true for deallocation functions. */
15597 if (DECL_NAMESPACE_SCOPE_P (decl))
15599 if (CP_DECL_CONTEXT (decl) != global_namespace)
15601 error_at (loc, "%qD may not be declared within a namespace",
15602 decl);
15603 return false;
15606 if (!TREE_PUBLIC (decl))
15608 error_at (loc, "%qD may not be declared as static", decl);
15609 return false;
15613 if (op_flags & OVL_OP_FLAG_DELETE)
15615 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15616 coerce_delete_type (decl, loc);
15618 else
15620 DECL_SET_IS_OPERATOR_NEW (decl, true);
15621 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15624 return true;
15627 /* An operator function must either be a non-static member function
15628 or have at least one parameter of a class, a reference to a class,
15629 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15630 if (! methodp || DECL_STATIC_FUNCTION_P (decl))
15632 if (operator_code == TYPE_EXPR
15633 || operator_code == COMPONENT_REF
15634 || operator_code == NOP_EXPR)
15636 error_at (loc, "%qD must be a non-static member function", decl);
15637 return false;
15640 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
15642 if (! DECL_STATIC_FUNCTION_P (decl))
15644 error_at (loc, "%qD must be a member function", decl);
15645 return false;
15647 if (cxx_dialect < cxx23
15648 /* For lambdas we diagnose static lambda specifier elsewhere. */
15649 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
15650 /* For instantiations, we have diagnosed this already. */
15651 && ! DECL_USE_TEMPLATE (decl))
15652 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
15653 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
15654 decl);
15655 if (operator_code == ARRAY_REF)
15656 /* static operator[] should have exactly one argument
15657 for C++20 and earlier, so that it isn't multidimensional. */
15658 op_flags = OVL_OP_FLAG_UNARY;
15660 else if (DECL_STATIC_FUNCTION_P (decl))
15662 error_at (loc, "%qD must be either a non-static member "
15663 "function or a non-member function", decl);
15664 return false;
15666 else
15667 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
15669 if (!arg || arg == void_list_node)
15671 if (complain)
15672 error_at (loc, "%qD must have an argument of class or "
15673 "enumerated type", decl);
15674 return false;
15677 tree type = non_reference (TREE_VALUE (arg));
15678 if (type == error_mark_node)
15679 return false;
15681 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
15682 because these checks are performed even on template
15683 functions. */
15684 if (MAYBE_CLASS_TYPE_P (type)
15685 || TREE_CODE (type) == ENUMERAL_TYPE)
15686 break;
15690 if (operator_code == CALL_EXPR)
15691 /* There are no further restrictions on the arguments to an overloaded
15692 "operator ()". */
15693 return true;
15695 /* C++23 allows an arbitrary number of parameters and default arguments for
15696 operator[], and none of the other checks below apply. */
15697 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15698 return true;
15700 if (operator_code == COND_EXPR)
15702 /* 13.4.0.3 */
15703 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
15704 return false;
15707 /* Count the number of arguments and check for ellipsis. */
15708 int arity = 0;
15709 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15711 if (!arg)
15713 error_at (loc, "%qD must not have variable number of arguments",
15714 decl);
15715 return false;
15717 ++arity;
15720 /* Verify correct number of arguments. */
15721 switch (op_flags)
15723 case OVL_OP_FLAG_AMBIARY:
15724 if (arity == 1)
15726 /* We have a unary instance of an ambi-ary op. Remap to the
15727 unary one. */
15728 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
15729 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
15730 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
15731 operator_code = ovl_op->tree_code;
15732 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15734 else if (arity != 2)
15736 /* This was an ambiguous operator but is invalid. */
15737 error_at (loc,
15738 methodp
15739 ? G_("%qD must have either zero or one argument")
15740 : G_("%qD must have either one or two arguments"), decl);
15741 return false;
15743 else if ((operator_code == POSTINCREMENT_EXPR
15744 || operator_code == POSTDECREMENT_EXPR)
15745 && ! processing_template_decl
15746 /* x++ and x--'s second argument must be an int. */
15747 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
15748 integer_type_node))
15750 error_at (loc,
15751 methodp
15752 ? G_("postfix %qD must have %<int%> as its argument")
15753 : G_("postfix %qD must have %<int%> as its second argument"),
15754 decl);
15755 return false;
15757 break;
15759 case OVL_OP_FLAG_UNARY:
15760 if (arity != 1)
15762 error_at (loc,
15763 methodp
15764 ? G_("%qD must have no arguments")
15765 : G_("%qD must have exactly one argument"), decl);
15766 return false;
15768 break;
15770 case OVL_OP_FLAG_BINARY:
15771 if (arity != 2)
15773 error_at (loc,
15774 methodp
15775 ? G_("%qD must have exactly one argument")
15776 : G_("%qD must have exactly two arguments"), decl);
15777 return false;
15779 break;
15781 default:
15782 gcc_unreachable ();
15785 /* There can be no default arguments. */
15786 for (tree arg = argtypes; arg && arg != void_list_node;
15787 arg = TREE_CHAIN (arg))
15788 if (TREE_PURPOSE (arg))
15790 TREE_PURPOSE (arg) = NULL_TREE;
15791 error_at (loc, "%qD cannot have default arguments", decl);
15792 return false;
15795 /* At this point the declaration is well-formed. It may not be
15796 sensible though. */
15798 /* Check member function warnings only on the in-class declaration.
15799 There's no point warning on an out-of-class definition. */
15800 if (class_type && class_type != current_class_type)
15801 return true;
15803 /* Warn about conversion operators that will never be used. */
15804 if (IDENTIFIER_CONV_OP_P (name)
15805 && ! DECL_TEMPLATE_INFO (decl)
15806 && warn_class_conversion)
15808 tree t = TREE_TYPE (name);
15809 int ref = TYPE_REF_P (t);
15811 if (ref)
15812 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
15814 if (VOID_TYPE_P (t))
15815 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
15816 "will never use a type conversion operator", class_type);
15817 else if (class_type)
15819 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
15820 warning_at (loc, OPT_Wclass_conversion,
15822 ? G_("converting %qT to a reference to the same type "
15823 "will never use a type conversion operator")
15824 : G_("converting %qT to the same type "
15825 "will never use a type conversion operator"),
15826 class_type);
15827 /* Don't force t to be complete here. */
15828 else if (MAYBE_CLASS_TYPE_P (t)
15829 && COMPLETE_TYPE_P (t)
15830 && DERIVED_FROM_P (t, class_type))
15831 warning_at (loc, OPT_Wclass_conversion,
15833 ? G_("converting %qT to a reference to a base class "
15834 "%qT will never use a type conversion operator")
15835 : G_("converting %qT to a base class %qT "
15836 "will never use a type conversion operator"),
15837 class_type, t);
15841 if (!warn_ecpp)
15842 return true;
15844 /* Effective C++ rules below. */
15846 /* More Effective C++ rule 7. */
15847 if (operator_code == TRUTH_ANDIF_EXPR
15848 || operator_code == TRUTH_ORIF_EXPR
15849 || operator_code == COMPOUND_EXPR)
15850 warning_at (loc, OPT_Weffc__,
15851 "user-defined %qD always evaluates both arguments", decl);
15853 /* More Effective C++ rule 6. */
15854 if (operator_code == POSTINCREMENT_EXPR
15855 || operator_code == POSTDECREMENT_EXPR
15856 || operator_code == PREINCREMENT_EXPR
15857 || operator_code == PREDECREMENT_EXPR)
15859 tree arg = TREE_VALUE (argtypes);
15860 tree ret = TREE_TYPE (TREE_TYPE (decl));
15861 if (methodp || TYPE_REF_P (arg))
15862 arg = TREE_TYPE (arg);
15863 arg = TYPE_MAIN_VARIANT (arg);
15865 if (operator_code == PREINCREMENT_EXPR
15866 || operator_code == PREDECREMENT_EXPR)
15868 if (!TYPE_REF_P (ret)
15869 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
15870 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
15871 build_reference_type (arg));
15873 else
15875 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
15876 warning_at (loc, OPT_Weffc__,
15877 "postfix %qD should return %qT", decl, arg);
15881 /* Effective C++ rule 23. */
15882 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
15883 && (operator_code == PLUS_EXPR
15884 || operator_code == MINUS_EXPR
15885 || operator_code == TRUNC_DIV_EXPR
15886 || operator_code == MULT_EXPR
15887 || operator_code == TRUNC_MOD_EXPR)
15888 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
15889 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
15891 return true;
15894 /* Return a string giving the keyword associate with CODE. */
15896 static const char *
15897 tag_name (enum tag_types code)
15899 switch (code)
15901 case record_type:
15902 return "struct";
15903 case class_type:
15904 return "class";
15905 case union_type:
15906 return "union";
15907 case enum_type:
15908 return "enum";
15909 case typename_type:
15910 return "typename";
15911 default:
15912 gcc_unreachable ();
15916 /* Name lookup in an elaborated-type-specifier (after the keyword
15917 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
15918 elaborated-type-specifier is invalid, issue a diagnostic and return
15919 error_mark_node; otherwise, return the *_TYPE to which it referred.
15920 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
15922 tree
15923 check_elaborated_type_specifier (enum tag_types tag_code,
15924 tree decl,
15925 bool allow_template_p)
15927 tree type;
15929 /* In the case of:
15931 struct S { struct S *p; };
15933 name lookup will find the TYPE_DECL for the implicit "S::S"
15934 typedef. Adjust for that here. */
15935 if (DECL_SELF_REFERENCE_P (decl))
15936 decl = TYPE_NAME (TREE_TYPE (decl));
15938 type = TREE_TYPE (decl);
15940 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
15941 is false for this case as well. */
15942 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15944 error ("using template type parameter %qT after %qs",
15945 type, tag_name (tag_code));
15946 return error_mark_node;
15948 /* Accept template template parameters. */
15949 else if (allow_template_p
15950 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
15951 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
15953 /* [dcl.type.elab]
15955 If the identifier resolves to a typedef-name or the
15956 simple-template-id resolves to an alias template
15957 specialization, the elaborated-type-specifier is ill-formed.
15959 In other words, the only legitimate declaration to use in the
15960 elaborated type specifier is the implicit typedef created when
15961 the type is declared. */
15962 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
15963 && !DECL_SELF_REFERENCE_P (decl)
15964 && tag_code != typename_type)
15966 if (alias_template_specialization_p (type, nt_opaque))
15967 error ("using alias template specialization %qT after %qs",
15968 type, tag_name (tag_code));
15969 else
15970 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
15971 inform (DECL_SOURCE_LOCATION (decl),
15972 "%qD has a previous declaration here", decl);
15973 return error_mark_node;
15975 else if (TREE_CODE (type) != RECORD_TYPE
15976 && TREE_CODE (type) != UNION_TYPE
15977 && tag_code != enum_type
15978 && tag_code != typename_type)
15980 error ("%qT referred to as %qs", type, tag_name (tag_code));
15981 inform (location_of (type), "%qT has a previous declaration here", type);
15982 return error_mark_node;
15984 else if (TREE_CODE (type) != ENUMERAL_TYPE
15985 && tag_code == enum_type)
15987 error ("%qT referred to as enum", type);
15988 inform (location_of (type), "%qT has a previous declaration here", type);
15989 return error_mark_node;
15991 else if (!allow_template_p
15992 && TREE_CODE (type) == RECORD_TYPE
15993 && CLASSTYPE_IS_TEMPLATE (type))
15995 /* If a class template appears as elaborated type specifier
15996 without a template header such as:
15998 template <class T> class C {};
15999 void f(class C); // No template header here
16001 then the required template argument is missing. */
16002 error ("template argument required for %<%s %T%>",
16003 tag_name (tag_code),
16004 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
16005 return error_mark_node;
16008 return type;
16011 /* Lookup NAME of an elaborated type specifier according to SCOPE and
16012 issue diagnostics if necessary. Return *_TYPE node upon success,
16013 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
16014 error. */
16016 static tree
16017 lookup_and_check_tag (enum tag_types tag_code, tree name,
16018 TAG_how how, bool template_header_p)
16020 tree decl;
16021 if (how == TAG_how::GLOBAL)
16023 /* First try ordinary name lookup, ignoring hidden class name
16024 injected via friend declaration. */
16025 decl = lookup_name (name, LOOK_want::TYPE);
16026 decl = strip_using_decl (decl);
16027 /* If that fails, the name will be placed in the smallest
16028 non-class, non-function-prototype scope according to 3.3.1/5.
16029 We may already have a hidden name declared as friend in this
16030 scope. So lookup again but not ignoring hidden names.
16031 If we find one, that name will be made visible rather than
16032 creating a new tag. */
16033 if (!decl)
16034 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
16036 else
16037 decl = lookup_elaborated_type (name, how);
16039 if (!decl)
16040 /* We found nothing. */
16041 return NULL_TREE;
16043 if (TREE_CODE (decl) == TREE_LIST)
16045 error ("reference to %qD is ambiguous", name);
16046 print_candidates (decl);
16047 return error_mark_node;
16050 if (DECL_CLASS_TEMPLATE_P (decl)
16051 && !template_header_p
16052 && how == TAG_how::CURRENT_ONLY)
16054 error ("class template %qD redeclared as non-template", name);
16055 inform (location_of (decl), "previous declaration here");
16056 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
16057 return error_mark_node;
16060 if (DECL_CLASS_TEMPLATE_P (decl)
16061 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
16062 so ignore a template template parameter. */
16063 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
16064 decl = DECL_TEMPLATE_RESULT (decl);
16066 if (TREE_CODE (decl) != TYPE_DECL)
16067 /* Found not-a-type. */
16068 return NULL_TREE;
16070 /* Look for invalid nested type:
16071 class C {
16072 class C {};
16073 }; */
16074 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
16076 error ("%qD has the same name as the class in which it is "
16077 "declared", decl);
16078 return error_mark_node;
16081 /* Two cases we need to consider when deciding if a class
16082 template is allowed as an elaborated type specifier:
16083 1. It is a self reference to its own class.
16084 2. It comes with a template header.
16086 For example:
16088 template <class T> class C {
16089 class C *c1; // DECL_SELF_REFERENCE_P is true
16090 class D;
16092 template <class U> class C; // template_header_p is true
16093 template <class T> class C<T>::D {
16094 class C *c2; // DECL_SELF_REFERENCE_P is true
16095 }; */
16097 tree t = check_elaborated_type_specifier (tag_code, decl,
16098 template_header_p
16099 | DECL_SELF_REFERENCE_P (decl));
16100 if (template_header_p && t && CLASS_TYPE_P (t)
16101 && (!CLASSTYPE_TEMPLATE_INFO (t)
16102 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
16104 error ("%qT is not a template", t);
16105 inform (location_of (t), "previous declaration here");
16106 if (TYPE_CLASS_SCOPE_P (t)
16107 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
16108 inform (input_location,
16109 "perhaps you want to explicitly add %<%T::%>",
16110 TYPE_CONTEXT (t));
16111 return error_mark_node;
16114 return t;
16117 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
16118 Define the tag as a forward-reference if it is not defined.
16120 If a declaration is given, process it here, and report an error if
16121 multiple declarations are not identical.
16123 SCOPE is TS_CURRENT when this is also a definition. Only look in
16124 the current frame for the name (since C++ allows new names in any
16125 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
16126 declaration. Only look beginning from the current scope outward up
16127 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
16129 TEMPLATE_HEADER_P is true when this declaration is preceded by
16130 a set of template parameters. */
16132 tree
16133 xref_tag (enum tag_types tag_code, tree name,
16134 TAG_how how, bool template_header_p)
16136 enum tree_code code;
16137 tree context = NULL_TREE;
16139 auto_cond_timevar tv (TV_NAME_LOOKUP);
16141 gcc_assert (identifier_p (name));
16143 switch (tag_code)
16145 case record_type:
16146 case class_type:
16147 code = RECORD_TYPE;
16148 break;
16149 case union_type:
16150 code = UNION_TYPE;
16151 break;
16152 case enum_type:
16153 code = ENUMERAL_TYPE;
16154 break;
16155 default:
16156 gcc_unreachable ();
16159 /* In case of anonymous name, xref_tag is only called to
16160 make type node and push name. Name lookup is not required. */
16161 tree t = NULL_TREE;
16162 if (!IDENTIFIER_ANON_P (name))
16163 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16165 if (t == error_mark_node)
16166 return error_mark_node;
16168 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16169 && template_class_depth (current_class_type)
16170 && template_header_p)
16172 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16173 return t;
16175 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16176 a definition of this tag. Since, in addition, we are
16177 currently processing a (member) template declaration of a
16178 template class, we must be very careful; consider:
16180 template <class X> struct S1
16182 template <class U> struct S2
16184 template <class V> friend struct S1;
16187 Here, the S2::S1 declaration should not be confused with the
16188 outer declaration. In particular, the inner version should
16189 have a template parameter of level 2, not level 1.
16191 On the other hand, when presented with:
16193 template <class T> struct S1
16195 template <class U> struct S2 {};
16196 template <class U> friend struct S2;
16199 the friend must find S1::S2 eventually. We accomplish this
16200 by making sure that the new type we create to represent this
16201 declaration has the right TYPE_CONTEXT. */
16202 context = TYPE_CONTEXT (t);
16203 t = NULL_TREE;
16206 if (! t)
16208 /* If no such tag is yet defined, create a forward-reference node
16209 and record it as the "definition".
16210 When a real declaration of this type is found,
16211 the forward-reference will be altered into a real type. */
16212 if (code == ENUMERAL_TYPE)
16214 error ("use of enum %q#D without previous declaration", name);
16215 return error_mark_node;
16218 t = make_class_type (code);
16219 TYPE_CONTEXT (t) = context;
16220 if (IDENTIFIER_LAMBDA_P (name))
16221 /* Mark it as a lambda type right now. Our caller will
16222 correct the value. */
16223 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16224 t = pushtag (name, t, how);
16226 else
16228 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16230 /* Check that we aren't trying to overload a class with different
16231 constraints. */
16232 if (!redeclare_class_template (t, current_template_parms,
16233 current_template_constraints ()))
16234 return error_mark_node;
16236 else if (!processing_template_decl
16237 && CLASS_TYPE_P (t)
16238 && CLASSTYPE_IS_TEMPLATE (t))
16240 error ("redeclaration of %qT as a non-template", t);
16241 inform (location_of (t), "previous declaration %qD", t);
16242 return error_mark_node;
16245 if (modules_p ()
16246 && how == TAG_how::CURRENT_ONLY)
16248 tree decl = TYPE_NAME (t);
16249 if (!module_may_redeclare (decl))
16251 error ("cannot declare %qD in a different module", decl);
16252 inform (DECL_SOURCE_LOCATION (decl), "declared here");
16253 return error_mark_node;
16256 tree maybe_tmpl = decl;
16257 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16258 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16260 if (DECL_LANG_SPECIFIC (decl)
16261 && DECL_MODULE_IMPORT_P (decl)
16262 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
16264 /* Push it into this TU's symbol slot. */
16265 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
16266 if (maybe_tmpl != decl)
16267 /* We're in the template parm binding level.
16268 Pushtag has logic to slide under that, but we're
16269 not pushing a *new* type. */
16270 push_nested_namespace (CP_DECL_CONTEXT (decl));
16272 pushdecl (maybe_tmpl);
16273 if (maybe_tmpl != decl)
16274 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16277 set_instantiating_module (maybe_tmpl);
16281 return t;
16284 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16285 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16286 access_* node, and the TREE_VALUE is the type of the base-class.
16287 Non-NULL TREE_TYPE indicates virtual inheritance. */
16289 void
16290 xref_basetypes (tree ref, tree base_list)
16292 tree *basep;
16293 tree binfo, base_binfo;
16294 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16295 unsigned max_bases = 0; /* Maximum direct bases. */
16296 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16297 int i;
16298 tree default_access;
16299 tree igo_prev; /* Track Inheritance Graph Order. */
16301 if (ref == error_mark_node)
16302 return;
16304 /* The base of a derived class is private by default, all others are
16305 public. */
16306 default_access = (TREE_CODE (ref) == RECORD_TYPE
16307 && CLASSTYPE_DECLARED_CLASS (ref)
16308 ? access_private_node : access_public_node);
16310 /* First, make sure that any templates in base-classes are
16311 instantiated. This ensures that if we call ourselves recursively
16312 we do not get confused about which classes are marked and which
16313 are not. */
16314 basep = &base_list;
16315 while (*basep)
16317 tree basetype = TREE_VALUE (*basep);
16319 /* The dependent_type_p call below should really be dependent_scope_p
16320 so that we give a hard error about using an incomplete type as a
16321 base, but we allow it with a pedwarn for backward
16322 compatibility. */
16323 if (processing_template_decl
16324 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16325 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16326 if (!dependent_type_p (basetype)
16327 && !complete_type_or_else (basetype, NULL))
16328 /* An incomplete type. Remove it from the list. */
16329 *basep = TREE_CHAIN (*basep);
16330 else
16332 max_bases++;
16333 if (TREE_TYPE (*basep))
16334 max_dvbases++;
16335 if (CLASS_TYPE_P (basetype))
16336 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16337 basep = &TREE_CHAIN (*basep);
16340 max_vbases += max_dvbases;
16342 TYPE_MARKED_P (ref) = 1;
16344 /* The binfo slot should be empty, unless this is an (ill-formed)
16345 redefinition. */
16346 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16348 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16350 binfo = make_tree_binfo (max_bases);
16352 TYPE_BINFO (ref) = binfo;
16353 BINFO_OFFSET (binfo) = size_zero_node;
16354 BINFO_TYPE (binfo) = ref;
16356 /* Apply base-class info set up to the variants of this type. */
16357 fixup_type_variants (ref);
16359 if (max_bases)
16361 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16362 /* A C++98 POD cannot have base classes. */
16363 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16365 if (TREE_CODE (ref) == UNION_TYPE)
16367 error ("derived union %qT invalid", ref);
16368 return;
16372 if (max_bases > 1)
16373 warning (OPT_Wmultiple_inheritance,
16374 "%qT defined with multiple direct bases", ref);
16376 if (max_vbases)
16378 /* An aggregate can't have virtual base classes. */
16379 CLASSTYPE_NON_AGGREGATE (ref) = true;
16381 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16383 if (max_dvbases)
16384 warning (OPT_Wvirtual_inheritance,
16385 "%qT defined with direct virtual base", ref);
16388 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16390 tree access = TREE_PURPOSE (base_list);
16391 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16392 tree basetype = TREE_VALUE (base_list);
16394 if (access == access_default_node)
16395 access = default_access;
16397 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16398 aggregate can't have virtual, private, or protected base classes. */
16399 if (cxx_dialect < cxx17
16400 || access != access_public_node
16401 || via_virtual)
16402 CLASSTYPE_NON_AGGREGATE (ref) = true;
16404 if (PACK_EXPANSION_P (basetype))
16405 basetype = PACK_EXPANSION_PATTERN (basetype);
16406 if (TREE_CODE (basetype) == TYPE_DECL)
16407 basetype = TREE_TYPE (basetype);
16408 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16410 error ("base type %qT fails to be a struct or class type",
16411 basetype);
16412 goto dropped_base;
16415 base_binfo = NULL_TREE;
16416 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16418 base_binfo = TYPE_BINFO (basetype);
16419 /* The original basetype could have been a typedef'd type. */
16420 basetype = BINFO_TYPE (base_binfo);
16422 /* Inherit flags from the base. */
16423 TYPE_HAS_NEW_OPERATOR (ref)
16424 |= TYPE_HAS_NEW_OPERATOR (basetype);
16425 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16426 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16427 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16428 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16429 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16430 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16431 CLASSTYPE_REPEATED_BASE_P (ref)
16432 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16435 /* We must do this test after we've seen through a typedef
16436 type. */
16437 if (TYPE_MARKED_P (basetype))
16439 if (basetype == ref)
16440 error ("recursive type %qT undefined", basetype);
16441 else
16442 error ("duplicate base type %qT invalid", basetype);
16443 goto dropped_base;
16446 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16447 /* Regenerate the pack expansion for the bases. */
16448 basetype = make_pack_expansion (basetype);
16450 TYPE_MARKED_P (basetype) = 1;
16452 base_binfo = copy_binfo (base_binfo, basetype, ref,
16453 &igo_prev, via_virtual);
16454 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16455 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16457 BINFO_BASE_APPEND (binfo, base_binfo);
16458 BINFO_BASE_ACCESS_APPEND (binfo, access);
16459 continue;
16461 dropped_base:
16462 /* Update max_vbases to reflect the reality that we are dropping
16463 this base: if it reaches zero we want to undo the vec_alloc
16464 above to avoid inconsistencies during error-recovery: eg, in
16465 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16466 and vtt null (c++/27952). */
16467 if (via_virtual)
16468 max_vbases--;
16469 if (CLASS_TYPE_P (basetype))
16470 max_vbases
16471 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16474 if (CLASSTYPE_VBASECLASSES (ref)
16475 && max_vbases == 0)
16476 vec_free (CLASSTYPE_VBASECLASSES (ref));
16478 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16479 /* If we didn't get max_vbases vbases, we must have shared at
16480 least one of them, and are therefore diamond shaped. */
16481 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16483 /* Unmark all the types. */
16484 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16485 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16486 TYPE_MARKED_P (ref) = 0;
16488 /* Now see if we have a repeated base type. */
16489 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16491 for (base_binfo = binfo; base_binfo;
16492 base_binfo = TREE_CHAIN (base_binfo))
16494 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16496 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16497 break;
16499 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16501 for (base_binfo = binfo; base_binfo;
16502 base_binfo = TREE_CHAIN (base_binfo))
16503 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16504 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16505 else
16506 break;
16511 /* Copies the enum-related properties from type SRC to type DST.
16512 Used with the underlying type of an enum and the enum itself. */
16513 static void
16514 copy_type_enum (tree dst, tree src)
16516 tree t;
16517 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16519 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16520 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16521 TYPE_SIZE (t) = TYPE_SIZE (src);
16522 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16523 SET_TYPE_MODE (dst, TYPE_MODE (src));
16524 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16525 unsigned valign = TYPE_ALIGN (src);
16526 if (TYPE_USER_ALIGN (t))
16527 valign = MAX (valign, TYPE_ALIGN (t));
16528 else
16529 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16530 SET_TYPE_ALIGN (t, valign);
16531 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16535 /* Begin compiling the definition of an enumeration type.
16536 NAME is its name,
16538 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16540 UNDERLYING_TYPE is the type that will be used as the storage for
16541 the enumeration type. This should be NULL_TREE if no storage type
16542 was specified.
16544 ATTRIBUTES are any attributes specified after the enum-key.
16546 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16548 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16550 Returns the type object, as yet incomplete.
16551 Also records info about it so that build_enumerator
16552 may be used to declare the individual values as they are read. */
16554 tree
16555 start_enum (tree name, tree enumtype, tree underlying_type,
16556 tree attributes, bool scoped_enum_p, bool *is_new)
16558 tree prevtype = NULL_TREE;
16559 gcc_assert (identifier_p (name));
16561 if (is_new)
16562 *is_new = false;
16563 /* [C++0x dcl.enum]p5:
16565 If not explicitly specified, the underlying type of a scoped
16566 enumeration type is int. */
16567 if (!underlying_type && scoped_enum_p)
16568 underlying_type = integer_type_node;
16570 if (underlying_type)
16571 underlying_type = cv_unqualified (underlying_type);
16573 /* If this is the real definition for a previous forward reference,
16574 fill in the contents in the same object that used to be the
16575 forward reference. */
16576 if (!enumtype)
16577 enumtype = lookup_and_check_tag (enum_type, name,
16578 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16579 /*template_header_p=*/false);
16581 /* In case of a template_decl, the only check that should be deferred
16582 to instantiation time is the comparison of underlying types. */
16583 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16585 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16587 error_at (input_location, "scoped/unscoped mismatch "
16588 "in enum %q#T", enumtype);
16589 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16590 "previous definition here");
16591 enumtype = error_mark_node;
16593 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16595 error_at (input_location, "underlying type mismatch "
16596 "in enum %q#T", enumtype);
16597 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16598 "previous definition here");
16599 enumtype = error_mark_node;
16601 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16602 && !same_type_p (underlying_type,
16603 ENUM_UNDERLYING_TYPE (enumtype)))
16605 error_at (input_location, "different underlying type "
16606 "in enum %q#T", enumtype);
16607 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16608 "previous definition here");
16609 underlying_type = NULL_TREE;
16612 if (modules_p ())
16614 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16616 error ("cannot define %qD in different module",
16617 TYPE_NAME (enumtype));
16618 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16619 "declared here");
16620 enumtype = error_mark_node;
16622 set_instantiating_module (TYPE_NAME (enumtype));
16626 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16627 || processing_template_decl)
16629 /* In case of error, make a dummy enum to allow parsing to
16630 continue. */
16631 if (enumtype == error_mark_node)
16633 name = make_anon_name ();
16634 enumtype = NULL_TREE;
16637 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
16638 of an opaque enum, or an opaque enum of an already defined
16639 enumeration (C++11).
16640 In any other case, it'll be NULL_TREE. */
16641 if (!enumtype)
16643 if (is_new)
16644 *is_new = true;
16646 prevtype = enumtype;
16648 /* Do not push the decl more than once. */
16649 if (!enumtype
16650 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
16652 enumtype = cxx_make_type (ENUMERAL_TYPE);
16653 enumtype = pushtag (name, enumtype);
16655 /* std::byte aliases anything. */
16656 if (enumtype != error_mark_node
16657 && TYPE_CONTEXT (enumtype) == std_node
16658 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
16659 TYPE_ALIAS_SET (enumtype) = 0;
16661 else
16662 enumtype = xref_tag (enum_type, name);
16664 if (enumtype == error_mark_node)
16665 return error_mark_node;
16667 /* The enum is considered opaque until the opening '{' of the
16668 enumerator list. */
16669 SET_OPAQUE_ENUM_P (enumtype, true);
16670 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
16673 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
16675 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
16677 if (underlying_type)
16679 if (ENUM_UNDERLYING_TYPE (enumtype))
16680 /* We already checked that it matches, don't change it to a different
16681 typedef variant. */;
16682 else if (CP_INTEGRAL_TYPE_P (underlying_type))
16684 copy_type_enum (enumtype, underlying_type);
16685 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16687 else if (dependent_type_p (underlying_type))
16688 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16689 else
16691 error ("underlying type %qT of %qT must be an integral type",
16692 underlying_type, enumtype);
16693 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
16697 /* If into a template class, the returned enum is always the first
16698 declaration (opaque or not) seen. This way all the references to
16699 this type will be to the same declaration. The following ones are used
16700 only to check for definition errors. */
16701 if (prevtype && processing_template_decl)
16702 return prevtype;
16703 else
16704 return enumtype;
16707 /* After processing and defining all the values of an enumeration type,
16708 install their decls in the enumeration type.
16709 ENUMTYPE is the type object. */
16711 void
16712 finish_enum_value_list (tree enumtype)
16714 tree values;
16715 tree underlying_type;
16716 tree decl;
16717 tree value;
16718 tree minnode, maxnode;
16719 tree t;
16721 bool fixed_underlying_type_p
16722 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
16724 /* We built up the VALUES in reverse order. */
16725 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
16727 /* For an enum defined in a template, just set the type of the values;
16728 all further processing is postponed until the template is
16729 instantiated. We need to set the type so that tsubst of a CONST_DECL
16730 works. */
16731 if (processing_template_decl)
16733 for (values = TYPE_VALUES (enumtype);
16734 values;
16735 values = TREE_CHAIN (values))
16736 TREE_TYPE (TREE_VALUE (values)) = enumtype;
16737 return;
16740 /* Determine the minimum and maximum values of the enumerators. */
16741 if (TYPE_VALUES (enumtype))
16743 minnode = maxnode = NULL_TREE;
16745 for (values = TYPE_VALUES (enumtype);
16746 values;
16747 values = TREE_CHAIN (values))
16749 decl = TREE_VALUE (values);
16751 /* [dcl.enum]: Following the closing brace of an enum-specifier,
16752 each enumerator has the type of its enumeration. Prior to the
16753 closing brace, the type of each enumerator is the type of its
16754 initializing value. */
16755 TREE_TYPE (decl) = enumtype;
16757 /* Update the minimum and maximum values, if appropriate. */
16758 value = DECL_INITIAL (decl);
16759 if (TREE_CODE (value) != INTEGER_CST)
16760 value = integer_zero_node;
16761 /* Figure out what the minimum and maximum values of the
16762 enumerators are. */
16763 if (!minnode)
16764 minnode = maxnode = value;
16765 else if (tree_int_cst_lt (maxnode, value))
16766 maxnode = value;
16767 else if (tree_int_cst_lt (value, minnode))
16768 minnode = value;
16771 else
16772 /* [dcl.enum]
16774 If the enumerator-list is empty, the underlying type is as if
16775 the enumeration had a single enumerator with value 0. */
16776 minnode = maxnode = integer_zero_node;
16778 if (!fixed_underlying_type_p)
16780 /* Compute the number of bits require to represent all values of the
16781 enumeration. We must do this before the type of MINNODE and
16782 MAXNODE are transformed, since tree_int_cst_min_precision relies
16783 on the TREE_TYPE of the value it is passed. */
16784 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
16785 int lowprec = tree_int_cst_min_precision (minnode, sgn);
16786 int highprec = tree_int_cst_min_precision (maxnode, sgn);
16787 int precision = MAX (lowprec, highprec);
16788 unsigned int itk;
16789 bool use_short_enum;
16791 /* Determine the underlying type of the enumeration.
16793 [dcl.enum]
16795 The underlying type of an enumeration is an integral type that
16796 can represent all the enumerator values defined in the
16797 enumeration. It is implementation-defined which integral type is
16798 used as the underlying type for an enumeration except that the
16799 underlying type shall not be larger than int unless the value of
16800 an enumerator cannot fit in an int or unsigned int.
16802 We use "int" or an "unsigned int" as the underlying type, even if
16803 a smaller integral type would work, unless the user has
16804 explicitly requested that we use the smallest possible type. The
16805 user can request that for all enumerations with a command line
16806 flag, or for just one enumeration with an attribute. */
16808 use_short_enum = flag_short_enums
16809 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
16811 /* If the precision of the type was specified with an attribute and it
16812 was too small, give an error. Otherwise, use it. */
16813 if (TYPE_PRECISION (enumtype))
16815 if (precision > TYPE_PRECISION (enumtype))
16816 error ("specified mode too small for enumerated values");
16817 else
16819 use_short_enum = true;
16820 precision = TYPE_PRECISION (enumtype);
16824 for (itk = (use_short_enum ? itk_char : itk_int);
16825 itk != itk_none;
16826 itk++)
16828 underlying_type = integer_types[itk];
16829 if (underlying_type != NULL_TREE
16830 && TYPE_PRECISION (underlying_type) >= precision
16831 && TYPE_SIGN (underlying_type) == sgn)
16832 break;
16834 if (itk == itk_none)
16836 /* DR 377
16838 IF no integral type can represent all the enumerator values, the
16839 enumeration is ill-formed. */
16840 error ("no integral type can represent all of the enumerator values "
16841 "for %qT", enumtype);
16842 precision = TYPE_PRECISION (long_long_integer_type_node);
16843 underlying_type = integer_types[itk_unsigned_long_long];
16846 /* [dcl.enum]
16848 The value of sizeof() applied to an enumeration type, an object
16849 of an enumeration type, or an enumerator, is the value of sizeof()
16850 applied to the underlying type. */
16851 copy_type_enum (enumtype, underlying_type);
16853 /* Compute the minimum and maximum values for the type.
16855 [dcl.enum]
16857 For an enumeration where emin is the smallest enumerator and emax
16858 is the largest, the values of the enumeration are the values of the
16859 underlying type in the range bmin to bmax, where bmin and bmax are,
16860 respectively, the smallest and largest values of the smallest bit-
16861 field that can store emin and emax. */
16863 /* The middle-end currently assumes that types with TYPE_PRECISION
16864 narrower than their underlying type are suitably zero or sign
16865 extended to fill their mode. Similarly, it assumes that the front
16866 end assures that a value of a particular type must be within
16867 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
16869 We used to set these fields based on bmin and bmax, but that led
16870 to invalid assumptions like optimizing away bounds checking. So
16871 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
16872 TYPE_MAX_VALUE to the values for the mode above and only restrict
16873 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
16874 ENUM_UNDERLYING_TYPE (enumtype)
16875 = build_distinct_type_copy (underlying_type);
16876 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
16877 set_min_and_max_values_for_integral_type
16878 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
16880 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
16881 if (flag_strict_enums)
16882 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
16884 else
16885 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
16887 /* If the enum is exported, mark the consts too. */
16888 bool export_p = (UNSCOPED_ENUM_P (enumtype)
16889 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
16890 && at_namespace_scope_p ());
16892 /* Convert each of the enumerators to the type of the underlying
16893 type of the enumeration. */
16894 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
16896 decl = TREE_VALUE (values);
16897 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
16898 if (fixed_underlying_type_p)
16899 /* If the enumeration type has a fixed underlying type, we
16900 already checked all of the enumerator values. */
16901 value = DECL_INITIAL (decl);
16902 else
16903 value = perform_implicit_conversion (underlying_type,
16904 DECL_INITIAL (decl),
16905 tf_warning_or_error);
16906 /* Do not clobber shared ints. */
16907 if (value != error_mark_node)
16909 value = copy_node (value);
16911 TREE_TYPE (value) = enumtype;
16913 DECL_INITIAL (decl) = value;
16914 if (export_p)
16915 DECL_MODULE_EXPORT_P (decl) = true;
16918 /* Fix up all variant types of this enum type. */
16919 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
16920 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
16922 if (at_class_scope_p ()
16923 && COMPLETE_TYPE_P (current_class_type)
16924 && UNSCOPED_ENUM_P (enumtype))
16926 insert_late_enum_def_bindings (current_class_type, enumtype);
16927 /* TYPE_FIELDS needs fixup. */
16928 fixup_type_variants (current_class_type);
16931 /* Finish debugging output for this type. */
16932 rest_of_type_compilation (enumtype, namespace_bindings_p ());
16934 /* Each enumerator now has the type of its enumeration. Clear the cache
16935 so that this change in types doesn't confuse us later on. */
16936 clear_cv_and_fold_caches ();
16939 /* Finishes the enum type. This is called only the first time an
16940 enumeration is seen, be it opaque or odinary.
16941 ENUMTYPE is the type object. */
16943 void
16944 finish_enum (tree enumtype)
16946 if (processing_template_decl)
16948 if (at_function_scope_p ())
16949 add_stmt (build_min (TAG_DEFN, enumtype));
16950 return;
16953 /* If this is a forward declaration, there should not be any variants,
16954 though we can get a variant in the middle of an enum-specifier with
16955 wacky code like 'enum E { e = sizeof(const E*) };' */
16956 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
16957 && (TYPE_VALUES (enumtype)
16958 || !TYPE_NEXT_VARIANT (enumtype)));
16961 /* Build and install a CONST_DECL for an enumeration constant of the
16962 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
16963 Apply ATTRIBUTES if available. LOC is the location of NAME.
16964 Assignment of sequential values by default is handled here. */
16966 tree
16967 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
16968 location_t loc)
16970 tree decl;
16971 tree context;
16972 tree type;
16974 /* scalar_constant_value will pull out this expression, so make sure
16975 it's folded as appropriate. */
16976 if (processing_template_decl)
16977 value = fold_non_dependent_expr (value);
16979 /* If the VALUE was erroneous, pretend it wasn't there; that will
16980 result in the enum being assigned the next value in sequence. */
16981 if (value == error_mark_node)
16982 value = NULL_TREE;
16984 /* Remove no-op casts from the value. */
16985 if (value)
16986 STRIP_TYPE_NOPS (value);
16988 if (! processing_template_decl)
16990 /* Validate and default VALUE. */
16991 if (value != NULL_TREE)
16993 if (!ENUM_UNDERLYING_TYPE (enumtype))
16995 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
16996 value, true);
16997 if (tmp_value)
16998 value = tmp_value;
17000 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17001 (TREE_TYPE (value)))
17002 value = perform_implicit_conversion_flags
17003 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
17004 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
17006 if (value == error_mark_node)
17007 value = NULL_TREE;
17009 if (value != NULL_TREE)
17011 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17012 (TREE_TYPE (value)))
17014 error_at (cp_expr_loc_or_input_loc (value),
17015 "enumerator value for %qD must have integral or "
17016 "unscoped enumeration type", name);
17017 value = NULL_TREE;
17019 else
17021 value = cxx_constant_value (value);
17023 if (TREE_CODE (value) != INTEGER_CST)
17025 error ("enumerator value for %qD is not an integer "
17026 "constant", name);
17027 value = NULL_TREE;
17033 /* Default based on previous value. */
17034 if (value == NULL_TREE)
17036 if (TYPE_VALUES (enumtype))
17038 tree prev_value;
17040 /* C++03 7.2/4: If no initializer is specified for the first
17041 enumerator, the type is an unspecified integral
17042 type. Otherwise the type is the same as the type of the
17043 initializing value of the preceding enumerator unless the
17044 incremented value is not representable in that type, in
17045 which case the type is an unspecified integral type
17046 sufficient to contain the incremented value. */
17047 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
17048 if (TREE_CODE (prev_value) != INTEGER_CST)
17049 value = error_mark_node;
17050 else
17052 wi::overflow_type overflowed;
17053 tree type = TREE_TYPE (prev_value);
17054 signop sgn = TYPE_SIGN (type);
17055 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
17056 &overflowed);
17057 if (!overflowed)
17059 bool pos = !wi::neg_p (wi, sgn);
17060 if (!wi::fits_to_tree_p (wi, type))
17062 unsigned int itk;
17063 for (itk = itk_int; itk != itk_none; itk++)
17065 type = integer_types[itk];
17066 if (type != NULL_TREE
17067 && (pos || !TYPE_UNSIGNED (type))
17068 && wi::fits_to_tree_p (wi, type))
17069 break;
17071 if (type && cxx_dialect < cxx11
17072 && itk > itk_unsigned_long)
17073 pedwarn (input_location, OPT_Wlong_long,
17074 pos ? G_("\
17075 incremented enumerator value is too large for %<unsigned long%>") : G_("\
17076 incremented enumerator value is too large for %<long%>"));
17078 if (type == NULL_TREE)
17079 overflowed = wi::OVF_UNKNOWN;
17080 else
17081 value = wide_int_to_tree (type, wi);
17084 if (overflowed)
17086 error ("overflow in enumeration values at %qD", name);
17087 value = error_mark_node;
17091 else
17092 value = integer_zero_node;
17095 /* Remove no-op casts from the value. */
17096 STRIP_TYPE_NOPS (value);
17098 /* If the underlying type of the enum is fixed, check whether
17099 the enumerator values fits in the underlying type. If it
17100 does not fit, the program is ill-formed [C++0x dcl.enum]. */
17101 if (ENUM_UNDERLYING_TYPE (enumtype)
17102 && value
17103 && TREE_CODE (value) == INTEGER_CST)
17105 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
17106 error ("enumerator value %qE is outside the range of underlying "
17107 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
17109 /* Convert the value to the appropriate type. */
17110 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
17114 /* C++ associates enums with global, function, or class declarations. */
17115 context = current_scope ();
17117 /* Build the actual enumeration constant. Note that the enumeration
17118 constants have the underlying type of the enum (if it is fixed)
17119 or the type of their initializer (if the underlying type of the
17120 enum is not fixed):
17122 [ C++0x dcl.enum ]
17124 If the underlying type is fixed, the type of each enumerator
17125 prior to the closing brace is the underlying type; if the
17126 initializing value of an enumerator cannot be represented by
17127 the underlying type, the program is ill-formed. If the
17128 underlying type is not fixed, the type of each enumerator is
17129 the type of its initializing value.
17131 If the underlying type is not fixed, it will be computed by
17132 finish_enum and we will reset the type of this enumerator. Of
17133 course, if we're processing a template, there may be no value. */
17134 type = value ? TREE_TYPE (value) : NULL_TREE;
17136 decl = build_decl (loc, CONST_DECL, name, type);
17138 DECL_CONTEXT (decl) = enumtype;
17139 TREE_CONSTANT (decl) = 1;
17140 TREE_READONLY (decl) = 1;
17141 DECL_INITIAL (decl) = value;
17143 if (attributes)
17144 cplus_decl_attributes (&decl, attributes, 0);
17146 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17148 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17149 on the TYPE_FIELDS list for `S'. (That's so that you can say
17150 things like `S::i' later.) */
17152 /* The enumerator may be getting declared outside of its enclosing
17153 class, like so:
17155 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17157 For which case we need to make sure that the access of `S::i'
17158 matches the access of `S::E'. */
17159 auto cas = make_temp_override (current_access_specifier);
17160 set_current_access_from_decl (TYPE_NAME (enumtype));
17161 finish_member_declaration (decl);
17163 else
17164 pushdecl (decl);
17166 /* Add this enumeration constant to the list for this type. */
17167 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17169 return decl;
17172 /* Look for an enumerator with the given NAME within the enumeration
17173 type ENUMTYPE. This routine is used primarily for qualified name
17174 lookup into an enumerator in C++0x, e.g.,
17176 enum class Color { Red, Green, Blue };
17178 Color color = Color::Red;
17180 Returns the value corresponding to the enumerator, or
17181 NULL_TREE if no such enumerator was found. */
17182 tree
17183 lookup_enumerator (tree enumtype, tree name)
17185 tree e;
17186 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17188 e = purpose_member (name, TYPE_VALUES (enumtype));
17189 return e? TREE_VALUE (e) : NULL_TREE;
17192 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17194 tree
17195 cxx_simulate_enum_decl (location_t loc, const char *name,
17196 vec<string_int_pair> *values)
17198 location_t saved_loc = input_location;
17199 input_location = loc;
17201 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17202 NULL_TREE, false, NULL);
17203 if (!OPAQUE_ENUM_P (enumtype))
17205 error_at (loc, "multiple definition of %q#T", enumtype);
17206 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17207 "previous definition here");
17208 return enumtype;
17210 SET_OPAQUE_ENUM_P (enumtype, false);
17211 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17213 for (const string_int_pair &value : values)
17214 build_enumerator (get_identifier (value.first),
17215 build_int_cst (integer_type_node, value.second),
17216 enumtype, NULL_TREE, loc);
17218 finish_enum_value_list (enumtype);
17219 finish_enum (enumtype);
17221 input_location = saved_loc;
17222 return enumtype;
17225 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17227 tree
17228 cxx_simulate_record_decl (location_t loc, const char *name,
17229 array_slice<const tree> fields)
17231 iloc_sentinel ils (loc);
17233 tree ident = get_identifier (name);
17234 tree type = xref_tag (/*tag_code=*/record_type, ident);
17235 if (type != error_mark_node
17236 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17238 error ("redefinition of %q#T", type);
17239 type = error_mark_node;
17241 if (type == error_mark_node)
17242 return lhd_simulate_record_decl (loc, name, fields);
17244 xref_basetypes (type, NULL_TREE);
17245 type = begin_class_definition (type);
17246 if (type == error_mark_node)
17247 return lhd_simulate_record_decl (loc, name, fields);
17249 for (tree field : fields)
17250 finish_member_declaration (field);
17252 type = finish_struct (type, NULL_TREE);
17254 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17255 set_underlying_type (decl);
17256 lang_hooks.decls.pushdecl (decl);
17258 return type;
17261 /* We're defining DECL. Make sure that its type is OK. */
17263 static void
17264 check_function_type (tree decl, tree current_function_parms)
17266 tree fntype = TREE_TYPE (decl);
17267 tree return_type = complete_type (TREE_TYPE (fntype));
17269 /* In a function definition, arg types must be complete. */
17270 require_complete_types_for_parms (current_function_parms);
17272 if (dependent_type_p (return_type)
17273 || type_uses_auto (return_type))
17274 return;
17275 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17277 tree args = TYPE_ARG_TYPES (fntype);
17279 error ("return type %q#T is incomplete", return_type);
17281 /* Make it return void instead. */
17282 if (TREE_CODE (fntype) == METHOD_TYPE)
17283 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17284 void_type_node,
17285 TREE_CHAIN (args));
17286 else
17287 fntype = build_function_type (void_type_node, args);
17288 fntype = (cp_build_type_attribute_variant
17289 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17290 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17291 TREE_TYPE (decl) = fntype;
17293 else
17295 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17296 maybe_warn_parm_abi (TREE_TYPE (fntype),
17297 DECL_SOURCE_LOCATION (decl));
17301 /* True iff FN is an implicitly-defined default constructor. */
17303 static bool
17304 implicit_default_ctor_p (tree fn)
17306 return (DECL_CONSTRUCTOR_P (fn)
17307 && !user_provided_p (fn)
17308 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17311 /* Clobber the contents of *this to let the back end know that the object
17312 storage is dead when we enter the constructor or leave the destructor. */
17314 static tree
17315 build_clobber_this ()
17317 /* Clobbering an empty base is pointless, and harmful if its one byte
17318 TYPE_SIZE overlays real data. */
17319 if (is_empty_class (current_class_type))
17320 return void_node;
17322 /* If we have virtual bases, clobber the whole object, but only if we're in
17323 charge. If we don't have virtual bases, clobber the as-base type so we
17324 don't mess with tail padding. */
17325 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17327 tree ctype = current_class_type;
17328 if (!vbases)
17329 ctype = CLASSTYPE_AS_BASE (ctype);
17331 tree clobber = build_clobber (ctype);
17333 tree thisref = current_class_ref;
17334 if (ctype != current_class_type)
17336 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17337 thisref = convert_from_reference (thisref);
17340 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17341 if (vbases)
17342 exprstmt = build_if_in_charge (exprstmt);
17344 return exprstmt;
17347 /* Create the FUNCTION_DECL for a function definition.
17348 DECLSPECS and DECLARATOR are the parts of the declaration;
17349 they describe the function's name and the type it returns,
17350 but twisted together in a fashion that parallels the syntax of C.
17352 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17353 DECLARATOR is really the DECL for the function we are about to
17354 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17355 indicating that the function is an inline defined in-class.
17357 This function creates a binding context for the function body
17358 as well as setting up the FUNCTION_DECL in current_function_decl.
17360 For C++, we must first check whether that datum makes any sense.
17361 For example, "class A local_a(1,2);" means that variable local_a
17362 is an aggregate of type A, which should have a constructor
17363 applied to it with the argument list [1, 2].
17365 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17366 or may be a BLOCK if the function has been defined previously
17367 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17368 error_mark_node if the function has never been defined, or
17369 a BLOCK if the function has been defined somewhere. */
17371 bool
17372 start_preparsed_function (tree decl1, tree attrs, int flags)
17374 tree ctype = NULL_TREE;
17375 bool doing_friend = false;
17377 /* Sanity check. */
17378 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17379 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17381 tree fntype = TREE_TYPE (decl1);
17382 if (TREE_CODE (fntype) == METHOD_TYPE)
17383 ctype = TYPE_METHOD_BASETYPE (fntype);
17384 else
17386 ctype = DECL_FRIEND_CONTEXT (decl1);
17388 if (ctype)
17389 doing_friend = true;
17392 if (DECL_DECLARED_INLINE_P (decl1)
17393 && lookup_attribute ("noinline", attrs))
17394 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17395 "inline function %qD given attribute %qs", decl1, "noinline");
17397 /* Handle gnu_inline attribute. */
17398 if (GNU_INLINE_P (decl1))
17400 DECL_EXTERNAL (decl1) = 1;
17401 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17402 DECL_INTERFACE_KNOWN (decl1) = 1;
17403 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17406 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17407 /* This is a constructor, we must ensure that any default args
17408 introduced by this definition are propagated to the clones
17409 now. The clones are used directly in overload resolution. */
17410 adjust_clone_args (decl1);
17412 /* Sometimes we don't notice that a function is a static member, and
17413 build a METHOD_TYPE for it. Fix that up now. */
17414 gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
17415 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17417 /* Set up current_class_type, and enter the scope of the class, if
17418 appropriate. */
17419 if (ctype)
17420 push_nested_class (ctype);
17421 else if (DECL_STATIC_FUNCTION_P (decl1))
17422 push_nested_class (DECL_CONTEXT (decl1));
17424 /* Now that we have entered the scope of the class, we must restore
17425 the bindings for any template parameters surrounding DECL1, if it
17426 is an inline member template. (Order is important; consider the
17427 case where a template parameter has the same name as a field of
17428 the class.) It is not until after this point that
17429 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17430 if (flags & SF_INCLASS_INLINE)
17431 maybe_begin_member_template_processing (decl1);
17433 /* Effective C++ rule 15. */
17434 if (warn_ecpp
17435 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17436 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17437 && VOID_TYPE_P (TREE_TYPE (fntype)))
17438 warning (OPT_Weffc__,
17439 "%<operator=%> should return a reference to %<*this%>");
17441 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17442 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17443 if (!DECL_INITIAL (decl1))
17444 DECL_INITIAL (decl1) = error_mark_node;
17446 /* This function exists in static storage.
17447 (This does not mean `static' in the C sense!) */
17448 TREE_STATIC (decl1) = 1;
17450 /* We must call push_template_decl after current_class_type is set
17451 up. (If we are processing inline definitions after exiting a
17452 class scope, current_class_type will be NULL_TREE until set above
17453 by push_nested_class.) */
17454 if (processing_template_decl)
17456 tree newdecl1 = push_template_decl (decl1, doing_friend);
17457 if (newdecl1 == error_mark_node)
17459 if (ctype || DECL_STATIC_FUNCTION_P (decl1))
17460 pop_nested_class ();
17461 return false;
17463 decl1 = newdecl1;
17466 /* Make sure the parameter and return types are reasonable. When
17467 you declare a function, these types can be incomplete, but they
17468 must be complete when you define the function. */
17469 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17471 /* Build the return declaration for the function. */
17472 tree restype = TREE_TYPE (fntype);
17474 if (DECL_RESULT (decl1) == NULL_TREE)
17476 /* In a template instantiation, copy the return type location. When
17477 parsing, the location will be set in grokdeclarator. */
17478 location_t loc = input_location;
17479 if (DECL_TEMPLATE_INSTANTIATION (decl1))
17481 tree tmpl = template_for_substitution (decl1);
17482 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
17483 loc = DECL_SOURCE_LOCATION (res);
17486 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
17487 DECL_ARTIFICIAL (resdecl) = 1;
17488 DECL_IGNORED_P (resdecl) = 1;
17489 DECL_RESULT (decl1) = resdecl;
17491 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17494 /* Record the decl so that the function name is defined.
17495 If we already have a decl for this name, and it is a FUNCTION_DECL,
17496 use the old decl. */
17497 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17499 /* A specialization is not used to guide overload resolution. */
17500 if (!DECL_FUNCTION_MEMBER_P (decl1)
17501 && !(DECL_USE_TEMPLATE (decl1) &&
17502 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17504 tree olddecl = pushdecl (decl1);
17506 if (olddecl == error_mark_node)
17507 /* If something went wrong when registering the declaration,
17508 use DECL1; we have to have a FUNCTION_DECL to use when
17509 parsing the body of the function. */
17511 else
17513 /* Otherwise, OLDDECL is either a previous declaration
17514 of the same function or DECL1 itself. */
17516 if (warn_missing_declarations
17517 && olddecl == decl1
17518 && !DECL_MAIN_P (decl1)
17519 && TREE_PUBLIC (decl1)
17520 && !DECL_DECLARED_INLINE_P (decl1))
17522 tree context;
17524 /* Check whether DECL1 is in an anonymous
17525 namespace. */
17526 for (context = DECL_CONTEXT (decl1);
17527 context;
17528 context = DECL_CONTEXT (context))
17530 if (TREE_CODE (context) == NAMESPACE_DECL
17531 && DECL_NAME (context) == NULL_TREE)
17532 break;
17535 if (context == NULL)
17536 warning_at (DECL_SOURCE_LOCATION (decl1),
17537 OPT_Wmissing_declarations,
17538 "no previous declaration for %qD", decl1);
17541 decl1 = olddecl;
17544 else
17546 /* We need to set the DECL_CONTEXT. */
17547 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17548 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17550 fntype = TREE_TYPE (decl1);
17551 restype = TREE_TYPE (fntype);
17553 /* If #pragma weak applies, mark the decl appropriately now.
17554 The pragma only applies to global functions. Because
17555 determining whether or not the #pragma applies involves
17556 computing the mangled name for the declaration, we cannot
17557 apply the pragma until after we have merged this declaration
17558 with any previous declarations; if the original declaration
17559 has a linkage specification, that specification applies to
17560 the definition as well, and may affect the mangled name. */
17561 if (DECL_FILE_SCOPE_P (decl1))
17562 maybe_apply_pragma_weak (decl1);
17565 /* We are now in the scope of the function being defined. */
17566 current_function_decl = decl1;
17568 /* Save the parm names or decls from this function's declarator
17569 where store_parm_decls will find them. */
17570 tree current_function_parms = DECL_ARGUMENTS (decl1);
17572 /* Let the user know we're compiling this function. */
17573 announce_function (decl1);
17575 gcc_assert (DECL_INITIAL (decl1));
17577 /* This function may already have been parsed, in which case just
17578 return; our caller will skip over the body without parsing. */
17579 if (DECL_INITIAL (decl1) != error_mark_node)
17580 return true;
17582 /* Initialize RTL machinery. We cannot do this until
17583 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17584 even when processing a template; this is how we get
17585 CFUN set up, and our per-function variables initialized.
17586 FIXME factor out the non-RTL stuff. */
17587 cp_binding_level *bl = current_binding_level;
17588 allocate_struct_function (decl1, processing_template_decl);
17590 /* Initialize the language data structures. Whenever we start
17591 a new function, we destroy temporaries in the usual way. */
17592 cfun->language = ggc_cleared_alloc<language_function> ();
17593 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17594 current_binding_level = bl;
17596 /* If we are (erroneously) defining a function that we have already
17597 defined before, wipe out what we knew before. */
17598 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17599 FNDECL_USED_AUTO (decl1) = false;
17600 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17602 if (!processing_template_decl && type_uses_auto (restype))
17604 FNDECL_USED_AUTO (decl1) = true;
17605 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17608 /* Start the statement-tree, start the tree now. */
17609 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17611 if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
17613 /* We know that this was set up by `grokclassfn'. We do not
17614 wait until `store_parm_decls', since evil parse errors may
17615 never get us to that point. Here we keep the consistency
17616 between `current_class_type' and `current_class_ptr'. */
17617 tree t = DECL_ARGUMENTS (decl1);
17619 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
17620 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
17622 cp_function_chain->x_current_class_ref
17623 = cp_build_fold_indirect_ref (t);
17624 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
17625 cp_function_chain->x_current_class_ptr = t;
17627 /* Constructors and destructors need to know whether they're "in
17628 charge" of initializing virtual base classes. */
17629 t = DECL_CHAIN (t);
17630 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
17632 current_in_charge_parm = t;
17633 t = DECL_CHAIN (t);
17635 if (DECL_HAS_VTT_PARM_P (decl1))
17637 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
17638 current_vtt_parm = t;
17642 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
17643 /* Implicitly-defined methods (like the
17644 destructor for a class in which no destructor
17645 is explicitly declared) must not be defined
17646 until their definition is needed. So, we
17647 ignore interface specifications for
17648 compiler-generated functions. */
17649 && !DECL_ARTIFICIAL (decl1));
17650 struct c_fileinfo *finfo
17651 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
17653 if (processing_template_decl)
17654 /* Don't mess with interface flags. */;
17655 else if (DECL_INTERFACE_KNOWN (decl1))
17657 tree ctx = decl_function_context (decl1);
17659 if (DECL_NOT_REALLY_EXTERN (decl1))
17660 DECL_EXTERNAL (decl1) = 0;
17662 if (ctx != NULL_TREE && vague_linkage_p (ctx))
17663 /* This is a function in a local class in an extern inline
17664 or template function. */
17665 comdat_linkage (decl1);
17667 /* If this function belongs to an interface, it is public.
17668 If it belongs to someone else's interface, it is also external.
17669 This only affects inlines and template instantiations. */
17670 else if (!finfo->interface_unknown && honor_interface)
17672 if (DECL_DECLARED_INLINE_P (decl1)
17673 || DECL_TEMPLATE_INSTANTIATION (decl1))
17675 DECL_EXTERNAL (decl1)
17676 = (finfo->interface_only
17677 || (DECL_DECLARED_INLINE_P (decl1)
17678 && ! flag_implement_inlines
17679 && !DECL_VINDEX (decl1)));
17681 /* For WIN32 we also want to put these in linkonce sections. */
17682 maybe_make_one_only (decl1);
17684 else
17685 DECL_EXTERNAL (decl1) = 0;
17686 DECL_INTERFACE_KNOWN (decl1) = 1;
17687 /* If this function is in an interface implemented in this file,
17688 make sure that the back end knows to emit this function
17689 here. */
17690 if (!DECL_EXTERNAL (decl1))
17691 mark_needed (decl1);
17693 else if (finfo->interface_unknown && finfo->interface_only
17694 && honor_interface)
17696 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
17697 interface, we will have both finfo->interface_unknown and
17698 finfo->interface_only set. In that case, we don't want to
17699 use the normal heuristics because someone will supply a
17700 #pragma implementation elsewhere, and deducing it here would
17701 produce a conflict. */
17702 comdat_linkage (decl1);
17703 DECL_EXTERNAL (decl1) = 0;
17704 DECL_INTERFACE_KNOWN (decl1) = 1;
17705 DECL_DEFER_OUTPUT (decl1) = 1;
17707 else
17709 /* This is a definition, not a reference.
17710 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
17711 if (!GNU_INLINE_P (decl1))
17712 DECL_EXTERNAL (decl1) = 0;
17714 if ((DECL_DECLARED_INLINE_P (decl1)
17715 || DECL_TEMPLATE_INSTANTIATION (decl1))
17716 && ! DECL_INTERFACE_KNOWN (decl1))
17717 DECL_DEFER_OUTPUT (decl1) = 1;
17718 else
17719 DECL_INTERFACE_KNOWN (decl1) = 1;
17722 /* Determine the ELF visibility attribute for the function. We must not
17723 do this before calling "pushdecl", as we must allow "duplicate_decls"
17724 to merge any attributes appropriately. We also need to wait until
17725 linkage is set. */
17726 if (!DECL_CLONED_FUNCTION_P (decl1))
17727 determine_visibility (decl1);
17729 if (!processing_template_decl)
17730 maybe_instantiate_noexcept (decl1);
17732 begin_scope (sk_function_parms, decl1);
17734 ++function_depth;
17736 start_fname_decls ();
17738 store_parm_decls (current_function_parms);
17740 start_function_contracts (decl1);
17742 if (!processing_template_decl
17743 && (flag_lifetime_dse > 1)
17744 && DECL_CONSTRUCTOR_P (decl1)
17745 && !DECL_CLONED_FUNCTION_P (decl1)
17746 /* Clobbering an empty base is harmful if it overlays real data. */
17747 && !is_empty_class (current_class_type)
17748 /* We can't clobber safely for an implicitly-defined default constructor
17749 because part of the initialization might happen before we enter the
17750 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
17751 && !implicit_default_ctor_p (decl1))
17752 finish_expr_stmt (build_clobber_this ());
17754 if (!processing_template_decl
17755 && DECL_CONSTRUCTOR_P (decl1)
17756 && sanitize_flags_p (SANITIZE_VPTR)
17757 && !DECL_CLONED_FUNCTION_P (decl1)
17758 && !implicit_default_ctor_p (decl1))
17759 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
17761 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
17762 start_lambda_scope (decl1);
17764 return true;
17768 /* Like start_preparsed_function, except that instead of a
17769 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
17771 Returns true on success. If the DECLARATOR is not suitable
17772 for a function, we return false, which tells the parser to
17773 skip the entire function. */
17775 bool
17776 start_function (cp_decl_specifier_seq *declspecs,
17777 const cp_declarator *declarator,
17778 tree attrs)
17780 tree decl1;
17782 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
17783 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
17784 if (decl1 == error_mark_node)
17785 return false;
17787 if (DECL_MAIN_P (decl1))
17788 /* main must return int. grokfndecl should have corrected it
17789 (and issued a diagnostic) if the user got it wrong. */
17790 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
17791 integer_type_node));
17793 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
17796 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
17797 FN. */
17799 static bool
17800 use_eh_spec_block (tree fn)
17802 return (flag_exceptions && flag_enforce_eh_specs
17803 && !processing_template_decl
17804 /* We insert the EH_SPEC_BLOCK only in the original
17805 function; then, it is copied automatically to the
17806 clones. */
17807 && !DECL_CLONED_FUNCTION_P (fn)
17808 /* Implicitly-generated constructors and destructors have
17809 exception specifications. However, those specifications
17810 are the union of the possible exceptions specified by the
17811 constructors/destructors for bases and members, so no
17812 unallowed exception will ever reach this function. By
17813 not creating the EH_SPEC_BLOCK we save a little memory,
17814 and we avoid spurious warnings about unreachable
17815 code. */
17816 && !DECL_DEFAULTED_FN (fn)
17817 && !type_throw_all_p (TREE_TYPE (fn)));
17820 /* Helper function to push ARGS into the current lexical scope. DECL
17821 is the function declaration. NONPARMS is used to handle enum
17822 constants. */
17824 void
17825 do_push_parm_decls (tree decl, tree args, tree *nonparms)
17827 /* If we're doing semantic analysis, then we'll call pushdecl
17828 for each of these. We must do them in reverse order so that
17829 they end in the correct forward order. */
17830 args = nreverse (args);
17832 tree next;
17833 for (tree parm = args; parm; parm = next)
17835 next = DECL_CHAIN (parm);
17836 if (TREE_CODE (parm) == PARM_DECL)
17837 pushdecl (parm);
17838 else if (nonparms)
17840 /* If we find an enum constant or a type tag, put it aside for
17841 the moment. */
17842 TREE_CHAIN (parm) = NULL_TREE;
17843 *nonparms = chainon (*nonparms, parm);
17847 /* Get the decls in their original chain order and record in the
17848 function. This is all and only the PARM_DECLs that were
17849 pushed into scope by the loop above. */
17850 DECL_ARGUMENTS (decl) = get_local_decls ();
17853 /* Store the parameter declarations into the current function declaration.
17854 This is called after parsing the parameter declarations, before
17855 digesting the body of the function.
17857 Also install to binding contour return value identifier, if any. */
17859 static void
17860 store_parm_decls (tree current_function_parms)
17862 tree fndecl = current_function_decl;
17864 /* This is a chain of any other decls that came in among the parm
17865 declarations. If a parm is declared with enum {foo, bar} x;
17866 then CONST_DECLs for foo and bar are put here. */
17867 tree nonparms = NULL_TREE;
17869 if (current_function_parms)
17871 /* This case is when the function was defined with an ANSI prototype.
17872 The parms already have decls, so we need not do anything here
17873 except record them as in effect
17874 and complain if any redundant old-style parm decls were written. */
17876 tree specparms = current_function_parms;
17878 /* Must clear this because it might contain TYPE_DECLs declared
17879 at class level. */
17880 current_binding_level->names = NULL;
17882 do_push_parm_decls (fndecl, specparms, &nonparms);
17884 else
17885 DECL_ARGUMENTS (fndecl) = NULL_TREE;
17887 /* Now store the final chain of decls for the arguments
17888 as the decl-chain of the current lexical scope.
17889 Put the enumerators in as well, at the front so that
17890 DECL_ARGUMENTS is not modified. */
17891 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
17893 if (use_eh_spec_block (current_function_decl))
17894 current_eh_spec_block = begin_eh_spec_block ();
17898 /* Set the return value of the [cd]tor if the ABI wants that. */
17900 void
17901 maybe_return_this (void)
17903 if (targetm.cxx.cdtor_returns_this ())
17905 /* Return the address of the object. */
17906 tree val = DECL_ARGUMENTS (current_function_decl);
17907 suppress_warning (val, OPT_Wuse_after_free);
17908 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
17909 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17910 DECL_RESULT (current_function_decl), val);
17911 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17912 add_stmt (exprstmt);
17916 /* Do all the processing for the beginning of a destructor; set up the
17917 vtable pointers and cleanups for bases and members. */
17919 static void
17920 begin_destructor_body (void)
17922 tree compound_stmt;
17924 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
17925 issued an error message. We still want to try to process the
17926 body of the function, but initialize_vtbl_ptrs will crash if
17927 TYPE_BINFO is NULL. */
17928 if (COMPLETE_TYPE_P (current_class_type))
17930 compound_stmt = begin_compound_stmt (0);
17931 /* Make all virtual function table pointers in non-virtual base
17932 classes point to CURRENT_CLASS_TYPE's virtual function
17933 tables. */
17934 initialize_vtbl_ptrs (current_class_ptr);
17935 finish_compound_stmt (compound_stmt);
17937 if (flag_lifetime_dse
17938 /* Clobbering an empty base is harmful if it overlays real data. */
17939 && !is_empty_class (current_class_type))
17941 if (sanitize_flags_p (SANITIZE_VPTR)
17942 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
17943 && TYPE_CONTAINS_VPTR_P (current_class_type))
17945 tree binfo = TYPE_BINFO (current_class_type);
17946 tree ref
17947 = cp_build_fold_indirect_ref (current_class_ptr);
17949 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
17950 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
17951 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
17952 NOP_EXPR, vtbl,
17953 tf_warning_or_error);
17954 /* If the vptr is shared with some virtual nearly empty base,
17955 don't clear it if not in charge, the dtor of the virtual
17956 nearly empty base will do that later. */
17957 if (CLASSTYPE_VBASECLASSES (current_class_type))
17959 tree c = current_class_type;
17960 while (CLASSTYPE_PRIMARY_BINFO (c))
17962 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
17964 stmt = convert_to_void (stmt, ICV_STATEMENT,
17965 tf_warning_or_error);
17966 stmt = build_if_in_charge (stmt);
17967 break;
17969 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
17972 finish_decl_cleanup (NULL_TREE, stmt);
17974 else
17975 finish_decl_cleanup (NULL_TREE, build_clobber_this ());
17978 /* And insert cleanups for our bases and members so that they
17979 will be properly destroyed if we throw. */
17980 push_base_cleanups ();
17984 /* Do the necessary processing for the beginning of a function body, which
17985 in this case includes member-initializers, but not the catch clauses of
17986 a function-try-block. Currently, this means opening a binding level
17987 for the member-initializers (in a ctor), member cleanups (in a dtor),
17988 and capture proxies (in a lambda operator()). */
17990 tree
17991 begin_function_body (void)
17993 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
17994 return NULL_TREE;
17996 if (processing_template_decl)
17997 /* Do nothing now. */;
17998 else
17999 /* Always keep the BLOCK node associated with the outermost pair of
18000 curly braces of a function. These are needed for correct
18001 operation of dwarfout.c. */
18002 keep_next_level (true);
18004 tree stmt = begin_compound_stmt (BCS_FN_BODY);
18005 current_binding_level->artificial = 1;
18007 if (processing_template_decl)
18008 /* Do nothing now. */;
18009 else if (DECL_DESTRUCTOR_P (current_function_decl))
18010 begin_destructor_body ();
18012 return stmt;
18015 /* Do the processing for the end of a function body. Currently, this means
18016 closing out the cleanups for fully-constructed bases and members, and in
18017 the case of the destructor, deleting the object if desired. Again, this
18018 is only meaningful for [cd]tors, since they are the only functions where
18019 there is a significant distinction between the main body and any
18020 function catch clauses. Handling, say, main() return semantics here
18021 would be wrong, as flowing off the end of a function catch clause for
18022 main() would also need to return 0. */
18024 void
18025 finish_function_body (tree compstmt)
18027 if (compstmt == NULL_TREE)
18028 return;
18030 /* Close the block. */
18031 finish_compound_stmt (compstmt);
18033 if (processing_template_decl)
18034 /* Do nothing now. */;
18035 else if (DECL_CONSTRUCTOR_P (current_function_decl)
18036 || DECL_DESTRUCTOR_P (current_function_decl))
18037 maybe_return_this ();
18040 /* Given a function, returns the BLOCK corresponding to the outermost level
18041 of curly braces, skipping the artificial block created for constructor
18042 initializers. */
18044 tree
18045 outer_curly_brace_block (tree fndecl)
18047 tree block = DECL_INITIAL (fndecl);
18048 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18049 return block;
18050 block = BLOCK_SUBBLOCKS (block);
18051 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18052 return block;
18053 block = BLOCK_SUBBLOCKS (block);
18054 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
18055 return block;
18058 /* If FNDECL is a class's key method, add the class to the list of
18059 keyed classes that should be emitted. */
18061 static void
18062 record_key_method_defined (tree fndecl)
18064 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
18065 && DECL_VIRTUAL_P (fndecl)
18066 && !processing_template_decl)
18068 tree fnclass = DECL_CONTEXT (fndecl);
18069 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
18070 vec_safe_push (keyed_classes, fnclass);
18074 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
18075 of "return *this;" immediately before its location, using FNDECL's
18076 first statement (if any) to give the indentation, if appropriate. */
18078 static void
18079 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
18081 location_t indent = UNKNOWN_LOCATION;
18082 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
18083 if (stmts)
18084 indent = EXPR_LOCATION (stmts);
18085 richloc->add_fixit_insert_formatted ("return *this;",
18086 richloc->get_loc (),
18087 indent);
18090 /* This function carries out the subset of finish_function operations needed
18091 to emit the compiler-generated outlined helper functions used by the
18092 coroutines implementation. */
18094 static void
18095 emit_coro_helper (tree helper)
18097 /* This is a partial set of the operations done by finish_function()
18098 plus emitting the result. */
18099 set_cfun (NULL);
18100 current_function_decl = helper;
18101 begin_scope (sk_function_parms, NULL);
18102 store_parm_decls (DECL_ARGUMENTS (helper));
18103 announce_function (helper);
18104 allocate_struct_function (helper, false);
18105 cfun->language = ggc_cleared_alloc<language_function> ();
18106 poplevel (1, 0, 1);
18107 maybe_save_constexpr_fundef (helper);
18108 /* We must start each function with a clear fold cache. */
18109 clear_fold_cache ();
18110 cp_fold_function (helper);
18111 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
18112 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
18113 /* This function has coroutine IFNs that we should handle in middle
18114 end lowering. */
18115 cfun->coroutine_component = true;
18116 cp_genericize (helper);
18117 expand_or_defer_fn (helper);
18120 /* Finish up a function declaration and compile that function
18121 all the way to assembler language output. The free the storage
18122 for the function definition. INLINE_P is TRUE if we just
18123 finished processing the body of an in-class inline function
18124 definition. (This processing will have taken place after the
18125 class definition is complete.) */
18127 tree
18128 finish_function (bool inline_p)
18130 tree fndecl = current_function_decl;
18131 tree fntype, ctype = NULL_TREE;
18132 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18133 bool coro_p = flag_coroutines
18134 && !processing_template_decl
18135 && DECL_COROUTINE_P (fndecl);
18136 bool coro_emit_helpers = false;
18138 /* When we get some parse errors, we can end up without a
18139 current_function_decl, so cope. */
18140 if (fndecl == NULL_TREE)
18141 return error_mark_node;
18143 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18144 finish_lambda_scope ();
18146 if (c_dialect_objc ())
18147 objc_finish_function ();
18149 record_key_method_defined (fndecl);
18151 fntype = TREE_TYPE (fndecl);
18153 /* TREE_READONLY (fndecl) = 1;
18154 This caused &foo to be of type ptr-to-const-function
18155 which then got a warning when stored in a ptr-to-function variable. */
18157 gcc_assert (building_stmt_list_p ());
18158 /* The current function is being defined, so its DECL_INITIAL should
18159 be set, and unless there's a multiple definition, it should be
18160 error_mark_node. */
18161 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18163 if (coro_p)
18165 /* Only try to emit the coroutine outlined helper functions if the
18166 transforms succeeded. Otherwise, treat errors in the same way as
18167 a regular function. */
18168 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
18170 /* We should handle coroutine IFNs in middle end lowering. */
18171 cfun->coroutine_component = true;
18173 /* Do not try to process the ramp's EH unless outlining succeeded. */
18174 if (coro_emit_helpers && use_eh_spec_block (fndecl))
18175 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18176 (TREE_TYPE (fndecl)),
18177 current_eh_spec_block);
18179 else
18180 /* For a cloned function, we've already got all the code we need;
18181 there's no need to add any extra bits. */
18182 if (!DECL_CLONED_FUNCTION_P (fndecl))
18184 /* Make it so that `main' always returns 0 by default. */
18185 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18186 && !TREE_THIS_VOLATILE (current_function_decl))
18187 finish_return_stmt (integer_zero_node);
18189 if (use_eh_spec_block (current_function_decl))
18190 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18191 (TREE_TYPE (current_function_decl)),
18192 current_eh_spec_block);
18195 /* If we're saving up tree structure, tie off the function now. */
18196 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18198 finish_fname_decls ();
18200 /* This must come after expand_function_end because cleanups might
18201 have declarations (from inline functions) that need to go into
18202 this function's blocks. */
18204 /* If the current binding level isn't the outermost binding level
18205 for this function, either there is a bug, or we have experienced
18206 syntax errors and the statement tree is malformed. */
18207 if (current_binding_level->kind != sk_function_parms)
18209 /* Make sure we have already experienced errors. */
18210 gcc_assert (errorcount);
18212 /* Throw away the broken statement tree and extra binding
18213 levels. */
18214 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18216 while (current_binding_level->kind != sk_function_parms)
18218 if (current_binding_level->kind == sk_class)
18219 pop_nested_class ();
18220 else
18221 poplevel (0, 0, 0);
18224 poplevel (1, 0, 1);
18226 /* Statements should always be full-expressions at the outermost set
18227 of curly braces for a function. */
18228 gcc_assert (stmts_are_full_exprs_p ());
18230 /* If there are no return statements in a function with auto return type,
18231 the return type is void. But if the declared type is something like
18232 auto*, this is an error. */
18233 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18234 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18236 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18237 && !current_function_returns_value
18238 && !current_function_returns_null)
18240 /* We haven't applied return type deduction because we haven't
18241 seen any return statements. Do that now. */
18242 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18243 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18244 void_node, node, tf_warning_or_error,
18245 adc_return_type);
18247 apply_deduced_return_type (fndecl, void_type_node);
18248 fntype = TREE_TYPE (fndecl);
18250 else if (!current_function_returns_value
18251 && !current_function_returns_null)
18253 error ("no return statements in function returning %qT",
18254 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18255 inform (input_location, "only plain %<auto%> return type can be "
18256 "deduced to %<void%>");
18260 /* Remember that we were in class scope. */
18261 if (current_class_name)
18262 ctype = current_class_type;
18264 if (DECL_DELETED_FN (fndecl))
18266 DECL_INITIAL (fndecl) = error_mark_node;
18267 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18268 goto cleanup;
18271 // If this is a concept, check that the definition is reasonable.
18272 if (DECL_DECLARED_CONCEPT_P (fndecl))
18273 check_function_concept (fndecl);
18275 if (flag_openmp)
18276 if (tree attr = lookup_attribute ("omp declare variant base",
18277 DECL_ATTRIBUTES (fndecl)))
18278 omp_declare_variant_finalize (fndecl, attr);
18280 /* Complain if there's just no return statement. */
18281 if ((warn_return_type
18282 || (cxx_dialect >= cxx14
18283 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18284 && !VOID_TYPE_P (TREE_TYPE (fntype))
18285 && !dependent_type_p (TREE_TYPE (fntype))
18286 && !current_function_returns_value && !current_function_returns_null
18287 /* Don't complain if we abort or throw. */
18288 && !current_function_returns_abnormally
18289 /* Don't complain if there's an infinite loop. */
18290 && !current_function_infinite_loop
18291 /* Don't complain if we are declared noreturn. */
18292 && !TREE_THIS_VOLATILE (fndecl)
18293 && !DECL_NAME (DECL_RESULT (fndecl))
18294 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18295 /* Structor return values (if any) are set by the compiler. */
18296 && !DECL_CONSTRUCTOR_P (fndecl)
18297 && !DECL_DESTRUCTOR_P (fndecl)
18298 && targetm.warn_func_return (fndecl))
18300 gcc_rich_location richloc (input_location);
18301 /* Potentially add a "return *this;" fix-it hint for
18302 assignment operators. */
18303 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18305 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18306 if (TREE_CODE (valtype) == REFERENCE_TYPE
18307 && current_class_ref
18308 && same_type_ignoring_top_level_qualifiers_p
18309 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18310 && global_dc->option_enabled (OPT_Wreturn_type,
18311 global_dc->lang_mask,
18312 global_dc->option_state))
18313 add_return_star_this_fixit (&richloc, fndecl);
18315 if (cxx_dialect >= cxx14
18316 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18317 error_at (&richloc, "no return statement in %<constexpr%> function "
18318 "returning non-void");
18319 else if (warning_at (&richloc, OPT_Wreturn_type,
18320 "no return statement in function returning "
18321 "non-void"))
18322 suppress_warning (fndecl, OPT_Wreturn_type);
18325 /* Lambda closure members are implicitly constexpr if possible. */
18326 if (cxx_dialect >= cxx17
18327 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18328 DECL_DECLARED_CONSTEXPR_P (fndecl)
18329 = ((processing_template_decl
18330 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18331 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18333 /* Save constexpr function body before it gets munged by
18334 the NRV transformation. */
18335 maybe_save_constexpr_fundef (fndecl);
18337 /* Invoke the pre-genericize plugin before we start munging things. */
18338 if (!processing_template_decl)
18339 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18341 /* Perform delayed folding before NRV transformation. */
18342 if (!processing_template_decl
18343 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18344 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18345 cp_fold_function (fndecl);
18347 /* Set up the named return value optimization, if we can. Candidate
18348 variables are selected in check_return_expr. */
18349 if (tree r = current_function_return_value)
18351 if (r != error_mark_node)
18352 finalize_nrv (fndecl, r);
18353 current_function_return_value = NULL_TREE;
18356 /* Must mark the RESULT_DECL as being in this function. */
18357 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18359 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18360 to the FUNCTION_DECL node itself. */
18361 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18363 /* Store the end of the function, so that we get good line number
18364 info for the epilogue. */
18365 cfun->function_end_locus = input_location;
18367 /* Complain about parameters that are only set, but never otherwise used. */
18368 if (warn_unused_but_set_parameter
18369 && !processing_template_decl
18370 && errorcount == unused_but_set_errorcount
18371 && !DECL_CLONED_FUNCTION_P (fndecl))
18373 tree decl;
18375 for (decl = DECL_ARGUMENTS (fndecl);
18376 decl;
18377 decl = DECL_CHAIN (decl))
18378 if (TREE_USED (decl)
18379 && TREE_CODE (decl) == PARM_DECL
18380 && !DECL_READ_P (decl)
18381 && DECL_NAME (decl)
18382 && !DECL_ARTIFICIAL (decl)
18383 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18384 && !DECL_IN_SYSTEM_HEADER (decl)
18385 && TREE_TYPE (decl) != error_mark_node
18386 && !TYPE_REF_P (TREE_TYPE (decl))
18387 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18388 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18389 warning_at (DECL_SOURCE_LOCATION (decl),
18390 OPT_Wunused_but_set_parameter,
18391 "parameter %qD set but not used", decl);
18392 unused_but_set_errorcount = errorcount;
18395 /* Complain about locally defined typedefs that are not used in this
18396 function. */
18397 maybe_warn_unused_local_typedefs ();
18399 /* Possibly warn about unused parameters. */
18400 if (warn_unused_parameter
18401 && !processing_template_decl
18402 && !DECL_CLONED_FUNCTION_P (fndecl))
18403 do_warn_unused_parameter (fndecl);
18405 /* Genericize before inlining. */
18406 if (!processing_template_decl
18407 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18408 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18409 cp_genericize (fndecl);
18411 /* If this function can't throw any exceptions, remember that. */
18412 if (!processing_template_decl
18413 && !cp_function_chain->can_throw
18414 && !flag_non_call_exceptions
18415 && !decl_replaceable_p (fndecl,
18416 opt_for_fn (fndecl, flag_semantic_interposition)))
18417 TREE_NOTHROW (fndecl) = 1;
18419 /* Emit the resumer and destroyer functions now, providing that we have
18420 not encountered some fatal error. */
18421 if (coro_emit_helpers)
18423 emit_coro_helper (resumer);
18424 emit_coro_helper (destroyer);
18427 cleanup:
18428 /* We're leaving the context of this function, so zap cfun. It's still in
18429 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18430 set_cfun (NULL);
18431 current_function_decl = NULL;
18433 /* If this is an in-class inline definition, we may have to pop the
18434 bindings for the template parameters that we added in
18435 maybe_begin_member_template_processing when start_function was
18436 called. */
18437 if (inline_p)
18438 maybe_end_member_template_processing ();
18440 /* Leave the scope of the class. */
18441 if (ctype)
18442 pop_nested_class ();
18444 --function_depth;
18446 /* Clean up. */
18447 current_function_decl = NULL_TREE;
18449 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18451 finish_function_contracts (fndecl);
18453 return fndecl;
18456 /* Create the FUNCTION_DECL for a function definition.
18457 DECLSPECS and DECLARATOR are the parts of the declaration;
18458 they describe the return type and the name of the function,
18459 but twisted together in a fashion that parallels the syntax of C.
18461 This function creates a binding context for the function body
18462 as well as setting up the FUNCTION_DECL in current_function_decl.
18464 Returns a FUNCTION_DECL on success.
18466 If the DECLARATOR is not suitable for a function (it defines a datum
18467 instead), we return 0, which tells yyparse to report a parse error.
18469 May return void_type_node indicating that this method is actually
18470 a friend. See grokfield for more details.
18472 Came here with a `.pushlevel' .
18474 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18475 CHANGES TO CODE IN `grokfield'. */
18477 tree
18478 grokmethod (cp_decl_specifier_seq *declspecs,
18479 const cp_declarator *declarator, tree attrlist)
18481 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18482 &attrlist);
18484 if (fndecl == error_mark_node)
18485 return error_mark_node;
18487 if (attrlist)
18488 cplus_decl_attributes (&fndecl, attrlist, 0);
18490 /* Pass friends other than inline friend functions back. */
18491 if (fndecl == void_type_node)
18492 return fndecl;
18494 if (DECL_IN_AGGR_P (fndecl))
18496 if (DECL_CLASS_SCOPE_P (fndecl))
18497 error ("%qD is already defined in class %qT", fndecl,
18498 DECL_CONTEXT (fndecl));
18499 return error_mark_node;
18502 check_template_shadow (fndecl);
18504 /* p1779 ABI-Isolation makes inline not a default for in-class
18505 definitions in named module purview. If the user explicitly
18506 made it inline, grokdeclarator will already have done the right
18507 things. */
18508 if ((!named_module_purview_p ()
18509 || flag_module_implicit_inline
18510 /* Lambda's operator function remains inline. */
18511 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18512 /* If the user explicitly asked for this to be inline, we don't
18513 need to do more, but more importantly we want to warn if we
18514 can't inline it. */
18515 && !DECL_DECLARED_INLINE_P (fndecl))
18517 if (TREE_PUBLIC (fndecl))
18518 DECL_COMDAT (fndecl) = 1;
18519 DECL_DECLARED_INLINE_P (fndecl) = 1;
18520 /* It's ok if we can't inline this. */
18521 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18524 /* We process method specializations in finish_struct_1. */
18525 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18527 /* Avoid calling decl_spec_seq... until we have to. */
18528 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18529 fndecl = push_template_decl (fndecl, friendp);
18530 if (fndecl == error_mark_node)
18531 return fndecl;
18534 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18536 fndecl = copy_node (fndecl);
18537 TREE_CHAIN (fndecl) = NULL_TREE;
18540 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18542 DECL_IN_AGGR_P (fndecl) = 1;
18543 return fndecl;
18547 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18548 we can lay it out later, when and if its type becomes complete.
18550 Also handle constexpr variables where the initializer involves
18551 an unlowered PTRMEM_CST because the class isn't complete yet. */
18553 void
18554 maybe_register_incomplete_var (tree var)
18556 gcc_assert (VAR_P (var));
18558 /* Keep track of variables with incomplete types. */
18559 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18560 && DECL_EXTERNAL (var))
18562 tree inner_type = TREE_TYPE (var);
18564 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18565 inner_type = TREE_TYPE (inner_type);
18566 inner_type = TYPE_MAIN_VARIANT (inner_type);
18568 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18569 /* RTTI TD entries are created while defining the type_info. */
18570 || (TYPE_LANG_SPECIFIC (inner_type)
18571 && TYPE_BEING_DEFINED (inner_type)))
18573 incomplete_var iv = {var, inner_type};
18574 vec_safe_push (incomplete_vars, iv);
18576 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18577 && decl_constant_var_p (var)
18578 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18580 /* When the outermost open class is complete we can resolve any
18581 pointers-to-members. */
18582 tree context = outermost_open_class ();
18583 incomplete_var iv = {var, context};
18584 vec_safe_push (incomplete_vars, iv);
18589 /* Called when a class type (given by TYPE) is defined. If there are
18590 any existing VAR_DECLs whose type has been completed by this
18591 declaration, update them now. */
18593 void
18594 complete_vars (tree type)
18596 unsigned ix;
18597 incomplete_var *iv;
18599 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18601 if (same_type_p (type, iv->incomplete_type))
18603 tree var = iv->decl;
18604 tree type = TREE_TYPE (var);
18606 if (type != error_mark_node
18607 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18608 == iv->incomplete_type))
18610 /* Complete the type of the variable. */
18611 complete_type (type);
18612 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
18613 if (COMPLETE_TYPE_P (type))
18614 layout_var_decl (var);
18617 /* Remove this entry from the list. */
18618 incomplete_vars->unordered_remove (ix);
18620 else
18621 ix++;
18625 /* If DECL is of a type which needs a cleanup, build and return an
18626 expression to perform that cleanup here. Return NULL_TREE if no
18627 cleanup need be done. DECL can also be a _REF when called from
18628 split_nonconstant_init_1. */
18630 tree
18631 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
18633 tree type;
18634 tree attr;
18635 tree cleanup;
18637 /* Assume no cleanup is required. */
18638 cleanup = NULL_TREE;
18640 if (error_operand_p (decl))
18641 return cleanup;
18643 /* Handle "__attribute__((cleanup))". We run the cleanup function
18644 before the destructor since the destructor is what actually
18645 terminates the lifetime of the object. */
18646 if (DECL_P (decl))
18647 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
18648 else
18649 attr = NULL_TREE;
18650 if (attr)
18652 tree id;
18653 tree fn;
18654 tree arg;
18656 /* Get the name specified by the user for the cleanup function. */
18657 id = TREE_VALUE (TREE_VALUE (attr));
18658 /* Look up the name to find the cleanup function to call. It is
18659 important to use lookup_name here because that is what is
18660 used in c-common.cc:handle_cleanup_attribute when performing
18661 initial checks on the attribute. Note that those checks
18662 include ensuring that the function found is not an overloaded
18663 function, or an object with an overloaded call operator,
18664 etc.; we can rely on the fact that the function found is an
18665 ordinary FUNCTION_DECL. */
18666 fn = lookup_name (id);
18667 arg = build_address (decl);
18668 if (!mark_used (decl, complain) && !(complain & tf_error))
18669 return error_mark_node;
18670 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
18671 if (cleanup == error_mark_node)
18672 return error_mark_node;
18674 /* Handle ordinary C++ destructors. */
18675 type = TREE_TYPE (decl);
18676 if (type_build_dtor_call (type))
18678 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
18679 tree addr;
18680 tree call;
18682 if (TREE_CODE (type) == ARRAY_TYPE)
18683 addr = decl;
18684 else
18685 addr = build_address (decl);
18687 call = build_delete (input_location, TREE_TYPE (addr), addr,
18688 sfk_complete_destructor, flags, 0, complain);
18689 if (call == error_mark_node)
18690 cleanup = error_mark_node;
18691 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
18692 /* Discard the call. */;
18693 else if (decl_maybe_constant_destruction (decl, type)
18694 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
18695 cxx_constant_dtor (call, decl);
18696 else if (cleanup)
18697 cleanup = cp_build_compound_expr (cleanup, call, complain);
18698 else
18699 cleanup = call;
18702 /* build_delete sets the location of the destructor call to the
18703 current location, even though the destructor is going to be
18704 called later, at the end of the current scope. This can lead to
18705 a "jumpy" behavior for users of debuggers when they step around
18706 the end of the block. So let's unset the location of the
18707 destructor call instead. */
18708 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
18709 if (cleanup && CONVERT_EXPR_P (cleanup))
18710 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
18712 if (cleanup
18713 && DECL_P (decl)
18714 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
18715 /* Treat objects with destructors as used; the destructor may do
18716 something substantive. */
18717 && !mark_used (decl, complain) && !(complain & tf_error))
18718 return error_mark_node;
18720 if (cleanup && cfun && !processing_template_decl
18721 && !expr_noexcept_p (cleanup, tf_none))
18722 cp_function_chain->throwing_cleanup = true;
18724 return cleanup;
18728 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
18729 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
18730 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
18732 tree
18733 static_fn_type (tree memfntype)
18735 tree fntype;
18736 tree args;
18738 if (TYPE_PTRMEMFUNC_P (memfntype))
18739 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
18740 if (INDIRECT_TYPE_P (memfntype)
18741 || TREE_CODE (memfntype) == FUNCTION_DECL)
18742 memfntype = TREE_TYPE (memfntype);
18743 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
18744 return memfntype;
18745 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
18746 args = TYPE_ARG_TYPES (memfntype);
18747 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
18748 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
18749 fntype = (cp_build_type_attribute_variant
18750 (fntype, TYPE_ATTRIBUTES (memfntype)));
18751 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
18752 return fntype;
18755 /* DECL was originally constructed as a non-static member function,
18756 but turned out to be static. Update it accordingly. */
18758 void
18759 revert_static_member_fn (tree decl)
18761 tree stype = static_fn_type (decl);
18762 cp_cv_quals quals = type_memfn_quals (stype);
18763 cp_ref_qualifier rqual = type_memfn_rqual (stype);
18765 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
18766 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
18768 TREE_TYPE (decl) = stype;
18770 if (DECL_ARGUMENTS (decl))
18771 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
18772 DECL_STATIC_FUNCTION_P (decl) = 1;
18775 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
18776 one of the language-independent trees. */
18778 enum cp_tree_node_structure_enum
18779 cp_tree_node_structure (union lang_tree_node * t)
18781 switch (TREE_CODE (&t->generic))
18783 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
18784 case BASELINK: return TS_CP_BASELINK;
18785 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
18786 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
18787 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
18788 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
18789 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
18790 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
18791 case OVERLOAD: return TS_CP_OVERLOAD;
18792 case PTRMEM_CST: return TS_CP_PTRMEM;
18793 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
18794 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
18795 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
18796 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
18797 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
18798 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
18799 default: return TS_CP_GENERIC;
18803 bool
18804 cp_missing_noreturn_ok_p (tree decl)
18806 /* A missing noreturn is ok for the `main' function. */
18807 return DECL_MAIN_P (decl);
18810 /* Return the decl used to identify the COMDAT group into which DECL should
18811 be placed. */
18813 tree
18814 cxx_comdat_group (tree decl)
18816 /* Virtual tables, construction virtual tables, and virtual table
18817 tables all go in a single COMDAT group, named after the primary
18818 virtual table. */
18819 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
18820 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
18821 /* For all other DECLs, the COMDAT group is the mangled name of the
18822 declaration itself. */
18823 else
18825 while (DECL_THUNK_P (decl))
18827 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
18828 into the same section as the target function. In that case
18829 we must return target's name. */
18830 tree target = THUNK_TARGET (decl);
18831 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
18832 && DECL_SECTION_NAME (target) != NULL
18833 && DECL_ONE_ONLY (target))
18834 decl = target;
18835 else
18836 break;
18840 return decl;
18843 /* Returns the return type for FN as written by the user, which may include
18844 a placeholder for a deduced return type. */
18846 tree
18847 fndecl_declared_return_type (tree fn)
18849 fn = STRIP_TEMPLATE (fn);
18850 if (FNDECL_USED_AUTO (fn))
18851 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
18853 return TREE_TYPE (TREE_TYPE (fn));
18856 /* Returns true iff DECL is a variable or function declared with an auto type
18857 that has not yet been deduced to a real type. */
18859 bool
18860 undeduced_auto_decl (tree decl)
18862 if (cxx_dialect < cxx11)
18863 return false;
18864 STRIP_ANY_LOCATION_WRAPPER (decl);
18865 return ((VAR_OR_FUNCTION_DECL_P (decl)
18866 || TREE_CODE (decl) == TEMPLATE_DECL)
18867 && type_uses_auto (TREE_TYPE (decl)));
18870 /* Complain if DECL has an undeduced return type. */
18872 bool
18873 require_deduced_type (tree decl, tsubst_flags_t complain)
18875 if (undeduced_auto_decl (decl))
18877 if (TREE_CODE (decl) == FUNCTION_DECL
18878 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
18879 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
18881 /* Set the return type of __builtin_source_location. */
18882 tree type = get_source_location_impl_type ();
18883 if (type == error_mark_node)
18885 inform (input_location, "using %qs", "__builtin_source_location");
18886 return false;
18888 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
18889 type = build_pointer_type (type);
18890 apply_deduced_return_type (decl, type);
18891 return true;
18894 if (warning_suppressed_p (decl) && seen_error ())
18895 /* We probably already complained about deduction failure. */;
18896 else if (complain & tf_error)
18897 error ("use of %qD before deduction of %<auto%>", decl);
18898 note_failed_type_completion_for_satisfaction (decl);
18899 return false;
18901 return true;
18904 /* Create a representation of the explicit-specifier with
18905 constant-expression of EXPR. COMPLAIN is as for tsubst. */
18907 tree
18908 build_explicit_specifier (tree expr, tsubst_flags_t complain)
18910 if (check_for_bare_parameter_packs (expr))
18911 return error_mark_node;
18913 if (instantiation_dependent_expression_p (expr))
18914 /* Wait for instantiation, tsubst_function_decl will handle it. */
18915 return expr;
18917 expr = build_converted_constant_bool_expr (expr, complain);
18918 expr = instantiate_non_dependent_expr (expr, complain);
18919 expr = cxx_constant_value (expr, complain);
18920 return expr;
18923 #include "gt-cp-decl.h"